ol-debug.js 3.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559
  1. // OpenLayers 3. See http://openlayers.org/
  2. // License: https://raw.githubusercontent.com/openlayers/ol3/master/LICENSE.md
  3. // Version: v3.10.1
  4. (function (root, factory) {
  5. if (typeof exports === "object") {
  6. module.exports = factory();
  7. } else if (typeof define === "function" && define.amd) {
  8. define([], factory);
  9. } else {
  10. root.ol = factory();
  11. }
  12. }(this, function () {
  13. var OPENLAYERS = {};
  14. var goog = this.goog = {};
  15. this.CLOSURE_NO_DEPS = true;
  16. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  17. //
  18. // Licensed under the Apache License, Version 2.0 (the "License");
  19. // you may not use this file except in compliance with the License.
  20. // You may obtain a copy of the License at
  21. //
  22. // http://www.apache.org/licenses/LICENSE-2.0
  23. //
  24. // Unless required by applicable law or agreed to in writing, software
  25. // distributed under the License is distributed on an "AS-IS" BASIS,
  26. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. // See the License for the specific language governing permissions and
  28. // limitations under the License.
  29. /**
  30. * @fileoverview Bootstrap for the Google JS Library (Closure).
  31. *
  32. * In uncompiled mode base.js will write out Closure's deps file, unless the
  33. * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
  34. * include their own deps file(s) from different locations.
  35. *
  36. * @author arv@google.com (Erik Arvidsson)
  37. *
  38. * @provideGoog
  39. */
  40. /**
  41. * @define {boolean} Overridden to true by the compiler when
  42. * --process_closure_primitives is specified.
  43. */
  44. var COMPILED = false;
  45. /**
  46. * Base namespace for the Closure library. Checks to see goog is already
  47. * defined in the current scope before assigning to prevent clobbering if
  48. * base.js is loaded more than once.
  49. *
  50. * @const
  51. */
  52. var goog = goog || {};
  53. /**
  54. * Reference to the global context. In most cases this will be 'window'.
  55. */
  56. goog.global = this;
  57. /**
  58. * A hook for overriding the define values in uncompiled mode.
  59. *
  60. * In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before
  61. * loading base.js. If a key is defined in {@code CLOSURE_UNCOMPILED_DEFINES},
  62. * {@code goog.define} will use the value instead of the default value. This
  63. * allows flags to be overwritten without compilation (this is normally
  64. * accomplished with the compiler's "define" flag).
  65. *
  66. * Example:
  67. * <pre>
  68. * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};
  69. * </pre>
  70. *
  71. * @type {Object<string, (string|number|boolean)>|undefined}
  72. */
  73. goog.global.CLOSURE_UNCOMPILED_DEFINES;
  74. /**
  75. * A hook for overriding the define values in uncompiled or compiled mode,
  76. * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In
  77. * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.
  78. *
  79. * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or
  80. * string literals or the compiler will emit an error.
  81. *
  82. * While any @define value may be set, only those set with goog.define will be
  83. * effective for uncompiled code.
  84. *
  85. * Example:
  86. * <pre>
  87. * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;
  88. * </pre>
  89. *
  90. * @type {Object<string, (string|number|boolean)>|undefined}
  91. */
  92. goog.global.CLOSURE_DEFINES;
  93. /**
  94. * Returns true if the specified value is not undefined.
  95. * WARNING: Do not use this to test if an object has a property. Use the in
  96. * operator instead.
  97. *
  98. * @param {?} val Variable to test.
  99. * @return {boolean} Whether variable is defined.
  100. */
  101. goog.isDef = function(val) {
  102. // void 0 always evaluates to undefined and hence we do not need to depend on
  103. // the definition of the global variable named 'undefined'.
  104. return val !== void 0;
  105. };
  106. /**
  107. * Builds an object structure for the provided namespace path, ensuring that
  108. * names that already exist are not overwritten. For example:
  109. * "a.b.c" -> a = {};a.b={};a.b.c={};
  110. * Used by goog.provide and goog.exportSymbol.
  111. * @param {string} name name of the object that this file defines.
  112. * @param {*=} opt_object the object to expose at the end of the path.
  113. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  114. * is |goog.global|.
  115. * @private
  116. */
  117. goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
  118. var parts = name.split('.');
  119. var cur = opt_objectToExportTo || goog.global;
  120. // Internet Explorer exhibits strange behavior when throwing errors from
  121. // methods externed in this manner. See the testExportSymbolExceptions in
  122. // base_test.html for an example.
  123. if (!(parts[0] in cur) && cur.execScript) {
  124. cur.execScript('var ' + parts[0]);
  125. }
  126. // Certain browsers cannot parse code in the form for((a in b); c;);
  127. // This pattern is produced by the JSCompiler when it collapses the
  128. // statement above into the conditional loop below. To prevent this from
  129. // happening, use a for-loop and reserve the init logic as below.
  130. // Parentheses added to eliminate strict JS warning in Firefox.
  131. for (var part; parts.length && (part = parts.shift());) {
  132. if (!parts.length && goog.isDef(opt_object)) {
  133. // last part and we have an object; use it
  134. cur[part] = opt_object;
  135. } else if (cur[part]) {
  136. cur = cur[part];
  137. } else {
  138. cur = cur[part] = {};
  139. }
  140. }
  141. };
  142. /**
  143. * Defines a named value. In uncompiled mode, the value is retrieved from
  144. * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and
  145. * has the property specified, and otherwise used the defined defaultValue.
  146. * When compiled the default can be overridden using the compiler
  147. * options or the value set in the CLOSURE_DEFINES object.
  148. *
  149. * @param {string} name The distinguished name to provide.
  150. * @param {string|number|boolean} defaultValue
  151. */
  152. goog.define = function(name, defaultValue) {
  153. var value = defaultValue;
  154. if (!COMPILED) {
  155. if (goog.global.CLOSURE_UNCOMPILED_DEFINES &&
  156. Object.prototype.hasOwnProperty.call(
  157. goog.global.CLOSURE_UNCOMPILED_DEFINES, name)) {
  158. value = goog.global.CLOSURE_UNCOMPILED_DEFINES[name];
  159. } else if (goog.global.CLOSURE_DEFINES &&
  160. Object.prototype.hasOwnProperty.call(
  161. goog.global.CLOSURE_DEFINES, name)) {
  162. value = goog.global.CLOSURE_DEFINES[name];
  163. }
  164. }
  165. goog.exportPath_(name, value);
  166. };
  167. /**
  168. * @define {boolean} DEBUG is provided as a convenience so that debugging code
  169. * that should not be included in a production js_binary can be easily stripped
  170. * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
  171. * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
  172. * because they are generally used for debugging purposes and it is difficult
  173. * for the JSCompiler to statically determine whether they are used.
  174. */
  175. goog.define('goog.DEBUG', true);
  176. /**
  177. * @define {string} LOCALE defines the locale being used for compilation. It is
  178. * used to select locale specific data to be compiled in js binary. BUILD rule
  179. * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
  180. * option.
  181. *
  182. * Take into account that the locale code format is important. You should use
  183. * the canonical Unicode format with hyphen as a delimiter. Language must be
  184. * lowercase, Language Script - Capitalized, Region - UPPERCASE.
  185. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
  186. *
  187. * See more info about locale codes here:
  188. * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
  189. *
  190. * For language codes you should use values defined by ISO 693-1. See it here
  191. * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
  192. * this rule: the Hebrew language. For legacy reasons the old code (iw) should
  193. * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
  194. */
  195. goog.define('goog.LOCALE', 'en'); // default to en
  196. /**
  197. * @define {boolean} Whether this code is running on trusted sites.
  198. *
  199. * On untrusted sites, several native functions can be defined or overridden by
  200. * external libraries like Prototype, Datejs, and JQuery and setting this flag
  201. * to false forces closure to use its own implementations when possible.
  202. *
  203. * If your JavaScript can be loaded by a third party site and you are wary about
  204. * relying on non-standard implementations, specify
  205. * "--define goog.TRUSTED_SITE=false" to the JSCompiler.
  206. */
  207. goog.define('goog.TRUSTED_SITE', true);
  208. /**
  209. * @define {boolean} Whether a project is expected to be running in strict mode.
  210. *
  211. * This define can be used to trigger alternate implementations compatible with
  212. * running in EcmaScript Strict mode or warn about unavailable functionality.
  213. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
  214. *
  215. */
  216. goog.define('goog.STRICT_MODE_COMPATIBLE', false);
  217. /**
  218. * @define {boolean} Whether code that calls {@link goog.setTestOnly} should
  219. * be disallowed in the compilation unit.
  220. */
  221. goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);
  222. /**
  223. * @define {boolean} Whether to use a Chrome app CSP-compliant method for
  224. * loading scripts via goog.require. @see appendScriptSrcNode_.
  225. */
  226. goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);
  227. /**
  228. * Defines a namespace in Closure.
  229. *
  230. * A namespace may only be defined once in a codebase. It may be defined using
  231. * goog.provide() or goog.module().
  232. *
  233. * The presence of one or more goog.provide() calls in a file indicates
  234. * that the file defines the given objects/namespaces.
  235. * Provided symbols must not be null or undefined.
  236. *
  237. * In addition, goog.provide() creates the object stubs for a namespace
  238. * (for example, goog.provide("goog.foo.bar") will create the object
  239. * goog.foo.bar if it does not already exist).
  240. *
  241. * Build tools also scan for provide/require/module statements
  242. * to discern dependencies, build dependency files (see deps.js), etc.
  243. *
  244. * @see goog.require
  245. * @see goog.module
  246. * @param {string} name Namespace provided by this file in the form
  247. * "goog.package.part".
  248. */
  249. goog.provide = function(name) {
  250. if (!COMPILED) {
  251. // Ensure that the same namespace isn't provided twice.
  252. // A goog.module/goog.provide maps a goog.require to a specific file
  253. if (goog.isProvided_(name)) {
  254. throw Error('Namespace "' + name + '" already declared.');
  255. }
  256. }
  257. goog.constructNamespace_(name);
  258. };
  259. /**
  260. * @param {string} name Namespace provided by this file in the form
  261. * "goog.package.part".
  262. * @param {Object=} opt_obj The object to embed in the namespace.
  263. * @private
  264. */
  265. goog.constructNamespace_ = function(name, opt_obj) {
  266. if (!COMPILED) {
  267. delete goog.implicitNamespaces_[name];
  268. var namespace = name;
  269. while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
  270. if (goog.getObjectByName(namespace)) {
  271. break;
  272. }
  273. goog.implicitNamespaces_[namespace] = true;
  274. }
  275. }
  276. goog.exportPath_(name, opt_obj);
  277. };
  278. /**
  279. * Module identifier validation regexp.
  280. * Note: This is a conservative check, it is very possible to be more lenient,
  281. * the primary exclusion here is "/" and "\" and a leading ".", these
  282. * restrictions are intended to leave the door open for using goog.require
  283. * with relative file paths rather than module identifiers.
  284. * @private
  285. */
  286. goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
  287. /**
  288. * Defines a module in Closure.
  289. *
  290. * Marks that this file must be loaded as a module and claims the namespace.
  291. *
  292. * A namespace may only be defined once in a codebase. It may be defined using
  293. * goog.provide() or goog.module().
  294. *
  295. * goog.module() has three requirements:
  296. * - goog.module may not be used in the same file as goog.provide.
  297. * - goog.module must be the first statement in the file.
  298. * - only one goog.module is allowed per file.
  299. *
  300. * When a goog.module annotated file is loaded, it is enclosed in
  301. * a strict function closure. This means that:
  302. * - any variables declared in a goog.module file are private to the file
  303. * (not global), though the compiler is expected to inline the module.
  304. * - The code must obey all the rules of "strict" JavaScript.
  305. * - the file will be marked as "use strict"
  306. *
  307. * NOTE: unlike goog.provide, goog.module does not declare any symbols by
  308. * itself. If declared symbols are desired, use
  309. * goog.module.declareLegacyNamespace().
  310. *
  311. *
  312. * See the public goog.module proposal: http://goo.gl/Va1hin
  313. *
  314. * @param {string} name Namespace provided by this file in the form
  315. * "goog.package.part", is expected but not required.
  316. */
  317. goog.module = function(name) {
  318. if (!goog.isString(name) ||
  319. !name ||
  320. name.search(goog.VALID_MODULE_RE_) == -1) {
  321. throw Error('Invalid module identifier');
  322. }
  323. if (!goog.isInModuleLoader_()) {
  324. throw Error('Module ' + name + ' has been loaded incorrectly.');
  325. }
  326. if (goog.moduleLoaderState_.moduleName) {
  327. throw Error('goog.module may only be called once per module.');
  328. }
  329. // Store the module name for the loader.
  330. goog.moduleLoaderState_.moduleName = name;
  331. if (!COMPILED) {
  332. // Ensure that the same namespace isn't provided twice.
  333. // A goog.module/goog.provide maps a goog.require to a specific file
  334. if (goog.isProvided_(name)) {
  335. throw Error('Namespace "' + name + '" already declared.');
  336. }
  337. delete goog.implicitNamespaces_[name];
  338. }
  339. };
  340. /**
  341. * @param {string} name The module identifier.
  342. * @return {?} The module exports for an already loaded module or null.
  343. *
  344. * Note: This is not an alternative to goog.require, it does not
  345. * indicate a hard dependency, instead it is used to indicate
  346. * an optional dependency or to access the exports of a module
  347. * that has already been loaded.
  348. * @suppress {missingProvide}
  349. */
  350. goog.module.get = function(name) {
  351. return goog.module.getInternal_(name);
  352. };
  353. /**
  354. * @param {string} name The module identifier.
  355. * @return {?} The module exports for an already loaded module or null.
  356. * @private
  357. */
  358. goog.module.getInternal_ = function(name) {
  359. if (!COMPILED) {
  360. if (goog.isProvided_(name)) {
  361. // goog.require only return a value with-in goog.module files.
  362. return name in goog.loadedModules_ ?
  363. goog.loadedModules_[name] :
  364. goog.getObjectByName(name);
  365. } else {
  366. return null;
  367. }
  368. }
  369. };
  370. /**
  371. * @private {?{moduleName: (string|undefined)}}
  372. */
  373. goog.moduleLoaderState_ = null;
  374. /**
  375. * @private
  376. * @return {boolean} Whether a goog.module is currently being initialized.
  377. */
  378. goog.isInModuleLoader_ = function() {
  379. return goog.moduleLoaderState_ != null;
  380. };
  381. /**
  382. * Provide the module's exports as a globally accessible object under the
  383. * module's declared name. This is intended to ease migration to goog.module
  384. * for files that have existing usages.
  385. * @suppress {missingProvide}
  386. */
  387. goog.module.declareLegacyNamespace = function() {
  388. if (!COMPILED && !goog.isInModuleLoader_()) {
  389. throw new Error('goog.module.declareLegacyNamespace must be called from ' +
  390. 'within a goog.module');
  391. }
  392. if (!COMPILED && !goog.moduleLoaderState_.moduleName) {
  393. throw Error('goog.module must be called prior to ' +
  394. 'goog.module.declareLegacyNamespace.');
  395. }
  396. goog.moduleLoaderState_.declareLegacyNamespace = true;
  397. };
  398. /**
  399. * Marks that the current file should only be used for testing, and never for
  400. * live code in production.
  401. *
  402. * In the case of unit tests, the message may optionally be an exact namespace
  403. * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra
  404. * provide (if not explicitly defined in the code).
  405. *
  406. * @param {string=} opt_message Optional message to add to the error that's
  407. * raised when used in production code.
  408. */
  409. goog.setTestOnly = function(opt_message) {
  410. if (goog.DISALLOW_TEST_ONLY_CODE) {
  411. opt_message = opt_message || '';
  412. throw Error('Importing test-only code into non-debug environment' +
  413. (opt_message ? ': ' + opt_message : '.'));
  414. }
  415. };
  416. /**
  417. * Forward declares a symbol. This is an indication to the compiler that the
  418. * symbol may be used in the source yet is not required and may not be provided
  419. * in compilation.
  420. *
  421. * The most common usage of forward declaration is code that takes a type as a
  422. * function parameter but does not need to require it. By forward declaring
  423. * instead of requiring, no hard dependency is made, and (if not required
  424. * elsewhere) the namespace may never be required and thus, not be pulled
  425. * into the JavaScript binary. If it is required elsewhere, it will be type
  426. * checked as normal.
  427. *
  428. *
  429. * @param {string} name The namespace to forward declare in the form of
  430. * "goog.package.part".
  431. */
  432. goog.forwardDeclare = function(name) {};
  433. /**
  434. * Forward declare type information. Used to assign types to goog.global
  435. * referenced object that would otherwise result in unknown type references
  436. * and thus block property disambiguation.
  437. */
  438. goog.forwardDeclare('Document');
  439. goog.forwardDeclare('XMLHttpRequest');
  440. if (!COMPILED) {
  441. /**
  442. * Check if the given name has been goog.provided. This will return false for
  443. * names that are available only as implicit namespaces.
  444. * @param {string} name name of the object to look for.
  445. * @return {boolean} Whether the name has been provided.
  446. * @private
  447. */
  448. goog.isProvided_ = function(name) {
  449. return (name in goog.loadedModules_) ||
  450. (!goog.implicitNamespaces_[name] &&
  451. goog.isDefAndNotNull(goog.getObjectByName(name)));
  452. };
  453. /**
  454. * Namespaces implicitly defined by goog.provide. For example,
  455. * goog.provide('goog.events.Event') implicitly declares that 'goog' and
  456. * 'goog.events' must be namespaces.
  457. *
  458. * @type {!Object<string, (boolean|undefined)>}
  459. * @private
  460. */
  461. goog.implicitNamespaces_ = {'goog.module': true};
  462. // NOTE: We add goog.module as an implicit namespace as goog.module is defined
  463. // here and because the existing module package has not been moved yet out of
  464. // the goog.module namespace. This satisifies both the debug loader and
  465. // ahead-of-time dependency management.
  466. }
  467. /**
  468. * Returns an object based on its fully qualified external name. The object
  469. * is not found if null or undefined. If you are using a compilation pass that
  470. * renames property names beware that using this function will not find renamed
  471. * properties.
  472. *
  473. * @param {string} name The fully qualified name.
  474. * @param {Object=} opt_obj The object within which to look; default is
  475. * |goog.global|.
  476. * @return {?} The value (object or primitive) or, if not found, null.
  477. */
  478. goog.getObjectByName = function(name, opt_obj) {
  479. var parts = name.split('.');
  480. var cur = opt_obj || goog.global;
  481. for (var part; part = parts.shift(); ) {
  482. if (goog.isDefAndNotNull(cur[part])) {
  483. cur = cur[part];
  484. } else {
  485. return null;
  486. }
  487. }
  488. return cur;
  489. };
  490. /**
  491. * Globalizes a whole namespace, such as goog or goog.lang.
  492. *
  493. * @param {!Object} obj The namespace to globalize.
  494. * @param {Object=} opt_global The object to add the properties to.
  495. * @deprecated Properties may be explicitly exported to the global scope, but
  496. * this should no longer be done in bulk.
  497. */
  498. goog.globalize = function(obj, opt_global) {
  499. var global = opt_global || goog.global;
  500. for (var x in obj) {
  501. global[x] = obj[x];
  502. }
  503. };
  504. /**
  505. * Adds a dependency from a file to the files it requires.
  506. * @param {string} relPath The path to the js file.
  507. * @param {!Array<string>} provides An array of strings with
  508. * the names of the objects this file provides.
  509. * @param {!Array<string>} requires An array of strings with
  510. * the names of the objects this file requires.
  511. * @param {boolean=} opt_isModule Whether this dependency must be loaded as
  512. * a module as declared by goog.module.
  513. */
  514. goog.addDependency = function(relPath, provides, requires, opt_isModule) {
  515. if (goog.DEPENDENCIES_ENABLED) {
  516. var provide, require;
  517. var path = relPath.replace(/\\/g, '/');
  518. var deps = goog.dependencies_;
  519. for (var i = 0; provide = provides[i]; i++) {
  520. deps.nameToPath[provide] = path;
  521. deps.pathIsModule[path] = !!opt_isModule;
  522. }
  523. for (var j = 0; require = requires[j]; j++) {
  524. if (!(path in deps.requires)) {
  525. deps.requires[path] = {};
  526. }
  527. deps.requires[path][require] = true;
  528. }
  529. }
  530. };
  531. // NOTE(nnaze): The debug DOM loader was included in base.js as an original way
  532. // to do "debug-mode" development. The dependency system can sometimes be
  533. // confusing, as can the debug DOM loader's asynchronous nature.
  534. //
  535. // With the DOM loader, a call to goog.require() is not blocking -- the script
  536. // will not load until some point after the current script. If a namespace is
  537. // needed at runtime, it needs to be defined in a previous script, or loaded via
  538. // require() with its registered dependencies.
  539. // User-defined namespaces may need their own deps file. See http://go/js_deps,
  540. // http://go/genjsdeps, or, externally, DepsWriter.
  541. // https://developers.google.com/closure/library/docs/depswriter
  542. //
  543. // Because of legacy clients, the DOM loader can't be easily removed from
  544. // base.js. Work is being done to make it disableable or replaceable for
  545. // different environments (DOM-less JavaScript interpreters like Rhino or V8,
  546. // for example). See bootstrap/ for more information.
  547. /**
  548. * @define {boolean} Whether to enable the debug loader.
  549. *
  550. * If enabled, a call to goog.require() will attempt to load the namespace by
  551. * appending a script tag to the DOM (if the namespace has been registered).
  552. *
  553. * If disabled, goog.require() will simply assert that the namespace has been
  554. * provided (and depend on the fact that some outside tool correctly ordered
  555. * the script).
  556. */
  557. goog.define('goog.ENABLE_DEBUG_LOADER', true);
  558. /**
  559. * @param {string} msg
  560. * @private
  561. */
  562. goog.logToConsole_ = function(msg) {
  563. if (goog.global.console) {
  564. goog.global.console['error'](msg);
  565. }
  566. };
  567. /**
  568. * Implements a system for the dynamic resolution of dependencies that works in
  569. * parallel with the BUILD system. Note that all calls to goog.require will be
  570. * stripped by the JSCompiler when the --process_closure_primitives option is
  571. * used.
  572. * @see goog.provide
  573. * @param {string} name Namespace to include (as was given in goog.provide()) in
  574. * the form "goog.package.part".
  575. * @return {?} If called within a goog.module file, the associated namespace or
  576. * module otherwise null.
  577. */
  578. goog.require = function(name) {
  579. // If the object already exists we do not need do do anything.
  580. if (!COMPILED) {
  581. if (goog.ENABLE_DEBUG_LOADER && goog.IS_OLD_IE_) {
  582. goog.maybeProcessDeferredDep_(name);
  583. }
  584. if (goog.isProvided_(name)) {
  585. if (goog.isInModuleLoader_()) {
  586. return goog.module.getInternal_(name);
  587. } else {
  588. return null;
  589. }
  590. }
  591. if (goog.ENABLE_DEBUG_LOADER) {
  592. var path = goog.getPathFromDeps_(name);
  593. if (path) {
  594. goog.writeScripts_(path);
  595. return null;
  596. }
  597. }
  598. var errorMessage = 'goog.require could not find: ' + name;
  599. goog.logToConsole_(errorMessage);
  600. throw Error(errorMessage);
  601. }
  602. };
  603. /**
  604. * Path for included scripts.
  605. * @type {string}
  606. */
  607. goog.basePath = '';
  608. /**
  609. * A hook for overriding the base path.
  610. * @type {string|undefined}
  611. */
  612. goog.global.CLOSURE_BASE_PATH;
  613. /**
  614. * Whether to write out Closure's deps file. By default, the deps are written.
  615. * @type {boolean|undefined}
  616. */
  617. goog.global.CLOSURE_NO_DEPS;
  618. /**
  619. * A function to import a single script. This is meant to be overridden when
  620. * Closure is being run in non-HTML contexts, such as web workers. It's defined
  621. * in the global scope so that it can be set before base.js is loaded, which
  622. * allows deps.js to be imported properly.
  623. *
  624. * The function is passed the script source, which is a relative URI. It should
  625. * return true if the script was imported, false otherwise.
  626. * @type {(function(string): boolean)|undefined}
  627. */
  628. goog.global.CLOSURE_IMPORT_SCRIPT;
  629. /**
  630. * Null function used for default values of callbacks, etc.
  631. * @return {void} Nothing.
  632. */
  633. goog.nullFunction = function() {};
  634. /**
  635. * When defining a class Foo with an abstract method bar(), you can do:
  636. * Foo.prototype.bar = goog.abstractMethod
  637. *
  638. * Now if a subclass of Foo fails to override bar(), an error will be thrown
  639. * when bar() is invoked.
  640. *
  641. * Note: This does not take the name of the function to override as an argument
  642. * because that would make it more difficult to obfuscate our JavaScript code.
  643. *
  644. * @type {!Function}
  645. * @throws {Error} when invoked to indicate the method should be overridden.
  646. */
  647. goog.abstractMethod = function() {
  648. throw Error('unimplemented abstract method');
  649. };
  650. /**
  651. * Adds a {@code getInstance} static method that always returns the same
  652. * instance object.
  653. * @param {!Function} ctor The constructor for the class to add the static
  654. * method to.
  655. */
  656. goog.addSingletonGetter = function(ctor) {
  657. ctor.getInstance = function() {
  658. if (ctor.instance_) {
  659. return ctor.instance_;
  660. }
  661. if (goog.DEBUG) {
  662. // NOTE: JSCompiler can't optimize away Array#push.
  663. goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
  664. }
  665. return ctor.instance_ = new ctor;
  666. };
  667. };
  668. /**
  669. * All singleton classes that have been instantiated, for testing. Don't read
  670. * it directly, use the {@code goog.testing.singleton} module. The compiler
  671. * removes this variable if unused.
  672. * @type {!Array<!Function>}
  673. * @private
  674. */
  675. goog.instantiatedSingletons_ = [];
  676. /**
  677. * @define {boolean} Whether to load goog.modules using {@code eval} when using
  678. * the debug loader. This provides a better debugging experience as the
  679. * source is unmodified and can be edited using Chrome Workspaces or similar.
  680. * However in some environments the use of {@code eval} is banned
  681. * so we provide an alternative.
  682. */
  683. goog.define('goog.LOAD_MODULE_USING_EVAL', true);
  684. /**
  685. * @define {boolean} Whether the exports of goog.modules should be sealed when
  686. * possible.
  687. */
  688. goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);
  689. /**
  690. * The registry of initialized modules:
  691. * the module identifier to module exports map.
  692. * @private @const {!Object<string, ?>}
  693. */
  694. goog.loadedModules_ = {};
  695. /**
  696. * True if goog.dependencies_ is available.
  697. * @const {boolean}
  698. */
  699. goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;
  700. if (goog.DEPENDENCIES_ENABLED) {
  701. /**
  702. * This object is used to keep track of dependencies and other data that is
  703. * used for loading scripts.
  704. * @private
  705. * @type {{
  706. * pathIsModule: !Object<string, boolean>,
  707. * nameToPath: !Object<string, string>,
  708. * requires: !Object<string, !Object<string, boolean>>,
  709. * visited: !Object<string, boolean>,
  710. * written: !Object<string, boolean>,
  711. * deferred: !Object<string, string>
  712. * }}
  713. */
  714. goog.dependencies_ = {
  715. pathIsModule: {}, // 1 to 1
  716. nameToPath: {}, // 1 to 1
  717. requires: {}, // 1 to many
  718. // Used when resolving dependencies to prevent us from visiting file twice.
  719. visited: {},
  720. written: {}, // Used to keep track of script files we have written.
  721. deferred: {} // Used to track deferred module evaluations in old IEs
  722. };
  723. /**
  724. * Tries to detect whether is in the context of an HTML document.
  725. * @return {boolean} True if it looks like HTML document.
  726. * @private
  727. */
  728. goog.inHtmlDocument_ = function() {
  729. /** @type {Document} */
  730. var doc = goog.global.document;
  731. return typeof doc != 'undefined' &&
  732. 'write' in doc; // XULDocument misses write.
  733. };
  734. /**
  735. * Tries to detect the base path of base.js script that bootstraps Closure.
  736. * @private
  737. */
  738. goog.findBasePath_ = function() {
  739. if (goog.isDef(goog.global.CLOSURE_BASE_PATH)) {
  740. goog.basePath = goog.global.CLOSURE_BASE_PATH;
  741. return;
  742. } else if (!goog.inHtmlDocument_()) {
  743. return;
  744. }
  745. /** @type {Document} */
  746. var doc = goog.global.document;
  747. var scripts = doc.getElementsByTagName('SCRIPT');
  748. // Search backwards since the current script is in almost all cases the one
  749. // that has base.js.
  750. for (var i = scripts.length - 1; i >= 0; --i) {
  751. var script = /** @type {!HTMLScriptElement} */ (scripts[i]);
  752. var src = script.src;
  753. var qmark = src.lastIndexOf('?');
  754. var l = qmark == -1 ? src.length : qmark;
  755. if (src.substr(l - 7, 7) == 'base.js') {
  756. goog.basePath = src.substr(0, l - 7);
  757. return;
  758. }
  759. }
  760. };
  761. /**
  762. * Imports a script if, and only if, that script hasn't already been imported.
  763. * (Must be called at execution time)
  764. * @param {string} src Script source.
  765. * @param {string=} opt_sourceText The optionally source text to evaluate
  766. * @private
  767. */
  768. goog.importScript_ = function(src, opt_sourceText) {
  769. var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
  770. goog.writeScriptTag_;
  771. if (importScript(src, opt_sourceText)) {
  772. goog.dependencies_.written[src] = true;
  773. }
  774. };
  775. /** @const @private {boolean} */
  776. goog.IS_OLD_IE_ = !!(!goog.global.atob && goog.global.document &&
  777. goog.global.document.all);
  778. /**
  779. * Given a URL initiate retrieval and execution of the module.
  780. * @param {string} src Script source URL.
  781. * @private
  782. */
  783. goog.importModule_ = function(src) {
  784. // In an attempt to keep browsers from timing out loading scripts using
  785. // synchronous XHRs, put each load in its own script block.
  786. var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");';
  787. if (goog.importScript_('', bootstrap)) {
  788. goog.dependencies_.written[src] = true;
  789. }
  790. };
  791. /** @private {!Array<string>} */
  792. goog.queuedModules_ = [];
  793. /**
  794. * Return an appropriate module text. Suitable to insert into
  795. * a script tag (that is unescaped).
  796. * @param {string} srcUrl
  797. * @param {string} scriptText
  798. * @return {string}
  799. * @private
  800. */
  801. goog.wrapModule_ = function(srcUrl, scriptText) {
  802. if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {
  803. return '' +
  804. 'goog.loadModule(function(exports) {' +
  805. '"use strict";' +
  806. scriptText +
  807. '\n' + // terminate any trailing single line comment.
  808. ';return exports' +
  809. '});' +
  810. '\n//# sourceURL=' + srcUrl + '\n';
  811. } else {
  812. return '' +
  813. 'goog.loadModule(' +
  814. goog.global.JSON.stringify(
  815. scriptText + '\n//# sourceURL=' + srcUrl + '\n') +
  816. ');';
  817. }
  818. };
  819. // On IE9 and earlier, it is necessary to handle
  820. // deferred module loads. In later browsers, the
  821. // code to be evaluated is simply inserted as a script
  822. // block in the correct order. To eval deferred
  823. // code at the right time, we piggy back on goog.require to call
  824. // goog.maybeProcessDeferredDep_.
  825. //
  826. // The goog.requires are used both to bootstrap
  827. // the loading process (when no deps are available) and
  828. // declare that they should be available.
  829. //
  830. // Here we eval the sources, if all the deps are available
  831. // either already eval'd or goog.require'd. This will
  832. // be the case when all the dependencies have already
  833. // been loaded, and the dependent module is loaded.
  834. //
  835. // But this alone isn't sufficient because it is also
  836. // necessary to handle the case where there is no root
  837. // that is not deferred. For that there we register for an event
  838. // and trigger goog.loadQueuedModules_ handle any remaining deferred
  839. // evaluations.
  840. /**
  841. * Handle any remaining deferred goog.module evals.
  842. * @private
  843. */
  844. goog.loadQueuedModules_ = function() {
  845. var count = goog.queuedModules_.length;
  846. if (count > 0) {
  847. var queue = goog.queuedModules_;
  848. goog.queuedModules_ = [];
  849. for (var i = 0; i < count; i++) {
  850. var path = queue[i];
  851. goog.maybeProcessDeferredPath_(path);
  852. }
  853. }
  854. };
  855. /**
  856. * Eval the named module if its dependencies are
  857. * available.
  858. * @param {string} name The module to load.
  859. * @private
  860. */
  861. goog.maybeProcessDeferredDep_ = function(name) {
  862. if (goog.isDeferredModule_(name) &&
  863. goog.allDepsAreAvailable_(name)) {
  864. var path = goog.getPathFromDeps_(name);
  865. goog.maybeProcessDeferredPath_(goog.basePath + path);
  866. }
  867. };
  868. /**
  869. * @param {string} name The module to check.
  870. * @return {boolean} Whether the name represents a
  871. * module whose evaluation has been deferred.
  872. * @private
  873. */
  874. goog.isDeferredModule_ = function(name) {
  875. var path = goog.getPathFromDeps_(name);
  876. if (path && goog.dependencies_.pathIsModule[path]) {
  877. var abspath = goog.basePath + path;
  878. return (abspath) in goog.dependencies_.deferred;
  879. }
  880. return false;
  881. };
  882. /**
  883. * @param {string} name The module to check.
  884. * @return {boolean} Whether the name represents a
  885. * module whose declared dependencies have all been loaded
  886. * (eval'd or a deferred module load)
  887. * @private
  888. */
  889. goog.allDepsAreAvailable_ = function(name) {
  890. var path = goog.getPathFromDeps_(name);
  891. if (path && (path in goog.dependencies_.requires)) {
  892. for (var requireName in goog.dependencies_.requires[path]) {
  893. if (!goog.isProvided_(requireName) &&
  894. !goog.isDeferredModule_(requireName)) {
  895. return false;
  896. }
  897. }
  898. }
  899. return true;
  900. };
  901. /**
  902. * @param {string} abspath
  903. * @private
  904. */
  905. goog.maybeProcessDeferredPath_ = function(abspath) {
  906. if (abspath in goog.dependencies_.deferred) {
  907. var src = goog.dependencies_.deferred[abspath];
  908. delete goog.dependencies_.deferred[abspath];
  909. goog.globalEval(src);
  910. }
  911. };
  912. /**
  913. * @param {function(?):?|string} moduleDef The module definition.
  914. */
  915. goog.loadModule = function(moduleDef) {
  916. // NOTE: we allow function definitions to be either in the from
  917. // of a string to eval (which keeps the original source intact) or
  918. // in a eval forbidden environment (CSP) we allow a function definition
  919. // which in its body must call {@code goog.module}, and return the exports
  920. // of the module.
  921. var previousState = goog.moduleLoaderState_;
  922. try {
  923. goog.moduleLoaderState_ = {moduleName: undefined};
  924. var exports;
  925. if (goog.isFunction(moduleDef)) {
  926. exports = moduleDef.call(goog.global, {});
  927. } else if (goog.isString(moduleDef)) {
  928. exports = goog.loadModuleFromSource_.call(goog.global, moduleDef);
  929. } else {
  930. throw Error('Invalid module definition');
  931. }
  932. var moduleName = goog.moduleLoaderState_.moduleName;
  933. if (!goog.isString(moduleName) || !moduleName) {
  934. throw Error('Invalid module name \"' + moduleName + '\"');
  935. }
  936. // Don't seal legacy namespaces as they may be uses as a parent of
  937. // another namespace
  938. if (goog.moduleLoaderState_.declareLegacyNamespace) {
  939. goog.constructNamespace_(moduleName, exports);
  940. } else if (goog.SEAL_MODULE_EXPORTS && Object.seal) {
  941. Object.seal(exports);
  942. }
  943. goog.loadedModules_[moduleName] = exports;
  944. } finally {
  945. goog.moduleLoaderState_ = previousState;
  946. }
  947. };
  948. /**
  949. * @private @const {function(string):?}
  950. * @suppress {newCheckTypes}
  951. */
  952. goog.loadModuleFromSource_ = function() {
  953. // NOTE: we avoid declaring parameters or local variables here to avoid
  954. // masking globals or leaking values into the module definition.
  955. 'use strict';
  956. var exports = {};
  957. eval(arguments[0]);
  958. return exports;
  959. };
  960. /**
  961. * Writes a new script pointing to {@code src} directly into the DOM.
  962. *
  963. * NOTE: This method is not CSP-compliant. @see goog.appendScriptSrcNode_ for
  964. * the fallback mechanism.
  965. *
  966. * @param {string} src The script URL.
  967. * @private
  968. */
  969. goog.writeScriptSrcNode_ = function(src) {
  970. goog.global.document.write(
  971. '<script type="text/javascript" src="' + src + '"></' + 'script>');
  972. };
  973. /**
  974. * Appends a new script node to the DOM using a CSP-compliant mechanism. This
  975. * method exists as a fallback for document.write (which is not allowed in a
  976. * strict CSP context, e.g., Chrome apps).
  977. *
  978. * NOTE: This method is not analogous to using document.write to insert a
  979. * <script> tag; specifically, the user agent will execute a script added by
  980. * document.write immediately after the current script block finishes
  981. * executing, whereas the DOM-appended script node will not be executed until
  982. * the entire document is parsed and executed. That is to say, this script is
  983. * added to the end of the script execution queue.
  984. *
  985. * The page must not attempt to call goog.required entities until after the
  986. * document has loaded, e.g., in or after the window.onload callback.
  987. *
  988. * @param {string} src The script URL.
  989. * @private
  990. */
  991. goog.appendScriptSrcNode_ = function(src) {
  992. /** @type {Document} */
  993. var doc = goog.global.document;
  994. var scriptEl = doc.createElement('script');
  995. scriptEl.type = 'text/javascript';
  996. scriptEl.src = src;
  997. scriptEl.defer = false;
  998. scriptEl.async = false;
  999. doc.head.appendChild(scriptEl);
  1000. };
  1001. /**
  1002. * The default implementation of the import function. Writes a script tag to
  1003. * import the script.
  1004. *
  1005. * @param {string} src The script url.
  1006. * @param {string=} opt_sourceText The optionally source text to evaluate
  1007. * @return {boolean} True if the script was imported, false otherwise.
  1008. * @private
  1009. */
  1010. goog.writeScriptTag_ = function(src, opt_sourceText) {
  1011. if (goog.inHtmlDocument_()) {
  1012. /** @type {Document} */
  1013. var doc = goog.global.document;
  1014. // If the user tries to require a new symbol after document load,
  1015. // something has gone terribly wrong. Doing a document.write would
  1016. // wipe out the page. This does not apply to the CSP-compliant method
  1017. // of writing script tags.
  1018. if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&
  1019. doc.readyState == 'complete') {
  1020. // Certain test frameworks load base.js multiple times, which tries
  1021. // to write deps.js each time. If that happens, just fail silently.
  1022. // These frameworks wipe the page between each load of base.js, so this
  1023. // is OK.
  1024. var isDeps = /\bdeps.js$/.test(src);
  1025. if (isDeps) {
  1026. return false;
  1027. } else {
  1028. throw Error('Cannot write "' + src + '" after document load');
  1029. }
  1030. }
  1031. var isOldIE = goog.IS_OLD_IE_;
  1032. if (opt_sourceText === undefined) {
  1033. if (!isOldIE) {
  1034. if (goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {
  1035. goog.appendScriptSrcNode_(src);
  1036. } else {
  1037. goog.writeScriptSrcNode_(src);
  1038. }
  1039. } else {
  1040. var state = " onreadystatechange='goog.onScriptLoad_(this, " +
  1041. ++goog.lastNonModuleScriptIndex_ + ")' ";
  1042. doc.write(
  1043. '<script type="text/javascript" src="' +
  1044. src + '"' + state + '></' + 'script>');
  1045. }
  1046. } else {
  1047. doc.write(
  1048. '<script type="text/javascript">' +
  1049. opt_sourceText +
  1050. '</' + 'script>');
  1051. }
  1052. return true;
  1053. } else {
  1054. return false;
  1055. }
  1056. };
  1057. /** @private {number} */
  1058. goog.lastNonModuleScriptIndex_ = 0;
  1059. /**
  1060. * A readystatechange handler for legacy IE
  1061. * @param {!HTMLScriptElement} script
  1062. * @param {number} scriptIndex
  1063. * @return {boolean}
  1064. * @private
  1065. */
  1066. goog.onScriptLoad_ = function(script, scriptIndex) {
  1067. // for now load the modules when we reach the last script,
  1068. // later allow more inter-mingling.
  1069. if (script.readyState == 'complete' &&
  1070. goog.lastNonModuleScriptIndex_ == scriptIndex) {
  1071. goog.loadQueuedModules_();
  1072. }
  1073. return true;
  1074. };
  1075. /**
  1076. * Resolves dependencies based on the dependencies added using addDependency
  1077. * and calls importScript_ in the correct order.
  1078. * @param {string} pathToLoad The path from which to start discovering
  1079. * dependencies.
  1080. * @private
  1081. */
  1082. goog.writeScripts_ = function(pathToLoad) {
  1083. /** @type {!Array<string>} The scripts we need to write this time. */
  1084. var scripts = [];
  1085. var seenScript = {};
  1086. var deps = goog.dependencies_;
  1087. /** @param {string} path */
  1088. function visitNode(path) {
  1089. if (path in deps.written) {
  1090. return;
  1091. }
  1092. // We have already visited this one. We can get here if we have cyclic
  1093. // dependencies.
  1094. if (path in deps.visited) {
  1095. return;
  1096. }
  1097. deps.visited[path] = true;
  1098. if (path in deps.requires) {
  1099. for (var requireName in deps.requires[path]) {
  1100. // If the required name is defined, we assume that it was already
  1101. // bootstrapped by other means.
  1102. if (!goog.isProvided_(requireName)) {
  1103. if (requireName in deps.nameToPath) {
  1104. visitNode(deps.nameToPath[requireName]);
  1105. } else {
  1106. throw Error('Undefined nameToPath for ' + requireName);
  1107. }
  1108. }
  1109. }
  1110. }
  1111. if (!(path in seenScript)) {
  1112. seenScript[path] = true;
  1113. scripts.push(path);
  1114. }
  1115. }
  1116. visitNode(pathToLoad);
  1117. // record that we are going to load all these scripts.
  1118. for (var i = 0; i < scripts.length; i++) {
  1119. var path = scripts[i];
  1120. goog.dependencies_.written[path] = true;
  1121. }
  1122. // If a module is loaded synchronously then we need to
  1123. // clear the current inModuleLoader value, and restore it when we are
  1124. // done loading the current "requires".
  1125. var moduleState = goog.moduleLoaderState_;
  1126. goog.moduleLoaderState_ = null;
  1127. for (var i = 0; i < scripts.length; i++) {
  1128. var path = scripts[i];
  1129. if (path) {
  1130. if (!deps.pathIsModule[path]) {
  1131. goog.importScript_(goog.basePath + path);
  1132. } else {
  1133. goog.importModule_(goog.basePath + path);
  1134. }
  1135. } else {
  1136. goog.moduleLoaderState_ = moduleState;
  1137. throw Error('Undefined script input');
  1138. }
  1139. }
  1140. // restore the current "module loading state"
  1141. goog.moduleLoaderState_ = moduleState;
  1142. };
  1143. /**
  1144. * Looks at the dependency rules and tries to determine the script file that
  1145. * fulfills a particular rule.
  1146. * @param {string} rule In the form goog.namespace.Class or project.script.
  1147. * @return {?string} Url corresponding to the rule, or null.
  1148. * @private
  1149. */
  1150. goog.getPathFromDeps_ = function(rule) {
  1151. if (rule in goog.dependencies_.nameToPath) {
  1152. return goog.dependencies_.nameToPath[rule];
  1153. } else {
  1154. return null;
  1155. }
  1156. };
  1157. goog.findBasePath_();
  1158. // Allow projects to manage the deps files themselves.
  1159. if (!goog.global.CLOSURE_NO_DEPS) {
  1160. goog.importScript_(goog.basePath + 'deps.js');
  1161. }
  1162. }
  1163. /**
  1164. * Normalize a file path by removing redundant ".." and extraneous "." file
  1165. * path components.
  1166. * @param {string} path
  1167. * @return {string}
  1168. * @private
  1169. */
  1170. goog.normalizePath_ = function(path) {
  1171. var components = path.split('/');
  1172. var i = 0;
  1173. while (i < components.length) {
  1174. if (components[i] == '.') {
  1175. components.splice(i, 1);
  1176. } else if (i && components[i] == '..' &&
  1177. components[i - 1] && components[i - 1] != '..') {
  1178. components.splice(--i, 2);
  1179. } else {
  1180. i++;
  1181. }
  1182. }
  1183. return components.join('/');
  1184. };
  1185. /**
  1186. * Loads file by synchronous XHR. Should not be used in production environments.
  1187. * @param {string} src Source URL.
  1188. * @return {string} File contents.
  1189. * @private
  1190. */
  1191. goog.loadFileSync_ = function(src) {
  1192. if (goog.global.CLOSURE_LOAD_FILE_SYNC) {
  1193. return goog.global.CLOSURE_LOAD_FILE_SYNC(src);
  1194. } else {
  1195. /** @type {XMLHttpRequest} */
  1196. var xhr = new goog.global['XMLHttpRequest']();
  1197. xhr.open('get', src, false);
  1198. xhr.send();
  1199. return xhr.responseText;
  1200. }
  1201. };
  1202. /**
  1203. * Retrieve and execute a module.
  1204. * @param {string} src Script source URL.
  1205. * @private
  1206. */
  1207. goog.retrieveAndExecModule_ = function(src) {
  1208. if (!COMPILED) {
  1209. // The full but non-canonicalized URL for later use.
  1210. var originalPath = src;
  1211. // Canonicalize the path, removing any /./ or /../ since Chrome's debugging
  1212. // console doesn't auto-canonicalize XHR loads as it does <script> srcs.
  1213. src = goog.normalizePath_(src);
  1214. var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
  1215. goog.writeScriptTag_;
  1216. var scriptText = goog.loadFileSync_(src);
  1217. if (scriptText != null) {
  1218. var execModuleScript = goog.wrapModule_(src, scriptText);
  1219. var isOldIE = goog.IS_OLD_IE_;
  1220. if (isOldIE) {
  1221. goog.dependencies_.deferred[originalPath] = execModuleScript;
  1222. goog.queuedModules_.push(originalPath);
  1223. } else {
  1224. importScript(src, execModuleScript);
  1225. }
  1226. } else {
  1227. throw new Error('load of ' + src + 'failed');
  1228. }
  1229. }
  1230. };
  1231. //==============================================================================
  1232. // Language Enhancements
  1233. //==============================================================================
  1234. /**
  1235. * This is a "fixed" version of the typeof operator. It differs from the typeof
  1236. * operator in such a way that null returns 'null' and arrays return 'array'.
  1237. * @param {*} value The value to get the type of.
  1238. * @return {string} The name of the type.
  1239. */
  1240. goog.typeOf = function(value) {
  1241. var s = typeof value;
  1242. if (s == 'object') {
  1243. if (value) {
  1244. // Check these first, so we can avoid calling Object.prototype.toString if
  1245. // possible.
  1246. //
  1247. // IE improperly marshals tyepof across execution contexts, but a
  1248. // cross-context object will still return false for "instanceof Object".
  1249. if (value instanceof Array) {
  1250. return 'array';
  1251. } else if (value instanceof Object) {
  1252. return s;
  1253. }
  1254. // HACK: In order to use an Object prototype method on the arbitrary
  1255. // value, the compiler requires the value be cast to type Object,
  1256. // even though the ECMA spec explicitly allows it.
  1257. var className = Object.prototype.toString.call(
  1258. /** @type {Object} */ (value));
  1259. // In Firefox 3.6, attempting to access iframe window objects' length
  1260. // property throws an NS_ERROR_FAILURE, so we need to special-case it
  1261. // here.
  1262. if (className == '[object Window]') {
  1263. return 'object';
  1264. }
  1265. // We cannot always use constructor == Array or instanceof Array because
  1266. // different frames have different Array objects. In IE6, if the iframe
  1267. // where the array was created is destroyed, the array loses its
  1268. // prototype. Then dereferencing val.splice here throws an exception, so
  1269. // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
  1270. // so that will work. In this case, this function will return false and
  1271. // most array functions will still work because the array is still
  1272. // array-like (supports length and []) even though it has lost its
  1273. // prototype.
  1274. // Mark Miller noticed that Object.prototype.toString
  1275. // allows access to the unforgeable [[Class]] property.
  1276. // 15.2.4.2 Object.prototype.toString ( )
  1277. // When the toString method is called, the following steps are taken:
  1278. // 1. Get the [[Class]] property of this object.
  1279. // 2. Compute a string value by concatenating the three strings
  1280. // "[object ", Result(1), and "]".
  1281. // 3. Return Result(2).
  1282. // and this behavior survives the destruction of the execution context.
  1283. if ((className == '[object Array]' ||
  1284. // In IE all non value types are wrapped as objects across window
  1285. // boundaries (not iframe though) so we have to do object detection
  1286. // for this edge case.
  1287. typeof value.length == 'number' &&
  1288. typeof value.splice != 'undefined' &&
  1289. typeof value.propertyIsEnumerable != 'undefined' &&
  1290. !value.propertyIsEnumerable('splice')
  1291. )) {
  1292. return 'array';
  1293. }
  1294. // HACK: There is still an array case that fails.
  1295. // function ArrayImpostor() {}
  1296. // ArrayImpostor.prototype = [];
  1297. // var impostor = new ArrayImpostor;
  1298. // this can be fixed by getting rid of the fast path
  1299. // (value instanceof Array) and solely relying on
  1300. // (value && Object.prototype.toString.vall(value) === '[object Array]')
  1301. // but that would require many more function calls and is not warranted
  1302. // unless closure code is receiving objects from untrusted sources.
  1303. // IE in cross-window calls does not correctly marshal the function type
  1304. // (it appears just as an object) so we cannot use just typeof val ==
  1305. // 'function'. However, if the object has a call property, it is a
  1306. // function.
  1307. if ((className == '[object Function]' ||
  1308. typeof value.call != 'undefined' &&
  1309. typeof value.propertyIsEnumerable != 'undefined' &&
  1310. !value.propertyIsEnumerable('call'))) {
  1311. return 'function';
  1312. }
  1313. } else {
  1314. return 'null';
  1315. }
  1316. } else if (s == 'function' && typeof value.call == 'undefined') {
  1317. // In Safari typeof nodeList returns 'function', and on Firefox typeof
  1318. // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We
  1319. // would like to return object for those and we can detect an invalid
  1320. // function by making sure that the function object has a call method.
  1321. return 'object';
  1322. }
  1323. return s;
  1324. };
  1325. /**
  1326. * Returns true if the specified value is null.
  1327. * @param {?} val Variable to test.
  1328. * @return {boolean} Whether variable is null.
  1329. */
  1330. goog.isNull = function(val) {
  1331. return val === null;
  1332. };
  1333. /**
  1334. * Returns true if the specified value is defined and not null.
  1335. * @param {?} val Variable to test.
  1336. * @return {boolean} Whether variable is defined and not null.
  1337. */
  1338. goog.isDefAndNotNull = function(val) {
  1339. // Note that undefined == null.
  1340. return val != null;
  1341. };
  1342. /**
  1343. * Returns true if the specified value is an array.
  1344. * @param {?} val Variable to test.
  1345. * @return {boolean} Whether variable is an array.
  1346. */
  1347. goog.isArray = function(val) {
  1348. return goog.typeOf(val) == 'array';
  1349. };
  1350. /**
  1351. * Returns true if the object looks like an array. To qualify as array like
  1352. * the value needs to be either a NodeList or an object with a Number length
  1353. * property. As a special case, a function value is not array like, because its
  1354. * length property is fixed to correspond to the number of expected arguments.
  1355. * @param {?} val Variable to test.
  1356. * @return {boolean} Whether variable is an array.
  1357. */
  1358. goog.isArrayLike = function(val) {
  1359. var type = goog.typeOf(val);
  1360. // We do not use goog.isObject here in order to exclude function values.
  1361. return type == 'array' || type == 'object' && typeof val.length == 'number';
  1362. };
  1363. /**
  1364. * Returns true if the object looks like a Date. To qualify as Date-like the
  1365. * value needs to be an object and have a getFullYear() function.
  1366. * @param {?} val Variable to test.
  1367. * @return {boolean} Whether variable is a like a Date.
  1368. */
  1369. goog.isDateLike = function(val) {
  1370. return goog.isObject(val) && typeof val.getFullYear == 'function';
  1371. };
  1372. /**
  1373. * Returns true if the specified value is a string.
  1374. * @param {?} val Variable to test.
  1375. * @return {boolean} Whether variable is a string.
  1376. */
  1377. goog.isString = function(val) {
  1378. return typeof val == 'string';
  1379. };
  1380. /**
  1381. * Returns true if the specified value is a boolean.
  1382. * @param {?} val Variable to test.
  1383. * @return {boolean} Whether variable is boolean.
  1384. */
  1385. goog.isBoolean = function(val) {
  1386. return typeof val == 'boolean';
  1387. };
  1388. /**
  1389. * Returns true if the specified value is a number.
  1390. * @param {?} val Variable to test.
  1391. * @return {boolean} Whether variable is a number.
  1392. */
  1393. goog.isNumber = function(val) {
  1394. return typeof val == 'number';
  1395. };
  1396. /**
  1397. * Returns true if the specified value is a function.
  1398. * @param {?} val Variable to test.
  1399. * @return {boolean} Whether variable is a function.
  1400. */
  1401. goog.isFunction = function(val) {
  1402. return goog.typeOf(val) == 'function';
  1403. };
  1404. /**
  1405. * Returns true if the specified value is an object. This includes arrays and
  1406. * functions.
  1407. * @param {?} val Variable to test.
  1408. * @return {boolean} Whether variable is an object.
  1409. */
  1410. goog.isObject = function(val) {
  1411. var type = typeof val;
  1412. return type == 'object' && val != null || type == 'function';
  1413. // return Object(val) === val also works, but is slower, especially if val is
  1414. // not an object.
  1415. };
  1416. /**
  1417. * Gets a unique ID for an object. This mutates the object so that further calls
  1418. * with the same object as a parameter returns the same value. The unique ID is
  1419. * guaranteed to be unique across the current session amongst objects that are
  1420. * passed into {@code getUid}. There is no guarantee that the ID is unique or
  1421. * consistent across sessions. It is unsafe to generate unique ID for function
  1422. * prototypes.
  1423. *
  1424. * @param {Object} obj The object to get the unique ID for.
  1425. * @return {number} The unique ID for the object.
  1426. */
  1427. goog.getUid = function(obj) {
  1428. // TODO(arv): Make the type stricter, do not accept null.
  1429. // In Opera window.hasOwnProperty exists but always returns false so we avoid
  1430. // using it. As a consequence the unique ID generated for BaseClass.prototype
  1431. // and SubClass.prototype will be the same.
  1432. return obj[goog.UID_PROPERTY_] ||
  1433. (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
  1434. };
  1435. /**
  1436. * Whether the given object is already assigned a unique ID.
  1437. *
  1438. * This does not modify the object.
  1439. *
  1440. * @param {!Object} obj The object to check.
  1441. * @return {boolean} Whether there is an assigned unique id for the object.
  1442. */
  1443. goog.hasUid = function(obj) {
  1444. return !!obj[goog.UID_PROPERTY_];
  1445. };
  1446. /**
  1447. * Removes the unique ID from an object. This is useful if the object was
  1448. * previously mutated using {@code goog.getUid} in which case the mutation is
  1449. * undone.
  1450. * @param {Object} obj The object to remove the unique ID field from.
  1451. */
  1452. goog.removeUid = function(obj) {
  1453. // TODO(arv): Make the type stricter, do not accept null.
  1454. // In IE, DOM nodes are not instances of Object and throw an exception if we
  1455. // try to delete. Instead we try to use removeAttribute.
  1456. if ('removeAttribute' in obj) {
  1457. obj.removeAttribute(goog.UID_PROPERTY_);
  1458. }
  1459. /** @preserveTry */
  1460. try {
  1461. delete obj[goog.UID_PROPERTY_];
  1462. } catch (ex) {
  1463. }
  1464. };
  1465. /**
  1466. * Name for unique ID property. Initialized in a way to help avoid collisions
  1467. * with other closure JavaScript on the same page.
  1468. * @type {string}
  1469. * @private
  1470. */
  1471. goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);
  1472. /**
  1473. * Counter for UID.
  1474. * @type {number}
  1475. * @private
  1476. */
  1477. goog.uidCounter_ = 0;
  1478. /**
  1479. * Adds a hash code field to an object. The hash code is unique for the
  1480. * given object.
  1481. * @param {Object} obj The object to get the hash code for.
  1482. * @return {number} The hash code for the object.
  1483. * @deprecated Use goog.getUid instead.
  1484. */
  1485. goog.getHashCode = goog.getUid;
  1486. /**
  1487. * Removes the hash code field from an object.
  1488. * @param {Object} obj The object to remove the field from.
  1489. * @deprecated Use goog.removeUid instead.
  1490. */
  1491. goog.removeHashCode = goog.removeUid;
  1492. /**
  1493. * Clones a value. The input may be an Object, Array, or basic type. Objects and
  1494. * arrays will be cloned recursively.
  1495. *
  1496. * WARNINGS:
  1497. * <code>goog.cloneObject</code> does not detect reference loops. Objects that
  1498. * refer to themselves will cause infinite recursion.
  1499. *
  1500. * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
  1501. * UIDs created by <code>getUid</code> into cloned results.
  1502. *
  1503. * @param {*} obj The value to clone.
  1504. * @return {*} A clone of the input value.
  1505. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
  1506. */
  1507. goog.cloneObject = function(obj) {
  1508. var type = goog.typeOf(obj);
  1509. if (type == 'object' || type == 'array') {
  1510. if (obj.clone) {
  1511. return obj.clone();
  1512. }
  1513. var clone = type == 'array' ? [] : {};
  1514. for (var key in obj) {
  1515. clone[key] = goog.cloneObject(obj[key]);
  1516. }
  1517. return clone;
  1518. }
  1519. return obj;
  1520. };
  1521. /**
  1522. * A native implementation of goog.bind.
  1523. * @param {Function} fn A function to partially apply.
  1524. * @param {Object|undefined} selfObj Specifies the object which this should
  1525. * point to when the function is run.
  1526. * @param {...*} var_args Additional arguments that are partially applied to the
  1527. * function.
  1528. * @return {!Function} A partially-applied form of the function bind() was
  1529. * invoked as a method of.
  1530. * @private
  1531. * @suppress {deprecated} The compiler thinks that Function.prototype.bind is
  1532. * deprecated because some people have declared a pure-JS version.
  1533. * Only the pure-JS version is truly deprecated.
  1534. */
  1535. goog.bindNative_ = function(fn, selfObj, var_args) {
  1536. return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
  1537. };
  1538. /**
  1539. * A pure-JS implementation of goog.bind.
  1540. * @param {Function} fn A function to partially apply.
  1541. * @param {Object|undefined} selfObj Specifies the object which this should
  1542. * point to when the function is run.
  1543. * @param {...*} var_args Additional arguments that are partially applied to the
  1544. * function.
  1545. * @return {!Function} A partially-applied form of the function bind() was
  1546. * invoked as a method of.
  1547. * @private
  1548. */
  1549. goog.bindJs_ = function(fn, selfObj, var_args) {
  1550. if (!fn) {
  1551. throw new Error();
  1552. }
  1553. if (arguments.length > 2) {
  1554. var boundArgs = Array.prototype.slice.call(arguments, 2);
  1555. return function() {
  1556. // Prepend the bound arguments to the current arguments.
  1557. var newArgs = Array.prototype.slice.call(arguments);
  1558. Array.prototype.unshift.apply(newArgs, boundArgs);
  1559. return fn.apply(selfObj, newArgs);
  1560. };
  1561. } else {
  1562. return function() {
  1563. return fn.apply(selfObj, arguments);
  1564. };
  1565. }
  1566. };
  1567. /**
  1568. * Partially applies this function to a particular 'this object' and zero or
  1569. * more arguments. The result is a new function with some arguments of the first
  1570. * function pre-filled and the value of this 'pre-specified'.
  1571. *
  1572. * Remaining arguments specified at call-time are appended to the pre-specified
  1573. * ones.
  1574. *
  1575. * Also see: {@link #partial}.
  1576. *
  1577. * Usage:
  1578. * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');
  1579. * barMethBound('arg3', 'arg4');</pre>
  1580. *
  1581. * @param {?function(this:T, ...)} fn A function to partially apply.
  1582. * @param {T} selfObj Specifies the object which this should point to when the
  1583. * function is run.
  1584. * @param {...*} var_args Additional arguments that are partially applied to the
  1585. * function.
  1586. * @return {!Function} A partially-applied form of the function goog.bind() was
  1587. * invoked as a method of.
  1588. * @template T
  1589. * @suppress {deprecated} See above.
  1590. */
  1591. goog.bind = function(fn, selfObj, var_args) {
  1592. // TODO(nicksantos): narrow the type signature.
  1593. if (Function.prototype.bind &&
  1594. // NOTE(nicksantos): Somebody pulled base.js into the default Chrome
  1595. // extension environment. This means that for Chrome extensions, they get
  1596. // the implementation of Function.prototype.bind that calls goog.bind
  1597. // instead of the native one. Even worse, we don't want to introduce a
  1598. // circular dependency between goog.bind and Function.prototype.bind, so
  1599. // we have to hack this to make sure it works correctly.
  1600. Function.prototype.bind.toString().indexOf('native code') != -1) {
  1601. goog.bind = goog.bindNative_;
  1602. } else {
  1603. goog.bind = goog.bindJs_;
  1604. }
  1605. return goog.bind.apply(null, arguments);
  1606. };
  1607. /**
  1608. * Like goog.bind(), except that a 'this object' is not required. Useful when
  1609. * the target function is already bound.
  1610. *
  1611. * Usage:
  1612. * var g = goog.partial(f, arg1, arg2);
  1613. * g(arg3, arg4);
  1614. *
  1615. * @param {Function} fn A function to partially apply.
  1616. * @param {...*} var_args Additional arguments that are partially applied to fn.
  1617. * @return {!Function} A partially-applied form of the function goog.partial()
  1618. * was invoked as a method of.
  1619. */
  1620. goog.partial = function(fn, var_args) {
  1621. var args = Array.prototype.slice.call(arguments, 1);
  1622. return function() {
  1623. // Clone the array (with slice()) and append additional arguments
  1624. // to the existing arguments.
  1625. var newArgs = args.slice();
  1626. newArgs.push.apply(newArgs, arguments);
  1627. return fn.apply(this, newArgs);
  1628. };
  1629. };
  1630. /**
  1631. * Copies all the members of a source object to a target object. This method
  1632. * does not work on all browsers for all objects that contain keys such as
  1633. * toString or hasOwnProperty. Use goog.object.extend for this purpose.
  1634. * @param {Object} target Target.
  1635. * @param {Object} source Source.
  1636. */
  1637. goog.mixin = function(target, source) {
  1638. for (var x in source) {
  1639. target[x] = source[x];
  1640. }
  1641. // For IE7 or lower, the for-in-loop does not contain any properties that are
  1642. // not enumerable on the prototype object (for example, isPrototypeOf from
  1643. // Object.prototype) but also it will not include 'replace' on objects that
  1644. // extend String and change 'replace' (not that it is common for anyone to
  1645. // extend anything except Object).
  1646. };
  1647. /**
  1648. * @return {number} An integer value representing the number of milliseconds
  1649. * between midnight, January 1, 1970 and the current time.
  1650. */
  1651. goog.now = (goog.TRUSTED_SITE && Date.now) || (function() {
  1652. // Unary plus operator converts its operand to a number which in the case of
  1653. // a date is done by calling getTime().
  1654. return +new Date();
  1655. });
  1656. /**
  1657. * Evals JavaScript in the global scope. In IE this uses execScript, other
  1658. * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
  1659. * global scope (for example, in Safari), appends a script tag instead.
  1660. * Throws an exception if neither execScript or eval is defined.
  1661. * @param {string} script JavaScript string.
  1662. */
  1663. goog.globalEval = function(script) {
  1664. if (goog.global.execScript) {
  1665. goog.global.execScript(script, 'JavaScript');
  1666. } else if (goog.global.eval) {
  1667. // Test to see if eval works
  1668. if (goog.evalWorksForGlobals_ == null) {
  1669. goog.global.eval('var _evalTest_ = 1;');
  1670. if (typeof goog.global['_evalTest_'] != 'undefined') {
  1671. try {
  1672. delete goog.global['_evalTest_'];
  1673. } catch (ignore) {
  1674. // Microsoft edge fails the deletion above in strict mode.
  1675. }
  1676. goog.evalWorksForGlobals_ = true;
  1677. } else {
  1678. goog.evalWorksForGlobals_ = false;
  1679. }
  1680. }
  1681. if (goog.evalWorksForGlobals_) {
  1682. goog.global.eval(script);
  1683. } else {
  1684. /** @type {Document} */
  1685. var doc = goog.global.document;
  1686. var scriptElt = doc.createElement('SCRIPT');
  1687. scriptElt.type = 'text/javascript';
  1688. scriptElt.defer = false;
  1689. // Note(user): can't use .innerHTML since "t('<test>')" will fail and
  1690. // .text doesn't work in Safari 2. Therefore we append a text node.
  1691. scriptElt.appendChild(doc.createTextNode(script));
  1692. doc.body.appendChild(scriptElt);
  1693. doc.body.removeChild(scriptElt);
  1694. }
  1695. } else {
  1696. throw Error('goog.globalEval not available');
  1697. }
  1698. };
  1699. /**
  1700. * Indicates whether or not we can call 'eval' directly to eval code in the
  1701. * global scope. Set to a Boolean by the first call to goog.globalEval (which
  1702. * empirically tests whether eval works for globals). @see goog.globalEval
  1703. * @type {?boolean}
  1704. * @private
  1705. */
  1706. goog.evalWorksForGlobals_ = null;
  1707. /**
  1708. * Optional map of CSS class names to obfuscated names used with
  1709. * goog.getCssName().
  1710. * @private {!Object<string, string>|undefined}
  1711. * @see goog.setCssNameMapping
  1712. */
  1713. goog.cssNameMapping_;
  1714. /**
  1715. * Optional obfuscation style for CSS class names. Should be set to either
  1716. * 'BY_WHOLE' or 'BY_PART' if defined.
  1717. * @type {string|undefined}
  1718. * @private
  1719. * @see goog.setCssNameMapping
  1720. */
  1721. goog.cssNameMappingStyle_;
  1722. /**
  1723. * Handles strings that are intended to be used as CSS class names.
  1724. *
  1725. * This function works in tandem with @see goog.setCssNameMapping.
  1726. *
  1727. * Without any mapping set, the arguments are simple joined with a hyphen and
  1728. * passed through unaltered.
  1729. *
  1730. * When there is a mapping, there are two possible styles in which these
  1731. * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)
  1732. * of the passed in css name is rewritten according to the map. In the BY_WHOLE
  1733. * style, the full css name is looked up in the map directly. If a rewrite is
  1734. * not specified by the map, the compiler will output a warning.
  1735. *
  1736. * When the mapping is passed to the compiler, it will replace calls to
  1737. * goog.getCssName with the strings from the mapping, e.g.
  1738. * var x = goog.getCssName('foo');
  1739. * var y = goog.getCssName(this.baseClass, 'active');
  1740. * becomes:
  1741. * var x= 'foo';
  1742. * var y = this.baseClass + '-active';
  1743. *
  1744. * If one argument is passed it will be processed, if two are passed only the
  1745. * modifier will be processed, as it is assumed the first argument was generated
  1746. * as a result of calling goog.getCssName.
  1747. *
  1748. * @param {string} className The class name.
  1749. * @param {string=} opt_modifier A modifier to be appended to the class name.
  1750. * @return {string} The class name or the concatenation of the class name and
  1751. * the modifier.
  1752. */
  1753. goog.getCssName = function(className, opt_modifier) {
  1754. var getMapping = function(cssName) {
  1755. return goog.cssNameMapping_[cssName] || cssName;
  1756. };
  1757. var renameByParts = function(cssName) {
  1758. // Remap all the parts individually.
  1759. var parts = cssName.split('-');
  1760. var mapped = [];
  1761. for (var i = 0; i < parts.length; i++) {
  1762. mapped.push(getMapping(parts[i]));
  1763. }
  1764. return mapped.join('-');
  1765. };
  1766. var rename;
  1767. if (goog.cssNameMapping_) {
  1768. rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?
  1769. getMapping : renameByParts;
  1770. } else {
  1771. rename = function(a) {
  1772. return a;
  1773. };
  1774. }
  1775. if (opt_modifier) {
  1776. return className + '-' + rename(opt_modifier);
  1777. } else {
  1778. return rename(className);
  1779. }
  1780. };
  1781. /**
  1782. * Sets the map to check when returning a value from goog.getCssName(). Example:
  1783. * <pre>
  1784. * goog.setCssNameMapping({
  1785. * "goog": "a",
  1786. * "disabled": "b",
  1787. * });
  1788. *
  1789. * var x = goog.getCssName('goog');
  1790. * // The following evaluates to: "a a-b".
  1791. * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
  1792. * </pre>
  1793. * When declared as a map of string literals to string literals, the JSCompiler
  1794. * will replace all calls to goog.getCssName() using the supplied map if the
  1795. * --process_closure_primitives flag is set.
  1796. *
  1797. * @param {!Object} mapping A map of strings to strings where keys are possible
  1798. * arguments to goog.getCssName() and values are the corresponding values
  1799. * that should be returned.
  1800. * @param {string=} opt_style The style of css name mapping. There are two valid
  1801. * options: 'BY_PART', and 'BY_WHOLE'.
  1802. * @see goog.getCssName for a description.
  1803. */
  1804. goog.setCssNameMapping = function(mapping, opt_style) {
  1805. goog.cssNameMapping_ = mapping;
  1806. goog.cssNameMappingStyle_ = opt_style;
  1807. };
  1808. /**
  1809. * To use CSS renaming in compiled mode, one of the input files should have a
  1810. * call to goog.setCssNameMapping() with an object literal that the JSCompiler
  1811. * can extract and use to replace all calls to goog.getCssName(). In uncompiled
  1812. * mode, JavaScript code should be loaded before this base.js file that declares
  1813. * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
  1814. * to ensure that the mapping is loaded before any calls to goog.getCssName()
  1815. * are made in uncompiled mode.
  1816. *
  1817. * A hook for overriding the CSS name mapping.
  1818. * @type {!Object<string, string>|undefined}
  1819. */
  1820. goog.global.CLOSURE_CSS_NAME_MAPPING;
  1821. if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
  1822. // This does not call goog.setCssNameMapping() because the JSCompiler
  1823. // requires that goog.setCssNameMapping() be called with an object literal.
  1824. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
  1825. }
  1826. /**
  1827. * Gets a localized message.
  1828. *
  1829. * This function is a compiler primitive. If you give the compiler a localized
  1830. * message bundle, it will replace the string at compile-time with a localized
  1831. * version, and expand goog.getMsg call to a concatenated string.
  1832. *
  1833. * Messages must be initialized in the form:
  1834. * <code>
  1835. * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});
  1836. * </code>
  1837. *
  1838. * @param {string} str Translatable string, places holders in the form {$foo}.
  1839. * @param {Object<string, string>=} opt_values Maps place holder name to value.
  1840. * @return {string} message with placeholders filled.
  1841. */
  1842. goog.getMsg = function(str, opt_values) {
  1843. if (opt_values) {
  1844. str = str.replace(/\{\$([^}]+)}/g, function(match, key) {
  1845. return key in opt_values ? opt_values[key] : match;
  1846. });
  1847. }
  1848. return str;
  1849. };
  1850. /**
  1851. * Gets a localized message. If the message does not have a translation, gives a
  1852. * fallback message.
  1853. *
  1854. * This is useful when introducing a new message that has not yet been
  1855. * translated into all languages.
  1856. *
  1857. * This function is a compiler primitive. Must be used in the form:
  1858. * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>
  1859. * where MSG_A and MSG_B were initialized with goog.getMsg.
  1860. *
  1861. * @param {string} a The preferred message.
  1862. * @param {string} b The fallback message.
  1863. * @return {string} The best translated message.
  1864. */
  1865. goog.getMsgWithFallback = function(a, b) {
  1866. return a;
  1867. };
  1868. /**
  1869. * Exposes an unobfuscated global namespace path for the given object.
  1870. * Note that fields of the exported object *will* be obfuscated, unless they are
  1871. * exported in turn via this function or goog.exportProperty.
  1872. *
  1873. * Also handy for making public items that are defined in anonymous closures.
  1874. *
  1875. * ex. goog.exportSymbol('public.path.Foo', Foo);
  1876. *
  1877. * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);
  1878. * public.path.Foo.staticFunction();
  1879. *
  1880. * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
  1881. * Foo.prototype.myMethod);
  1882. * new public.path.Foo().myMethod();
  1883. *
  1884. * @param {string} publicPath Unobfuscated name to export.
  1885. * @param {*} object Object the name should point to.
  1886. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  1887. * is goog.global.
  1888. */
  1889. goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
  1890. goog.exportPath_(publicPath, object, opt_objectToExportTo);
  1891. };
  1892. /**
  1893. * Exports a property unobfuscated into the object's namespace.
  1894. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
  1895. * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
  1896. * @param {Object} object Object whose static property is being exported.
  1897. * @param {string} publicName Unobfuscated name to export.
  1898. * @param {*} symbol Object the name should point to.
  1899. */
  1900. goog.exportProperty = function(object, publicName, symbol) {
  1901. object[publicName] = symbol;
  1902. };
  1903. /**
  1904. * Inherit the prototype methods from one constructor into another.
  1905. *
  1906. * Usage:
  1907. * <pre>
  1908. * function ParentClass(a, b) { }
  1909. * ParentClass.prototype.foo = function(a) { };
  1910. *
  1911. * function ChildClass(a, b, c) {
  1912. * ChildClass.base(this, 'constructor', a, b);
  1913. * }
  1914. * goog.inherits(ChildClass, ParentClass);
  1915. *
  1916. * var child = new ChildClass('a', 'b', 'see');
  1917. * child.foo(); // This works.
  1918. * </pre>
  1919. *
  1920. * @param {!Function} childCtor Child class.
  1921. * @param {!Function} parentCtor Parent class.
  1922. */
  1923. goog.inherits = function(childCtor, parentCtor) {
  1924. /** @constructor */
  1925. function tempCtor() {};
  1926. tempCtor.prototype = parentCtor.prototype;
  1927. childCtor.superClass_ = parentCtor.prototype;
  1928. childCtor.prototype = new tempCtor();
  1929. /** @override */
  1930. childCtor.prototype.constructor = childCtor;
  1931. /**
  1932. * Calls superclass constructor/method.
  1933. *
  1934. * This function is only available if you use goog.inherits to
  1935. * express inheritance relationships between classes.
  1936. *
  1937. * NOTE: This is a replacement for goog.base and for superClass_
  1938. * property defined in childCtor.
  1939. *
  1940. * @param {!Object} me Should always be "this".
  1941. * @param {string} methodName The method name to call. Calling
  1942. * superclass constructor can be done with the special string
  1943. * 'constructor'.
  1944. * @param {...*} var_args The arguments to pass to superclass
  1945. * method/constructor.
  1946. * @return {*} The return value of the superclass method/constructor.
  1947. */
  1948. childCtor.base = function(me, methodName, var_args) {
  1949. // Copying using loop to avoid deop due to passing arguments object to
  1950. // function. This is faster in many JS engines as of late 2014.
  1951. var args = new Array(arguments.length - 2);
  1952. for (var i = 2; i < arguments.length; i++) {
  1953. args[i - 2] = arguments[i];
  1954. }
  1955. return parentCtor.prototype[methodName].apply(me, args);
  1956. };
  1957. };
  1958. /**
  1959. * Call up to the superclass.
  1960. *
  1961. * If this is called from a constructor, then this calls the superclass
  1962. * constructor with arguments 1-N.
  1963. *
  1964. * If this is called from a prototype method, then you must pass the name of the
  1965. * method as the second argument to this function. If you do not, you will get a
  1966. * runtime error. This calls the superclass' method with arguments 2-N.
  1967. *
  1968. * This function only works if you use goog.inherits to express inheritance
  1969. * relationships between your classes.
  1970. *
  1971. * This function is a compiler primitive. At compile-time, the compiler will do
  1972. * macro expansion to remove a lot of the extra overhead that this function
  1973. * introduces. The compiler will also enforce a lot of the assumptions that this
  1974. * function makes, and treat it as a compiler error if you break them.
  1975. *
  1976. * @param {!Object} me Should always be "this".
  1977. * @param {*=} opt_methodName The method name if calling a super method.
  1978. * @param {...*} var_args The rest of the arguments.
  1979. * @return {*} The return value of the superclass method.
  1980. * @suppress {es5Strict} This method can not be used in strict mode, but
  1981. * all Closure Library consumers must depend on this file.
  1982. */
  1983. goog.base = function(me, opt_methodName, var_args) {
  1984. var caller = arguments.callee.caller;
  1985. if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {
  1986. throw Error('arguments.caller not defined. goog.base() cannot be used ' +
  1987. 'with strict mode code. See ' +
  1988. 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');
  1989. }
  1990. if (caller.superClass_) {
  1991. // Copying using loop to avoid deop due to passing arguments object to
  1992. // function. This is faster in many JS engines as of late 2014.
  1993. var ctorArgs = new Array(arguments.length - 1);
  1994. for (var i = 1; i < arguments.length; i++) {
  1995. ctorArgs[i - 1] = arguments[i];
  1996. }
  1997. // This is a constructor. Call the superclass constructor.
  1998. return caller.superClass_.constructor.apply(me, ctorArgs);
  1999. }
  2000. // Copying using loop to avoid deop due to passing arguments object to
  2001. // function. This is faster in many JS engines as of late 2014.
  2002. var args = new Array(arguments.length - 2);
  2003. for (var i = 2; i < arguments.length; i++) {
  2004. args[i - 2] = arguments[i];
  2005. }
  2006. var foundCaller = false;
  2007. for (var ctor = me.constructor;
  2008. ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  2009. if (ctor.prototype[opt_methodName] === caller) {
  2010. foundCaller = true;
  2011. } else if (foundCaller) {
  2012. return ctor.prototype[opt_methodName].apply(me, args);
  2013. }
  2014. }
  2015. // If we did not find the caller in the prototype chain, then one of two
  2016. // things happened:
  2017. // 1) The caller is an instance method.
  2018. // 2) This method was not called by the right caller.
  2019. if (me[opt_methodName] === caller) {
  2020. return me.constructor.prototype[opt_methodName].apply(me, args);
  2021. } else {
  2022. throw Error(
  2023. 'goog.base called from a method of one name ' +
  2024. 'to a method of a different name');
  2025. }
  2026. };
  2027. /**
  2028. * Allow for aliasing within scope functions. This function exists for
  2029. * uncompiled code - in compiled code the calls will be inlined and the aliases
  2030. * applied. In uncompiled code the function is simply run since the aliases as
  2031. * written are valid JavaScript.
  2032. *
  2033. *
  2034. * @param {function()} fn Function to call. This function can contain aliases
  2035. * to namespaces (e.g. "var dom = goog.dom") or classes
  2036. * (e.g. "var Timer = goog.Timer").
  2037. */
  2038. goog.scope = function(fn) {
  2039. fn.call(goog.global);
  2040. };
  2041. /*
  2042. * To support uncompiled, strict mode bundles that use eval to divide source
  2043. * like so:
  2044. * eval('someSource;//# sourceUrl sourcefile.js');
  2045. * We need to export the globally defined symbols "goog" and "COMPILED".
  2046. * Exporting "goog" breaks the compiler optimizations, so we required that
  2047. * be defined externally.
  2048. * NOTE: We don't use goog.exportSymbol here because we don't want to trigger
  2049. * extern generation when that compiler option is enabled.
  2050. */
  2051. if (!COMPILED) {
  2052. goog.global['COMPILED'] = COMPILED;
  2053. }
  2054. //==============================================================================
  2055. // goog.defineClass implementation
  2056. //==============================================================================
  2057. /**
  2058. * Creates a restricted form of a Closure "class":
  2059. * - from the compiler's perspective, the instance returned from the
  2060. * constructor is sealed (no new properties may be added). This enables
  2061. * better checks.
  2062. * - the compiler will rewrite this definition to a form that is optimal
  2063. * for type checking and optimization (initially this will be a more
  2064. * traditional form).
  2065. *
  2066. * @param {Function} superClass The superclass, Object or null.
  2067. * @param {goog.defineClass.ClassDescriptor} def
  2068. * An object literal describing
  2069. * the class. It may have the following properties:
  2070. * "constructor": the constructor function
  2071. * "statics": an object literal containing methods to add to the constructor
  2072. * as "static" methods or a function that will receive the constructor
  2073. * function as its only parameter to which static properties can
  2074. * be added.
  2075. * all other properties are added to the prototype.
  2076. * @return {!Function} The class constructor.
  2077. */
  2078. goog.defineClass = function(superClass, def) {
  2079. // TODO(johnlenz): consider making the superClass an optional parameter.
  2080. var constructor = def.constructor;
  2081. var statics = def.statics;
  2082. // Wrap the constructor prior to setting up the prototype and static methods.
  2083. if (!constructor || constructor == Object.prototype.constructor) {
  2084. constructor = function() {
  2085. throw Error('cannot instantiate an interface (no constructor defined).');
  2086. };
  2087. }
  2088. var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);
  2089. if (superClass) {
  2090. goog.inherits(cls, superClass);
  2091. }
  2092. // Remove all the properties that should not be copied to the prototype.
  2093. delete def.constructor;
  2094. delete def.statics;
  2095. goog.defineClass.applyProperties_(cls.prototype, def);
  2096. if (statics != null) {
  2097. if (statics instanceof Function) {
  2098. statics(cls);
  2099. } else {
  2100. goog.defineClass.applyProperties_(cls, statics);
  2101. }
  2102. }
  2103. return cls;
  2104. };
  2105. /**
  2106. * @typedef {
  2107. * !Object|
  2108. * {constructor:!Function}|
  2109. * {constructor:!Function, statics:(Object|function(Function):void)}}
  2110. * @suppress {missingProvide}
  2111. */
  2112. goog.defineClass.ClassDescriptor;
  2113. /**
  2114. * @define {boolean} Whether the instances returned by
  2115. * goog.defineClass should be sealed when possible.
  2116. */
  2117. goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);
  2118. /**
  2119. * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is
  2120. * defined, this function will wrap the constructor in a function that seals the
  2121. * results of the provided constructor function.
  2122. *
  2123. * @param {!Function} ctr The constructor whose results maybe be sealed.
  2124. * @param {Function} superClass The superclass constructor.
  2125. * @return {!Function} The replacement constructor.
  2126. * @private
  2127. */
  2128. goog.defineClass.createSealingConstructor_ = function(ctr, superClass) {
  2129. if (goog.defineClass.SEAL_CLASS_INSTANCES &&
  2130. Object.seal instanceof Function) {
  2131. // Don't seal subclasses of unsealable-tagged legacy classes.
  2132. if (superClass && superClass.prototype &&
  2133. superClass.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]) {
  2134. return ctr;
  2135. }
  2136. /**
  2137. * @this {Object}
  2138. * @return {?}
  2139. */
  2140. var wrappedCtr = function() {
  2141. // Don't seal an instance of a subclass when it calls the constructor of
  2142. // its super class as there is most likely still setup to do.
  2143. var instance = ctr.apply(this, arguments) || this;
  2144. instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];
  2145. if (this.constructor === wrappedCtr) {
  2146. Object.seal(instance);
  2147. }
  2148. return instance;
  2149. };
  2150. return wrappedCtr;
  2151. }
  2152. return ctr;
  2153. };
  2154. // TODO(johnlenz): share these values with the goog.object
  2155. /**
  2156. * The names of the fields that are defined on Object.prototype.
  2157. * @type {!Array<string>}
  2158. * @private
  2159. * @const
  2160. */
  2161. goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [
  2162. 'constructor',
  2163. 'hasOwnProperty',
  2164. 'isPrototypeOf',
  2165. 'propertyIsEnumerable',
  2166. 'toLocaleString',
  2167. 'toString',
  2168. 'valueOf'
  2169. ];
  2170. // TODO(johnlenz): share this function with the goog.object
  2171. /**
  2172. * @param {!Object} target The object to add properties to.
  2173. * @param {!Object} source The object to copy properties from.
  2174. * @private
  2175. */
  2176. goog.defineClass.applyProperties_ = function(target, source) {
  2177. // TODO(johnlenz): update this to support ES5 getters/setters
  2178. var key;
  2179. for (key in source) {
  2180. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2181. target[key] = source[key];
  2182. }
  2183. }
  2184. // For IE the for-in-loop does not contain any properties that are not
  2185. // enumerable on the prototype object (for example isPrototypeOf from
  2186. // Object.prototype) and it will also not include 'replace' on objects that
  2187. // extend String and change 'replace' (not that it is common for anyone to
  2188. // extend anything except Object).
  2189. for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {
  2190. key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];
  2191. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2192. target[key] = source[key];
  2193. }
  2194. }
  2195. };
  2196. /**
  2197. * Sealing classes breaks the older idiom of assigning properties on the
  2198. * prototype rather than in the constructor. As such, goog.defineClass
  2199. * must not seal subclasses of these old-style classes until they are fixed.
  2200. * Until then, this marks a class as "broken", instructing defineClass
  2201. * not to seal subclasses.
  2202. * @param {!Function} ctr The legacy constructor to tag as unsealable.
  2203. */
  2204. goog.tagUnsealableClass = function(ctr) {
  2205. if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {
  2206. ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;
  2207. }
  2208. };
  2209. /**
  2210. * Name for unsealable tag property.
  2211. * @const @private {string}
  2212. */
  2213. goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';
  2214. goog.provide('ol');
  2215. /**
  2216. * Constants defined with the define tag cannot be changed in application
  2217. * code, but can be set at compile time.
  2218. * Some reduce the size of the build in advanced compile mode.
  2219. */
  2220. /**
  2221. * @define {boolean} Assume touch. Default is `false`.
  2222. */
  2223. ol.ASSUME_TOUCH = false;
  2224. /**
  2225. * TODO: rename this to something having to do with tile grids
  2226. * see https://github.com/openlayers/ol3/issues/2076
  2227. * @define {number} Default maximum zoom for default tile grids.
  2228. */
  2229. ol.DEFAULT_MAX_ZOOM = 42;
  2230. /**
  2231. * @define {number} Default min zoom level for the map view. Default is `0`.
  2232. */
  2233. ol.DEFAULT_MIN_ZOOM = 0;
  2234. /**
  2235. * @define {number} Default high water mark.
  2236. */
  2237. ol.DEFAULT_TILE_CACHE_HIGH_WATER_MARK = 2048;
  2238. /**
  2239. * @define {number} Default tile size.
  2240. */
  2241. ol.DEFAULT_TILE_SIZE = 256;
  2242. /**
  2243. * @define {string} Default WMS version.
  2244. */
  2245. ol.DEFAULT_WMS_VERSION = '1.3.0';
  2246. /**
  2247. * @define {number} Hysteresis pixels.
  2248. */
  2249. ol.DRAG_BOX_HYSTERESIS_PIXELS = 8;
  2250. /**
  2251. * @define {boolean} Enable the Canvas renderer. Default is `true`. Setting
  2252. * this to false at compile time in advanced mode removes all code
  2253. * supporting the Canvas renderer from the build.
  2254. */
  2255. ol.ENABLE_CANVAS = true;
  2256. /**
  2257. * @define {boolean} Enable the DOM renderer (used as a fallback where Canvas is
  2258. * not available). Default is `true`. Setting this to false at compile time
  2259. * in advanced mode removes all code supporting the DOM renderer from the
  2260. * build.
  2261. */
  2262. ol.ENABLE_DOM = true;
  2263. /**
  2264. * @define {boolean} Enable rendering of ol.layer.Image based layers. Default
  2265. * is `true`. Setting this to false at compile time in advanced mode removes
  2266. * all code supporting Image layers from the build.
  2267. */
  2268. ol.ENABLE_IMAGE = true;
  2269. /**
  2270. * @define {boolean} Enable Closure named colors (`goog.color.names`).
  2271. * Enabling these colors adds about 3KB uncompressed / 1.5KB compressed to
  2272. * the final build size. Default is `false`. This setting has no effect
  2273. * with Canvas renderer, which uses its own names, whether this is true or
  2274. * false.
  2275. */
  2276. ol.ENABLE_NAMED_COLORS = false;
  2277. /**
  2278. * @define {boolean} Enable integration with the Proj4js library. Default is
  2279. * `true`.
  2280. */
  2281. ol.ENABLE_PROJ4JS = true;
  2282. /**
  2283. * @define {boolean} Enable rendering of ol.layer.Tile based layers. Default is
  2284. * `true`. Setting this to false at compile time in advanced mode removes
  2285. * all code supporting Tile layers from the build.
  2286. */
  2287. ol.ENABLE_TILE = true;
  2288. /**
  2289. * @define {boolean} Enable rendering of ol.layer.Vector based layers. Default
  2290. * is `true`. Setting this to false at compile time in advanced mode removes
  2291. * all code supporting Vector layers from the build.
  2292. */
  2293. ol.ENABLE_VECTOR = true;
  2294. /**
  2295. * @define {boolean} Enable the WebGL renderer. Default is `true`. Setting
  2296. * this to false at compile time in advanced mode removes all code
  2297. * supporting the WebGL renderer from the build.
  2298. */
  2299. ol.ENABLE_WEBGL = true;
  2300. /**
  2301. * @define {number} The size in pixels of the first atlas image. Default is
  2302. * `256`.
  2303. */
  2304. ol.INITIAL_ATLAS_SIZE = 256;
  2305. /**
  2306. * @define {number} The maximum size in pixels of atlas images. Default is
  2307. * `-1`, meaning it is not used (and `ol.WEBGL_MAX_TEXTURE_SIZE` is
  2308. * used instead).
  2309. */
  2310. ol.MAX_ATLAS_SIZE = -1;
  2311. /**
  2312. * @define {number} Maximum mouse wheel delta.
  2313. */
  2314. ol.MOUSEWHEELZOOM_MAXDELTA = 1;
  2315. /**
  2316. * @define {number} Mouse wheel timeout duration.
  2317. */
  2318. ol.MOUSEWHEELZOOM_TIMEOUT_DURATION = 80;
  2319. /**
  2320. * @define {number} Maximum width and/or height extent ratio that determines
  2321. * when the overview map should be zoomed out.
  2322. */
  2323. ol.OVERVIEWMAP_MAX_RATIO = 0.75;
  2324. /**
  2325. * @define {number} Minimum width and/or height extent ratio that determines
  2326. * when the overview map should be zoomed in.
  2327. */
  2328. ol.OVERVIEWMAP_MIN_RATIO = 0.1;
  2329. /**
  2330. * @define {number} Tolerance for geometry simplification in device pixels.
  2331. */
  2332. ol.SIMPLIFY_TOLERANCE = 0.5;
  2333. /**
  2334. * @define {number} Texture cache high water mark.
  2335. */
  2336. ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK = 1024;
  2337. /**
  2338. * The maximum supported WebGL texture size in pixels. If WebGL is not
  2339. * supported, the value is set to `undefined`.
  2340. * @const
  2341. * @type {number|undefined}
  2342. */
  2343. ol.WEBGL_MAX_TEXTURE_SIZE; // value is set in `ol.has`
  2344. /**
  2345. * List of supported WebGL extensions.
  2346. * @const
  2347. * @type {Array.<string>}
  2348. */
  2349. ol.WEBGL_EXTENSIONS; // value is set in `ol.has`
  2350. /**
  2351. * Inherit the prototype methods from one constructor into another.
  2352. *
  2353. * Usage:
  2354. *
  2355. * function ParentClass(a, b) { }
  2356. * ParentClass.prototype.foo = function(a) { }
  2357. *
  2358. * function ChildClass(a, b, c) {
  2359. * // Call parent constructor
  2360. * ParentClass.call(this, a, b);
  2361. * }
  2362. * ol.inherits(ChildClass, ParentClass);
  2363. *
  2364. * var child = new ChildClass('a', 'b', 'see');
  2365. * child.foo(); // This works.
  2366. *
  2367. * In addition, a superclass' implementation of a method can be invoked as
  2368. * follows:
  2369. *
  2370. * ChildClass.prototype.foo = function(a) {
  2371. * ChildClass.base(this, 'foo', a);
  2372. * // Other code here.
  2373. * };
  2374. *
  2375. * @param {!Function} childCtor Child constructor.
  2376. * @param {!Function} parentCtor Parent constructor.
  2377. * @function
  2378. * @api
  2379. */
  2380. ol.inherits =
  2381. goog.inherits;
  2382. // note that the newline above is necessary to satisfy the linter
  2383. /**
  2384. * A reusable function, used e.g. as a default for callbacks.
  2385. *
  2386. * @return {undefined} Nothing.
  2387. */
  2388. ol.nullFunction = function() {};
  2389. // FIXME factor out common code between usedTiles and wantedTiles
  2390. goog.provide('ol.PostRenderFunction');
  2391. goog.provide('ol.PreRenderFunction');
  2392. /**
  2393. * @typedef {function(ol.Map, ?olx.FrameState): boolean}
  2394. */
  2395. ol.PostRenderFunction;
  2396. /**
  2397. * Function to perform manipulations before rendering. This function is called
  2398. * with the {@link ol.Map} as first and an optional {@link olx.FrameState} as
  2399. * second argument. Return `true` to keep this function for the next frame,
  2400. * `false` to remove it.
  2401. * @typedef {function(ol.Map, ?olx.FrameState): boolean}
  2402. * @api
  2403. */
  2404. ol.PreRenderFunction;
  2405. // Copyright 2009 The Closure Library Authors. All Rights Reserved.
  2406. //
  2407. // Licensed under the Apache License, Version 2.0 (the "License");
  2408. // you may not use this file except in compliance with the License.
  2409. // You may obtain a copy of the License at
  2410. //
  2411. // http://www.apache.org/licenses/LICENSE-2.0
  2412. //
  2413. // Unless required by applicable law or agreed to in writing, software
  2414. // distributed under the License is distributed on an "AS-IS" BASIS,
  2415. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2416. // See the License for the specific language governing permissions and
  2417. // limitations under the License.
  2418. /**
  2419. * @fileoverview Provides a base class for custom Error objects such that the
  2420. * stack is correctly maintained.
  2421. *
  2422. * You should never need to throw goog.debug.Error(msg) directly, Error(msg) is
  2423. * sufficient.
  2424. *
  2425. */
  2426. goog.provide('goog.debug.Error');
  2427. /**
  2428. * Base class for custom error objects.
  2429. * @param {*=} opt_msg The message associated with the error.
  2430. * @constructor
  2431. * @extends {Error}
  2432. */
  2433. goog.debug.Error = function(opt_msg) {
  2434. // Attempt to ensure there is a stack trace.
  2435. if (Error.captureStackTrace) {
  2436. Error.captureStackTrace(this, goog.debug.Error);
  2437. } else {
  2438. var stack = new Error().stack;
  2439. if (stack) {
  2440. this.stack = stack;
  2441. }
  2442. }
  2443. if (opt_msg) {
  2444. this.message = String(opt_msg);
  2445. }
  2446. /**
  2447. * Whether to report this error to the server. Setting this to false will
  2448. * cause the error reporter to not report the error back to the server,
  2449. * which can be useful if the client knows that the error has already been
  2450. * logged on the server.
  2451. * @type {boolean}
  2452. */
  2453. this.reportErrorToServer = true;
  2454. };
  2455. goog.inherits(goog.debug.Error, Error);
  2456. /** @override */
  2457. goog.debug.Error.prototype.name = 'CustomError';
  2458. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2459. //
  2460. // Licensed under the Apache License, Version 2.0 (the "License");
  2461. // you may not use this file except in compliance with the License.
  2462. // You may obtain a copy of the License at
  2463. //
  2464. // http://www.apache.org/licenses/LICENSE-2.0
  2465. //
  2466. // Unless required by applicable law or agreed to in writing, software
  2467. // distributed under the License is distributed on an "AS-IS" BASIS,
  2468. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2469. // See the License for the specific language governing permissions and
  2470. // limitations under the License.
  2471. /**
  2472. * @fileoverview Definition of goog.dom.NodeType.
  2473. */
  2474. goog.provide('goog.dom.NodeType');
  2475. /**
  2476. * Constants for the nodeType attribute in the Node interface.
  2477. *
  2478. * These constants match those specified in the Node interface. These are
  2479. * usually present on the Node object in recent browsers, but not in older
  2480. * browsers (specifically, early IEs) and thus are given here.
  2481. *
  2482. * In some browsers (early IEs), these are not defined on the Node object,
  2483. * so they are provided here.
  2484. *
  2485. * See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247
  2486. * @enum {number}
  2487. */
  2488. goog.dom.NodeType = {
  2489. ELEMENT: 1,
  2490. ATTRIBUTE: 2,
  2491. TEXT: 3,
  2492. CDATA_SECTION: 4,
  2493. ENTITY_REFERENCE: 5,
  2494. ENTITY: 6,
  2495. PROCESSING_INSTRUCTION: 7,
  2496. COMMENT: 8,
  2497. DOCUMENT: 9,
  2498. DOCUMENT_TYPE: 10,
  2499. DOCUMENT_FRAGMENT: 11,
  2500. NOTATION: 12
  2501. };
  2502. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2503. //
  2504. // Licensed under the Apache License, Version 2.0 (the "License");
  2505. // you may not use this file except in compliance with the License.
  2506. // You may obtain a copy of the License at
  2507. //
  2508. // http://www.apache.org/licenses/LICENSE-2.0
  2509. //
  2510. // Unless required by applicable law or agreed to in writing, software
  2511. // distributed under the License is distributed on an "AS-IS" BASIS,
  2512. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2513. // See the License for the specific language governing permissions and
  2514. // limitations under the License.
  2515. /**
  2516. * @fileoverview Utilities for string manipulation.
  2517. * @author arv@google.com (Erik Arvidsson)
  2518. */
  2519. /**
  2520. * Namespace for string utilities
  2521. */
  2522. goog.provide('goog.string');
  2523. goog.provide('goog.string.Unicode');
  2524. /**
  2525. * @define {boolean} Enables HTML escaping of lowercase letter "e" which helps
  2526. * with detection of double-escaping as this letter is frequently used.
  2527. */
  2528. goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);
  2529. /**
  2530. * @define {boolean} Whether to force non-dom html unescaping.
  2531. */
  2532. goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);
  2533. /**
  2534. * Common Unicode string characters.
  2535. * @enum {string}
  2536. */
  2537. goog.string.Unicode = {
  2538. NBSP: '\xa0'
  2539. };
  2540. /**
  2541. * Fast prefix-checker.
  2542. * @param {string} str The string to check.
  2543. * @param {string} prefix A string to look for at the start of {@code str}.
  2544. * @return {boolean} True if {@code str} begins with {@code prefix}.
  2545. */
  2546. goog.string.startsWith = function(str, prefix) {
  2547. return str.lastIndexOf(prefix, 0) == 0;
  2548. };
  2549. /**
  2550. * Fast suffix-checker.
  2551. * @param {string} str The string to check.
  2552. * @param {string} suffix A string to look for at the end of {@code str}.
  2553. * @return {boolean} True if {@code str} ends with {@code suffix}.
  2554. */
  2555. goog.string.endsWith = function(str, suffix) {
  2556. var l = str.length - suffix.length;
  2557. return l >= 0 && str.indexOf(suffix, l) == l;
  2558. };
  2559. /**
  2560. * Case-insensitive prefix-checker.
  2561. * @param {string} str The string to check.
  2562. * @param {string} prefix A string to look for at the end of {@code str}.
  2563. * @return {boolean} True if {@code str} begins with {@code prefix} (ignoring
  2564. * case).
  2565. */
  2566. goog.string.caseInsensitiveStartsWith = function(str, prefix) {
  2567. return goog.string.caseInsensitiveCompare(
  2568. prefix, str.substr(0, prefix.length)) == 0;
  2569. };
  2570. /**
  2571. * Case-insensitive suffix-checker.
  2572. * @param {string} str The string to check.
  2573. * @param {string} suffix A string to look for at the end of {@code str}.
  2574. * @return {boolean} True if {@code str} ends with {@code suffix} (ignoring
  2575. * case).
  2576. */
  2577. goog.string.caseInsensitiveEndsWith = function(str, suffix) {
  2578. return goog.string.caseInsensitiveCompare(
  2579. suffix, str.substr(str.length - suffix.length, suffix.length)) == 0;
  2580. };
  2581. /**
  2582. * Case-insensitive equality checker.
  2583. * @param {string} str1 First string to check.
  2584. * @param {string} str2 Second string to check.
  2585. * @return {boolean} True if {@code str1} and {@code str2} are the same string,
  2586. * ignoring case.
  2587. */
  2588. goog.string.caseInsensitiveEquals = function(str1, str2) {
  2589. return str1.toLowerCase() == str2.toLowerCase();
  2590. };
  2591. /**
  2592. * Does simple python-style string substitution.
  2593. * subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog".
  2594. * @param {string} str The string containing the pattern.
  2595. * @param {...*} var_args The items to substitute into the pattern.
  2596. * @return {string} A copy of {@code str} in which each occurrence of
  2597. * {@code %s} has been replaced an argument from {@code var_args}.
  2598. */
  2599. goog.string.subs = function(str, var_args) {
  2600. var splitParts = str.split('%s');
  2601. var returnString = '';
  2602. var subsArguments = Array.prototype.slice.call(arguments, 1);
  2603. while (subsArguments.length &&
  2604. // Replace up to the last split part. We are inserting in the
  2605. // positions between split parts.
  2606. splitParts.length > 1) {
  2607. returnString += splitParts.shift() + subsArguments.shift();
  2608. }
  2609. return returnString + splitParts.join('%s'); // Join unused '%s'
  2610. };
  2611. /**
  2612. * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines
  2613. * and tabs) to a single space, and strips leading and trailing whitespace.
  2614. * @param {string} str Input string.
  2615. * @return {string} A copy of {@code str} with collapsed whitespace.
  2616. */
  2617. goog.string.collapseWhitespace = function(str) {
  2618. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  2619. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  2620. // include it in the regexp to enforce consistent cross-browser behavior.
  2621. return str.replace(/[\s\xa0]+/g, ' ').replace(/^\s+|\s+$/g, '');
  2622. };
  2623. /**
  2624. * Checks if a string is empty or contains only whitespaces.
  2625. * @param {string} str The string to check.
  2626. * @return {boolean} Whether {@code str} is empty or whitespace only.
  2627. */
  2628. goog.string.isEmptyOrWhitespace = function(str) {
  2629. // testing length == 0 first is actually slower in all browsers (about the
  2630. // same in Opera).
  2631. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  2632. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  2633. // include it in the regexp to enforce consistent cross-browser behavior.
  2634. return /^[\s\xa0]*$/.test(str);
  2635. };
  2636. /**
  2637. * Checks if a string is empty.
  2638. * @param {string} str The string to check.
  2639. * @return {boolean} Whether {@code str} is empty.
  2640. */
  2641. goog.string.isEmptyString = function(str) {
  2642. return str.length == 0;
  2643. };
  2644. /**
  2645. * Checks if a string is empty or contains only whitespaces.
  2646. *
  2647. * TODO(user): Deprecate this when clients have been switched over to
  2648. * goog.string.isEmptyOrWhitespace.
  2649. *
  2650. * @param {string} str The string to check.
  2651. * @return {boolean} Whether {@code str} is empty or whitespace only.
  2652. */
  2653. goog.string.isEmpty = goog.string.isEmptyOrWhitespace;
  2654. /**
  2655. * Checks if a string is null, undefined, empty or contains only whitespaces.
  2656. * @param {*} str The string to check.
  2657. * @return {boolean} Whether {@code str} is null, undefined, empty, or
  2658. * whitespace only.
  2659. * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))
  2660. * instead.
  2661. */
  2662. goog.string.isEmptyOrWhitespaceSafe = function(str) {
  2663. return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));
  2664. };
  2665. /**
  2666. * Checks if a string is null, undefined, empty or contains only whitespaces.
  2667. *
  2668. * TODO(user): Deprecate this when clients have been switched over to
  2669. * goog.string.isEmptyOrWhitespaceSafe.
  2670. *
  2671. * @param {*} str The string to check.
  2672. * @return {boolean} Whether {@code str} is null, undefined, empty, or
  2673. * whitespace only.
  2674. */
  2675. goog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;
  2676. /**
  2677. * Checks if a string is all breaking whitespace.
  2678. * @param {string} str The string to check.
  2679. * @return {boolean} Whether the string is all breaking whitespace.
  2680. */
  2681. goog.string.isBreakingWhitespace = function(str) {
  2682. return !/[^\t\n\r ]/.test(str);
  2683. };
  2684. /**
  2685. * Checks if a string contains all letters.
  2686. * @param {string} str string to check.
  2687. * @return {boolean} True if {@code str} consists entirely of letters.
  2688. */
  2689. goog.string.isAlpha = function(str) {
  2690. return !/[^a-zA-Z]/.test(str);
  2691. };
  2692. /**
  2693. * Checks if a string contains only numbers.
  2694. * @param {*} str string to check. If not a string, it will be
  2695. * casted to one.
  2696. * @return {boolean} True if {@code str} is numeric.
  2697. */
  2698. goog.string.isNumeric = function(str) {
  2699. return !/[^0-9]/.test(str);
  2700. };
  2701. /**
  2702. * Checks if a string contains only numbers or letters.
  2703. * @param {string} str string to check.
  2704. * @return {boolean} True if {@code str} is alphanumeric.
  2705. */
  2706. goog.string.isAlphaNumeric = function(str) {
  2707. return !/[^a-zA-Z0-9]/.test(str);
  2708. };
  2709. /**
  2710. * Checks if a character is a space character.
  2711. * @param {string} ch Character to check.
  2712. * @return {boolean} True if {@code ch} is a space.
  2713. */
  2714. goog.string.isSpace = function(ch) {
  2715. return ch == ' ';
  2716. };
  2717. /**
  2718. * Checks if a character is a valid unicode character.
  2719. * @param {string} ch Character to check.
  2720. * @return {boolean} True if {@code ch} is a valid unicode character.
  2721. */
  2722. goog.string.isUnicodeChar = function(ch) {
  2723. return ch.length == 1 && ch >= ' ' && ch <= '~' ||
  2724. ch >= '\u0080' && ch <= '\uFFFD';
  2725. };
  2726. /**
  2727. * Takes a string and replaces newlines with a space. Multiple lines are
  2728. * replaced with a single space.
  2729. * @param {string} str The string from which to strip newlines.
  2730. * @return {string} A copy of {@code str} stripped of newlines.
  2731. */
  2732. goog.string.stripNewlines = function(str) {
  2733. return str.replace(/(\r\n|\r|\n)+/g, ' ');
  2734. };
  2735. /**
  2736. * Replaces Windows and Mac new lines with unix style: \r or \r\n with \n.
  2737. * @param {string} str The string to in which to canonicalize newlines.
  2738. * @return {string} {@code str} A copy of {@code} with canonicalized newlines.
  2739. */
  2740. goog.string.canonicalizeNewlines = function(str) {
  2741. return str.replace(/(\r\n|\r|\n)/g, '\n');
  2742. };
  2743. /**
  2744. * Normalizes whitespace in a string, replacing all whitespace chars with
  2745. * a space.
  2746. * @param {string} str The string in which to normalize whitespace.
  2747. * @return {string} A copy of {@code str} with all whitespace normalized.
  2748. */
  2749. goog.string.normalizeWhitespace = function(str) {
  2750. return str.replace(/\xa0|\s/g, ' ');
  2751. };
  2752. /**
  2753. * Normalizes spaces in a string, replacing all consecutive spaces and tabs
  2754. * with a single space. Replaces non-breaking space with a space.
  2755. * @param {string} str The string in which to normalize spaces.
  2756. * @return {string} A copy of {@code str} with all consecutive spaces and tabs
  2757. * replaced with a single space.
  2758. */
  2759. goog.string.normalizeSpaces = function(str) {
  2760. return str.replace(/\xa0|[ \t]+/g, ' ');
  2761. };
  2762. /**
  2763. * Removes the breaking spaces from the left and right of the string and
  2764. * collapses the sequences of breaking spaces in the middle into single spaces.
  2765. * The original and the result strings render the same way in HTML.
  2766. * @param {string} str A string in which to collapse spaces.
  2767. * @return {string} Copy of the string with normalized breaking spaces.
  2768. */
  2769. goog.string.collapseBreakingSpaces = function(str) {
  2770. return str.replace(/[\t\r\n ]+/g, ' ').replace(
  2771. /^[\t\r\n ]+|[\t\r\n ]+$/g, '');
  2772. };
  2773. /**
  2774. * Trims white spaces to the left and right of a string.
  2775. * @param {string} str The string to trim.
  2776. * @return {string} A trimmed copy of {@code str}.
  2777. */
  2778. goog.string.trim = (goog.TRUSTED_SITE && String.prototype.trim) ?
  2779. function(str) {
  2780. return str.trim();
  2781. } :
  2782. function(str) {
  2783. // Since IE doesn't include non-breaking-space (0xa0) in their \s
  2784. // character class (as required by section 7.2 of the ECMAScript spec),
  2785. // we explicitly include it in the regexp to enforce consistent
  2786. // cross-browser behavior.
  2787. return str.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  2788. };
  2789. /**
  2790. * Trims whitespaces at the left end of a string.
  2791. * @param {string} str The string to left trim.
  2792. * @return {string} A trimmed copy of {@code str}.
  2793. */
  2794. goog.string.trimLeft = function(str) {
  2795. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  2796. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  2797. // include it in the regexp to enforce consistent cross-browser behavior.
  2798. return str.replace(/^[\s\xa0]+/, '');
  2799. };
  2800. /**
  2801. * Trims whitespaces at the right end of a string.
  2802. * @param {string} str The string to right trim.
  2803. * @return {string} A trimmed copy of {@code str}.
  2804. */
  2805. goog.string.trimRight = function(str) {
  2806. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  2807. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  2808. // include it in the regexp to enforce consistent cross-browser behavior.
  2809. return str.replace(/[\s\xa0]+$/, '');
  2810. };
  2811. /**
  2812. * A string comparator that ignores case.
  2813. * -1 = str1 less than str2
  2814. * 0 = str1 equals str2
  2815. * 1 = str1 greater than str2
  2816. *
  2817. * @param {string} str1 The string to compare.
  2818. * @param {string} str2 The string to compare {@code str1} to.
  2819. * @return {number} The comparator result, as described above.
  2820. */
  2821. goog.string.caseInsensitiveCompare = function(str1, str2) {
  2822. var test1 = String(str1).toLowerCase();
  2823. var test2 = String(str2).toLowerCase();
  2824. if (test1 < test2) {
  2825. return -1;
  2826. } else if (test1 == test2) {
  2827. return 0;
  2828. } else {
  2829. return 1;
  2830. }
  2831. };
  2832. /**
  2833. * Regular expression used for splitting a string into substrings of fractional
  2834. * numbers, integers, and non-numeric characters.
  2835. * @type {RegExp}
  2836. * @private
  2837. */
  2838. goog.string.numerateCompareRegExp_ = /(\.\d+)|(\d+)|(\D+)/g;
  2839. /**
  2840. * String comparison function that handles numbers in a way humans might expect.
  2841. * Using this function, the string "File 2.jpg" sorts before "File 10.jpg". The
  2842. * comparison is mostly case-insensitive, though strings that are identical
  2843. * except for case are sorted with the upper-case strings before lower-case.
  2844. *
  2845. * This comparison function is significantly slower (about 500x) than either
  2846. * the default or the case-insensitive compare. It should not be used in
  2847. * time-critical code, but should be fast enough to sort several hundred short
  2848. * strings (like filenames) with a reasonable delay.
  2849. *
  2850. * @param {string} str1 The string to compare in a numerically sensitive way.
  2851. * @param {string} str2 The string to compare {@code str1} to.
  2852. * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than
  2853. * 0 if str1 > str2.
  2854. */
  2855. goog.string.numerateCompare = function(str1, str2) {
  2856. if (str1 == str2) {
  2857. return 0;
  2858. }
  2859. if (!str1) {
  2860. return -1;
  2861. }
  2862. if (!str2) {
  2863. return 1;
  2864. }
  2865. // Using match to split the entire string ahead of time turns out to be faster
  2866. // for most inputs than using RegExp.exec or iterating over each character.
  2867. var tokens1 = str1.toLowerCase().match(goog.string.numerateCompareRegExp_);
  2868. var tokens2 = str2.toLowerCase().match(goog.string.numerateCompareRegExp_);
  2869. var count = Math.min(tokens1.length, tokens2.length);
  2870. for (var i = 0; i < count; i++) {
  2871. var a = tokens1[i];
  2872. var b = tokens2[i];
  2873. // Compare pairs of tokens, returning if one token sorts before the other.
  2874. if (a != b) {
  2875. // Only if both tokens are integers is a special comparison required.
  2876. // Decimal numbers are sorted as strings (e.g., '.09' < '.1').
  2877. var num1 = parseInt(a, 10);
  2878. if (!isNaN(num1)) {
  2879. var num2 = parseInt(b, 10);
  2880. if (!isNaN(num2) && num1 - num2) {
  2881. return num1 - num2;
  2882. }
  2883. }
  2884. return a < b ? -1 : 1;
  2885. }
  2886. }
  2887. // If one string is a substring of the other, the shorter string sorts first.
  2888. if (tokens1.length != tokens2.length) {
  2889. return tokens1.length - tokens2.length;
  2890. }
  2891. // The two strings must be equivalent except for case (perfect equality is
  2892. // tested at the head of the function.) Revert to default ASCII-betical string
  2893. // comparison to stablize the sort.
  2894. return str1 < str2 ? -1 : 1;
  2895. };
  2896. /**
  2897. * URL-encodes a string
  2898. * @param {*} str The string to url-encode.
  2899. * @return {string} An encoded copy of {@code str} that is safe for urls.
  2900. * Note that '#', ':', and other characters used to delimit portions
  2901. * of URLs *will* be encoded.
  2902. */
  2903. goog.string.urlEncode = function(str) {
  2904. return encodeURIComponent(String(str));
  2905. };
  2906. /**
  2907. * URL-decodes the string. We need to specially handle '+'s because
  2908. * the javascript library doesn't convert them to spaces.
  2909. * @param {string} str The string to url decode.
  2910. * @return {string} The decoded {@code str}.
  2911. */
  2912. goog.string.urlDecode = function(str) {
  2913. return decodeURIComponent(str.replace(/\+/g, ' '));
  2914. };
  2915. /**
  2916. * Converts \n to <br>s or <br />s.
  2917. * @param {string} str The string in which to convert newlines.
  2918. * @param {boolean=} opt_xml Whether to use XML compatible tags.
  2919. * @return {string} A copy of {@code str} with converted newlines.
  2920. */
  2921. goog.string.newLineToBr = function(str, opt_xml) {
  2922. return str.replace(/(\r\n|\r|\n)/g, opt_xml ? '<br />' : '<br>');
  2923. };
  2924. /**
  2925. * Escapes double quote '"' and single quote '\'' characters in addition to
  2926. * '&', '<', and '>' so that a string can be included in an HTML tag attribute
  2927. * value within double or single quotes.
  2928. *
  2929. * It should be noted that > doesn't need to be escaped for the HTML or XML to
  2930. * be valid, but it has been decided to escape it for consistency with other
  2931. * implementations.
  2932. *
  2933. * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the
  2934. * lowercase letter "e".
  2935. *
  2936. * NOTE(user):
  2937. * HtmlEscape is often called during the generation of large blocks of HTML.
  2938. * Using statics for the regular expressions and strings is an optimization
  2939. * that can more than half the amount of time IE spends in this function for
  2940. * large apps, since strings and regexes both contribute to GC allocations.
  2941. *
  2942. * Testing for the presence of a character before escaping increases the number
  2943. * of function calls, but actually provides a speed increase for the average
  2944. * case -- since the average case often doesn't require the escaping of all 4
  2945. * characters and indexOf() is much cheaper than replace().
  2946. * The worst case does suffer slightly from the additional calls, therefore the
  2947. * opt_isLikelyToContainHtmlChars option has been included for situations
  2948. * where all 4 HTML entities are very likely to be present and need escaping.
  2949. *
  2950. * Some benchmarks (times tended to fluctuate +-0.05ms):
  2951. * FireFox IE6
  2952. * (no chars / average (mix of cases) / all 4 chars)
  2953. * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80
  2954. * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84
  2955. * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85
  2956. *
  2957. * An additional advantage of checking if replace actually needs to be called
  2958. * is a reduction in the number of object allocations, so as the size of the
  2959. * application grows the difference between the various methods would increase.
  2960. *
  2961. * @param {string} str string to be escaped.
  2962. * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see
  2963. * if the character needs replacing - use this option if you expect each of
  2964. * the characters to appear often. Leave false if you expect few html
  2965. * characters to occur in your strings, such as if you are escaping HTML.
  2966. * @return {string} An escaped copy of {@code str}.
  2967. */
  2968. goog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {
  2969. if (opt_isLikelyToContainHtmlChars) {
  2970. str = str.replace(goog.string.AMP_RE_, '&amp;')
  2971. .replace(goog.string.LT_RE_, '&lt;')
  2972. .replace(goog.string.GT_RE_, '&gt;')
  2973. .replace(goog.string.QUOT_RE_, '&quot;')
  2974. .replace(goog.string.SINGLE_QUOTE_RE_, '&#39;')
  2975. .replace(goog.string.NULL_RE_, '&#0;');
  2976. if (goog.string.DETECT_DOUBLE_ESCAPING) {
  2977. str = str.replace(goog.string.E_RE_, '&#101;');
  2978. }
  2979. return str;
  2980. } else {
  2981. // quick test helps in the case when there are no chars to replace, in
  2982. // worst case this makes barely a difference to the time taken
  2983. if (!goog.string.ALL_RE_.test(str)) return str;
  2984. // str.indexOf is faster than regex.test in this case
  2985. if (str.indexOf('&') != -1) {
  2986. str = str.replace(goog.string.AMP_RE_, '&amp;');
  2987. }
  2988. if (str.indexOf('<') != -1) {
  2989. str = str.replace(goog.string.LT_RE_, '&lt;');
  2990. }
  2991. if (str.indexOf('>') != -1) {
  2992. str = str.replace(goog.string.GT_RE_, '&gt;');
  2993. }
  2994. if (str.indexOf('"') != -1) {
  2995. str = str.replace(goog.string.QUOT_RE_, '&quot;');
  2996. }
  2997. if (str.indexOf('\'') != -1) {
  2998. str = str.replace(goog.string.SINGLE_QUOTE_RE_, '&#39;');
  2999. }
  3000. if (str.indexOf('\x00') != -1) {
  3001. str = str.replace(goog.string.NULL_RE_, '&#0;');
  3002. }
  3003. if (goog.string.DETECT_DOUBLE_ESCAPING && str.indexOf('e') != -1) {
  3004. str = str.replace(goog.string.E_RE_, '&#101;');
  3005. }
  3006. return str;
  3007. }
  3008. };
  3009. /**
  3010. * Regular expression that matches an ampersand, for use in escaping.
  3011. * @const {!RegExp}
  3012. * @private
  3013. */
  3014. goog.string.AMP_RE_ = /&/g;
  3015. /**
  3016. * Regular expression that matches a less than sign, for use in escaping.
  3017. * @const {!RegExp}
  3018. * @private
  3019. */
  3020. goog.string.LT_RE_ = /</g;
  3021. /**
  3022. * Regular expression that matches a greater than sign, for use in escaping.
  3023. * @const {!RegExp}
  3024. * @private
  3025. */
  3026. goog.string.GT_RE_ = />/g;
  3027. /**
  3028. * Regular expression that matches a double quote, for use in escaping.
  3029. * @const {!RegExp}
  3030. * @private
  3031. */
  3032. goog.string.QUOT_RE_ = /"/g;
  3033. /**
  3034. * Regular expression that matches a single quote, for use in escaping.
  3035. * @const {!RegExp}
  3036. * @private
  3037. */
  3038. goog.string.SINGLE_QUOTE_RE_ = /'/g;
  3039. /**
  3040. * Regular expression that matches null character, for use in escaping.
  3041. * @const {!RegExp}
  3042. * @private
  3043. */
  3044. goog.string.NULL_RE_ = /\x00/g;
  3045. /**
  3046. * Regular expression that matches a lowercase letter "e", for use in escaping.
  3047. * @const {!RegExp}
  3048. * @private
  3049. */
  3050. goog.string.E_RE_ = /e/g;
  3051. /**
  3052. * Regular expression that matches any character that needs to be escaped.
  3053. * @const {!RegExp}
  3054. * @private
  3055. */
  3056. goog.string.ALL_RE_ = (goog.string.DETECT_DOUBLE_ESCAPING ?
  3057. /[\x00&<>"'e]/ :
  3058. /[\x00&<>"']/);
  3059. /**
  3060. * Unescapes an HTML string.
  3061. *
  3062. * @param {string} str The string to unescape.
  3063. * @return {string} An unescaped copy of {@code str}.
  3064. */
  3065. goog.string.unescapeEntities = function(str) {
  3066. if (goog.string.contains(str, '&')) {
  3067. // We are careful not to use a DOM if we do not have one or we explicitly
  3068. // requested non-DOM html unescaping.
  3069. if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&
  3070. 'document' in goog.global) {
  3071. return goog.string.unescapeEntitiesUsingDom_(str);
  3072. } else {
  3073. // Fall back on pure XML entities
  3074. return goog.string.unescapePureXmlEntities_(str);
  3075. }
  3076. }
  3077. return str;
  3078. };
  3079. /**
  3080. * Unescapes a HTML string using the provided document.
  3081. *
  3082. * @param {string} str The string to unescape.
  3083. * @param {!Document} document A document to use in escaping the string.
  3084. * @return {string} An unescaped copy of {@code str}.
  3085. */
  3086. goog.string.unescapeEntitiesWithDocument = function(str, document) {
  3087. if (goog.string.contains(str, '&')) {
  3088. return goog.string.unescapeEntitiesUsingDom_(str, document);
  3089. }
  3090. return str;
  3091. };
  3092. /**
  3093. * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric
  3094. * entities. This function is XSS-safe and whitespace-preserving.
  3095. * @private
  3096. * @param {string} str The string to unescape.
  3097. * @param {Document=} opt_document An optional document to use for creating
  3098. * elements. If this is not specified then the default window.document
  3099. * will be used.
  3100. * @return {string} The unescaped {@code str} string.
  3101. */
  3102. goog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {
  3103. /** @type {!Object<string, string>} */
  3104. var seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"'};
  3105. var div;
  3106. if (opt_document) {
  3107. div = opt_document.createElement('div');
  3108. } else {
  3109. div = goog.global.document.createElement('div');
  3110. }
  3111. // Match as many valid entity characters as possible. If the actual entity
  3112. // happens to be shorter, it will still work as innerHTML will return the
  3113. // trailing characters unchanged. Since the entity characters do not include
  3114. // open angle bracket, there is no chance of XSS from the innerHTML use.
  3115. // Since no whitespace is passed to innerHTML, whitespace is preserved.
  3116. return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {
  3117. // Check for cached entity.
  3118. var value = seen[s];
  3119. if (value) {
  3120. return value;
  3121. }
  3122. // Check for numeric entity.
  3123. if (entity.charAt(0) == '#') {
  3124. // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.
  3125. var n = Number('0' + entity.substr(1));
  3126. if (!isNaN(n)) {
  3127. value = String.fromCharCode(n);
  3128. }
  3129. }
  3130. // Fall back to innerHTML otherwise.
  3131. if (!value) {
  3132. // Append a non-entity character to avoid a bug in Webkit that parses
  3133. // an invalid entity at the end of innerHTML text as the empty string.
  3134. div.innerHTML = s + ' ';
  3135. // Then remove the trailing character from the result.
  3136. value = div.firstChild.nodeValue.slice(0, -1);
  3137. }
  3138. // Cache and return.
  3139. return seen[s] = value;
  3140. });
  3141. };
  3142. /**
  3143. * Unescapes XML entities.
  3144. * @private
  3145. * @param {string} str The string to unescape.
  3146. * @return {string} An unescaped copy of {@code str}.
  3147. */
  3148. goog.string.unescapePureXmlEntities_ = function(str) {
  3149. return str.replace(/&([^;]+);/g, function(s, entity) {
  3150. switch (entity) {
  3151. case 'amp':
  3152. return '&';
  3153. case 'lt':
  3154. return '<';
  3155. case 'gt':
  3156. return '>';
  3157. case 'quot':
  3158. return '"';
  3159. default:
  3160. if (entity.charAt(0) == '#') {
  3161. // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.
  3162. var n = Number('0' + entity.substr(1));
  3163. if (!isNaN(n)) {
  3164. return String.fromCharCode(n);
  3165. }
  3166. }
  3167. // For invalid entities we just return the entity
  3168. return s;
  3169. }
  3170. });
  3171. };
  3172. /**
  3173. * Regular expression that matches an HTML entity.
  3174. * See also HTML5: Tokenization / Tokenizing character references.
  3175. * @private
  3176. * @type {!RegExp}
  3177. */
  3178. goog.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g;
  3179. /**
  3180. * Do escaping of whitespace to preserve spatial formatting. We use character
  3181. * entity #160 to make it safer for xml.
  3182. * @param {string} str The string in which to escape whitespace.
  3183. * @param {boolean=} opt_xml Whether to use XML compatible tags.
  3184. * @return {string} An escaped copy of {@code str}.
  3185. */
  3186. goog.string.whitespaceEscape = function(str, opt_xml) {
  3187. // This doesn't use goog.string.preserveSpaces for backwards compatibility.
  3188. return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);
  3189. };
  3190. /**
  3191. * Preserve spaces that would be otherwise collapsed in HTML by replacing them
  3192. * with non-breaking space Unicode characters.
  3193. * @param {string} str The string in which to preserve whitespace.
  3194. * @return {string} A copy of {@code str} with preserved whitespace.
  3195. */
  3196. goog.string.preserveSpaces = function(str) {
  3197. return str.replace(/(^|[\n ]) /g, '$1' + goog.string.Unicode.NBSP);
  3198. };
  3199. /**
  3200. * Strip quote characters around a string. The second argument is a string of
  3201. * characters to treat as quotes. This can be a single character or a string of
  3202. * multiple character and in that case each of those are treated as possible
  3203. * quote characters. For example:
  3204. *
  3205. * <pre>
  3206. * goog.string.stripQuotes('"abc"', '"`') --> 'abc'
  3207. * goog.string.stripQuotes('`abc`', '"`') --> 'abc'
  3208. * </pre>
  3209. *
  3210. * @param {string} str The string to strip.
  3211. * @param {string} quoteChars The quote characters to strip.
  3212. * @return {string} A copy of {@code str} without the quotes.
  3213. */
  3214. goog.string.stripQuotes = function(str, quoteChars) {
  3215. var length = quoteChars.length;
  3216. for (var i = 0; i < length; i++) {
  3217. var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);
  3218. if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {
  3219. return str.substring(1, str.length - 1);
  3220. }
  3221. }
  3222. return str;
  3223. };
  3224. /**
  3225. * Truncates a string to a certain length and adds '...' if necessary. The
  3226. * length also accounts for the ellipsis, so a maximum length of 10 and a string
  3227. * 'Hello World!' produces 'Hello W...'.
  3228. * @param {string} str The string to truncate.
  3229. * @param {number} chars Max number of characters.
  3230. * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped
  3231. * characters from being cut off in the middle.
  3232. * @return {string} The truncated {@code str} string.
  3233. */
  3234. goog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {
  3235. if (opt_protectEscapedCharacters) {
  3236. str = goog.string.unescapeEntities(str);
  3237. }
  3238. if (str.length > chars) {
  3239. str = str.substring(0, chars - 3) + '...';
  3240. }
  3241. if (opt_protectEscapedCharacters) {
  3242. str = goog.string.htmlEscape(str);
  3243. }
  3244. return str;
  3245. };
  3246. /**
  3247. * Truncate a string in the middle, adding "..." if necessary,
  3248. * and favoring the beginning of the string.
  3249. * @param {string} str The string to truncate the middle of.
  3250. * @param {number} chars Max number of characters.
  3251. * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped
  3252. * characters from being cutoff in the middle.
  3253. * @param {number=} opt_trailingChars Optional number of trailing characters to
  3254. * leave at the end of the string, instead of truncating as close to the
  3255. * middle as possible.
  3256. * @return {string} A truncated copy of {@code str}.
  3257. */
  3258. goog.string.truncateMiddle = function(str, chars,
  3259. opt_protectEscapedCharacters, opt_trailingChars) {
  3260. if (opt_protectEscapedCharacters) {
  3261. str = goog.string.unescapeEntities(str);
  3262. }
  3263. if (opt_trailingChars && str.length > chars) {
  3264. if (opt_trailingChars > chars) {
  3265. opt_trailingChars = chars;
  3266. }
  3267. var endPoint = str.length - opt_trailingChars;
  3268. var startPoint = chars - opt_trailingChars;
  3269. str = str.substring(0, startPoint) + '...' + str.substring(endPoint);
  3270. } else if (str.length > chars) {
  3271. // Favor the beginning of the string:
  3272. var half = Math.floor(chars / 2);
  3273. var endPos = str.length - half;
  3274. half += chars % 2;
  3275. str = str.substring(0, half) + '...' + str.substring(endPos);
  3276. }
  3277. if (opt_protectEscapedCharacters) {
  3278. str = goog.string.htmlEscape(str);
  3279. }
  3280. return str;
  3281. };
  3282. /**
  3283. * Special chars that need to be escaped for goog.string.quote.
  3284. * @private {!Object<string, string>}
  3285. */
  3286. goog.string.specialEscapeChars_ = {
  3287. '\0': '\\0',
  3288. '\b': '\\b',
  3289. '\f': '\\f',
  3290. '\n': '\\n',
  3291. '\r': '\\r',
  3292. '\t': '\\t',
  3293. '\x0B': '\\x0B', // '\v' is not supported in JScript
  3294. '"': '\\"',
  3295. '\\': '\\\\'
  3296. };
  3297. /**
  3298. * Character mappings used internally for goog.string.escapeChar.
  3299. * @private {!Object<string, string>}
  3300. */
  3301. goog.string.jsEscapeCache_ = {
  3302. '\'': '\\\''
  3303. };
  3304. /**
  3305. * Encloses a string in double quotes and escapes characters so that the
  3306. * string is a valid JS string.
  3307. * @param {string} s The string to quote.
  3308. * @return {string} A copy of {@code s} surrounded by double quotes.
  3309. */
  3310. goog.string.quote = function(s) {
  3311. s = String(s);
  3312. if (s.quote) {
  3313. return s.quote();
  3314. } else {
  3315. var sb = ['"'];
  3316. for (var i = 0; i < s.length; i++) {
  3317. var ch = s.charAt(i);
  3318. var cc = ch.charCodeAt(0);
  3319. sb[i + 1] = goog.string.specialEscapeChars_[ch] ||
  3320. ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));
  3321. }
  3322. sb.push('"');
  3323. return sb.join('');
  3324. }
  3325. };
  3326. /**
  3327. * Takes a string and returns the escaped string for that character.
  3328. * @param {string} str The string to escape.
  3329. * @return {string} An escaped string representing {@code str}.
  3330. */
  3331. goog.string.escapeString = function(str) {
  3332. var sb = [];
  3333. for (var i = 0; i < str.length; i++) {
  3334. sb[i] = goog.string.escapeChar(str.charAt(i));
  3335. }
  3336. return sb.join('');
  3337. };
  3338. /**
  3339. * Takes a character and returns the escaped string for that character. For
  3340. * example escapeChar(String.fromCharCode(15)) -> "\\x0E".
  3341. * @param {string} c The character to escape.
  3342. * @return {string} An escaped string representing {@code c}.
  3343. */
  3344. goog.string.escapeChar = function(c) {
  3345. if (c in goog.string.jsEscapeCache_) {
  3346. return goog.string.jsEscapeCache_[c];
  3347. }
  3348. if (c in goog.string.specialEscapeChars_) {
  3349. return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];
  3350. }
  3351. var rv = c;
  3352. var cc = c.charCodeAt(0);
  3353. if (cc > 31 && cc < 127) {
  3354. rv = c;
  3355. } else {
  3356. // tab is 9 but handled above
  3357. if (cc < 256) {
  3358. rv = '\\x';
  3359. if (cc < 16 || cc > 256) {
  3360. rv += '0';
  3361. }
  3362. } else {
  3363. rv = '\\u';
  3364. if (cc < 4096) { // \u1000
  3365. rv += '0';
  3366. }
  3367. }
  3368. rv += cc.toString(16).toUpperCase();
  3369. }
  3370. return goog.string.jsEscapeCache_[c] = rv;
  3371. };
  3372. /**
  3373. * Determines whether a string contains a substring.
  3374. * @param {string} str The string to search.
  3375. * @param {string} subString The substring to search for.
  3376. * @return {boolean} Whether {@code str} contains {@code subString}.
  3377. */
  3378. goog.string.contains = function(str, subString) {
  3379. return str.indexOf(subString) != -1;
  3380. };
  3381. /**
  3382. * Determines whether a string contains a substring, ignoring case.
  3383. * @param {string} str The string to search.
  3384. * @param {string} subString The substring to search for.
  3385. * @return {boolean} Whether {@code str} contains {@code subString}.
  3386. */
  3387. goog.string.caseInsensitiveContains = function(str, subString) {
  3388. return goog.string.contains(str.toLowerCase(), subString.toLowerCase());
  3389. };
  3390. /**
  3391. * Returns the non-overlapping occurrences of ss in s.
  3392. * If either s or ss evalutes to false, then returns zero.
  3393. * @param {string} s The string to look in.
  3394. * @param {string} ss The string to look for.
  3395. * @return {number} Number of occurrences of ss in s.
  3396. */
  3397. goog.string.countOf = function(s, ss) {
  3398. return s && ss ? s.split(ss).length - 1 : 0;
  3399. };
  3400. /**
  3401. * Removes a substring of a specified length at a specific
  3402. * index in a string.
  3403. * @param {string} s The base string from which to remove.
  3404. * @param {number} index The index at which to remove the substring.
  3405. * @param {number} stringLength The length of the substring to remove.
  3406. * @return {string} A copy of {@code s} with the substring removed or the full
  3407. * string if nothing is removed or the input is invalid.
  3408. */
  3409. goog.string.removeAt = function(s, index, stringLength) {
  3410. var resultStr = s;
  3411. // If the index is greater or equal to 0 then remove substring
  3412. if (index >= 0 && index < s.length && stringLength > 0) {
  3413. resultStr = s.substr(0, index) +
  3414. s.substr(index + stringLength, s.length - index - stringLength);
  3415. }
  3416. return resultStr;
  3417. };
  3418. /**
  3419. * Removes the first occurrence of a substring from a string.
  3420. * @param {string} s The base string from which to remove.
  3421. * @param {string} ss The string to remove.
  3422. * @return {string} A copy of {@code s} with {@code ss} removed or the full
  3423. * string if nothing is removed.
  3424. */
  3425. goog.string.remove = function(s, ss) {
  3426. var re = new RegExp(goog.string.regExpEscape(ss), '');
  3427. return s.replace(re, '');
  3428. };
  3429. /**
  3430. * Removes all occurrences of a substring from a string.
  3431. * @param {string} s The base string from which to remove.
  3432. * @param {string} ss The string to remove.
  3433. * @return {string} A copy of {@code s} with {@code ss} removed or the full
  3434. * string if nothing is removed.
  3435. */
  3436. goog.string.removeAll = function(s, ss) {
  3437. var re = new RegExp(goog.string.regExpEscape(ss), 'g');
  3438. return s.replace(re, '');
  3439. };
  3440. /**
  3441. * Escapes characters in the string that are not safe to use in a RegExp.
  3442. * @param {*} s The string to escape. If not a string, it will be casted
  3443. * to one.
  3444. * @return {string} A RegExp safe, escaped copy of {@code s}.
  3445. */
  3446. goog.string.regExpEscape = function(s) {
  3447. return String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  3448. replace(/\x08/g, '\\x08');
  3449. };
  3450. /**
  3451. * Repeats a string n times.
  3452. * @param {string} string The string to repeat.
  3453. * @param {number} length The number of times to repeat.
  3454. * @return {string} A string containing {@code length} repetitions of
  3455. * {@code string}.
  3456. */
  3457. goog.string.repeat = (String.prototype.repeat) ?
  3458. function(string, length) {
  3459. // The native method is over 100 times faster than the alternative.
  3460. return string.repeat(length);
  3461. } :
  3462. function(string, length) {
  3463. return new Array(length + 1).join(string);
  3464. };
  3465. /**
  3466. * Pads number to given length and optionally rounds it to a given precision.
  3467. * For example:
  3468. * <pre>padNumber(1.25, 2, 3) -> '01.250'
  3469. * padNumber(1.25, 2) -> '01.25'
  3470. * padNumber(1.25, 2, 1) -> '01.3'
  3471. * padNumber(1.25, 0) -> '1.25'</pre>
  3472. *
  3473. * @param {number} num The number to pad.
  3474. * @param {number} length The desired length.
  3475. * @param {number=} opt_precision The desired precision.
  3476. * @return {string} {@code num} as a string with the given options.
  3477. */
  3478. goog.string.padNumber = function(num, length, opt_precision) {
  3479. var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num);
  3480. var index = s.indexOf('.');
  3481. if (index == -1) {
  3482. index = s.length;
  3483. }
  3484. return goog.string.repeat('0', Math.max(0, length - index)) + s;
  3485. };
  3486. /**
  3487. * Returns a string representation of the given object, with
  3488. * null and undefined being returned as the empty string.
  3489. *
  3490. * @param {*} obj The object to convert.
  3491. * @return {string} A string representation of the {@code obj}.
  3492. */
  3493. goog.string.makeSafe = function(obj) {
  3494. return obj == null ? '' : String(obj);
  3495. };
  3496. /**
  3497. * Concatenates string expressions. This is useful
  3498. * since some browsers are very inefficient when it comes to using plus to
  3499. * concat strings. Be careful when using null and undefined here since
  3500. * these will not be included in the result. If you need to represent these
  3501. * be sure to cast the argument to a String first.
  3502. * For example:
  3503. * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd'
  3504. * buildString(null, undefined) -> ''
  3505. * </pre>
  3506. * @param {...*} var_args A list of strings to concatenate. If not a string,
  3507. * it will be casted to one.
  3508. * @return {string} The concatenation of {@code var_args}.
  3509. */
  3510. goog.string.buildString = function(var_args) {
  3511. return Array.prototype.join.call(arguments, '');
  3512. };
  3513. /**
  3514. * Returns a string with at least 64-bits of randomness.
  3515. *
  3516. * Doesn't trust Javascript's random function entirely. Uses a combination of
  3517. * random and current timestamp, and then encodes the string in base-36 to
  3518. * make it shorter.
  3519. *
  3520. * @return {string} A random string, e.g. sn1s7vb4gcic.
  3521. */
  3522. goog.string.getRandomString = function() {
  3523. var x = 2147483648;
  3524. return Math.floor(Math.random() * x).toString(36) +
  3525. Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);
  3526. };
  3527. /**
  3528. * Compares two version numbers.
  3529. *
  3530. * @param {string|number} version1 Version of first item.
  3531. * @param {string|number} version2 Version of second item.
  3532. *
  3533. * @return {number} 1 if {@code version1} is higher.
  3534. * 0 if arguments are equal.
  3535. * -1 if {@code version2} is higher.
  3536. */
  3537. goog.string.compareVersions = function(version1, version2) {
  3538. var order = 0;
  3539. // Trim leading and trailing whitespace and split the versions into
  3540. // subversions.
  3541. var v1Subs = goog.string.trim(String(version1)).split('.');
  3542. var v2Subs = goog.string.trim(String(version2)).split('.');
  3543. var subCount = Math.max(v1Subs.length, v2Subs.length);
  3544. // Iterate over the subversions, as long as they appear to be equivalent.
  3545. for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {
  3546. var v1Sub = v1Subs[subIdx] || '';
  3547. var v2Sub = v2Subs[subIdx] || '';
  3548. // Split the subversions into pairs of numbers and qualifiers (like 'b').
  3549. // Two different RegExp objects are needed because they are both using
  3550. // the 'g' flag.
  3551. var v1CompParser = new RegExp('(\\d*)(\\D*)', 'g');
  3552. var v2CompParser = new RegExp('(\\d*)(\\D*)', 'g');
  3553. do {
  3554. var v1Comp = v1CompParser.exec(v1Sub) || ['', '', ''];
  3555. var v2Comp = v2CompParser.exec(v2Sub) || ['', '', ''];
  3556. // Break if there are no more matches.
  3557. if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {
  3558. break;
  3559. }
  3560. // Parse the numeric part of the subversion. A missing number is
  3561. // equivalent to 0.
  3562. var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);
  3563. var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);
  3564. // Compare the subversion components. The number has the highest
  3565. // precedence. Next, if the numbers are equal, a subversion without any
  3566. // qualifier is always higher than a subversion with any qualifier. Next,
  3567. // the qualifiers are compared as strings.
  3568. order = goog.string.compareElements_(v1CompNum, v2CompNum) ||
  3569. goog.string.compareElements_(v1Comp[2].length == 0,
  3570. v2Comp[2].length == 0) ||
  3571. goog.string.compareElements_(v1Comp[2], v2Comp[2]);
  3572. // Stop as soon as an inequality is discovered.
  3573. } while (order == 0);
  3574. }
  3575. return order;
  3576. };
  3577. /**
  3578. * Compares elements of a version number.
  3579. *
  3580. * @param {string|number|boolean} left An element from a version number.
  3581. * @param {string|number|boolean} right An element from a version number.
  3582. *
  3583. * @return {number} 1 if {@code left} is higher.
  3584. * 0 if arguments are equal.
  3585. * -1 if {@code right} is higher.
  3586. * @private
  3587. */
  3588. goog.string.compareElements_ = function(left, right) {
  3589. if (left < right) {
  3590. return -1;
  3591. } else if (left > right) {
  3592. return 1;
  3593. }
  3594. return 0;
  3595. };
  3596. /**
  3597. * String hash function similar to java.lang.String.hashCode().
  3598. * The hash code for a string is computed as
  3599. * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  3600. * where s[i] is the ith character of the string and n is the length of
  3601. * the string. We mod the result to make it between 0 (inclusive) and 2^32
  3602. * (exclusive).
  3603. * @param {string} str A string.
  3604. * @return {number} Hash value for {@code str}, between 0 (inclusive) and 2^32
  3605. * (exclusive). The empty string returns 0.
  3606. */
  3607. goog.string.hashCode = function(str) {
  3608. var result = 0;
  3609. for (var i = 0; i < str.length; ++i) {
  3610. // Normalize to 4 byte range, 0 ... 2^32.
  3611. result = (31 * result + str.charCodeAt(i)) >>> 0;
  3612. }
  3613. return result;
  3614. };
  3615. /**
  3616. * The most recent unique ID. |0 is equivalent to Math.floor in this case.
  3617. * @type {number}
  3618. * @private
  3619. */
  3620. goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;
  3621. /**
  3622. * Generates and returns a string which is unique in the current document.
  3623. * This is useful, for example, to create unique IDs for DOM elements.
  3624. * @return {string} A unique id.
  3625. */
  3626. goog.string.createUniqueString = function() {
  3627. return 'goog_' + goog.string.uniqueStringCounter_++;
  3628. };
  3629. /**
  3630. * Converts the supplied string to a number, which may be Infinity or NaN.
  3631. * This function strips whitespace: (toNumber(' 123') === 123)
  3632. * This function accepts scientific notation: (toNumber('1e1') === 10)
  3633. *
  3634. * This is better than Javascript's built-in conversions because, sadly:
  3635. * (Number(' ') === 0) and (parseFloat('123a') === 123)
  3636. *
  3637. * @param {string} str The string to convert.
  3638. * @return {number} The number the supplied string represents, or NaN.
  3639. */
  3640. goog.string.toNumber = function(str) {
  3641. var num = Number(str);
  3642. if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {
  3643. return NaN;
  3644. }
  3645. return num;
  3646. };
  3647. /**
  3648. * Returns whether the given string is lower camel case (e.g. "isFooBar").
  3649. *
  3650. * Note that this assumes the string is entirely letters.
  3651. * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms
  3652. *
  3653. * @param {string} str String to test.
  3654. * @return {boolean} Whether the string is lower camel case.
  3655. */
  3656. goog.string.isLowerCamelCase = function(str) {
  3657. return /^[a-z]+([A-Z][a-z]*)*$/.test(str);
  3658. };
  3659. /**
  3660. * Returns whether the given string is upper camel case (e.g. "FooBarBaz").
  3661. *
  3662. * Note that this assumes the string is entirely letters.
  3663. * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms
  3664. *
  3665. * @param {string} str String to test.
  3666. * @return {boolean} Whether the string is upper camel case.
  3667. */
  3668. goog.string.isUpperCamelCase = function(str) {
  3669. return /^([A-Z][a-z]*)+$/.test(str);
  3670. };
  3671. /**
  3672. * Converts a string from selector-case to camelCase (e.g. from
  3673. * "multi-part-string" to "multiPartString"), useful for converting
  3674. * CSS selectors and HTML dataset keys to their equivalent JS properties.
  3675. * @param {string} str The string in selector-case form.
  3676. * @return {string} The string in camelCase form.
  3677. */
  3678. goog.string.toCamelCase = function(str) {
  3679. return String(str).replace(/\-([a-z])/g, function(all, match) {
  3680. return match.toUpperCase();
  3681. });
  3682. };
  3683. /**
  3684. * Converts a string from camelCase to selector-case (e.g. from
  3685. * "multiPartString" to "multi-part-string"), useful for converting JS
  3686. * style and dataset properties to equivalent CSS selectors and HTML keys.
  3687. * @param {string} str The string in camelCase form.
  3688. * @return {string} The string in selector-case form.
  3689. */
  3690. goog.string.toSelectorCase = function(str) {
  3691. return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();
  3692. };
  3693. /**
  3694. * Converts a string into TitleCase. First character of the string is always
  3695. * capitalized in addition to the first letter of every subsequent word.
  3696. * Words are delimited by one or more whitespaces by default. Custom delimiters
  3697. * can optionally be specified to replace the default, which doesn't preserve
  3698. * whitespace delimiters and instead must be explicitly included if needed.
  3699. *
  3700. * Default delimiter => " ":
  3701. * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'
  3702. * goog.string.toTitleCase('one two three') => 'One Two Three'
  3703. * goog.string.toTitleCase(' one two ') => ' One Two '
  3704. * goog.string.toTitleCase('one_two_three') => 'One_two_three'
  3705. * goog.string.toTitleCase('one-two-three') => 'One-two-three'
  3706. *
  3707. * Custom delimiter => "_-.":
  3708. * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'
  3709. * goog.string.toTitleCase('one two three', '_-.') => 'One two three'
  3710. * goog.string.toTitleCase(' one two ', '_-.') => ' one two '
  3711. * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'
  3712. * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'
  3713. * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'
  3714. * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'
  3715. * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'
  3716. *
  3717. * @param {string} str String value in camelCase form.
  3718. * @param {string=} opt_delimiters Custom delimiter character set used to
  3719. * distinguish words in the string value. Each character represents a
  3720. * single delimiter. When provided, default whitespace delimiter is
  3721. * overridden and must be explicitly included if needed.
  3722. * @return {string} String value in TitleCase form.
  3723. */
  3724. goog.string.toTitleCase = function(str, opt_delimiters) {
  3725. var delimiters = goog.isString(opt_delimiters) ?
  3726. goog.string.regExpEscape(opt_delimiters) : '\\s';
  3727. // For IE8, we need to prevent using an empty character set. Otherwise,
  3728. // incorrect matching will occur.
  3729. delimiters = delimiters ? '|[' + delimiters + ']+' : '';
  3730. var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');
  3731. return str.replace(regexp, function(all, p1, p2) {
  3732. return p1 + p2.toUpperCase();
  3733. });
  3734. };
  3735. /**
  3736. * Capitalizes a string, i.e. converts the first letter to uppercase
  3737. * and all other letters to lowercase, e.g.:
  3738. *
  3739. * goog.string.capitalize('one') => 'One'
  3740. * goog.string.capitalize('ONE') => 'One'
  3741. * goog.string.capitalize('one two') => 'One two'
  3742. *
  3743. * Note that this function does not trim initial whitespace.
  3744. *
  3745. * @param {string} str String value to capitalize.
  3746. * @return {string} String value with first letter in uppercase.
  3747. */
  3748. goog.string.capitalize = function(str) {
  3749. return String(str.charAt(0)).toUpperCase() +
  3750. String(str.substr(1)).toLowerCase();
  3751. };
  3752. /**
  3753. * Parse a string in decimal or hexidecimal ('0xFFFF') form.
  3754. *
  3755. * To parse a particular radix, please use parseInt(string, radix) directly. See
  3756. * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt
  3757. *
  3758. * This is a wrapper for the built-in parseInt function that will only parse
  3759. * numbers as base 10 or base 16. Some JS implementations assume strings
  3760. * starting with "0" are intended to be octal. ES3 allowed but discouraged
  3761. * this behavior. ES5 forbids it. This function emulates the ES5 behavior.
  3762. *
  3763. * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj
  3764. *
  3765. * @param {string|number|null|undefined} value The value to be parsed.
  3766. * @return {number} The number, parsed. If the string failed to parse, this
  3767. * will be NaN.
  3768. */
  3769. goog.string.parseInt = function(value) {
  3770. // Force finite numbers to strings.
  3771. if (isFinite(value)) {
  3772. value = String(value);
  3773. }
  3774. if (goog.isString(value)) {
  3775. // If the string starts with '0x' or '-0x', parse as hex.
  3776. return /^\s*-?0x/i.test(value) ?
  3777. parseInt(value, 16) : parseInt(value, 10);
  3778. }
  3779. return NaN;
  3780. };
  3781. /**
  3782. * Splits a string on a separator a limited number of times.
  3783. *
  3784. * This implementation is more similar to Python or Java, where the limit
  3785. * parameter specifies the maximum number of splits rather than truncating
  3786. * the number of results.
  3787. *
  3788. * See http://docs.python.org/2/library/stdtypes.html#str.split
  3789. * See JavaDoc: http://goo.gl/F2AsY
  3790. * See Mozilla reference: http://goo.gl/dZdZs
  3791. *
  3792. * @param {string} str String to split.
  3793. * @param {string} separator The separator.
  3794. * @param {number} limit The limit to the number of splits. The resulting array
  3795. * will have a maximum length of limit+1. Negative numbers are the same
  3796. * as zero.
  3797. * @return {!Array<string>} The string, split.
  3798. */
  3799. goog.string.splitLimit = function(str, separator, limit) {
  3800. var parts = str.split(separator);
  3801. var returnVal = [];
  3802. // Only continue doing this while we haven't hit the limit and we have
  3803. // parts left.
  3804. while (limit > 0 && parts.length) {
  3805. returnVal.push(parts.shift());
  3806. limit--;
  3807. }
  3808. // If there are remaining parts, append them to the end.
  3809. if (parts.length) {
  3810. returnVal.push(parts.join(separator));
  3811. }
  3812. return returnVal;
  3813. };
  3814. /**
  3815. * Computes the Levenshtein edit distance between two strings.
  3816. * @param {string} a
  3817. * @param {string} b
  3818. * @return {number} The edit distance between the two strings.
  3819. */
  3820. goog.string.editDistance = function(a, b) {
  3821. var v0 = [];
  3822. var v1 = [];
  3823. if (a == b) {
  3824. return 0;
  3825. }
  3826. if (!a.length || !b.length) {
  3827. return Math.max(a.length, b.length);
  3828. }
  3829. for (var i = 0; i < b.length + 1; i++) {
  3830. v0[i] = i;
  3831. }
  3832. for (var i = 0; i < a.length; i++) {
  3833. v1[0] = i + 1;
  3834. for (var j = 0; j < b.length; j++) {
  3835. var cost = a[i] != b[j];
  3836. // Cost for the substring is the minimum of adding one character, removing
  3837. // one character, or a swap.
  3838. v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);
  3839. }
  3840. for (var j = 0; j < v0.length; j++) {
  3841. v0[j] = v1[j];
  3842. }
  3843. }
  3844. return v1[b.length];
  3845. };
  3846. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  3847. //
  3848. // Licensed under the Apache License, Version 2.0 (the "License");
  3849. // you may not use this file except in compliance with the License.
  3850. // You may obtain a copy of the License at
  3851. //
  3852. // http://www.apache.org/licenses/LICENSE-2.0
  3853. //
  3854. // Unless required by applicable law or agreed to in writing, software
  3855. // distributed under the License is distributed on an "AS-IS" BASIS,
  3856. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3857. // See the License for the specific language governing permissions and
  3858. // limitations under the License.
  3859. /**
  3860. * @fileoverview Utilities to check the preconditions, postconditions and
  3861. * invariants runtime.
  3862. *
  3863. * Methods in this package should be given special treatment by the compiler
  3864. * for type-inference. For example, <code>goog.asserts.assert(foo)</code>
  3865. * will restrict <code>foo</code> to a truthy value.
  3866. *
  3867. * The compiler has an option to disable asserts. So code like:
  3868. * <code>
  3869. * var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());
  3870. * </code>
  3871. * will be transformed into:
  3872. * <code>
  3873. * var x = foo();
  3874. * </code>
  3875. * The compiler will leave in foo() (because its return value is used),
  3876. * but it will remove bar() because it assumes it does not have side-effects.
  3877. *
  3878. * @author agrieve@google.com (Andrew Grieve)
  3879. */
  3880. goog.provide('goog.asserts');
  3881. goog.provide('goog.asserts.AssertionError');
  3882. goog.require('goog.debug.Error');
  3883. goog.require('goog.dom.NodeType');
  3884. goog.require('goog.string');
  3885. /**
  3886. * @define {boolean} Whether to strip out asserts or to leave them in.
  3887. */
  3888. goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);
  3889. /**
  3890. * Error object for failed assertions.
  3891. * @param {string} messagePattern The pattern that was used to form message.
  3892. * @param {!Array<*>} messageArgs The items to substitute into the pattern.
  3893. * @constructor
  3894. * @extends {goog.debug.Error}
  3895. * @final
  3896. */
  3897. goog.asserts.AssertionError = function(messagePattern, messageArgs) {
  3898. messageArgs.unshift(messagePattern);
  3899. goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));
  3900. // Remove the messagePattern afterwards to avoid permanently modifying the
  3901. // passed in array.
  3902. messageArgs.shift();
  3903. /**
  3904. * The message pattern used to format the error message. Error handlers can
  3905. * use this to uniquely identify the assertion.
  3906. * @type {string}
  3907. */
  3908. this.messagePattern = messagePattern;
  3909. };
  3910. goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
  3911. /** @override */
  3912. goog.asserts.AssertionError.prototype.name = 'AssertionError';
  3913. /**
  3914. * The default error handler.
  3915. * @param {!goog.asserts.AssertionError} e The exception to be handled.
  3916. */
  3917. goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; };
  3918. /**
  3919. * The handler responsible for throwing or logging assertion errors.
  3920. * @private {function(!goog.asserts.AssertionError)}
  3921. */
  3922. goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;
  3923. /**
  3924. * Throws an exception with the given message and "Assertion failed" prefixed
  3925. * onto it.
  3926. * @param {string} defaultMessage The message to use if givenMessage is empty.
  3927. * @param {Array<*>} defaultArgs The substitution arguments for defaultMessage.
  3928. * @param {string|undefined} givenMessage Message supplied by the caller.
  3929. * @param {Array<*>} givenArgs The substitution arguments for givenMessage.
  3930. * @throws {goog.asserts.AssertionError} When the value is not a number.
  3931. * @private
  3932. */
  3933. goog.asserts.doAssertFailure_ =
  3934. function(defaultMessage, defaultArgs, givenMessage, givenArgs) {
  3935. var message = 'Assertion failed';
  3936. if (givenMessage) {
  3937. message += ': ' + givenMessage;
  3938. var args = givenArgs;
  3939. } else if (defaultMessage) {
  3940. message += ': ' + defaultMessage;
  3941. args = defaultArgs;
  3942. }
  3943. // The '' + works around an Opera 10 bug in the unit tests. Without it,
  3944. // a stack trace is added to var message above. With this, a stack trace is
  3945. // not added until this line (it causes the extra garbage to be added after
  3946. // the assertion message instead of in the middle of it).
  3947. var e = new goog.asserts.AssertionError('' + message, args || []);
  3948. goog.asserts.errorHandler_(e);
  3949. };
  3950. /**
  3951. * Sets a custom error handler that can be used to customize the behavior of
  3952. * assertion failures, for example by turning all assertion failures into log
  3953. * messages.
  3954. * @param {function(!goog.asserts.AssertionError)} errorHandler
  3955. */
  3956. goog.asserts.setErrorHandler = function(errorHandler) {
  3957. if (goog.asserts.ENABLE_ASSERTS) {
  3958. goog.asserts.errorHandler_ = errorHandler;
  3959. }
  3960. };
  3961. /**
  3962. * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is
  3963. * true.
  3964. * @template T
  3965. * @param {T} condition The condition to check.
  3966. * @param {string=} opt_message Error message in case of failure.
  3967. * @param {...*} var_args The items to substitute into the failure message.
  3968. * @return {T} The value of the condition.
  3969. * @throws {goog.asserts.AssertionError} When the condition evaluates to false.
  3970. */
  3971. goog.asserts.assert = function(condition, opt_message, var_args) {
  3972. if (goog.asserts.ENABLE_ASSERTS && !condition) {
  3973. goog.asserts.doAssertFailure_('', null, opt_message,
  3974. Array.prototype.slice.call(arguments, 2));
  3975. }
  3976. return condition;
  3977. };
  3978. /**
  3979. * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case
  3980. * when we want to add a check in the unreachable area like switch-case
  3981. * statement:
  3982. *
  3983. * <pre>
  3984. * switch(type) {
  3985. * case FOO: doSomething(); break;
  3986. * case BAR: doSomethingElse(); break;
  3987. * default: goog.assert.fail('Unrecognized type: ' + type);
  3988. * // We have only 2 types - "default:" section is unreachable code.
  3989. * }
  3990. * </pre>
  3991. *
  3992. * @param {string=} opt_message Error message in case of failure.
  3993. * @param {...*} var_args The items to substitute into the failure message.
  3994. * @throws {goog.asserts.AssertionError} Failure.
  3995. */
  3996. goog.asserts.fail = function(opt_message, var_args) {
  3997. if (goog.asserts.ENABLE_ASSERTS) {
  3998. goog.asserts.errorHandler_(new goog.asserts.AssertionError(
  3999. 'Failure' + (opt_message ? ': ' + opt_message : ''),
  4000. Array.prototype.slice.call(arguments, 1)));
  4001. }
  4002. };
  4003. /**
  4004. * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.
  4005. * @param {*} value The value to check.
  4006. * @param {string=} opt_message Error message in case of failure.
  4007. * @param {...*} var_args The items to substitute into the failure message.
  4008. * @return {number} The value, guaranteed to be a number when asserts enabled.
  4009. * @throws {goog.asserts.AssertionError} When the value is not a number.
  4010. */
  4011. goog.asserts.assertNumber = function(value, opt_message, var_args) {
  4012. if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {
  4013. goog.asserts.doAssertFailure_('Expected number but got %s: %s.',
  4014. [goog.typeOf(value), value], opt_message,
  4015. Array.prototype.slice.call(arguments, 2));
  4016. }
  4017. return /** @type {number} */ (value);
  4018. };
  4019. /**
  4020. * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.
  4021. * @param {*} value The value to check.
  4022. * @param {string=} opt_message Error message in case of failure.
  4023. * @param {...*} var_args The items to substitute into the failure message.
  4024. * @return {string} The value, guaranteed to be a string when asserts enabled.
  4025. * @throws {goog.asserts.AssertionError} When the value is not a string.
  4026. */
  4027. goog.asserts.assertString = function(value, opt_message, var_args) {
  4028. if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {
  4029. goog.asserts.doAssertFailure_('Expected string but got %s: %s.',
  4030. [goog.typeOf(value), value], opt_message,
  4031. Array.prototype.slice.call(arguments, 2));
  4032. }
  4033. return /** @type {string} */ (value);
  4034. };
  4035. /**
  4036. * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.
  4037. * @param {*} value The value to check.
  4038. * @param {string=} opt_message Error message in case of failure.
  4039. * @param {...*} var_args The items to substitute into the failure message.
  4040. * @return {!Function} The value, guaranteed to be a function when asserts
  4041. * enabled.
  4042. * @throws {goog.asserts.AssertionError} When the value is not a function.
  4043. */
  4044. goog.asserts.assertFunction = function(value, opt_message, var_args) {
  4045. if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {
  4046. goog.asserts.doAssertFailure_('Expected function but got %s: %s.',
  4047. [goog.typeOf(value), value], opt_message,
  4048. Array.prototype.slice.call(arguments, 2));
  4049. }
  4050. return /** @type {!Function} */ (value);
  4051. };
  4052. /**
  4053. * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.
  4054. * @param {*} value The value to check.
  4055. * @param {string=} opt_message Error message in case of failure.
  4056. * @param {...*} var_args The items to substitute into the failure message.
  4057. * @return {!Object} The value, guaranteed to be a non-null object.
  4058. * @throws {goog.asserts.AssertionError} When the value is not an object.
  4059. */
  4060. goog.asserts.assertObject = function(value, opt_message, var_args) {
  4061. if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {
  4062. goog.asserts.doAssertFailure_('Expected object but got %s: %s.',
  4063. [goog.typeOf(value), value],
  4064. opt_message, Array.prototype.slice.call(arguments, 2));
  4065. }
  4066. return /** @type {!Object} */ (value);
  4067. };
  4068. /**
  4069. * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.
  4070. * @param {*} value The value to check.
  4071. * @param {string=} opt_message Error message in case of failure.
  4072. * @param {...*} var_args The items to substitute into the failure message.
  4073. * @return {!Array<?>} The value, guaranteed to be a non-null array.
  4074. * @throws {goog.asserts.AssertionError} When the value is not an array.
  4075. */
  4076. goog.asserts.assertArray = function(value, opt_message, var_args) {
  4077. if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {
  4078. goog.asserts.doAssertFailure_('Expected array but got %s: %s.',
  4079. [goog.typeOf(value), value], opt_message,
  4080. Array.prototype.slice.call(arguments, 2));
  4081. }
  4082. return /** @type {!Array<?>} */ (value);
  4083. };
  4084. /**
  4085. * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.
  4086. * @param {*} value The value to check.
  4087. * @param {string=} opt_message Error message in case of failure.
  4088. * @param {...*} var_args The items to substitute into the failure message.
  4089. * @return {boolean} The value, guaranteed to be a boolean when asserts are
  4090. * enabled.
  4091. * @throws {goog.asserts.AssertionError} When the value is not a boolean.
  4092. */
  4093. goog.asserts.assertBoolean = function(value, opt_message, var_args) {
  4094. if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {
  4095. goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',
  4096. [goog.typeOf(value), value], opt_message,
  4097. Array.prototype.slice.call(arguments, 2));
  4098. }
  4099. return /** @type {boolean} */ (value);
  4100. };
  4101. /**
  4102. * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.
  4103. * @param {*} value The value to check.
  4104. * @param {string=} opt_message Error message in case of failure.
  4105. * @param {...*} var_args The items to substitute into the failure message.
  4106. * @return {!Element} The value, likely to be a DOM Element when asserts are
  4107. * enabled.
  4108. * @throws {goog.asserts.AssertionError} When the value is not an Element.
  4109. */
  4110. goog.asserts.assertElement = function(value, opt_message, var_args) {
  4111. if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) ||
  4112. value.nodeType != goog.dom.NodeType.ELEMENT)) {
  4113. goog.asserts.doAssertFailure_('Expected Element but got %s: %s.',
  4114. [goog.typeOf(value), value], opt_message,
  4115. Array.prototype.slice.call(arguments, 2));
  4116. }
  4117. return /** @type {!Element} */ (value);
  4118. };
  4119. /**
  4120. * Checks if the value is an instance of the user-defined type if
  4121. * goog.asserts.ENABLE_ASSERTS is true.
  4122. *
  4123. * The compiler may tighten the type returned by this function.
  4124. *
  4125. * @param {*} value The value to check.
  4126. * @param {function(new: T, ...)} type A user-defined constructor.
  4127. * @param {string=} opt_message Error message in case of failure.
  4128. * @param {...*} var_args The items to substitute into the failure message.
  4129. * @throws {goog.asserts.AssertionError} When the value is not an instance of
  4130. * type.
  4131. * @return {T}
  4132. * @template T
  4133. */
  4134. goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {
  4135. if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {
  4136. goog.asserts.doAssertFailure_('Expected instanceof %s but got %s.',
  4137. [goog.asserts.getType_(type), goog.asserts.getType_(value)],
  4138. opt_message, Array.prototype.slice.call(arguments, 3));
  4139. }
  4140. return value;
  4141. };
  4142. /**
  4143. * Checks that no enumerable keys are present in Object.prototype. Such keys
  4144. * would break most code that use {@code for (var ... in ...)} loops.
  4145. */
  4146. goog.asserts.assertObjectPrototypeIsIntact = function() {
  4147. for (var key in Object.prototype) {
  4148. goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');
  4149. }
  4150. };
  4151. /**
  4152. * Returns the type of a value. If a constructor is passed, and a suitable
  4153. * string cannot be found, 'unknown type name' will be returned.
  4154. * @param {*} value A constructor, object, or primitive.
  4155. * @return {string} The best display name for the value, or 'unknown type name'.
  4156. * @private
  4157. */
  4158. goog.asserts.getType_ = function(value) {
  4159. if (value instanceof Function) {
  4160. return value.displayName || value.name || 'unknown type name';
  4161. } else if (value instanceof Object) {
  4162. return value.constructor.displayName || value.constructor.name ||
  4163. Object.prototype.toString.call(value);
  4164. } else {
  4165. return value === null ? 'null' : typeof value;
  4166. }
  4167. };
  4168. goog.provide('ol.math');
  4169. goog.require('goog.asserts');
  4170. /**
  4171. * Takes a number and clamps it to within the provided bounds.
  4172. * @param {number} value The input number.
  4173. * @param {number} min The minimum value to return.
  4174. * @param {number} max The maximum value to return.
  4175. * @return {number} The input number if it is within bounds, or the nearest
  4176. * number within the bounds.
  4177. */
  4178. ol.math.clamp = function(value, min, max) {
  4179. return Math.min(Math.max(value, min), max);
  4180. };
  4181. /**
  4182. * @param {number} x X.
  4183. * @return {number} Hyperbolic cosine of x.
  4184. */
  4185. ol.math.cosh = function(x) {
  4186. return (Math.exp(x) + Math.exp(-x)) / 2;
  4187. };
  4188. /**
  4189. * @param {number} x X.
  4190. * @return {number} Hyperbolic cotangent of x.
  4191. */
  4192. ol.math.coth = function(x) {
  4193. var expMinusTwoX = Math.exp(-2 * x);
  4194. return (1 + expMinusTwoX) / (1 - expMinusTwoX);
  4195. };
  4196. /**
  4197. * @param {number} x X.
  4198. * @return {number} Hyperbolic cosecant of x.
  4199. */
  4200. ol.math.csch = function(x) {
  4201. return 2 / (Math.exp(x) - Math.exp(-x));
  4202. };
  4203. /**
  4204. * @param {number} x X.
  4205. * @return {number} The smallest power of two greater than or equal to x.
  4206. */
  4207. ol.math.roundUpToPowerOfTwo = function(x) {
  4208. goog.asserts.assert(0 < x, 'x should be larger than 0');
  4209. return Math.pow(2, Math.ceil(Math.log(x) / Math.LN2));
  4210. };
  4211. /**
  4212. * @param {number} x X.
  4213. * @return {number} Hyperbolic secant of x.
  4214. */
  4215. ol.math.sech = function(x) {
  4216. return 2 / (Math.exp(x) + Math.exp(-x));
  4217. };
  4218. /**
  4219. * @param {number} x X.
  4220. * @return {number} Hyperbolic sine of x.
  4221. */
  4222. ol.math.sinh = function(x) {
  4223. return (Math.exp(x) - Math.exp(-x)) / 2;
  4224. };
  4225. /**
  4226. * Returns the square of the closest distance between the point (x, y) and the
  4227. * line segment (x1, y1) to (x2, y2).
  4228. * @param {number} x X.
  4229. * @param {number} y Y.
  4230. * @param {number} x1 X1.
  4231. * @param {number} y1 Y1.
  4232. * @param {number} x2 X2.
  4233. * @param {number} y2 Y2.
  4234. * @return {number} Squared distance.
  4235. */
  4236. ol.math.squaredSegmentDistance = function(x, y, x1, y1, x2, y2) {
  4237. var dx = x2 - x1;
  4238. var dy = y2 - y1;
  4239. if (dx !== 0 || dy !== 0) {
  4240. var t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
  4241. if (t > 1) {
  4242. x1 = x2;
  4243. y1 = y2;
  4244. } else if (t > 0) {
  4245. x1 += dx * t;
  4246. y1 += dy * t;
  4247. }
  4248. }
  4249. return ol.math.squaredDistance(x, y, x1, y1);
  4250. };
  4251. /**
  4252. * Returns the square of the distance between the points (x1, y1) and (x2, y2).
  4253. * @param {number} x1 X1.
  4254. * @param {number} y1 Y1.
  4255. * @param {number} x2 X2.
  4256. * @param {number} y2 Y2.
  4257. * @return {number} Squared distance.
  4258. */
  4259. ol.math.squaredDistance = function(x1, y1, x2, y2) {
  4260. var dx = x2 - x1;
  4261. var dy = y2 - y1;
  4262. return dx * dx + dy * dy;
  4263. };
  4264. /**
  4265. * @param {number} x X.
  4266. * @return {number} Hyperbolic tangent of x.
  4267. */
  4268. ol.math.tanh = function(x) {
  4269. var expMinusTwoX = Math.exp(-2 * x);
  4270. return (1 - expMinusTwoX) / (1 + expMinusTwoX);
  4271. };
  4272. goog.provide('ol.CenterConstraint');
  4273. goog.provide('ol.CenterConstraintType');
  4274. goog.require('ol.math');
  4275. /**
  4276. * @typedef {function((ol.Coordinate|undefined)): (ol.Coordinate|undefined)}
  4277. */
  4278. ol.CenterConstraintType;
  4279. /**
  4280. * @param {ol.Extent} extent Extent.
  4281. * @return {ol.CenterConstraintType}
  4282. */
  4283. ol.CenterConstraint.createExtent = function(extent) {
  4284. return (
  4285. /**
  4286. * @param {ol.Coordinate|undefined} center Center.
  4287. * @return {ol.Coordinate|undefined} Center.
  4288. */
  4289. function(center) {
  4290. if (center) {
  4291. return [
  4292. ol.math.clamp(center[0], extent[0], extent[2]),
  4293. ol.math.clamp(center[1], extent[1], extent[3])
  4294. ];
  4295. } else {
  4296. return undefined;
  4297. }
  4298. });
  4299. };
  4300. /**
  4301. * @param {ol.Coordinate|undefined} center Center.
  4302. * @return {ol.Coordinate|undefined} Center.
  4303. */
  4304. ol.CenterConstraint.none = function(center) {
  4305. return center;
  4306. };
  4307. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  4308. //
  4309. // Licensed under the Apache License, Version 2.0 (the "License");
  4310. // you may not use this file except in compliance with the License.
  4311. // You may obtain a copy of the License at
  4312. //
  4313. // http://www.apache.org/licenses/LICENSE-2.0
  4314. //
  4315. // Unless required by applicable law or agreed to in writing, software
  4316. // distributed under the License is distributed on an "AS-IS" BASIS,
  4317. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4318. // See the License for the specific language governing permissions and
  4319. // limitations under the License.
  4320. /**
  4321. * @fileoverview Utilities for manipulating arrays.
  4322. *
  4323. * @author arv@google.com (Erik Arvidsson)
  4324. */
  4325. goog.provide('goog.array');
  4326. goog.provide('goog.array.ArrayLike');
  4327. goog.require('goog.asserts');
  4328. /**
  4329. * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
  4330. * rely on Array.prototype functions, if available.
  4331. *
  4332. * The Array.prototype functions can be defined by external libraries like
  4333. * Prototype and setting this flag to false forces closure to use its own
  4334. * goog.array implementation.
  4335. *
  4336. * If your javascript can be loaded by a third party site and you are wary about
  4337. * relying on the prototype functions, specify
  4338. * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler.
  4339. *
  4340. * Setting goog.TRUSTED_SITE to false will automatically set
  4341. * NATIVE_ARRAY_PROTOTYPES to false.
  4342. */
  4343. goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);
  4344. /**
  4345. * @define {boolean} If true, JSCompiler will use the native implementation of
  4346. * array functions where appropriate (e.g., {@code Array#filter}) and remove the
  4347. * unused pure JS implementation.
  4348. */
  4349. goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);
  4350. /**
  4351. * @typedef {Array|NodeList|Arguments|{length: number}}
  4352. */
  4353. goog.array.ArrayLike;
  4354. /**
  4355. * Returns the last element in an array without removing it.
  4356. * Same as goog.array.last.
  4357. * @param {Array<T>|goog.array.ArrayLike} array The array.
  4358. * @return {T} Last item in array.
  4359. * @template T
  4360. */
  4361. goog.array.peek = function(array) {
  4362. return array[array.length - 1];
  4363. };
  4364. /**
  4365. * Returns the last element in an array without removing it.
  4366. * Same as goog.array.peek.
  4367. * @param {Array<T>|goog.array.ArrayLike} array The array.
  4368. * @return {T} Last item in array.
  4369. * @template T
  4370. */
  4371. goog.array.last = goog.array.peek;
  4372. /**
  4373. * Reference to the original {@code Array.prototype}.
  4374. * @private
  4375. */
  4376. goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
  4377. // NOTE(arv): Since most of the array functions are generic it allows you to
  4378. // pass an array-like object. Strings have a length and are considered array-
  4379. // like. However, the 'in' operator does not work on strings so we cannot just
  4380. // use the array path even if the browser supports indexing into strings. We
  4381. // therefore end up splitting the string.
  4382. /**
  4383. * Returns the index of the first element of an array with a specified value, or
  4384. * -1 if the element is not present in the array.
  4385. *
  4386. * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
  4387. *
  4388. * @param {Array<T>|goog.array.ArrayLike} arr The array to be searched.
  4389. * @param {T} obj The object for which we are searching.
  4390. * @param {number=} opt_fromIndex The index at which to start the search. If
  4391. * omitted the search starts at index 0.
  4392. * @return {number} The index of the first matching array element.
  4393. * @template T
  4394. */
  4395. goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
  4396. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4397. goog.array.ARRAY_PROTOTYPE_.indexOf) ?
  4398. function(arr, obj, opt_fromIndex) {
  4399. goog.asserts.assert(arr.length != null);
  4400. return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
  4401. } :
  4402. function(arr, obj, opt_fromIndex) {
  4403. var fromIndex = opt_fromIndex == null ?
  4404. 0 : (opt_fromIndex < 0 ?
  4405. Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
  4406. if (goog.isString(arr)) {
  4407. // Array.prototype.indexOf uses === so only strings should be found.
  4408. if (!goog.isString(obj) || obj.length != 1) {
  4409. return -1;
  4410. }
  4411. return arr.indexOf(obj, fromIndex);
  4412. }
  4413. for (var i = fromIndex; i < arr.length; i++) {
  4414. if (i in arr && arr[i] === obj)
  4415. return i;
  4416. }
  4417. return -1;
  4418. };
  4419. /**
  4420. * Returns the index of the last element of an array with a specified value, or
  4421. * -1 if the element is not present in the array.
  4422. *
  4423. * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}
  4424. *
  4425. * @param {!Array<T>|!goog.array.ArrayLike} arr The array to be searched.
  4426. * @param {T} obj The object for which we are searching.
  4427. * @param {?number=} opt_fromIndex The index at which to start the search. If
  4428. * omitted the search starts at the end of the array.
  4429. * @return {number} The index of the last matching array element.
  4430. * @template T
  4431. */
  4432. goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
  4433. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4434. goog.array.ARRAY_PROTOTYPE_.lastIndexOf) ?
  4435. function(arr, obj, opt_fromIndex) {
  4436. goog.asserts.assert(arr.length != null);
  4437. // Firefox treats undefined and null as 0 in the fromIndex argument which
  4438. // leads it to always return -1
  4439. var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
  4440. return goog.array.ARRAY_PROTOTYPE_.lastIndexOf.call(arr, obj, fromIndex);
  4441. } :
  4442. function(arr, obj, opt_fromIndex) {
  4443. var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;
  4444. if (fromIndex < 0) {
  4445. fromIndex = Math.max(0, arr.length + fromIndex);
  4446. }
  4447. if (goog.isString(arr)) {
  4448. // Array.prototype.lastIndexOf uses === so only strings should be found.
  4449. if (!goog.isString(obj) || obj.length != 1) {
  4450. return -1;
  4451. }
  4452. return arr.lastIndexOf(obj, fromIndex);
  4453. }
  4454. for (var i = fromIndex; i >= 0; i--) {
  4455. if (i in arr && arr[i] === obj)
  4456. return i;
  4457. }
  4458. return -1;
  4459. };
  4460. /**
  4461. * Calls a function for each element in an array. Skips holes in the array.
  4462. * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
  4463. *
  4464. * @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over
  4465. * which to iterate.
  4466. * @param {?function(this: S, T, number, ?): ?} f The function to call for every
  4467. * element. This function takes 3 arguments (the element, the index and the
  4468. * array). The return value is ignored.
  4469. * @param {S=} opt_obj The object to be used as the value of 'this' within f.
  4470. * @template T,S
  4471. */
  4472. goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
  4473. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4474. goog.array.ARRAY_PROTOTYPE_.forEach) ?
  4475. function(arr, f, opt_obj) {
  4476. goog.asserts.assert(arr.length != null);
  4477. goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
  4478. } :
  4479. function(arr, f, opt_obj) {
  4480. var l = arr.length; // must be fixed during loop... see docs
  4481. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4482. for (var i = 0; i < l; i++) {
  4483. if (i in arr2) {
  4484. f.call(opt_obj, arr2[i], i, arr);
  4485. }
  4486. }
  4487. };
  4488. /**
  4489. * Calls a function for each element in an array, starting from the last
  4490. * element rather than the first.
  4491. *
  4492. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4493. * like object over which to iterate.
  4494. * @param {?function(this: S, T, number, ?): ?} f The function to call for every
  4495. * element. This function
  4496. * takes 3 arguments (the element, the index and the array). The return
  4497. * value is ignored.
  4498. * @param {S=} opt_obj The object to be used as the value of 'this'
  4499. * within f.
  4500. * @template T,S
  4501. */
  4502. goog.array.forEachRight = function(arr, f, opt_obj) {
  4503. var l = arr.length; // must be fixed during loop... see docs
  4504. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4505. for (var i = l - 1; i >= 0; --i) {
  4506. if (i in arr2) {
  4507. f.call(opt_obj, arr2[i], i, arr);
  4508. }
  4509. }
  4510. };
  4511. /**
  4512. * Calls a function for each element in an array, and if the function returns
  4513. * true adds the element to a new array.
  4514. *
  4515. * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
  4516. *
  4517. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4518. * like object over which to iterate.
  4519. * @param {?function(this:S, T, number, ?):boolean} f The function to call for
  4520. * every element. This function
  4521. * takes 3 arguments (the element, the index and the array) and must
  4522. * return a Boolean. If the return value is true the element is added to the
  4523. * result array. If it is false the element is not included.
  4524. * @param {S=} opt_obj The object to be used as the value of 'this'
  4525. * within f.
  4526. * @return {!Array<T>} a new array in which only elements that passed the test
  4527. * are present.
  4528. * @template T,S
  4529. */
  4530. goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
  4531. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4532. goog.array.ARRAY_PROTOTYPE_.filter) ?
  4533. function(arr, f, opt_obj) {
  4534. goog.asserts.assert(arr.length != null);
  4535. return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
  4536. } :
  4537. function(arr, f, opt_obj) {
  4538. var l = arr.length; // must be fixed during loop... see docs
  4539. var res = [];
  4540. var resLength = 0;
  4541. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4542. for (var i = 0; i < l; i++) {
  4543. if (i in arr2) {
  4544. var val = arr2[i]; // in case f mutates arr2
  4545. if (f.call(opt_obj, val, i, arr)) {
  4546. res[resLength++] = val;
  4547. }
  4548. }
  4549. }
  4550. return res;
  4551. };
  4552. /**
  4553. * Calls a function for each element in an array and inserts the result into a
  4554. * new array.
  4555. *
  4556. * See {@link http://tinyurl.com/developer-mozilla-org-array-map}
  4557. *
  4558. * @param {Array<VALUE>|goog.array.ArrayLike} arr Array or array like object
  4559. * over which to iterate.
  4560. * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call
  4561. * for every element. This function takes 3 arguments (the element,
  4562. * the index and the array) and should return something. The result will be
  4563. * inserted into a new array.
  4564. * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.
  4565. * @return {!Array<RESULT>} a new array with the results from f.
  4566. * @template THIS, VALUE, RESULT
  4567. */
  4568. goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
  4569. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4570. goog.array.ARRAY_PROTOTYPE_.map) ?
  4571. function(arr, f, opt_obj) {
  4572. goog.asserts.assert(arr.length != null);
  4573. return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
  4574. } :
  4575. function(arr, f, opt_obj) {
  4576. var l = arr.length; // must be fixed during loop... see docs
  4577. var res = new Array(l);
  4578. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4579. for (var i = 0; i < l; i++) {
  4580. if (i in arr2) {
  4581. res[i] = f.call(opt_obj, arr2[i], i, arr);
  4582. }
  4583. }
  4584. return res;
  4585. };
  4586. /**
  4587. * Passes every element of an array into a function and accumulates the result.
  4588. *
  4589. * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}
  4590. *
  4591. * For example:
  4592. * var a = [1, 2, 3, 4];
  4593. * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);
  4594. * returns 10
  4595. *
  4596. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4597. * like object over which to iterate.
  4598. * @param {function(this:S, R, T, number, ?) : R} f The function to call for
  4599. * every element. This function
  4600. * takes 4 arguments (the function's previous result or the initial value,
  4601. * the value of the current array element, the current array index, and the
  4602. * array itself)
  4603. * function(previousValue, currentValue, index, array).
  4604. * @param {?} val The initial value to pass into the function on the first call.
  4605. * @param {S=} opt_obj The object to be used as the value of 'this'
  4606. * within f.
  4607. * @return {R} Result of evaluating f repeatedly across the values of the array.
  4608. * @template T,S,R
  4609. */
  4610. goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&
  4611. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4612. goog.array.ARRAY_PROTOTYPE_.reduce) ?
  4613. function(arr, f, val, opt_obj) {
  4614. goog.asserts.assert(arr.length != null);
  4615. if (opt_obj) {
  4616. f = goog.bind(f, opt_obj);
  4617. }
  4618. return goog.array.ARRAY_PROTOTYPE_.reduce.call(arr, f, val);
  4619. } :
  4620. function(arr, f, val, opt_obj) {
  4621. var rval = val;
  4622. goog.array.forEach(arr, function(val, index) {
  4623. rval = f.call(opt_obj, rval, val, index, arr);
  4624. });
  4625. return rval;
  4626. };
  4627. /**
  4628. * Passes every element of an array into a function and accumulates the result,
  4629. * starting from the last element and working towards the first.
  4630. *
  4631. * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}
  4632. *
  4633. * For example:
  4634. * var a = ['a', 'b', 'c'];
  4635. * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');
  4636. * returns 'cba'
  4637. *
  4638. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4639. * like object over which to iterate.
  4640. * @param {?function(this:S, R, T, number, ?) : R} f The function to call for
  4641. * every element. This function
  4642. * takes 4 arguments (the function's previous result or the initial value,
  4643. * the value of the current array element, the current array index, and the
  4644. * array itself)
  4645. * function(previousValue, currentValue, index, array).
  4646. * @param {?} val The initial value to pass into the function on the first call.
  4647. * @param {S=} opt_obj The object to be used as the value of 'this'
  4648. * within f.
  4649. * @return {R} Object returned as a result of evaluating f repeatedly across the
  4650. * values of the array.
  4651. * @template T,S,R
  4652. */
  4653. goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&
  4654. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4655. goog.array.ARRAY_PROTOTYPE_.reduceRight) ?
  4656. function(arr, f, val, opt_obj) {
  4657. goog.asserts.assert(arr.length != null);
  4658. if (opt_obj) {
  4659. f = goog.bind(f, opt_obj);
  4660. }
  4661. return goog.array.ARRAY_PROTOTYPE_.reduceRight.call(arr, f, val);
  4662. } :
  4663. function(arr, f, val, opt_obj) {
  4664. var rval = val;
  4665. goog.array.forEachRight(arr, function(val, index) {
  4666. rval = f.call(opt_obj, rval, val, index, arr);
  4667. });
  4668. return rval;
  4669. };
  4670. /**
  4671. * Calls f for each element of an array. If any call returns true, some()
  4672. * returns true (without checking the remaining elements). If all calls
  4673. * return false, some() returns false.
  4674. *
  4675. * See {@link http://tinyurl.com/developer-mozilla-org-array-some}
  4676. *
  4677. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4678. * like object over which to iterate.
  4679. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  4680. * for every element. This function takes 3 arguments (the element, the
  4681. * index and the array) and should return a boolean.
  4682. * @param {S=} opt_obj The object to be used as the value of 'this'
  4683. * within f.
  4684. * @return {boolean} true if any element passes the test.
  4685. * @template T,S
  4686. */
  4687. goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
  4688. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4689. goog.array.ARRAY_PROTOTYPE_.some) ?
  4690. function(arr, f, opt_obj) {
  4691. goog.asserts.assert(arr.length != null);
  4692. return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
  4693. } :
  4694. function(arr, f, opt_obj) {
  4695. var l = arr.length; // must be fixed during loop... see docs
  4696. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4697. for (var i = 0; i < l; i++) {
  4698. if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
  4699. return true;
  4700. }
  4701. }
  4702. return false;
  4703. };
  4704. /**
  4705. * Call f for each element of an array. If all calls return true, every()
  4706. * returns true. If any call returns false, every() returns false and
  4707. * does not continue to check the remaining elements.
  4708. *
  4709. * See {@link http://tinyurl.com/developer-mozilla-org-array-every}
  4710. *
  4711. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4712. * like object over which to iterate.
  4713. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  4714. * for every element. This function takes 3 arguments (the element, the
  4715. * index and the array) and should return a boolean.
  4716. * @param {S=} opt_obj The object to be used as the value of 'this'
  4717. * within f.
  4718. * @return {boolean} false if any element fails the test.
  4719. * @template T,S
  4720. */
  4721. goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
  4722. (goog.array.ASSUME_NATIVE_FUNCTIONS ||
  4723. goog.array.ARRAY_PROTOTYPE_.every) ?
  4724. function(arr, f, opt_obj) {
  4725. goog.asserts.assert(arr.length != null);
  4726. return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
  4727. } :
  4728. function(arr, f, opt_obj) {
  4729. var l = arr.length; // must be fixed during loop... see docs
  4730. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4731. for (var i = 0; i < l; i++) {
  4732. if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
  4733. return false;
  4734. }
  4735. }
  4736. return true;
  4737. };
  4738. /**
  4739. * Counts the array elements that fulfill the predicate, i.e. for which the
  4740. * callback function returns true. Skips holes in the array.
  4741. *
  4742. * @param {!(Array<T>|goog.array.ArrayLike)} arr Array or array like object
  4743. * over which to iterate.
  4744. * @param {function(this: S, T, number, ?): boolean} f The function to call for
  4745. * every element. Takes 3 arguments (the element, the index and the array).
  4746. * @param {S=} opt_obj The object to be used as the value of 'this' within f.
  4747. * @return {number} The number of the matching elements.
  4748. * @template T,S
  4749. */
  4750. goog.array.count = function(arr, f, opt_obj) {
  4751. var count = 0;
  4752. goog.array.forEach(arr, function(element, index, arr) {
  4753. if (f.call(opt_obj, element, index, arr)) {
  4754. ++count;
  4755. }
  4756. }, opt_obj);
  4757. return count;
  4758. };
  4759. /**
  4760. * Search an array for the first element that satisfies a given condition and
  4761. * return that element.
  4762. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4763. * like object over which to iterate.
  4764. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  4765. * for every element. This function takes 3 arguments (the element, the
  4766. * index and the array) and should return a boolean.
  4767. * @param {S=} opt_obj An optional "this" context for the function.
  4768. * @return {T|null} The first array element that passes the test, or null if no
  4769. * element is found.
  4770. * @template T,S
  4771. */
  4772. goog.array.find = function(arr, f, opt_obj) {
  4773. var i = goog.array.findIndex(arr, f, opt_obj);
  4774. return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
  4775. };
  4776. /**
  4777. * Search an array for the first element that satisfies a given condition and
  4778. * return its index.
  4779. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4780. * like object over which to iterate.
  4781. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for
  4782. * every element. This function
  4783. * takes 3 arguments (the element, the index and the array) and should
  4784. * return a boolean.
  4785. * @param {S=} opt_obj An optional "this" context for the function.
  4786. * @return {number} The index of the first array element that passes the test,
  4787. * or -1 if no element is found.
  4788. * @template T,S
  4789. */
  4790. goog.array.findIndex = function(arr, f, opt_obj) {
  4791. var l = arr.length; // must be fixed during loop... see docs
  4792. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4793. for (var i = 0; i < l; i++) {
  4794. if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
  4795. return i;
  4796. }
  4797. }
  4798. return -1;
  4799. };
  4800. /**
  4801. * Search an array (in reverse order) for the last element that satisfies a
  4802. * given condition and return that element.
  4803. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4804. * like object over which to iterate.
  4805. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  4806. * for every element. This function
  4807. * takes 3 arguments (the element, the index and the array) and should
  4808. * return a boolean.
  4809. * @param {S=} opt_obj An optional "this" context for the function.
  4810. * @return {T|null} The last array element that passes the test, or null if no
  4811. * element is found.
  4812. * @template T,S
  4813. */
  4814. goog.array.findRight = function(arr, f, opt_obj) {
  4815. var i = goog.array.findIndexRight(arr, f, opt_obj);
  4816. return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];
  4817. };
  4818. /**
  4819. * Search an array (in reverse order) for the last element that satisfies a
  4820. * given condition and return its index.
  4821. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4822. * like object over which to iterate.
  4823. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  4824. * for every element. This function
  4825. * takes 3 arguments (the element, the index and the array) and should
  4826. * return a boolean.
  4827. * @param {S=} opt_obj An optional "this" context for the function.
  4828. * @return {number} The index of the last array element that passes the test,
  4829. * or -1 if no element is found.
  4830. * @template T,S
  4831. */
  4832. goog.array.findIndexRight = function(arr, f, opt_obj) {
  4833. var l = arr.length; // must be fixed during loop... see docs
  4834. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  4835. for (var i = l - 1; i >= 0; i--) {
  4836. if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
  4837. return i;
  4838. }
  4839. }
  4840. return -1;
  4841. };
  4842. /**
  4843. * Whether the array contains the given object.
  4844. * @param {goog.array.ArrayLike} arr The array to test for the presence of the
  4845. * element.
  4846. * @param {*} obj The object for which to test.
  4847. * @return {boolean} true if obj is present.
  4848. */
  4849. goog.array.contains = function(arr, obj) {
  4850. return goog.array.indexOf(arr, obj) >= 0;
  4851. };
  4852. /**
  4853. * Whether the array is empty.
  4854. * @param {goog.array.ArrayLike} arr The array to test.
  4855. * @return {boolean} true if empty.
  4856. */
  4857. goog.array.isEmpty = function(arr) {
  4858. return arr.length == 0;
  4859. };
  4860. /**
  4861. * Clears the array.
  4862. * @param {goog.array.ArrayLike} arr Array or array like object to clear.
  4863. */
  4864. goog.array.clear = function(arr) {
  4865. // For non real arrays we don't have the magic length so we delete the
  4866. // indices.
  4867. if (!goog.isArray(arr)) {
  4868. for (var i = arr.length - 1; i >= 0; i--) {
  4869. delete arr[i];
  4870. }
  4871. }
  4872. arr.length = 0;
  4873. };
  4874. /**
  4875. * Pushes an item into an array, if it's not already in the array.
  4876. * @param {Array<T>} arr Array into which to insert the item.
  4877. * @param {T} obj Value to add.
  4878. * @template T
  4879. */
  4880. goog.array.insert = function(arr, obj) {
  4881. if (!goog.array.contains(arr, obj)) {
  4882. arr.push(obj);
  4883. }
  4884. };
  4885. /**
  4886. * Inserts an object at the given index of the array.
  4887. * @param {goog.array.ArrayLike} arr The array to modify.
  4888. * @param {*} obj The object to insert.
  4889. * @param {number=} opt_i The index at which to insert the object. If omitted,
  4890. * treated as 0. A negative index is counted from the end of the array.
  4891. */
  4892. goog.array.insertAt = function(arr, obj, opt_i) {
  4893. goog.array.splice(arr, opt_i, 0, obj);
  4894. };
  4895. /**
  4896. * Inserts at the given index of the array, all elements of another array.
  4897. * @param {goog.array.ArrayLike} arr The array to modify.
  4898. * @param {goog.array.ArrayLike} elementsToAdd The array of elements to add.
  4899. * @param {number=} opt_i The index at which to insert the object. If omitted,
  4900. * treated as 0. A negative index is counted from the end of the array.
  4901. */
  4902. goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {
  4903. goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);
  4904. };
  4905. /**
  4906. * Inserts an object into an array before a specified object.
  4907. * @param {Array<T>} arr The array to modify.
  4908. * @param {T} obj The object to insert.
  4909. * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2
  4910. * is omitted or not found, obj is inserted at the end of the array.
  4911. * @template T
  4912. */
  4913. goog.array.insertBefore = function(arr, obj, opt_obj2) {
  4914. var i;
  4915. if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {
  4916. arr.push(obj);
  4917. } else {
  4918. goog.array.insertAt(arr, obj, i);
  4919. }
  4920. };
  4921. /**
  4922. * Removes the first occurrence of a particular value from an array.
  4923. * @param {Array<T>|goog.array.ArrayLike} arr Array from which to remove
  4924. * value.
  4925. * @param {T} obj Object to remove.
  4926. * @return {boolean} True if an element was removed.
  4927. * @template T
  4928. */
  4929. goog.array.remove = function(arr, obj) {
  4930. var i = goog.array.indexOf(arr, obj);
  4931. var rv;
  4932. if ((rv = i >= 0)) {
  4933. goog.array.removeAt(arr, i);
  4934. }
  4935. return rv;
  4936. };
  4937. /**
  4938. * Removes from an array the element at index i
  4939. * @param {goog.array.ArrayLike} arr Array or array like object from which to
  4940. * remove value.
  4941. * @param {number} i The index to remove.
  4942. * @return {boolean} True if an element was removed.
  4943. */
  4944. goog.array.removeAt = function(arr, i) {
  4945. goog.asserts.assert(arr.length != null);
  4946. // use generic form of splice
  4947. // splice returns the removed items and if successful the length of that
  4948. // will be 1
  4949. return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
  4950. };
  4951. /**
  4952. * Removes the first value that satisfies the given condition.
  4953. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4954. * like object over which to iterate.
  4955. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  4956. * for every element. This function
  4957. * takes 3 arguments (the element, the index and the array) and should
  4958. * return a boolean.
  4959. * @param {S=} opt_obj An optional "this" context for the function.
  4960. * @return {boolean} True if an element was removed.
  4961. * @template T,S
  4962. */
  4963. goog.array.removeIf = function(arr, f, opt_obj) {
  4964. var i = goog.array.findIndex(arr, f, opt_obj);
  4965. if (i >= 0) {
  4966. goog.array.removeAt(arr, i);
  4967. return true;
  4968. }
  4969. return false;
  4970. };
  4971. /**
  4972. * Removes all values that satisfy the given condition.
  4973. * @param {Array<T>|goog.array.ArrayLike} arr Array or array
  4974. * like object over which to iterate.
  4975. * @param {?function(this:S, T, number, ?) : boolean} f The function to call
  4976. * for every element. This function
  4977. * takes 3 arguments (the element, the index and the array) and should
  4978. * return a boolean.
  4979. * @param {S=} opt_obj An optional "this" context for the function.
  4980. * @return {number} The number of items removed
  4981. * @template T,S
  4982. */
  4983. goog.array.removeAllIf = function(arr, f, opt_obj) {
  4984. var removedCount = 0;
  4985. goog.array.forEachRight(arr, function(val, index) {
  4986. if (f.call(opt_obj, val, index, arr)) {
  4987. if (goog.array.removeAt(arr, index)) {
  4988. removedCount++;
  4989. }
  4990. }
  4991. });
  4992. return removedCount;
  4993. };
  4994. /**
  4995. * Returns a new array that is the result of joining the arguments. If arrays
  4996. * are passed then their items are added, however, if non-arrays are passed they
  4997. * will be added to the return array as is.
  4998. *
  4999. * Note that ArrayLike objects will be added as is, rather than having their
  5000. * items added.
  5001. *
  5002. * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
  5003. * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
  5004. * goog.array.concat([1, 2], null) -> [1, 2, null]
  5005. *
  5006. * There is bug in all current versions of IE (6, 7 and 8) where arrays created
  5007. * in an iframe become corrupted soon (not immediately) after the iframe is
  5008. * destroyed. This is common if loading data via goog.net.IframeIo, for example.
  5009. * This corruption only affects the concat method which will start throwing
  5010. * Catastrophic Errors (#-2147418113).
  5011. *
  5012. * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
  5013. *
  5014. * Internally goog.array should use this, so that all methods will continue to
  5015. * work on these broken array objects.
  5016. *
  5017. * @param {...*} var_args Items to concatenate. Arrays will have each item
  5018. * added, while primitives and objects will be added as is.
  5019. * @return {!Array<?>} The new resultant array.
  5020. */
  5021. goog.array.concat = function(var_args) {
  5022. return goog.array.ARRAY_PROTOTYPE_.concat.apply(
  5023. goog.array.ARRAY_PROTOTYPE_, arguments);
  5024. };
  5025. /**
  5026. * Returns a new array that contains the contents of all the arrays passed.
  5027. * @param {...!Array<T>} var_args
  5028. * @return {!Array<T>}
  5029. * @template T
  5030. */
  5031. goog.array.join = function(var_args) {
  5032. return goog.array.ARRAY_PROTOTYPE_.concat.apply(
  5033. goog.array.ARRAY_PROTOTYPE_, arguments);
  5034. };
  5035. /**
  5036. * Converts an object to an array.
  5037. * @param {Array<T>|goog.array.ArrayLike} object The object to convert to an
  5038. * array.
  5039. * @return {!Array<T>} The object converted into an array. If object has a
  5040. * length property, every property indexed with a non-negative number
  5041. * less than length will be included in the result. If object does not
  5042. * have a length property, an empty array will be returned.
  5043. * @template T
  5044. */
  5045. goog.array.toArray = function(object) {
  5046. var length = object.length;
  5047. // If length is not a number the following it false. This case is kept for
  5048. // backwards compatibility since there are callers that pass objects that are
  5049. // not array like.
  5050. if (length > 0) {
  5051. var rv = new Array(length);
  5052. for (var i = 0; i < length; i++) {
  5053. rv[i] = object[i];
  5054. }
  5055. return rv;
  5056. }
  5057. return [];
  5058. };
  5059. /**
  5060. * Does a shallow copy of an array.
  5061. * @param {Array<T>|goog.array.ArrayLike} arr Array or array-like object to
  5062. * clone.
  5063. * @return {!Array<T>} Clone of the input array.
  5064. * @template T
  5065. */
  5066. goog.array.clone = goog.array.toArray;
  5067. /**
  5068. * Extends an array with another array, element, or "array like" object.
  5069. * This function operates 'in-place', it does not create a new Array.
  5070. *
  5071. * Example:
  5072. * var a = [];
  5073. * goog.array.extend(a, [0, 1]);
  5074. * a; // [0, 1]
  5075. * goog.array.extend(a, 2);
  5076. * a; // [0, 1, 2]
  5077. *
  5078. * @param {Array<VALUE>} arr1 The array to modify.
  5079. * @param {...(Array<VALUE>|VALUE)} var_args The elements or arrays of elements
  5080. * to add to arr1.
  5081. * @template VALUE
  5082. */
  5083. goog.array.extend = function(arr1, var_args) {
  5084. for (var i = 1; i < arguments.length; i++) {
  5085. var arr2 = arguments[i];
  5086. if (goog.isArrayLike(arr2)) {
  5087. var len1 = arr1.length || 0;
  5088. var len2 = arr2.length || 0;
  5089. arr1.length = len1 + len2;
  5090. for (var j = 0; j < len2; j++) {
  5091. arr1[len1 + j] = arr2[j];
  5092. }
  5093. } else {
  5094. arr1.push(arr2);
  5095. }
  5096. }
  5097. };
  5098. /**
  5099. * Adds or removes elements from an array. This is a generic version of Array
  5100. * splice. This means that it might work on other objects similar to arrays,
  5101. * such as the arguments object.
  5102. *
  5103. * @param {Array<T>|goog.array.ArrayLike} arr The array to modify.
  5104. * @param {number|undefined} index The index at which to start changing the
  5105. * array. If not defined, treated as 0.
  5106. * @param {number} howMany How many elements to remove (0 means no removal. A
  5107. * value below 0 is treated as zero and so is any other non number. Numbers
  5108. * are floored).
  5109. * @param {...T} var_args Optional, additional elements to insert into the
  5110. * array.
  5111. * @return {!Array<T>} the removed elements.
  5112. * @template T
  5113. */
  5114. goog.array.splice = function(arr, index, howMany, var_args) {
  5115. goog.asserts.assert(arr.length != null);
  5116. return goog.array.ARRAY_PROTOTYPE_.splice.apply(
  5117. arr, goog.array.slice(arguments, 1));
  5118. };
  5119. /**
  5120. * Returns a new array from a segment of an array. This is a generic version of
  5121. * Array slice. This means that it might work on other objects similar to
  5122. * arrays, such as the arguments object.
  5123. *
  5124. * @param {Array<T>|goog.array.ArrayLike} arr The array from
  5125. * which to copy a segment.
  5126. * @param {number} start The index of the first element to copy.
  5127. * @param {number=} opt_end The index after the last element to copy.
  5128. * @return {!Array<T>} A new array containing the specified segment of the
  5129. * original array.
  5130. * @template T
  5131. */
  5132. goog.array.slice = function(arr, start, opt_end) {
  5133. goog.asserts.assert(arr.length != null);
  5134. // passing 1 arg to slice is not the same as passing 2 where the second is
  5135. // null or undefined (in that case the second argument is treated as 0).
  5136. // we could use slice on the arguments object and then use apply instead of
  5137. // testing the length
  5138. if (arguments.length <= 2) {
  5139. return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
  5140. } else {
  5141. return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
  5142. }
  5143. };
  5144. /**
  5145. * Removes all duplicates from an array (retaining only the first
  5146. * occurrence of each array element). This function modifies the
  5147. * array in place and doesn't change the order of the non-duplicate items.
  5148. *
  5149. * For objects, duplicates are identified as having the same unique ID as
  5150. * defined by {@link goog.getUid}.
  5151. *
  5152. * Alternatively you can specify a custom hash function that returns a unique
  5153. * value for each item in the array it should consider unique.
  5154. *
  5155. * Runtime: N,
  5156. * Worstcase space: 2N (no dupes)
  5157. *
  5158. * @param {Array<T>|goog.array.ArrayLike} arr The array from which to remove
  5159. * duplicates.
  5160. * @param {Array=} opt_rv An optional array in which to return the results,
  5161. * instead of performing the removal inplace. If specified, the original
  5162. * array will remain unchanged.
  5163. * @param {function(T):string=} opt_hashFn An optional function to use to
  5164. * apply to every item in the array. This function should return a unique
  5165. * value for each item in the array it should consider unique.
  5166. * @template T
  5167. */
  5168. goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {
  5169. var returnArray = opt_rv || arr;
  5170. var defaultHashFn = function(item) {
  5171. // Prefix each type with a single character representing the type to
  5172. // prevent conflicting keys (e.g. true and 'true').
  5173. return goog.isObject(item) ? 'o' + goog.getUid(item) :
  5174. (typeof item).charAt(0) + item;
  5175. };
  5176. var hashFn = opt_hashFn || defaultHashFn;
  5177. var seen = {}, cursorInsert = 0, cursorRead = 0;
  5178. while (cursorRead < arr.length) {
  5179. var current = arr[cursorRead++];
  5180. var key = hashFn(current);
  5181. if (!Object.prototype.hasOwnProperty.call(seen, key)) {
  5182. seen[key] = true;
  5183. returnArray[cursorInsert++] = current;
  5184. }
  5185. }
  5186. returnArray.length = cursorInsert;
  5187. };
  5188. /**
  5189. * Searches the specified array for the specified target using the binary
  5190. * search algorithm. If no opt_compareFn is specified, elements are compared
  5191. * using <code>goog.array.defaultCompare</code>, which compares the elements
  5192. * using the built in < and > operators. This will produce the expected
  5193. * behavior for homogeneous arrays of String(s) and Number(s). The array
  5194. * specified <b>must</b> be sorted in ascending order (as defined by the
  5195. * comparison function). If the array is not sorted, results are undefined.
  5196. * If the array contains multiple instances of the specified target value, any
  5197. * of these instances may be found.
  5198. *
  5199. * Runtime: O(log n)
  5200. *
  5201. * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched.
  5202. * @param {TARGET} target The sought value.
  5203. * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison
  5204. * function by which the array is ordered. Should take 2 arguments to
  5205. * compare, and return a negative number, zero, or a positive number
  5206. * depending on whether the first argument is less than, equal to, or
  5207. * greater than the second.
  5208. * @return {number} Lowest index of the target value if found, otherwise
  5209. * (-(insertion point) - 1). The insertion point is where the value should
  5210. * be inserted into arr to preserve the sorted property. Return value >= 0
  5211. * iff target is found.
  5212. * @template TARGET, VALUE
  5213. */
  5214. goog.array.binarySearch = function(arr, target, opt_compareFn) {
  5215. return goog.array.binarySearch_(arr,
  5216. opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,
  5217. target);
  5218. };
  5219. /**
  5220. * Selects an index in the specified array using the binary search algorithm.
  5221. * The evaluator receives an element and determines whether the desired index
  5222. * is before, at, or after it. The evaluator must be consistent (formally,
  5223. * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)
  5224. * must be monotonically non-increasing).
  5225. *
  5226. * Runtime: O(log n)
  5227. *
  5228. * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched.
  5229. * @param {function(this:THIS, VALUE, number, ?): number} evaluator
  5230. * Evaluator function that receives 3 arguments (the element, the index and
  5231. * the array). Should return a negative number, zero, or a positive number
  5232. * depending on whether the desired index is before, at, or after the
  5233. * element passed to it.
  5234. * @param {THIS=} opt_obj The object to be used as the value of 'this'
  5235. * within evaluator.
  5236. * @return {number} Index of the leftmost element matched by the evaluator, if
  5237. * such exists; otherwise (-(insertion point) - 1). The insertion point is
  5238. * the index of the first element for which the evaluator returns negative,
  5239. * or arr.length if no such element exists. The return value is non-negative
  5240. * iff a match is found.
  5241. * @template THIS, VALUE
  5242. */
  5243. goog.array.binarySelect = function(arr, evaluator, opt_obj) {
  5244. return goog.array.binarySearch_(arr, evaluator, true /* isEvaluator */,
  5245. undefined /* opt_target */, opt_obj);
  5246. };
  5247. /**
  5248. * Implementation of a binary search algorithm which knows how to use both
  5249. * comparison functions and evaluators. If an evaluator is provided, will call
  5250. * the evaluator with the given optional data object, conforming to the
  5251. * interface defined in binarySelect. Otherwise, if a comparison function is
  5252. * provided, will call the comparison function against the given data object.
  5253. *
  5254. * This implementation purposefully does not use goog.bind or goog.partial for
  5255. * performance reasons.
  5256. *
  5257. * Runtime: O(log n)
  5258. *
  5259. * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to be searched.
  5260. * @param {function(TARGET, VALUE): number|
  5261. * function(this:THIS, VALUE, number, ?): number} compareFn Either an
  5262. * evaluator or a comparison function, as defined by binarySearch
  5263. * and binarySelect above.
  5264. * @param {boolean} isEvaluator Whether the function is an evaluator or a
  5265. * comparison function.
  5266. * @param {TARGET=} opt_target If the function is a comparison function, then
  5267. * this is the target to binary search for.
  5268. * @param {THIS=} opt_selfObj If the function is an evaluator, this is an
  5269. * optional this object for the evaluator.
  5270. * @return {number} Lowest index of the target value if found, otherwise
  5271. * (-(insertion point) - 1). The insertion point is where the value should
  5272. * be inserted into arr to preserve the sorted property. Return value >= 0
  5273. * iff target is found.
  5274. * @template THIS, VALUE, TARGET
  5275. * @private
  5276. */
  5277. goog.array.binarySearch_ = function(arr, compareFn, isEvaluator, opt_target,
  5278. opt_selfObj) {
  5279. var left = 0; // inclusive
  5280. var right = arr.length; // exclusive
  5281. var found;
  5282. while (left < right) {
  5283. var middle = (left + right) >> 1;
  5284. var compareResult;
  5285. if (isEvaluator) {
  5286. compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);
  5287. } else {
  5288. compareResult = compareFn(opt_target, arr[middle]);
  5289. }
  5290. if (compareResult > 0) {
  5291. left = middle + 1;
  5292. } else {
  5293. right = middle;
  5294. // We are looking for the lowest index so we can't return immediately.
  5295. found = !compareResult;
  5296. }
  5297. }
  5298. // left is the index if found, or the insertion point otherwise.
  5299. // ~left is a shorthand for -left - 1.
  5300. return found ? left : ~left;
  5301. };
  5302. /**
  5303. * Sorts the specified array into ascending order. If no opt_compareFn is
  5304. * specified, elements are compared using
  5305. * <code>goog.array.defaultCompare</code>, which compares the elements using
  5306. * the built in < and > operators. This will produce the expected behavior
  5307. * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
  5308. * but will give unpredictable results for heterogenous lists of strings and
  5309. * numbers with different numbers of digits.
  5310. *
  5311. * This sort is not guaranteed to be stable.
  5312. *
  5313. * Runtime: Same as <code>Array.prototype.sort</code>
  5314. *
  5315. * @param {Array<T>} arr The array to be sorted.
  5316. * @param {?function(T,T):number=} opt_compareFn Optional comparison
  5317. * function by which the
  5318. * array is to be ordered. Should take 2 arguments to compare, and return a
  5319. * negative number, zero, or a positive number depending on whether the
  5320. * first argument is less than, equal to, or greater than the second.
  5321. * @template T
  5322. */
  5323. goog.array.sort = function(arr, opt_compareFn) {
  5324. // TODO(arv): Update type annotation since null is not accepted.
  5325. arr.sort(opt_compareFn || goog.array.defaultCompare);
  5326. };
  5327. /**
  5328. * Sorts the specified array into ascending order in a stable way. If no
  5329. * opt_compareFn is specified, elements are compared using
  5330. * <code>goog.array.defaultCompare</code>, which compares the elements using
  5331. * the built in < and > operators. This will produce the expected behavior
  5332. * for homogeneous arrays of String(s) and Number(s).
  5333. *
  5334. * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional
  5335. * O(n) overhead of copying the array twice.
  5336. *
  5337. * @param {Array<T>} arr The array to be sorted.
  5338. * @param {?function(T, T): number=} opt_compareFn Optional comparison function
  5339. * by which the array is to be ordered. Should take 2 arguments to compare,
  5340. * and return a negative number, zero, or a positive number depending on
  5341. * whether the first argument is less than, equal to, or greater than the
  5342. * second.
  5343. * @template T
  5344. */
  5345. goog.array.stableSort = function(arr, opt_compareFn) {
  5346. for (var i = 0; i < arr.length; i++) {
  5347. arr[i] = {index: i, value: arr[i]};
  5348. }
  5349. var valueCompareFn = opt_compareFn || goog.array.defaultCompare;
  5350. function stableCompareFn(obj1, obj2) {
  5351. return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;
  5352. };
  5353. goog.array.sort(arr, stableCompareFn);
  5354. for (var i = 0; i < arr.length; i++) {
  5355. arr[i] = arr[i].value;
  5356. }
  5357. };
  5358. /**
  5359. * Sort the specified array into ascending order based on item keys
  5360. * returned by the specified key function.
  5361. * If no opt_compareFn is specified, the keys are compared in ascending order
  5362. * using <code>goog.array.defaultCompare</code>.
  5363. *
  5364. * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>
  5365. * and f(n) is runtime of the key function.
  5366. *
  5367. * @param {Array<T>} arr The array to be sorted.
  5368. * @param {function(T): K} keyFn Function taking array element and returning
  5369. * a key used for sorting this element.
  5370. * @param {?function(K, K): number=} opt_compareFn Optional comparison function
  5371. * by which the keys are to be ordered. Should take 2 arguments to compare,
  5372. * and return a negative number, zero, or a positive number depending on
  5373. * whether the first argument is less than, equal to, or greater than the
  5374. * second.
  5375. * @template T,K
  5376. */
  5377. goog.array.sortByKey = function(arr, keyFn, opt_compareFn) {
  5378. var keyCompareFn = opt_compareFn || goog.array.defaultCompare;
  5379. goog.array.sort(arr, function(a, b) {
  5380. return keyCompareFn(keyFn(a), keyFn(b));
  5381. });
  5382. };
  5383. /**
  5384. * Sorts an array of objects by the specified object key and compare
  5385. * function. If no compare function is provided, the key values are
  5386. * compared in ascending order using <code>goog.array.defaultCompare</code>.
  5387. * This won't work for keys that get renamed by the compiler. So use
  5388. * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.
  5389. * @param {Array<Object>} arr An array of objects to sort.
  5390. * @param {string} key The object key to sort by.
  5391. * @param {Function=} opt_compareFn The function to use to compare key
  5392. * values.
  5393. */
  5394. goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {
  5395. goog.array.sortByKey(arr,
  5396. function(obj) { return obj[key]; },
  5397. opt_compareFn);
  5398. };
  5399. /**
  5400. * Tells if the array is sorted.
  5401. * @param {!Array<T>} arr The array.
  5402. * @param {?function(T,T):number=} opt_compareFn Function to compare the
  5403. * array elements.
  5404. * Should take 2 arguments to compare, and return a negative number, zero,
  5405. * or a positive number depending on whether the first argument is less
  5406. * than, equal to, or greater than the second.
  5407. * @param {boolean=} opt_strict If true no equal elements are allowed.
  5408. * @return {boolean} Whether the array is sorted.
  5409. * @template T
  5410. */
  5411. goog.array.isSorted = function(arr, opt_compareFn, opt_strict) {
  5412. var compare = opt_compareFn || goog.array.defaultCompare;
  5413. for (var i = 1; i < arr.length; i++) {
  5414. var compareResult = compare(arr[i - 1], arr[i]);
  5415. if (compareResult > 0 || compareResult == 0 && opt_strict) {
  5416. return false;
  5417. }
  5418. }
  5419. return true;
  5420. };
  5421. /**
  5422. * Compares two arrays for equality. Two arrays are considered equal if they
  5423. * have the same length and their corresponding elements are equal according to
  5424. * the comparison function.
  5425. *
  5426. * @param {goog.array.ArrayLike} arr1 The first array to compare.
  5427. * @param {goog.array.ArrayLike} arr2 The second array to compare.
  5428. * @param {Function=} opt_equalsFn Optional comparison function.
  5429. * Should take 2 arguments to compare, and return true if the arguments
  5430. * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
  5431. * compares the elements using the built-in '===' operator.
  5432. * @return {boolean} Whether the two arrays are equal.
  5433. */
  5434. goog.array.equals = function(arr1, arr2, opt_equalsFn) {
  5435. if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
  5436. arr1.length != arr2.length) {
  5437. return false;
  5438. }
  5439. var l = arr1.length;
  5440. var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
  5441. for (var i = 0; i < l; i++) {
  5442. if (!equalsFn(arr1[i], arr2[i])) {
  5443. return false;
  5444. }
  5445. }
  5446. return true;
  5447. };
  5448. /**
  5449. * 3-way array compare function.
  5450. * @param {!Array<VALUE>|!goog.array.ArrayLike} arr1 The first array to
  5451. * compare.
  5452. * @param {!Array<VALUE>|!goog.array.ArrayLike} arr2 The second array to
  5453. * compare.
  5454. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  5455. * function by which the array is to be ordered. Should take 2 arguments to
  5456. * compare, and return a negative number, zero, or a positive number
  5457. * depending on whether the first argument is less than, equal to, or
  5458. * greater than the second.
  5459. * @return {number} Negative number, zero, or a positive number depending on
  5460. * whether the first argument is less than, equal to, or greater than the
  5461. * second.
  5462. * @template VALUE
  5463. */
  5464. goog.array.compare3 = function(arr1, arr2, opt_compareFn) {
  5465. var compare = opt_compareFn || goog.array.defaultCompare;
  5466. var l = Math.min(arr1.length, arr2.length);
  5467. for (var i = 0; i < l; i++) {
  5468. var result = compare(arr1[i], arr2[i]);
  5469. if (result != 0) {
  5470. return result;
  5471. }
  5472. }
  5473. return goog.array.defaultCompare(arr1.length, arr2.length);
  5474. };
  5475. /**
  5476. * Compares its two arguments for order, using the built in < and >
  5477. * operators.
  5478. * @param {VALUE} a The first object to be compared.
  5479. * @param {VALUE} b The second object to be compared.
  5480. * @return {number} A negative number, zero, or a positive number as the first
  5481. * argument is less than, equal to, or greater than the second,
  5482. * respectively.
  5483. * @template VALUE
  5484. */
  5485. goog.array.defaultCompare = function(a, b) {
  5486. return a > b ? 1 : a < b ? -1 : 0;
  5487. };
  5488. /**
  5489. * Compares its two arguments for inverse order, using the built in < and >
  5490. * operators.
  5491. * @param {VALUE} a The first object to be compared.
  5492. * @param {VALUE} b The second object to be compared.
  5493. * @return {number} A negative number, zero, or a positive number as the first
  5494. * argument is greater than, equal to, or less than the second,
  5495. * respectively.
  5496. * @template VALUE
  5497. */
  5498. goog.array.inverseDefaultCompare = function(a, b) {
  5499. return -goog.array.defaultCompare(a, b);
  5500. };
  5501. /**
  5502. * Compares its two arguments for equality, using the built in === operator.
  5503. * @param {*} a The first object to compare.
  5504. * @param {*} b The second object to compare.
  5505. * @return {boolean} True if the two arguments are equal, false otherwise.
  5506. */
  5507. goog.array.defaultCompareEquality = function(a, b) {
  5508. return a === b;
  5509. };
  5510. /**
  5511. * Inserts a value into a sorted array. The array is not modified if the
  5512. * value is already present.
  5513. * @param {Array<VALUE>|goog.array.ArrayLike} array The array to modify.
  5514. * @param {VALUE} value The object to insert.
  5515. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  5516. * function by which the array is ordered. Should take 2 arguments to
  5517. * compare, and return a negative number, zero, or a positive number
  5518. * depending on whether the first argument is less than, equal to, or
  5519. * greater than the second.
  5520. * @return {boolean} True if an element was inserted.
  5521. * @template VALUE
  5522. */
  5523. goog.array.binaryInsert = function(array, value, opt_compareFn) {
  5524. var index = goog.array.binarySearch(array, value, opt_compareFn);
  5525. if (index < 0) {
  5526. goog.array.insertAt(array, value, -(index + 1));
  5527. return true;
  5528. }
  5529. return false;
  5530. };
  5531. /**
  5532. * Removes a value from a sorted array.
  5533. * @param {!Array<VALUE>|!goog.array.ArrayLike} array The array to modify.
  5534. * @param {VALUE} value The object to remove.
  5535. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison
  5536. * function by which the array is ordered. Should take 2 arguments to
  5537. * compare, and return a negative number, zero, or a positive number
  5538. * depending on whether the first argument is less than, equal to, or
  5539. * greater than the second.
  5540. * @return {boolean} True if an element was removed.
  5541. * @template VALUE
  5542. */
  5543. goog.array.binaryRemove = function(array, value, opt_compareFn) {
  5544. var index = goog.array.binarySearch(array, value, opt_compareFn);
  5545. return (index >= 0) ? goog.array.removeAt(array, index) : false;
  5546. };
  5547. /**
  5548. * Splits an array into disjoint buckets according to a splitting function.
  5549. * @param {Array<T>} array The array.
  5550. * @param {function(this:S, T,number,Array<T>):?} sorter Function to call for
  5551. * every element. This takes 3 arguments (the element, the index and the
  5552. * array) and must return a valid object key (a string, number, etc), or
  5553. * undefined, if that object should not be placed in a bucket.
  5554. * @param {S=} opt_obj The object to be used as the value of 'this' within
  5555. * sorter.
  5556. * @return {!Object} An object, with keys being all of the unique return values
  5557. * of sorter, and values being arrays containing the items for
  5558. * which the splitter returned that key.
  5559. * @template T,S
  5560. */
  5561. goog.array.bucket = function(array, sorter, opt_obj) {
  5562. var buckets = {};
  5563. for (var i = 0; i < array.length; i++) {
  5564. var value = array[i];
  5565. var key = sorter.call(opt_obj, value, i, array);
  5566. if (goog.isDef(key)) {
  5567. // Push the value to the right bucket, creating it if necessary.
  5568. var bucket = buckets[key] || (buckets[key] = []);
  5569. bucket.push(value);
  5570. }
  5571. }
  5572. return buckets;
  5573. };
  5574. /**
  5575. * Creates a new object built from the provided array and the key-generation
  5576. * function.
  5577. * @param {Array<T>|goog.array.ArrayLike} arr Array or array like object over
  5578. * which to iterate whose elements will be the values in the new object.
  5579. * @param {?function(this:S, T, number, ?) : string} keyFunc The function to
  5580. * call for every element. This function takes 3 arguments (the element, the
  5581. * index and the array) and should return a string that will be used as the
  5582. * key for the element in the new object. If the function returns the same
  5583. * key for more than one element, the value for that key is
  5584. * implementation-defined.
  5585. * @param {S=} opt_obj The object to be used as the value of 'this'
  5586. * within keyFunc.
  5587. * @return {!Object<T>} The new object.
  5588. * @template T,S
  5589. */
  5590. goog.array.toObject = function(arr, keyFunc, opt_obj) {
  5591. var ret = {};
  5592. goog.array.forEach(arr, function(element, index) {
  5593. ret[keyFunc.call(opt_obj, element, index, arr)] = element;
  5594. });
  5595. return ret;
  5596. };
  5597. /**
  5598. * Creates a range of numbers in an arithmetic progression.
  5599. *
  5600. * Range takes 1, 2, or 3 arguments:
  5601. * <pre>
  5602. * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]
  5603. * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]
  5604. * range(-2, -5, -1) produces [-2, -3, -4]
  5605. * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.
  5606. * </pre>
  5607. *
  5608. * @param {number} startOrEnd The starting value of the range if an end argument
  5609. * is provided. Otherwise, the start value is 0, and this is the end value.
  5610. * @param {number=} opt_end The optional end value of the range.
  5611. * @param {number=} opt_step The step size between range values. Defaults to 1
  5612. * if opt_step is undefined or 0.
  5613. * @return {!Array<number>} An array of numbers for the requested range. May be
  5614. * an empty array if adding the step would not converge toward the end
  5615. * value.
  5616. */
  5617. goog.array.range = function(startOrEnd, opt_end, opt_step) {
  5618. var array = [];
  5619. var start = 0;
  5620. var end = startOrEnd;
  5621. var step = opt_step || 1;
  5622. if (opt_end !== undefined) {
  5623. start = startOrEnd;
  5624. end = opt_end;
  5625. }
  5626. if (step * (end - start) < 0) {
  5627. // Sign mismatch: start + step will never reach the end value.
  5628. return [];
  5629. }
  5630. if (step > 0) {
  5631. for (var i = start; i < end; i += step) {
  5632. array.push(i);
  5633. }
  5634. } else {
  5635. for (var i = start; i > end; i += step) {
  5636. array.push(i);
  5637. }
  5638. }
  5639. return array;
  5640. };
  5641. /**
  5642. * Returns an array consisting of the given value repeated N times.
  5643. *
  5644. * @param {VALUE} value The value to repeat.
  5645. * @param {number} n The repeat count.
  5646. * @return {!Array<VALUE>} An array with the repeated value.
  5647. * @template VALUE
  5648. */
  5649. goog.array.repeat = function(value, n) {
  5650. var array = [];
  5651. for (var i = 0; i < n; i++) {
  5652. array[i] = value;
  5653. }
  5654. return array;
  5655. };
  5656. /**
  5657. * Returns an array consisting of every argument with all arrays
  5658. * expanded in-place recursively.
  5659. *
  5660. * @param {...*} var_args The values to flatten.
  5661. * @return {!Array<?>} An array containing the flattened values.
  5662. */
  5663. goog.array.flatten = function(var_args) {
  5664. var CHUNK_SIZE = 8192;
  5665. var result = [];
  5666. for (var i = 0; i < arguments.length; i++) {
  5667. var element = arguments[i];
  5668. if (goog.isArray(element)) {
  5669. for (var c = 0; c < element.length; c += CHUNK_SIZE) {
  5670. var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);
  5671. var recurseResult = goog.array.flatten.apply(null, chunk);
  5672. for (var r = 0; r < recurseResult.length; r++) {
  5673. result.push(recurseResult[r]);
  5674. }
  5675. }
  5676. } else {
  5677. result.push(element);
  5678. }
  5679. }
  5680. return result;
  5681. };
  5682. /**
  5683. * Rotates an array in-place. After calling this method, the element at
  5684. * index i will be the element previously at index (i - n) %
  5685. * array.length, for all values of i between 0 and array.length - 1,
  5686. * inclusive.
  5687. *
  5688. * For example, suppose list comprises [t, a, n, k, s]. After invoking
  5689. * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].
  5690. *
  5691. * @param {!Array<T>} array The array to rotate.
  5692. * @param {number} n The amount to rotate.
  5693. * @return {!Array<T>} The array.
  5694. * @template T
  5695. */
  5696. goog.array.rotate = function(array, n) {
  5697. goog.asserts.assert(array.length != null);
  5698. if (array.length) {
  5699. n %= array.length;
  5700. if (n > 0) {
  5701. goog.array.ARRAY_PROTOTYPE_.unshift.apply(array, array.splice(-n, n));
  5702. } else if (n < 0) {
  5703. goog.array.ARRAY_PROTOTYPE_.push.apply(array, array.splice(0, -n));
  5704. }
  5705. }
  5706. return array;
  5707. };
  5708. /**
  5709. * Moves one item of an array to a new position keeping the order of the rest
  5710. * of the items. Example use case: keeping a list of JavaScript objects
  5711. * synchronized with the corresponding list of DOM elements after one of the
  5712. * elements has been dragged to a new position.
  5713. * @param {!(Array|Arguments|{length:number})} arr The array to modify.
  5714. * @param {number} fromIndex Index of the item to move between 0 and
  5715. * {@code arr.length - 1}.
  5716. * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.
  5717. */
  5718. goog.array.moveItem = function(arr, fromIndex, toIndex) {
  5719. goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);
  5720. goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);
  5721. // Remove 1 item at fromIndex.
  5722. var removedItems = goog.array.ARRAY_PROTOTYPE_.splice.call(arr, fromIndex, 1);
  5723. // Insert the removed item at toIndex.
  5724. goog.array.ARRAY_PROTOTYPE_.splice.call(arr, toIndex, 0, removedItems[0]);
  5725. // We don't use goog.array.insertAt and goog.array.removeAt, because they're
  5726. // significantly slower than splice.
  5727. };
  5728. /**
  5729. * Creates a new array for which the element at position i is an array of the
  5730. * ith element of the provided arrays. The returned array will only be as long
  5731. * as the shortest array provided; additional values are ignored. For example,
  5732. * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].
  5733. *
  5734. * This is similar to the zip() function in Python. See {@link
  5735. * http://docs.python.org/library/functions.html#zip}
  5736. *
  5737. * @param {...!goog.array.ArrayLike} var_args Arrays to be combined.
  5738. * @return {!Array<!Array<?>>} A new array of arrays created from
  5739. * provided arrays.
  5740. */
  5741. goog.array.zip = function(var_args) {
  5742. if (!arguments.length) {
  5743. return [];
  5744. }
  5745. var result = [];
  5746. for (var i = 0; true; i++) {
  5747. var value = [];
  5748. for (var j = 0; j < arguments.length; j++) {
  5749. var arr = arguments[j];
  5750. // If i is larger than the array length, this is the shortest array.
  5751. if (i >= arr.length) {
  5752. return result;
  5753. }
  5754. value.push(arr[i]);
  5755. }
  5756. result.push(value);
  5757. }
  5758. };
  5759. /**
  5760. * Shuffles the values in the specified array using the Fisher-Yates in-place
  5761. * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()
  5762. * and so resets the state of that random number generator. Similarly, may reset
  5763. * the state of the any other specified random number generator.
  5764. *
  5765. * Runtime: O(n)
  5766. *
  5767. * @param {!Array<?>} arr The array to be shuffled.
  5768. * @param {function():number=} opt_randFn Optional random function to use for
  5769. * shuffling.
  5770. * Takes no arguments, and returns a random number on the interval [0, 1).
  5771. * Defaults to Math.random() using JavaScript's built-in Math library.
  5772. */
  5773. goog.array.shuffle = function(arr, opt_randFn) {
  5774. var randFn = opt_randFn || Math.random;
  5775. for (var i = arr.length - 1; i > 0; i--) {
  5776. // Choose a random array index in [0, i] (inclusive with i).
  5777. var j = Math.floor(randFn() * (i + 1));
  5778. var tmp = arr[i];
  5779. arr[i] = arr[j];
  5780. arr[j] = tmp;
  5781. }
  5782. };
  5783. /**
  5784. * Returns a new array of elements from arr, based on the indexes of elements
  5785. * provided by index_arr. For example, the result of index copying
  5786. * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].
  5787. *
  5788. * @param {!Array<T>} arr The array to get a indexed copy from.
  5789. * @param {!Array<number>} index_arr An array of indexes to get from arr.
  5790. * @return {!Array<T>} A new array of elements from arr in index_arr order.
  5791. * @template T
  5792. */
  5793. goog.array.copyByIndex = function(arr, index_arr) {
  5794. var result = [];
  5795. goog.array.forEach(index_arr, function(index) {
  5796. result.push(arr[index]);
  5797. });
  5798. return result;
  5799. };
  5800. goog.provide('ol.array');
  5801. goog.require('goog.array');
  5802. goog.require('goog.asserts');
  5803. /**
  5804. * @param {Array.<number>} arr Array.
  5805. * @param {number} target Target.
  5806. * @return {number} Index.
  5807. */
  5808. ol.array.binaryFindNearest = function(arr, target) {
  5809. var index = goog.array.binarySearch(arr, target,
  5810. /**
  5811. * @param {number} a A.
  5812. * @param {number} b B.
  5813. * @return {number} b minus a.
  5814. */
  5815. function(a, b) {
  5816. return b - a;
  5817. });
  5818. if (index >= 0) {
  5819. return index;
  5820. } else if (index == -1) {
  5821. return 0;
  5822. } else if (index == -arr.length - 1) {
  5823. return arr.length - 1;
  5824. } else {
  5825. var left = -index - 2;
  5826. var right = -index - 1;
  5827. if (arr[left] - target < target - arr[right]) {
  5828. return left;
  5829. } else {
  5830. return right;
  5831. }
  5832. }
  5833. };
  5834. /**
  5835. * Whether the array contains the given object.
  5836. * @param {Array.<*>} arr The array to test for the presence of the element.
  5837. * @param {*} obj The object for which to test.
  5838. * @return {boolean} The object is in the array.
  5839. */
  5840. ol.array.includes = function(arr, obj) {
  5841. return arr.indexOf(obj) >= 0;
  5842. };
  5843. /**
  5844. * @param {Array.<number>} arr Array.
  5845. * @param {number} target Target.
  5846. * @param {number} direction 0 means return the nearest, > 0
  5847. * means return the largest nearest, < 0 means return the
  5848. * smallest nearest.
  5849. * @return {number} Index.
  5850. */
  5851. ol.array.linearFindNearest = function(arr, target, direction) {
  5852. var n = arr.length;
  5853. if (arr[0] <= target) {
  5854. return 0;
  5855. } else if (target <= arr[n - 1]) {
  5856. return n - 1;
  5857. } else {
  5858. var i;
  5859. if (direction > 0) {
  5860. for (i = 1; i < n; ++i) {
  5861. if (arr[i] < target) {
  5862. return i - 1;
  5863. }
  5864. }
  5865. } else if (direction < 0) {
  5866. for (i = 1; i < n; ++i) {
  5867. if (arr[i] <= target) {
  5868. return i;
  5869. }
  5870. }
  5871. } else {
  5872. for (i = 1; i < n; ++i) {
  5873. if (arr[i] == target) {
  5874. return i;
  5875. } else if (arr[i] < target) {
  5876. if (arr[i - 1] - target < target - arr[i]) {
  5877. return i - 1;
  5878. } else {
  5879. return i;
  5880. }
  5881. }
  5882. }
  5883. }
  5884. // We should never get here, but the compiler complains
  5885. // if it finds a path for which no number is returned.
  5886. goog.asserts.fail();
  5887. return n - 1;
  5888. }
  5889. };
  5890. /**
  5891. * @param {Array.<*>} arr Array.
  5892. * @param {number} begin Begin index.
  5893. * @param {number} end End index.
  5894. */
  5895. ol.array.reverseSubArray = function(arr, begin, end) {
  5896. goog.asserts.assert(begin >= 0,
  5897. 'Array begin index should be equal to or greater than 0');
  5898. goog.asserts.assert(end < arr.length,
  5899. 'Array end index should be less than the array length');
  5900. while (begin < end) {
  5901. var tmp = arr[begin];
  5902. arr[begin] = arr[end];
  5903. arr[end] = tmp;
  5904. ++begin;
  5905. --end;
  5906. }
  5907. };
  5908. goog.provide('ol.ResolutionConstraint');
  5909. goog.provide('ol.ResolutionConstraintType');
  5910. goog.require('ol.array');
  5911. goog.require('ol.math');
  5912. /**
  5913. * @typedef {function((number|undefined), number, number): (number|undefined)}
  5914. */
  5915. ol.ResolutionConstraintType;
  5916. /**
  5917. * @param {Array.<number>} resolutions Resolutions.
  5918. * @return {ol.ResolutionConstraintType} Zoom function.
  5919. */
  5920. ol.ResolutionConstraint.createSnapToResolutions =
  5921. function(resolutions) {
  5922. return (
  5923. /**
  5924. * @param {number|undefined} resolution Resolution.
  5925. * @param {number} delta Delta.
  5926. * @param {number} direction Direction.
  5927. * @return {number|undefined} Resolution.
  5928. */
  5929. function(resolution, delta, direction) {
  5930. if (resolution !== undefined) {
  5931. var z =
  5932. ol.array.linearFindNearest(resolutions, resolution, direction);
  5933. z = ol.math.clamp(z + delta, 0, resolutions.length - 1);
  5934. return resolutions[z];
  5935. } else {
  5936. return undefined;
  5937. }
  5938. });
  5939. };
  5940. /**
  5941. * @param {number} power Power.
  5942. * @param {number} maxResolution Maximum resolution.
  5943. * @param {number=} opt_maxLevel Maximum level.
  5944. * @return {ol.ResolutionConstraintType} Zoom function.
  5945. */
  5946. ol.ResolutionConstraint.createSnapToPower =
  5947. function(power, maxResolution, opt_maxLevel) {
  5948. return (
  5949. /**
  5950. * @param {number|undefined} resolution Resolution.
  5951. * @param {number} delta Delta.
  5952. * @param {number} direction Direction.
  5953. * @return {number|undefined} Resolution.
  5954. */
  5955. function(resolution, delta, direction) {
  5956. if (resolution !== undefined) {
  5957. var offset;
  5958. if (direction > 0) {
  5959. offset = 0;
  5960. } else if (direction < 0) {
  5961. offset = 1;
  5962. } else {
  5963. offset = 0.5;
  5964. }
  5965. var oldLevel = Math.floor(
  5966. Math.log(maxResolution / resolution) / Math.log(power) + offset);
  5967. var newLevel = Math.max(oldLevel + delta, 0);
  5968. if (opt_maxLevel !== undefined) {
  5969. newLevel = Math.min(newLevel, opt_maxLevel);
  5970. }
  5971. return maxResolution / Math.pow(power, newLevel);
  5972. } else {
  5973. return undefined;
  5974. }
  5975. });
  5976. };
  5977. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  5978. //
  5979. // Licensed under the Apache License, Version 2.0 (the "License");
  5980. // you may not use this file except in compliance with the License.
  5981. // You may obtain a copy of the License at
  5982. //
  5983. // http://www.apache.org/licenses/LICENSE-2.0
  5984. //
  5985. // Unless required by applicable law or agreed to in writing, software
  5986. // distributed under the License is distributed on an "AS-IS" BASIS,
  5987. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5988. // See the License for the specific language governing permissions and
  5989. // limitations under the License.
  5990. /**
  5991. * @fileoverview Additional mathematical functions.
  5992. */
  5993. goog.provide('goog.math');
  5994. goog.require('goog.array');
  5995. goog.require('goog.asserts');
  5996. /**
  5997. * Returns a random integer greater than or equal to 0 and less than {@code a}.
  5998. * @param {number} a The upper bound for the random integer (exclusive).
  5999. * @return {number} A random integer N such that 0 <= N < a.
  6000. */
  6001. goog.math.randomInt = function(a) {
  6002. return Math.floor(Math.random() * a);
  6003. };
  6004. /**
  6005. * Returns a random number greater than or equal to {@code a} and less than
  6006. * {@code b}.
  6007. * @param {number} a The lower bound for the random number (inclusive).
  6008. * @param {number} b The upper bound for the random number (exclusive).
  6009. * @return {number} A random number N such that a <= N < b.
  6010. */
  6011. goog.math.uniformRandom = function(a, b) {
  6012. return a + Math.random() * (b - a);
  6013. };
  6014. /**
  6015. * Takes a number and clamps it to within the provided bounds.
  6016. * @param {number} value The input number.
  6017. * @param {number} min The minimum value to return.
  6018. * @param {number} max The maximum value to return.
  6019. * @return {number} The input number if it is within bounds, or the nearest
  6020. * number within the bounds.
  6021. */
  6022. goog.math.clamp = function(value, min, max) {
  6023. return Math.min(Math.max(value, min), max);
  6024. };
  6025. /**
  6026. * The % operator in JavaScript returns the remainder of a / b, but differs from
  6027. * some other languages in that the result will have the same sign as the
  6028. * dividend. For example, -1 % 8 == -1, whereas in some other languages
  6029. * (such as Python) the result would be 7. This function emulates the more
  6030. * correct modulo behavior, which is useful for certain applications such as
  6031. * calculating an offset index in a circular list.
  6032. *
  6033. * @param {number} a The dividend.
  6034. * @param {number} b The divisor.
  6035. * @return {number} a % b where the result is between 0 and b (either 0 <= x < b
  6036. * or b < x <= 0, depending on the sign of b).
  6037. */
  6038. goog.math.modulo = function(a, b) {
  6039. var r = a % b;
  6040. // If r and b differ in sign, add b to wrap the result to the correct sign.
  6041. return (r * b < 0) ? r + b : r;
  6042. };
  6043. /**
  6044. * Performs linear interpolation between values a and b. Returns the value
  6045. * between a and b proportional to x (when x is between 0 and 1. When x is
  6046. * outside this range, the return value is a linear extrapolation).
  6047. * @param {number} a A number.
  6048. * @param {number} b A number.
  6049. * @param {number} x The proportion between a and b.
  6050. * @return {number} The interpolated value between a and b.
  6051. */
  6052. goog.math.lerp = function(a, b, x) {
  6053. return a + x * (b - a);
  6054. };
  6055. /**
  6056. * Tests whether the two values are equal to each other, within a certain
  6057. * tolerance to adjust for floating point errors.
  6058. * @param {number} a A number.
  6059. * @param {number} b A number.
  6060. * @param {number=} opt_tolerance Optional tolerance range. Defaults
  6061. * to 0.000001. If specified, should be greater than 0.
  6062. * @return {boolean} Whether {@code a} and {@code b} are nearly equal.
  6063. */
  6064. goog.math.nearlyEquals = function(a, b, opt_tolerance) {
  6065. return Math.abs(a - b) <= (opt_tolerance || 0.000001);
  6066. };
  6067. // TODO(user): Rename to normalizeAngle, retaining old name as deprecated
  6068. // alias.
  6069. /**
  6070. * Normalizes an angle to be in range [0-360). Angles outside this range will
  6071. * be normalized to be the equivalent angle with that range.
  6072. * @param {number} angle Angle in degrees.
  6073. * @return {number} Standardized angle.
  6074. */
  6075. goog.math.standardAngle = function(angle) {
  6076. return goog.math.modulo(angle, 360);
  6077. };
  6078. /**
  6079. * Normalizes an angle to be in range [0-2*PI). Angles outside this range will
  6080. * be normalized to be the equivalent angle with that range.
  6081. * @param {number} angle Angle in radians.
  6082. * @return {number} Standardized angle.
  6083. */
  6084. goog.math.standardAngleInRadians = function(angle) {
  6085. return goog.math.modulo(angle, 2 * Math.PI);
  6086. };
  6087. /**
  6088. * Converts degrees to radians.
  6089. * @param {number} angleDegrees Angle in degrees.
  6090. * @return {number} Angle in radians.
  6091. */
  6092. goog.math.toRadians = function(angleDegrees) {
  6093. return angleDegrees * Math.PI / 180;
  6094. };
  6095. /**
  6096. * Converts radians to degrees.
  6097. * @param {number} angleRadians Angle in radians.
  6098. * @return {number} Angle in degrees.
  6099. */
  6100. goog.math.toDegrees = function(angleRadians) {
  6101. return angleRadians * 180 / Math.PI;
  6102. };
  6103. /**
  6104. * For a given angle and radius, finds the X portion of the offset.
  6105. * @param {number} degrees Angle in degrees (zero points in +X direction).
  6106. * @param {number} radius Radius.
  6107. * @return {number} The x-distance for the angle and radius.
  6108. */
  6109. goog.math.angleDx = function(degrees, radius) {
  6110. return radius * Math.cos(goog.math.toRadians(degrees));
  6111. };
  6112. /**
  6113. * For a given angle and radius, finds the Y portion of the offset.
  6114. * @param {number} degrees Angle in degrees (zero points in +X direction).
  6115. * @param {number} radius Radius.
  6116. * @return {number} The y-distance for the angle and radius.
  6117. */
  6118. goog.math.angleDy = function(degrees, radius) {
  6119. return radius * Math.sin(goog.math.toRadians(degrees));
  6120. };
  6121. /**
  6122. * Computes the angle between two points (x1,y1) and (x2,y2).
  6123. * Angle zero points in the +X direction, 90 degrees points in the +Y
  6124. * direction (down) and from there we grow clockwise towards 360 degrees.
  6125. * @param {number} x1 x of first point.
  6126. * @param {number} y1 y of first point.
  6127. * @param {number} x2 x of second point.
  6128. * @param {number} y2 y of second point.
  6129. * @return {number} Standardized angle in degrees of the vector from
  6130. * x1,y1 to x2,y2.
  6131. */
  6132. goog.math.angle = function(x1, y1, x2, y2) {
  6133. return goog.math.standardAngle(goog.math.toDegrees(Math.atan2(y2 - y1,
  6134. x2 - x1)));
  6135. };
  6136. /**
  6137. * Computes the difference between startAngle and endAngle (angles in degrees).
  6138. * @param {number} startAngle Start angle in degrees.
  6139. * @param {number} endAngle End angle in degrees.
  6140. * @return {number} The number of degrees that when added to
  6141. * startAngle will result in endAngle. Positive numbers mean that the
  6142. * direction is clockwise. Negative numbers indicate a counter-clockwise
  6143. * direction.
  6144. * The shortest route (clockwise vs counter-clockwise) between the angles
  6145. * is used.
  6146. * When the difference is 180 degrees, the function returns 180 (not -180)
  6147. * angleDifference(30, 40) is 10, and angleDifference(40, 30) is -10.
  6148. * angleDifference(350, 10) is 20, and angleDifference(10, 350) is -20.
  6149. */
  6150. goog.math.angleDifference = function(startAngle, endAngle) {
  6151. var d = goog.math.standardAngle(endAngle) -
  6152. goog.math.standardAngle(startAngle);
  6153. if (d > 180) {
  6154. d = d - 360;
  6155. } else if (d <= -180) {
  6156. d = 360 + d;
  6157. }
  6158. return d;
  6159. };
  6160. /**
  6161. * Returns the sign of a number as per the "sign" or "signum" function.
  6162. * @param {number} x The number to take the sign of.
  6163. * @return {number} -1 when negative, 1 when positive, 0 when 0. Preserves
  6164. * signed zeros and NaN.
  6165. */
  6166. goog.math.sign = Math.sign || function(x) {
  6167. if (x > 0) {
  6168. return 1;
  6169. }
  6170. if (x < 0) {
  6171. return -1;
  6172. }
  6173. return x; // Preserves signed zeros and NaN.
  6174. };
  6175. /**
  6176. * JavaScript implementation of Longest Common Subsequence problem.
  6177. * http://en.wikipedia.org/wiki/Longest_common_subsequence
  6178. *
  6179. * Returns the longest possible array that is subarray of both of given arrays.
  6180. *
  6181. * @param {Array<Object>} array1 First array of objects.
  6182. * @param {Array<Object>} array2 Second array of objects.
  6183. * @param {Function=} opt_compareFn Function that acts as a custom comparator
  6184. * for the array ojects. Function should return true if objects are equal,
  6185. * otherwise false.
  6186. * @param {Function=} opt_collectorFn Function used to decide what to return
  6187. * as a result subsequence. It accepts 2 arguments: index of common element
  6188. * in the first array and index in the second. The default function returns
  6189. * element from the first array.
  6190. * @return {!Array<Object>} A list of objects that are common to both arrays
  6191. * such that there is no common subsequence with size greater than the
  6192. * length of the list.
  6193. */
  6194. goog.math.longestCommonSubsequence = function(
  6195. array1, array2, opt_compareFn, opt_collectorFn) {
  6196. var compare = opt_compareFn || function(a, b) {
  6197. return a == b;
  6198. };
  6199. var collect = opt_collectorFn || function(i1, i2) {
  6200. return array1[i1];
  6201. };
  6202. var length1 = array1.length;
  6203. var length2 = array2.length;
  6204. var arr = [];
  6205. for (var i = 0; i < length1 + 1; i++) {
  6206. arr[i] = [];
  6207. arr[i][0] = 0;
  6208. }
  6209. for (var j = 0; j < length2 + 1; j++) {
  6210. arr[0][j] = 0;
  6211. }
  6212. for (i = 1; i <= length1; i++) {
  6213. for (j = 1; j <= length2; j++) {
  6214. if (compare(array1[i - 1], array2[j - 1])) {
  6215. arr[i][j] = arr[i - 1][j - 1] + 1;
  6216. } else {
  6217. arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
  6218. }
  6219. }
  6220. }
  6221. // Backtracking
  6222. var result = [];
  6223. var i = length1, j = length2;
  6224. while (i > 0 && j > 0) {
  6225. if (compare(array1[i - 1], array2[j - 1])) {
  6226. result.unshift(collect(i - 1, j - 1));
  6227. i--;
  6228. j--;
  6229. } else {
  6230. if (arr[i - 1][j] > arr[i][j - 1]) {
  6231. i--;
  6232. } else {
  6233. j--;
  6234. }
  6235. }
  6236. }
  6237. return result;
  6238. };
  6239. /**
  6240. * Returns the sum of the arguments.
  6241. * @param {...number} var_args Numbers to add.
  6242. * @return {number} The sum of the arguments (0 if no arguments were provided,
  6243. * {@code NaN} if any of the arguments is not a valid number).
  6244. */
  6245. goog.math.sum = function(var_args) {
  6246. return /** @type {number} */ (goog.array.reduce(arguments,
  6247. function(sum, value) {
  6248. return sum + value;
  6249. }, 0));
  6250. };
  6251. /**
  6252. * Returns the arithmetic mean of the arguments.
  6253. * @param {...number} var_args Numbers to average.
  6254. * @return {number} The average of the arguments ({@code NaN} if no arguments
  6255. * were provided or any of the arguments is not a valid number).
  6256. */
  6257. goog.math.average = function(var_args) {
  6258. return goog.math.sum.apply(null, arguments) / arguments.length;
  6259. };
  6260. /**
  6261. * Returns the unbiased sample variance of the arguments. For a definition,
  6262. * see e.g. http://en.wikipedia.org/wiki/Variance
  6263. * @param {...number} var_args Number samples to analyze.
  6264. * @return {number} The unbiased sample variance of the arguments (0 if fewer
  6265. * than two samples were provided, or {@code NaN} if any of the samples is
  6266. * not a valid number).
  6267. */
  6268. goog.math.sampleVariance = function(var_args) {
  6269. var sampleSize = arguments.length;
  6270. if (sampleSize < 2) {
  6271. return 0;
  6272. }
  6273. var mean = goog.math.average.apply(null, arguments);
  6274. var variance = goog.math.sum.apply(null, goog.array.map(arguments,
  6275. function(val) {
  6276. return Math.pow(val - mean, 2);
  6277. })) / (sampleSize - 1);
  6278. return variance;
  6279. };
  6280. /**
  6281. * Returns the sample standard deviation of the arguments. For a definition of
  6282. * sample standard deviation, see e.g.
  6283. * http://en.wikipedia.org/wiki/Standard_deviation
  6284. * @param {...number} var_args Number samples to analyze.
  6285. * @return {number} The sample standard deviation of the arguments (0 if fewer
  6286. * than two samples were provided, or {@code NaN} if any of the samples is
  6287. * not a valid number).
  6288. */
  6289. goog.math.standardDeviation = function(var_args) {
  6290. return Math.sqrt(goog.math.sampleVariance.apply(null, arguments));
  6291. };
  6292. /**
  6293. * Returns whether the supplied number represents an integer, i.e. that is has
  6294. * no fractional component. No range-checking is performed on the number.
  6295. * @param {number} num The number to test.
  6296. * @return {boolean} Whether {@code num} is an integer.
  6297. */
  6298. goog.math.isInt = function(num) {
  6299. return isFinite(num) && num % 1 == 0;
  6300. };
  6301. /**
  6302. * Returns whether the supplied number is finite and not NaN.
  6303. * @param {number} num The number to test.
  6304. * @return {boolean} Whether {@code num} is a finite number.
  6305. */
  6306. goog.math.isFiniteNumber = function(num) {
  6307. return isFinite(num) && !isNaN(num);
  6308. };
  6309. /**
  6310. * @param {number} num The number to test.
  6311. * @return {boolean} Whether it is negative zero.
  6312. */
  6313. goog.math.isNegativeZero = function(num) {
  6314. return num == 0 && 1 / num < 0;
  6315. };
  6316. /**
  6317. * Returns the precise value of floor(log10(num)).
  6318. * Simpler implementations didn't work because of floating point rounding
  6319. * errors. For example
  6320. * <ul>
  6321. * <li>Math.floor(Math.log(num) / Math.LN10) is off by one for num == 1e+3.
  6322. * <li>Math.floor(Math.log(num) * Math.LOG10E) is off by one for num == 1e+15.
  6323. * <li>Math.floor(Math.log10(num)) is off by one for num == 1e+15 - 1.
  6324. * </ul>
  6325. * @param {number} num A floating point number.
  6326. * @return {number} Its logarithm to base 10 rounded down to the nearest
  6327. * integer if num > 0. -Infinity if num == 0. NaN if num < 0.
  6328. */
  6329. goog.math.log10Floor = function(num) {
  6330. if (num > 0) {
  6331. var x = Math.round(Math.log(num) * Math.LOG10E);
  6332. return x - (parseFloat('1e' + x) > num);
  6333. }
  6334. return num == 0 ? -Infinity : NaN;
  6335. };
  6336. /**
  6337. * A tweaked variant of {@code Math.floor} which tolerates if the passed number
  6338. * is infinitesimally smaller than the closest integer. It often happens with
  6339. * the results of floating point calculations because of the finite precision
  6340. * of the intermediate results. For example {@code Math.floor(Math.log(1000) /
  6341. * Math.LN10) == 2}, not 3 as one would expect.
  6342. * @param {number} num A number.
  6343. * @param {number=} opt_epsilon An infinitesimally small positive number, the
  6344. * rounding error to tolerate.
  6345. * @return {number} The largest integer less than or equal to {@code num}.
  6346. */
  6347. goog.math.safeFloor = function(num, opt_epsilon) {
  6348. goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
  6349. return Math.floor(num + (opt_epsilon || 2e-15));
  6350. };
  6351. /**
  6352. * A tweaked variant of {@code Math.ceil}. See {@code goog.math.safeFloor} for
  6353. * details.
  6354. * @param {number} num A number.
  6355. * @param {number=} opt_epsilon An infinitesimally small positive number, the
  6356. * rounding error to tolerate.
  6357. * @return {number} The smallest integer greater than or equal to {@code num}.
  6358. */
  6359. goog.math.safeCeil = function(num, opt_epsilon) {
  6360. goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
  6361. return Math.ceil(num - (opt_epsilon || 2e-15));
  6362. };
  6363. goog.provide('ol.RotationConstraint');
  6364. goog.provide('ol.RotationConstraintType');
  6365. goog.require('goog.math');
  6366. /**
  6367. * @typedef {function((number|undefined), number): (number|undefined)}
  6368. */
  6369. ol.RotationConstraintType;
  6370. /**
  6371. * @param {number|undefined} rotation Rotation.
  6372. * @param {number} delta Delta.
  6373. * @return {number|undefined} Rotation.
  6374. */
  6375. ol.RotationConstraint.disable = function(rotation, delta) {
  6376. if (rotation !== undefined) {
  6377. return 0;
  6378. } else {
  6379. return undefined;
  6380. }
  6381. };
  6382. /**
  6383. * @param {number|undefined} rotation Rotation.
  6384. * @param {number} delta Delta.
  6385. * @return {number|undefined} Rotation.
  6386. */
  6387. ol.RotationConstraint.none = function(rotation, delta) {
  6388. if (rotation !== undefined) {
  6389. return rotation + delta;
  6390. } else {
  6391. return undefined;
  6392. }
  6393. };
  6394. /**
  6395. * @param {number} n N.
  6396. * @return {ol.RotationConstraintType} Rotation constraint.
  6397. */
  6398. ol.RotationConstraint.createSnapToN = function(n) {
  6399. var theta = 2 * Math.PI / n;
  6400. return (
  6401. /**
  6402. * @param {number|undefined} rotation Rotation.
  6403. * @param {number} delta Delta.
  6404. * @return {number|undefined} Rotation.
  6405. */
  6406. function(rotation, delta) {
  6407. if (rotation !== undefined) {
  6408. rotation = Math.floor((rotation + delta) / theta + 0.5) * theta;
  6409. return rotation;
  6410. } else {
  6411. return undefined;
  6412. }
  6413. });
  6414. };
  6415. /**
  6416. * @param {number=} opt_tolerance Tolerance.
  6417. * @return {ol.RotationConstraintType} Rotation constraint.
  6418. */
  6419. ol.RotationConstraint.createSnapToZero = function(opt_tolerance) {
  6420. var tolerance = opt_tolerance || goog.math.toRadians(5);
  6421. return (
  6422. /**
  6423. * @param {number|undefined} rotation Rotation.
  6424. * @param {number} delta Delta.
  6425. * @return {number|undefined} Rotation.
  6426. */
  6427. function(rotation, delta) {
  6428. if (rotation !== undefined) {
  6429. if (Math.abs(rotation + delta) <= tolerance) {
  6430. return 0;
  6431. } else {
  6432. return rotation + delta;
  6433. }
  6434. } else {
  6435. return undefined;
  6436. }
  6437. });
  6438. };
  6439. goog.provide('ol.Constraints');
  6440. goog.require('ol.CenterConstraintType');
  6441. goog.require('ol.ResolutionConstraintType');
  6442. goog.require('ol.RotationConstraintType');
  6443. /**
  6444. * @constructor
  6445. * @param {ol.CenterConstraintType} centerConstraint Center constraint.
  6446. * @param {ol.ResolutionConstraintType} resolutionConstraint
  6447. * Resolution constraint.
  6448. * @param {ol.RotationConstraintType} rotationConstraint
  6449. * Rotation constraint.
  6450. */
  6451. ol.Constraints =
  6452. function(centerConstraint, resolutionConstraint, rotationConstraint) {
  6453. /**
  6454. * @type {ol.CenterConstraintType}
  6455. */
  6456. this.center = centerConstraint;
  6457. /**
  6458. * @type {ol.ResolutionConstraintType}
  6459. */
  6460. this.resolution = resolutionConstraint;
  6461. /**
  6462. * @type {ol.RotationConstraintType}
  6463. */
  6464. this.rotation = rotationConstraint;
  6465. };
  6466. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  6467. //
  6468. // Licensed under the Apache License, Version 2.0 (the "License");
  6469. // you may not use this file except in compliance with the License.
  6470. // You may obtain a copy of the License at
  6471. //
  6472. // http://www.apache.org/licenses/LICENSE-2.0
  6473. //
  6474. // Unless required by applicable law or agreed to in writing, software
  6475. // distributed under the License is distributed on an "AS-IS" BASIS,
  6476. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6477. // See the License for the specific language governing permissions and
  6478. // limitations under the License.
  6479. /**
  6480. * @fileoverview A global registry for entry points into a program,
  6481. * so that they can be instrumented. Each module should register their
  6482. * entry points with this registry. Designed to be compiled out
  6483. * if no instrumentation is requested.
  6484. *
  6485. * Entry points may be registered before or after a call to
  6486. * goog.debug.entryPointRegistry.monitorAll. If an entry point is registered
  6487. * later, the existing monitor will instrument the new entry point.
  6488. *
  6489. * @author nicksantos@google.com (Nick Santos)
  6490. */
  6491. goog.provide('goog.debug.EntryPointMonitor');
  6492. goog.provide('goog.debug.entryPointRegistry');
  6493. goog.require('goog.asserts');
  6494. /**
  6495. * @interface
  6496. */
  6497. goog.debug.EntryPointMonitor = function() {};
  6498. /**
  6499. * Instruments a function.
  6500. *
  6501. * @param {!Function} fn A function to instrument.
  6502. * @return {!Function} The instrumented function.
  6503. */
  6504. goog.debug.EntryPointMonitor.prototype.wrap;
  6505. /**
  6506. * Try to remove an instrumentation wrapper created by this monitor.
  6507. * If the function passed to unwrap is not a wrapper created by this
  6508. * monitor, then we will do nothing.
  6509. *
  6510. * Notice that some wrappers may not be unwrappable. For example, if other
  6511. * monitors have applied their own wrappers, then it will be impossible to
  6512. * unwrap them because their wrappers will have captured our wrapper.
  6513. *
  6514. * So it is important that entry points are unwrapped in the reverse
  6515. * order that they were wrapped.
  6516. *
  6517. * @param {!Function} fn A function to unwrap.
  6518. * @return {!Function} The unwrapped function, or {@code fn} if it was not
  6519. * a wrapped function created by this monitor.
  6520. */
  6521. goog.debug.EntryPointMonitor.prototype.unwrap;
  6522. /**
  6523. * An array of entry point callbacks.
  6524. * @type {!Array<function(!Function)>}
  6525. * @private
  6526. */
  6527. goog.debug.entryPointRegistry.refList_ = [];
  6528. /**
  6529. * Monitors that should wrap all the entry points.
  6530. * @type {!Array<!goog.debug.EntryPointMonitor>}
  6531. * @private
  6532. */
  6533. goog.debug.entryPointRegistry.monitors_ = [];
  6534. /**
  6535. * Whether goog.debug.entryPointRegistry.monitorAll has ever been called.
  6536. * Checking this allows the compiler to optimize out the registrations.
  6537. * @type {boolean}
  6538. * @private
  6539. */
  6540. goog.debug.entryPointRegistry.monitorsMayExist_ = false;
  6541. /**
  6542. * Register an entry point with this module.
  6543. *
  6544. * The entry point will be instrumented when a monitor is passed to
  6545. * goog.debug.entryPointRegistry.monitorAll. If this has already occurred, the
  6546. * entry point is instrumented immediately.
  6547. *
  6548. * @param {function(!Function)} callback A callback function which is called
  6549. * with a transforming function to instrument the entry point. The callback
  6550. * is responsible for wrapping the relevant entry point with the
  6551. * transforming function.
  6552. */
  6553. goog.debug.entryPointRegistry.register = function(callback) {
  6554. // Don't use push(), so that this can be compiled out.
  6555. goog.debug.entryPointRegistry.refList_[
  6556. goog.debug.entryPointRegistry.refList_.length] = callback;
  6557. // If no one calls monitorAll, this can be compiled out.
  6558. if (goog.debug.entryPointRegistry.monitorsMayExist_) {
  6559. var monitors = goog.debug.entryPointRegistry.monitors_;
  6560. for (var i = 0; i < monitors.length; i++) {
  6561. callback(goog.bind(monitors[i].wrap, monitors[i]));
  6562. }
  6563. }
  6564. };
  6565. /**
  6566. * Configures a monitor to wrap all entry points.
  6567. *
  6568. * Entry points that have already been registered are immediately wrapped by
  6569. * the monitor. When an entry point is registered in the future, it will also
  6570. * be wrapped by the monitor when it is registered.
  6571. *
  6572. * @param {!goog.debug.EntryPointMonitor} monitor An entry point monitor.
  6573. */
  6574. goog.debug.entryPointRegistry.monitorAll = function(monitor) {
  6575. goog.debug.entryPointRegistry.monitorsMayExist_ = true;
  6576. var transformer = goog.bind(monitor.wrap, monitor);
  6577. for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) {
  6578. goog.debug.entryPointRegistry.refList_[i](transformer);
  6579. }
  6580. goog.debug.entryPointRegistry.monitors_.push(monitor);
  6581. };
  6582. /**
  6583. * Try to unmonitor all the entry points that have already been registered. If
  6584. * an entry point is registered in the future, it will not be wrapped by the
  6585. * monitor when it is registered. Note that this may fail if the entry points
  6586. * have additional wrapping.
  6587. *
  6588. * @param {!goog.debug.EntryPointMonitor} monitor The last monitor to wrap
  6589. * the entry points.
  6590. * @throws {Error} If the monitor is not the most recently configured monitor.
  6591. */
  6592. goog.debug.entryPointRegistry.unmonitorAllIfPossible = function(monitor) {
  6593. var monitors = goog.debug.entryPointRegistry.monitors_;
  6594. goog.asserts.assert(monitor == monitors[monitors.length - 1],
  6595. 'Only the most recent monitor can be unwrapped.');
  6596. var transformer = goog.bind(monitor.unwrap, monitor);
  6597. for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) {
  6598. goog.debug.entryPointRegistry.refList_[i](transformer);
  6599. }
  6600. monitors.length--;
  6601. };
  6602. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  6603. //
  6604. // Licensed under the Apache License, Version 2.0 (the "License");
  6605. // you may not use this file except in compliance with the License.
  6606. // You may obtain a copy of the License at
  6607. //
  6608. // http://www.apache.org/licenses/LICENSE-2.0
  6609. //
  6610. // Unless required by applicable law or agreed to in writing, software
  6611. // distributed under the License is distributed on an "AS-IS" BASIS,
  6612. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6613. // See the License for the specific language governing permissions and
  6614. // limitations under the License.
  6615. /**
  6616. * @fileoverview Utilities used by goog.labs.userAgent tools. These functions
  6617. * should not be used outside of goog.labs.userAgent.*.
  6618. *
  6619. *
  6620. * @author nnaze@google.com (Nathan Naze)
  6621. */
  6622. goog.provide('goog.labs.userAgent.util');
  6623. goog.require('goog.string');
  6624. /**
  6625. * Gets the native userAgent string from navigator if it exists.
  6626. * If navigator or navigator.userAgent string is missing, returns an empty
  6627. * string.
  6628. * @return {string}
  6629. * @private
  6630. */
  6631. goog.labs.userAgent.util.getNativeUserAgentString_ = function() {
  6632. var navigator = goog.labs.userAgent.util.getNavigator_();
  6633. if (navigator) {
  6634. var userAgent = navigator.userAgent;
  6635. if (userAgent) {
  6636. return userAgent;
  6637. }
  6638. }
  6639. return '';
  6640. };
  6641. /**
  6642. * Getter for the native navigator.
  6643. * This is a separate function so it can be stubbed out in testing.
  6644. * @return {Navigator}
  6645. * @private
  6646. */
  6647. goog.labs.userAgent.util.getNavigator_ = function() {
  6648. return goog.global.navigator;
  6649. };
  6650. /**
  6651. * A possible override for applications which wish to not check
  6652. * navigator.userAgent but use a specified value for detection instead.
  6653. * @private {string}
  6654. */
  6655. goog.labs.userAgent.util.userAgent_ =
  6656. goog.labs.userAgent.util.getNativeUserAgentString_();
  6657. /**
  6658. * Applications may override browser detection on the built in
  6659. * navigator.userAgent object by setting this string. Set to null to use the
  6660. * browser object instead.
  6661. * @param {?string=} opt_userAgent The User-Agent override.
  6662. */
  6663. goog.labs.userAgent.util.setUserAgent = function(opt_userAgent) {
  6664. goog.labs.userAgent.util.userAgent_ = opt_userAgent ||
  6665. goog.labs.userAgent.util.getNativeUserAgentString_();
  6666. };
  6667. /**
  6668. * @return {string} The user agent string.
  6669. */
  6670. goog.labs.userAgent.util.getUserAgent = function() {
  6671. return goog.labs.userAgent.util.userAgent_;
  6672. };
  6673. /**
  6674. * @param {string} str
  6675. * @return {boolean} Whether the user agent contains the given string, ignoring
  6676. * case.
  6677. */
  6678. goog.labs.userAgent.util.matchUserAgent = function(str) {
  6679. var userAgent = goog.labs.userAgent.util.getUserAgent();
  6680. return goog.string.contains(userAgent, str);
  6681. };
  6682. /**
  6683. * @param {string} str
  6684. * @return {boolean} Whether the user agent contains the given string.
  6685. */
  6686. goog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) {
  6687. var userAgent = goog.labs.userAgent.util.getUserAgent();
  6688. return goog.string.caseInsensitiveContains(userAgent, str);
  6689. };
  6690. /**
  6691. * Parses the user agent into tuples for each section.
  6692. * @param {string} userAgent
  6693. * @return {!Array<!Array<string>>} Tuples of key, version, and the contents
  6694. * of the parenthetical.
  6695. */
  6696. goog.labs.userAgent.util.extractVersionTuples = function(userAgent) {
  6697. // Matches each section of a user agent string.
  6698. // Example UA:
  6699. // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)
  6700. // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405
  6701. // This has three version tuples: Mozilla, AppleWebKit, and Mobile.
  6702. var versionRegExp = new RegExp(
  6703. // Key. Note that a key may have a space.
  6704. // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')
  6705. '(\\w[\\w ]+)' +
  6706. '/' + // slash
  6707. '([^\\s]+)' + // version (i.e. '5.0b')
  6708. '\\s*' + // whitespace
  6709. '(?:\\((.*?)\\))?', // parenthetical info. parentheses not matched.
  6710. 'g');
  6711. var data = [];
  6712. var match;
  6713. // Iterate and collect the version tuples. Each iteration will be the
  6714. // next regex match.
  6715. while (match = versionRegExp.exec(userAgent)) {
  6716. data.push([
  6717. match[1], // key
  6718. match[2], // value
  6719. // || undefined as this is not undefined in IE7 and IE8
  6720. match[3] || undefined // info
  6721. ]);
  6722. }
  6723. return data;
  6724. };
  6725. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  6726. //
  6727. // Licensed under the Apache License, Version 2.0 (the "License");
  6728. // you may not use this file except in compliance with the License.
  6729. // You may obtain a copy of the License at
  6730. //
  6731. // http://www.apache.org/licenses/LICENSE-2.0
  6732. //
  6733. // Unless required by applicable law or agreed to in writing, software
  6734. // distributed under the License is distributed on an "AS-IS" BASIS,
  6735. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6736. // See the License for the specific language governing permissions and
  6737. // limitations under the License.
  6738. /**
  6739. * @fileoverview Utilities for manipulating objects/maps/hashes.
  6740. * @author arv@google.com (Erik Arvidsson)
  6741. */
  6742. goog.provide('goog.object');
  6743. /**
  6744. * Calls a function for each element in an object/map/hash.
  6745. *
  6746. * @param {Object<K,V>} obj The object over which to iterate.
  6747. * @param {function(this:T,V,?,Object<K,V>):?} f The function to call
  6748. * for every element. This function takes 3 arguments (the value, the
  6749. * key and the object) and the return value is ignored.
  6750. * @param {T=} opt_obj This is used as the 'this' object within f.
  6751. * @template T,K,V
  6752. */
  6753. goog.object.forEach = function(obj, f, opt_obj) {
  6754. for (var key in obj) {
  6755. f.call(opt_obj, obj[key], key, obj);
  6756. }
  6757. };
  6758. /**
  6759. * Calls a function for each element in an object/map/hash. If that call returns
  6760. * true, adds the element to a new object.
  6761. *
  6762. * @param {Object<K,V>} obj The object over which to iterate.
  6763. * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call
  6764. * for every element. This
  6765. * function takes 3 arguments (the value, the key and the object)
  6766. * and should return a boolean. If the return value is true the
  6767. * element is added to the result object. If it is false the
  6768. * element is not included.
  6769. * @param {T=} opt_obj This is used as the 'this' object within f.
  6770. * @return {!Object<K,V>} a new object in which only elements that passed the
  6771. * test are present.
  6772. * @template T,K,V
  6773. */
  6774. goog.object.filter = function(obj, f, opt_obj) {
  6775. var res = {};
  6776. for (var key in obj) {
  6777. if (f.call(opt_obj, obj[key], key, obj)) {
  6778. res[key] = obj[key];
  6779. }
  6780. }
  6781. return res;
  6782. };
  6783. /**
  6784. * For every element in an object/map/hash calls a function and inserts the
  6785. * result into a new object.
  6786. *
  6787. * @param {Object<K,V>} obj The object over which to iterate.
  6788. * @param {function(this:T,V,?,Object<K,V>):R} f The function to call
  6789. * for every element. This function
  6790. * takes 3 arguments (the value, the key and the object)
  6791. * and should return something. The result will be inserted
  6792. * into a new object.
  6793. * @param {T=} opt_obj This is used as the 'this' object within f.
  6794. * @return {!Object<K,R>} a new object with the results from f.
  6795. * @template T,K,V,R
  6796. */
  6797. goog.object.map = function(obj, f, opt_obj) {
  6798. var res = {};
  6799. for (var key in obj) {
  6800. res[key] = f.call(opt_obj, obj[key], key, obj);
  6801. }
  6802. return res;
  6803. };
  6804. /**
  6805. * Calls a function for each element in an object/map/hash. If any
  6806. * call returns true, returns true (without checking the rest). If
  6807. * all calls return false, returns false.
  6808. *
  6809. * @param {Object<K,V>} obj The object to check.
  6810. * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to
  6811. * call for every element. This function
  6812. * takes 3 arguments (the value, the key and the object) and should
  6813. * return a boolean.
  6814. * @param {T=} opt_obj This is used as the 'this' object within f.
  6815. * @return {boolean} true if any element passes the test.
  6816. * @template T,K,V
  6817. */
  6818. goog.object.some = function(obj, f, opt_obj) {
  6819. for (var key in obj) {
  6820. if (f.call(opt_obj, obj[key], key, obj)) {
  6821. return true;
  6822. }
  6823. }
  6824. return false;
  6825. };
  6826. /**
  6827. * Calls a function for each element in an object/map/hash. If
  6828. * all calls return true, returns true. If any call returns false, returns
  6829. * false at this point and does not continue to check the remaining elements.
  6830. *
  6831. * @param {Object<K,V>} obj The object to check.
  6832. * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to
  6833. * call for every element. This function
  6834. * takes 3 arguments (the value, the key and the object) and should
  6835. * return a boolean.
  6836. * @param {T=} opt_obj This is used as the 'this' object within f.
  6837. * @return {boolean} false if any element fails the test.
  6838. * @template T,K,V
  6839. */
  6840. goog.object.every = function(obj, f, opt_obj) {
  6841. for (var key in obj) {
  6842. if (!f.call(opt_obj, obj[key], key, obj)) {
  6843. return false;
  6844. }
  6845. }
  6846. return true;
  6847. };
  6848. /**
  6849. * Returns the number of key-value pairs in the object map.
  6850. *
  6851. * @param {Object} obj The object for which to get the number of key-value
  6852. * pairs.
  6853. * @return {number} The number of key-value pairs in the object map.
  6854. */
  6855. goog.object.getCount = function(obj) {
  6856. // JS1.5 has __count__ but it has been deprecated so it raises a warning...
  6857. // in other words do not use. Also __count__ only includes the fields on the
  6858. // actual object and not in the prototype chain.
  6859. var rv = 0;
  6860. for (var key in obj) {
  6861. rv++;
  6862. }
  6863. return rv;
  6864. };
  6865. /**
  6866. * Returns one key from the object map, if any exists.
  6867. * For map literals the returned key will be the first one in most of the
  6868. * browsers (a know exception is Konqueror).
  6869. *
  6870. * @param {Object} obj The object to pick a key from.
  6871. * @return {string|undefined} The key or undefined if the object is empty.
  6872. */
  6873. goog.object.getAnyKey = function(obj) {
  6874. for (var key in obj) {
  6875. return key;
  6876. }
  6877. };
  6878. /**
  6879. * Returns one value from the object map, if any exists.
  6880. * For map literals the returned value will be the first one in most of the
  6881. * browsers (a know exception is Konqueror).
  6882. *
  6883. * @param {Object<K,V>} obj The object to pick a value from.
  6884. * @return {V|undefined} The value or undefined if the object is empty.
  6885. * @template K,V
  6886. */
  6887. goog.object.getAnyValue = function(obj) {
  6888. for (var key in obj) {
  6889. return obj[key];
  6890. }
  6891. };
  6892. /**
  6893. * Whether the object/hash/map contains the given object as a value.
  6894. * An alias for goog.object.containsValue(obj, val).
  6895. *
  6896. * @param {Object<K,V>} obj The object in which to look for val.
  6897. * @param {V} val The object for which to check.
  6898. * @return {boolean} true if val is present.
  6899. * @template K,V
  6900. */
  6901. goog.object.contains = function(obj, val) {
  6902. return goog.object.containsValue(obj, val);
  6903. };
  6904. /**
  6905. * Returns the values of the object/map/hash.
  6906. *
  6907. * @param {Object<K,V>} obj The object from which to get the values.
  6908. * @return {!Array<V>} The values in the object/map/hash.
  6909. * @template K,V
  6910. */
  6911. goog.object.getValues = function(obj) {
  6912. var res = [];
  6913. var i = 0;
  6914. for (var key in obj) {
  6915. res[i++] = obj[key];
  6916. }
  6917. return res;
  6918. };
  6919. /**
  6920. * Returns the keys of the object/map/hash.
  6921. *
  6922. * @param {Object} obj The object from which to get the keys.
  6923. * @return {!Array<string>} Array of property keys.
  6924. */
  6925. goog.object.getKeys = function(obj) {
  6926. var res = [];
  6927. var i = 0;
  6928. for (var key in obj) {
  6929. res[i++] = key;
  6930. }
  6931. return res;
  6932. };
  6933. /**
  6934. * Get a value from an object multiple levels deep. This is useful for
  6935. * pulling values from deeply nested objects, such as JSON responses.
  6936. * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)
  6937. *
  6938. * @param {!Object} obj An object to get the value from. Can be array-like.
  6939. * @param {...(string|number|!Array<number|string>)} var_args A number of keys
  6940. * (as strings, or numbers, for array-like objects). Can also be
  6941. * specified as a single array of keys.
  6942. * @return {*} The resulting value. If, at any point, the value for a key
  6943. * is undefined, returns undefined.
  6944. */
  6945. goog.object.getValueByKeys = function(obj, var_args) {
  6946. var isArrayLike = goog.isArrayLike(var_args);
  6947. var keys = isArrayLike ? var_args : arguments;
  6948. // Start with the 2nd parameter for the variable parameters syntax.
  6949. for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {
  6950. obj = obj[keys[i]];
  6951. if (!goog.isDef(obj)) {
  6952. break;
  6953. }
  6954. }
  6955. return obj;
  6956. };
  6957. /**
  6958. * Whether the object/map/hash contains the given key.
  6959. *
  6960. * @param {Object} obj The object in which to look for key.
  6961. * @param {*} key The key for which to check.
  6962. * @return {boolean} true If the map contains the key.
  6963. */
  6964. goog.object.containsKey = function(obj, key) {
  6965. return key in obj;
  6966. };
  6967. /**
  6968. * Whether the object/map/hash contains the given value. This is O(n).
  6969. *
  6970. * @param {Object<K,V>} obj The object in which to look for val.
  6971. * @param {V} val The value for which to check.
  6972. * @return {boolean} true If the map contains the value.
  6973. * @template K,V
  6974. */
  6975. goog.object.containsValue = function(obj, val) {
  6976. for (var key in obj) {
  6977. if (obj[key] == val) {
  6978. return true;
  6979. }
  6980. }
  6981. return false;
  6982. };
  6983. /**
  6984. * Searches an object for an element that satisfies the given condition and
  6985. * returns its key.
  6986. * @param {Object<K,V>} obj The object to search in.
  6987. * @param {function(this:T,V,string,Object<K,V>):boolean} f The
  6988. * function to call for every element. Takes 3 arguments (the value,
  6989. * the key and the object) and should return a boolean.
  6990. * @param {T=} opt_this An optional "this" context for the function.
  6991. * @return {string|undefined} The key of an element for which the function
  6992. * returns true or undefined if no such element is found.
  6993. * @template T,K,V
  6994. */
  6995. goog.object.findKey = function(obj, f, opt_this) {
  6996. for (var key in obj) {
  6997. if (f.call(opt_this, obj[key], key, obj)) {
  6998. return key;
  6999. }
  7000. }
  7001. return undefined;
  7002. };
  7003. /**
  7004. * Searches an object for an element that satisfies the given condition and
  7005. * returns its value.
  7006. * @param {Object<K,V>} obj The object to search in.
  7007. * @param {function(this:T,V,string,Object<K,V>):boolean} f The function
  7008. * to call for every element. Takes 3 arguments (the value, the key
  7009. * and the object) and should return a boolean.
  7010. * @param {T=} opt_this An optional "this" context for the function.
  7011. * @return {V} The value of an element for which the function returns true or
  7012. * undefined if no such element is found.
  7013. * @template T,K,V
  7014. */
  7015. goog.object.findValue = function(obj, f, opt_this) {
  7016. var key = goog.object.findKey(obj, f, opt_this);
  7017. return key && obj[key];
  7018. };
  7019. /**
  7020. * Whether the object/map/hash is empty.
  7021. *
  7022. * @param {Object} obj The object to test.
  7023. * @return {boolean} true if obj is empty.
  7024. */
  7025. goog.object.isEmpty = function(obj) {
  7026. for (var key in obj) {
  7027. return false;
  7028. }
  7029. return true;
  7030. };
  7031. /**
  7032. * Removes all key value pairs from the object/map/hash.
  7033. *
  7034. * @param {Object} obj The object to clear.
  7035. */
  7036. goog.object.clear = function(obj) {
  7037. for (var i in obj) {
  7038. delete obj[i];
  7039. }
  7040. };
  7041. /**
  7042. * Removes a key-value pair based on the key.
  7043. *
  7044. * @param {Object} obj The object from which to remove the key.
  7045. * @param {*} key The key to remove.
  7046. * @return {boolean} Whether an element was removed.
  7047. */
  7048. goog.object.remove = function(obj, key) {
  7049. var rv;
  7050. if ((rv = key in obj)) {
  7051. delete obj[key];
  7052. }
  7053. return rv;
  7054. };
  7055. /**
  7056. * Adds a key-value pair to the object. Throws an exception if the key is
  7057. * already in use. Use set if you want to change an existing pair.
  7058. *
  7059. * @param {Object<K,V>} obj The object to which to add the key-value pair.
  7060. * @param {string} key The key to add.
  7061. * @param {V} val The value to add.
  7062. * @template K,V
  7063. */
  7064. goog.object.add = function(obj, key, val) {
  7065. if (key in obj) {
  7066. throw Error('The object already contains the key "' + key + '"');
  7067. }
  7068. goog.object.set(obj, key, val);
  7069. };
  7070. /**
  7071. * Returns the value for the given key.
  7072. *
  7073. * @param {Object<K,V>} obj The object from which to get the value.
  7074. * @param {string} key The key for which to get the value.
  7075. * @param {R=} opt_val The value to return if no item is found for the given
  7076. * key (default is undefined).
  7077. * @return {V|R|undefined} The value for the given key.
  7078. * @template K,V,R
  7079. */
  7080. goog.object.get = function(obj, key, opt_val) {
  7081. if (key in obj) {
  7082. return obj[key];
  7083. }
  7084. return opt_val;
  7085. };
  7086. /**
  7087. * Adds a key-value pair to the object/map/hash.
  7088. *
  7089. * @param {Object<K,V>} obj The object to which to add the key-value pair.
  7090. * @param {string} key The key to add.
  7091. * @param {V} value The value to add.
  7092. * @template K,V
  7093. */
  7094. goog.object.set = function(obj, key, value) {
  7095. obj[key] = value;
  7096. };
  7097. /**
  7098. * Adds a key-value pair to the object/map/hash if it doesn't exist yet.
  7099. *
  7100. * @param {Object<K,V>} obj The object to which to add the key-value pair.
  7101. * @param {string} key The key to add.
  7102. * @param {V} value The value to add if the key wasn't present.
  7103. * @return {V} The value of the entry at the end of the function.
  7104. * @template K,V
  7105. */
  7106. goog.object.setIfUndefined = function(obj, key, value) {
  7107. return key in obj ? obj[key] : (obj[key] = value);
  7108. };
  7109. /**
  7110. * Sets a key and value to an object if the key is not set. The value will be
  7111. * the return value of the given function. If the key already exists, the
  7112. * object will not be changed and the function will not be called (the function
  7113. * will be lazily evaluated -- only called if necessary).
  7114. *
  7115. * This function is particularly useful for use with a map used a as a cache.
  7116. *
  7117. * @param {!Object<K,V>} obj The object to which to add the key-value pair.
  7118. * @param {string} key The key to add.
  7119. * @param {function():V} f The value to add if the key wasn't present.
  7120. * @return {V} The value of the entry at the end of the function.
  7121. * @template K,V
  7122. */
  7123. goog.object.setWithReturnValueIfNotSet = function(obj, key, f) {
  7124. if (key in obj) {
  7125. return obj[key];
  7126. }
  7127. var val = f();
  7128. obj[key] = val;
  7129. return val;
  7130. };
  7131. /**
  7132. * Compares two objects for equality using === on the values.
  7133. *
  7134. * @param {!Object<K,V>} a
  7135. * @param {!Object<K,V>} b
  7136. * @return {boolean}
  7137. * @template K,V
  7138. */
  7139. goog.object.equals = function(a, b) {
  7140. for (var k in a) {
  7141. if (!(k in b) || a[k] !== b[k]) {
  7142. return false;
  7143. }
  7144. }
  7145. for (var k in b) {
  7146. if (!(k in a)) {
  7147. return false;
  7148. }
  7149. }
  7150. return true;
  7151. };
  7152. /**
  7153. * Does a flat clone of the object.
  7154. *
  7155. * @param {Object<K,V>} obj Object to clone.
  7156. * @return {!Object<K,V>} Clone of the input object.
  7157. * @template K,V
  7158. */
  7159. goog.object.clone = function(obj) {
  7160. // We cannot use the prototype trick because a lot of methods depend on where
  7161. // the actual key is set.
  7162. var res = {};
  7163. for (var key in obj) {
  7164. res[key] = obj[key];
  7165. }
  7166. return res;
  7167. // We could also use goog.mixin but I wanted this to be independent from that.
  7168. };
  7169. /**
  7170. * Clones a value. The input may be an Object, Array, or basic type. Objects and
  7171. * arrays will be cloned recursively.
  7172. *
  7173. * WARNINGS:
  7174. * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects
  7175. * that refer to themselves will cause infinite recursion.
  7176. *
  7177. * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and
  7178. * copies UIDs created by <code>getUid</code> into cloned results.
  7179. *
  7180. * @param {*} obj The value to clone.
  7181. * @return {*} A clone of the input value.
  7182. */
  7183. goog.object.unsafeClone = function(obj) {
  7184. var type = goog.typeOf(obj);
  7185. if (type == 'object' || type == 'array') {
  7186. if (goog.isFunction(obj.clone)) {
  7187. return obj.clone();
  7188. }
  7189. var clone = type == 'array' ? [] : {};
  7190. for (var key in obj) {
  7191. clone[key] = goog.object.unsafeClone(obj[key]);
  7192. }
  7193. return clone;
  7194. }
  7195. return obj;
  7196. };
  7197. /**
  7198. * Returns a new object in which all the keys and values are interchanged
  7199. * (keys become values and values become keys). If multiple keys map to the
  7200. * same value, the chosen transposed value is implementation-dependent.
  7201. *
  7202. * @param {Object} obj The object to transpose.
  7203. * @return {!Object} The transposed object.
  7204. */
  7205. goog.object.transpose = function(obj) {
  7206. var transposed = {};
  7207. for (var key in obj) {
  7208. transposed[obj[key]] = key;
  7209. }
  7210. return transposed;
  7211. };
  7212. /**
  7213. * The names of the fields that are defined on Object.prototype.
  7214. * @type {Array<string>}
  7215. * @private
  7216. */
  7217. goog.object.PROTOTYPE_FIELDS_ = [
  7218. 'constructor',
  7219. 'hasOwnProperty',
  7220. 'isPrototypeOf',
  7221. 'propertyIsEnumerable',
  7222. 'toLocaleString',
  7223. 'toString',
  7224. 'valueOf'
  7225. ];
  7226. /**
  7227. * Extends an object with another object.
  7228. * This operates 'in-place'; it does not create a new Object.
  7229. *
  7230. * Example:
  7231. * var o = {};
  7232. * goog.object.extend(o, {a: 0, b: 1});
  7233. * o; // {a: 0, b: 1}
  7234. * goog.object.extend(o, {b: 2, c: 3});
  7235. * o; // {a: 0, b: 2, c: 3}
  7236. *
  7237. * @param {Object} target The object to modify. Existing properties will be
  7238. * overwritten if they are also present in one of the objects in
  7239. * {@code var_args}.
  7240. * @param {...Object} var_args The objects from which values will be copied.
  7241. */
  7242. goog.object.extend = function(target, var_args) {
  7243. var key, source;
  7244. for (var i = 1; i < arguments.length; i++) {
  7245. source = arguments[i];
  7246. for (key in source) {
  7247. target[key] = source[key];
  7248. }
  7249. // For IE the for-in-loop does not contain any properties that are not
  7250. // enumerable on the prototype object (for example isPrototypeOf from
  7251. // Object.prototype) and it will also not include 'replace' on objects that
  7252. // extend String and change 'replace' (not that it is common for anyone to
  7253. // extend anything except Object).
  7254. for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
  7255. key = goog.object.PROTOTYPE_FIELDS_[j];
  7256. if (Object.prototype.hasOwnProperty.call(source, key)) {
  7257. target[key] = source[key];
  7258. }
  7259. }
  7260. }
  7261. };
  7262. /**
  7263. * Creates a new object built from the key-value pairs provided as arguments.
  7264. * @param {...*} var_args If only one argument is provided and it is an array
  7265. * then this is used as the arguments, otherwise even arguments are used as
  7266. * the property names and odd arguments are used as the property values.
  7267. * @return {!Object} The new object.
  7268. * @throws {Error} If there are uneven number of arguments or there is only one
  7269. * non array argument.
  7270. */
  7271. goog.object.create = function(var_args) {
  7272. var argLength = arguments.length;
  7273. if (argLength == 1 && goog.isArray(arguments[0])) {
  7274. return goog.object.create.apply(null, arguments[0]);
  7275. }
  7276. if (argLength % 2) {
  7277. throw Error('Uneven number of arguments');
  7278. }
  7279. var rv = {};
  7280. for (var i = 0; i < argLength; i += 2) {
  7281. rv[arguments[i]] = arguments[i + 1];
  7282. }
  7283. return rv;
  7284. };
  7285. /**
  7286. * Creates a new object where the property names come from the arguments but
  7287. * the value is always set to true
  7288. * @param {...*} var_args If only one argument is provided and it is an array
  7289. * then this is used as the arguments, otherwise the arguments are used
  7290. * as the property names.
  7291. * @return {!Object} The new object.
  7292. */
  7293. goog.object.createSet = function(var_args) {
  7294. var argLength = arguments.length;
  7295. if (argLength == 1 && goog.isArray(arguments[0])) {
  7296. return goog.object.createSet.apply(null, arguments[0]);
  7297. }
  7298. var rv = {};
  7299. for (var i = 0; i < argLength; i++) {
  7300. rv[arguments[i]] = true;
  7301. }
  7302. return rv;
  7303. };
  7304. /**
  7305. * Creates an immutable view of the underlying object, if the browser
  7306. * supports immutable objects.
  7307. *
  7308. * In default mode, writes to this view will fail silently. In strict mode,
  7309. * they will throw an error.
  7310. *
  7311. * @param {!Object<K,V>} obj An object.
  7312. * @return {!Object<K,V>} An immutable view of that object, or the
  7313. * original object if this browser does not support immutables.
  7314. * @template K,V
  7315. */
  7316. goog.object.createImmutableView = function(obj) {
  7317. var result = obj;
  7318. if (Object.isFrozen && !Object.isFrozen(obj)) {
  7319. result = Object.create(obj);
  7320. Object.freeze(result);
  7321. }
  7322. return result;
  7323. };
  7324. /**
  7325. * @param {!Object} obj An object.
  7326. * @return {boolean} Whether this is an immutable view of the object.
  7327. */
  7328. goog.object.isImmutableView = function(obj) {
  7329. return !!Object.isFrozen && Object.isFrozen(obj);
  7330. };
  7331. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  7332. //
  7333. // Licensed under the Apache License, Version 2.0 (the "License");
  7334. // you may not use this file except in compliance with the License.
  7335. // You may obtain a copy of the License at
  7336. //
  7337. // http://www.apache.org/licenses/LICENSE-2.0
  7338. //
  7339. // Unless required by applicable law or agreed to in writing, software
  7340. // distributed under the License is distributed on an "AS-IS" BASIS,
  7341. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7342. // See the License for the specific language governing permissions and
  7343. // limitations under the License.
  7344. /**
  7345. * @fileoverview Closure user agent detection (Browser).
  7346. * @see <a href="http://www.useragentstring.com/">User agent strings</a>
  7347. * For more information on rendering engine, platform, or device see the other
  7348. * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,
  7349. * goog.labs.userAgent.device respectively.)
  7350. *
  7351. * @author martone@google.com (Andy Martone)
  7352. */
  7353. goog.provide('goog.labs.userAgent.browser');
  7354. goog.require('goog.array');
  7355. goog.require('goog.labs.userAgent.util');
  7356. goog.require('goog.object');
  7357. goog.require('goog.string');
  7358. // TODO(nnaze): Refactor to remove excessive exclusion logic in matching
  7359. // functions.
  7360. /**
  7361. * @return {boolean} Whether the user's browser is Opera.
  7362. * @private
  7363. */
  7364. goog.labs.userAgent.browser.matchOpera_ = function() {
  7365. return goog.labs.userAgent.util.matchUserAgent('Opera') ||
  7366. goog.labs.userAgent.util.matchUserAgent('OPR');
  7367. };
  7368. /**
  7369. * @return {boolean} Whether the user's browser is IE.
  7370. * @private
  7371. */
  7372. goog.labs.userAgent.browser.matchIE_ = function() {
  7373. return goog.labs.userAgent.util.matchUserAgent('Trident') ||
  7374. goog.labs.userAgent.util.matchUserAgent('MSIE');
  7375. };
  7376. /**
  7377. * @return {boolean} Whether the user's browser is Edge.
  7378. * @private
  7379. */
  7380. goog.labs.userAgent.browser.matchEdge_ = function() {
  7381. return goog.labs.userAgent.util.matchUserAgent('Edge');
  7382. };
  7383. /**
  7384. * @return {boolean} Whether the user's browser is Firefox.
  7385. * @private
  7386. */
  7387. goog.labs.userAgent.browser.matchFirefox_ = function() {
  7388. return goog.labs.userAgent.util.matchUserAgent('Firefox');
  7389. };
  7390. /**
  7391. * @return {boolean} Whether the user's browser is Safari.
  7392. * @private
  7393. */
  7394. goog.labs.userAgent.browser.matchSafari_ = function() {
  7395. return goog.labs.userAgent.util.matchUserAgent('Safari') &&
  7396. !(goog.labs.userAgent.browser.matchChrome_() ||
  7397. goog.labs.userAgent.browser.matchCoast_() ||
  7398. goog.labs.userAgent.browser.matchOpera_() ||
  7399. goog.labs.userAgent.browser.matchEdge_() ||
  7400. goog.labs.userAgent.browser.isSilk() ||
  7401. goog.labs.userAgent.util.matchUserAgent('Android'));
  7402. };
  7403. /**
  7404. * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based
  7405. * iOS browser).
  7406. * @private
  7407. */
  7408. goog.labs.userAgent.browser.matchCoast_ = function() {
  7409. return goog.labs.userAgent.util.matchUserAgent('Coast');
  7410. };
  7411. /**
  7412. * @return {boolean} Whether the user's browser is iOS Webview.
  7413. * @private
  7414. */
  7415. goog.labs.userAgent.browser.matchIosWebview_ = function() {
  7416. // iOS Webview does not show up as Chrome or Safari. Also check for Opera's
  7417. // WebKit-based iOS browser, Coast.
  7418. return (goog.labs.userAgent.util.matchUserAgent('iPad') ||
  7419. goog.labs.userAgent.util.matchUserAgent('iPhone')) &&
  7420. !goog.labs.userAgent.browser.matchSafari_() &&
  7421. !goog.labs.userAgent.browser.matchChrome_() &&
  7422. !goog.labs.userAgent.browser.matchCoast_() &&
  7423. goog.labs.userAgent.util.matchUserAgent('AppleWebKit');
  7424. };
  7425. /**
  7426. * @return {boolean} Whether the user's browser is Chrome.
  7427. * @private
  7428. */
  7429. goog.labs.userAgent.browser.matchChrome_ = function() {
  7430. return (goog.labs.userAgent.util.matchUserAgent('Chrome') ||
  7431. goog.labs.userAgent.util.matchUserAgent('CriOS')) &&
  7432. !goog.labs.userAgent.browser.matchOpera_() &&
  7433. !goog.labs.userAgent.browser.matchEdge_();
  7434. };
  7435. /**
  7436. * @return {boolean} Whether the user's browser is the Android browser.
  7437. * @private
  7438. */
  7439. goog.labs.userAgent.browser.matchAndroidBrowser_ = function() {
  7440. // Android can appear in the user agent string for Chrome on Android.
  7441. // This is not the Android standalone browser if it does.
  7442. return goog.labs.userAgent.util.matchUserAgent('Android') &&
  7443. !(goog.labs.userAgent.browser.isChrome() ||
  7444. goog.labs.userAgent.browser.isFirefox() ||
  7445. goog.labs.userAgent.browser.isOpera() ||
  7446. goog.labs.userAgent.browser.isSilk());
  7447. };
  7448. /**
  7449. * @return {boolean} Whether the user's browser is Opera.
  7450. */
  7451. goog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;
  7452. /**
  7453. * @return {boolean} Whether the user's browser is IE.
  7454. */
  7455. goog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;
  7456. /**
  7457. * @return {boolean} Whether the user's browser is Edge.
  7458. */
  7459. goog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdge_;
  7460. /**
  7461. * @return {boolean} Whether the user's browser is Firefox.
  7462. */
  7463. goog.labs.userAgent.browser.isFirefox =
  7464. goog.labs.userAgent.browser.matchFirefox_;
  7465. /**
  7466. * @return {boolean} Whether the user's browser is Safari.
  7467. */
  7468. goog.labs.userAgent.browser.isSafari =
  7469. goog.labs.userAgent.browser.matchSafari_;
  7470. /**
  7471. * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based
  7472. * iOS browser).
  7473. */
  7474. goog.labs.userAgent.browser.isCoast =
  7475. goog.labs.userAgent.browser.matchCoast_;
  7476. /**
  7477. * @return {boolean} Whether the user's browser is iOS Webview.
  7478. */
  7479. goog.labs.userAgent.browser.isIosWebview =
  7480. goog.labs.userAgent.browser.matchIosWebview_;
  7481. /**
  7482. * @return {boolean} Whether the user's browser is Chrome.
  7483. */
  7484. goog.labs.userAgent.browser.isChrome =
  7485. goog.labs.userAgent.browser.matchChrome_;
  7486. /**
  7487. * @return {boolean} Whether the user's browser is the Android browser.
  7488. */
  7489. goog.labs.userAgent.browser.isAndroidBrowser =
  7490. goog.labs.userAgent.browser.matchAndroidBrowser_;
  7491. /**
  7492. * For more information, see:
  7493. * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html
  7494. * @return {boolean} Whether the user's browser is Silk.
  7495. */
  7496. goog.labs.userAgent.browser.isSilk = function() {
  7497. return goog.labs.userAgent.util.matchUserAgent('Silk');
  7498. };
  7499. /**
  7500. * @return {string} The browser version or empty string if version cannot be
  7501. * determined. Note that for Internet Explorer, this returns the version of
  7502. * the browser, not the version of the rendering engine. (IE 8 in
  7503. * compatibility mode will return 8.0 rather than 7.0. To determine the
  7504. * rendering engine version, look at document.documentMode instead. See
  7505. * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more
  7506. * details.)
  7507. */
  7508. goog.labs.userAgent.browser.getVersion = function() {
  7509. var userAgentString = goog.labs.userAgent.util.getUserAgent();
  7510. // Special case IE since IE's version is inside the parenthesis and
  7511. // without the '/'.
  7512. if (goog.labs.userAgent.browser.isIE()) {
  7513. return goog.labs.userAgent.browser.getIEVersion_(userAgentString);
  7514. }
  7515. var versionTuples = goog.labs.userAgent.util.extractVersionTuples(
  7516. userAgentString);
  7517. // Construct a map for easy lookup.
  7518. var versionMap = {};
  7519. goog.array.forEach(versionTuples, function(tuple) {
  7520. // Note that the tuple is of length three, but we only care about the
  7521. // first two.
  7522. var key = tuple[0];
  7523. var value = tuple[1];
  7524. versionMap[key] = value;
  7525. });
  7526. var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap);
  7527. // Gives the value with the first key it finds, otherwise empty string.
  7528. function lookUpValueWithKeys(keys) {
  7529. var key = goog.array.find(keys, versionMapHasKey);
  7530. return versionMap[key] || '';
  7531. }
  7532. // Check Opera before Chrome since Opera 15+ has "Chrome" in the string.
  7533. // See
  7534. // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond
  7535. if (goog.labs.userAgent.browser.isOpera()) {
  7536. // Opera 10 has Version/10.0 but Opera/9.8, so look for "Version" first.
  7537. // Opera uses 'OPR' for more recent UAs.
  7538. return lookUpValueWithKeys(['Version', 'Opera', 'OPR']);
  7539. }
  7540. // Check Edge before Chrome since it has Chrome in the string.
  7541. if (goog.labs.userAgent.browser.isEdge()) {
  7542. return lookUpValueWithKeys(['Edge']);
  7543. }
  7544. if (goog.labs.userAgent.browser.isChrome()) {
  7545. return lookUpValueWithKeys(['Chrome', 'CriOS']);
  7546. }
  7547. // Usually products browser versions are in the third tuple after "Mozilla"
  7548. // and the engine.
  7549. var tuple = versionTuples[2];
  7550. return tuple && tuple[1] || '';
  7551. };
  7552. /**
  7553. * @param {string|number} version The version to check.
  7554. * @return {boolean} Whether the browser version is higher or the same as the
  7555. * given version.
  7556. */
  7557. goog.labs.userAgent.browser.isVersionOrHigher = function(version) {
  7558. return goog.string.compareVersions(goog.labs.userAgent.browser.getVersion(),
  7559. version) >= 0;
  7560. };
  7561. /**
  7562. * Determines IE version. More information:
  7563. * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString
  7564. * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  7565. * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx
  7566. * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx
  7567. *
  7568. * @param {string} userAgent the User-Agent.
  7569. * @return {string}
  7570. * @private
  7571. */
  7572. goog.labs.userAgent.browser.getIEVersion_ = function(userAgent) {
  7573. // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade
  7574. // bug. Example UA:
  7575. // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)
  7576. // like Gecko.
  7577. // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.
  7578. var rv = /rv: *([\d\.]*)/.exec(userAgent);
  7579. if (rv && rv[1]) {
  7580. return rv[1];
  7581. }
  7582. var version = '';
  7583. var msie = /MSIE +([\d\.]+)/.exec(userAgent);
  7584. if (msie && msie[1]) {
  7585. // IE in compatibility mode usually identifies itself as MSIE 7.0; in this
  7586. // case, use the Trident version to determine the version of IE. For more
  7587. // details, see the links above.
  7588. var tridentVersion = /Trident\/(\d.\d)/.exec(userAgent);
  7589. if (msie[1] == '7.0') {
  7590. if (tridentVersion && tridentVersion[1]) {
  7591. switch (tridentVersion[1]) {
  7592. case '4.0':
  7593. version = '8.0';
  7594. break;
  7595. case '5.0':
  7596. version = '9.0';
  7597. break;
  7598. case '6.0':
  7599. version = '10.0';
  7600. break;
  7601. case '7.0':
  7602. version = '11.0';
  7603. break;
  7604. }
  7605. } else {
  7606. version = '7.0';
  7607. }
  7608. } else {
  7609. version = msie[1];
  7610. }
  7611. }
  7612. return version;
  7613. };
  7614. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  7615. //
  7616. // Licensed under the Apache License, Version 2.0 (the "License");
  7617. // you may not use this file except in compliance with the License.
  7618. // You may obtain a copy of the License at
  7619. //
  7620. // http://www.apache.org/licenses/LICENSE-2.0
  7621. //
  7622. // Unless required by applicable law or agreed to in writing, software
  7623. // distributed under the License is distributed on an "AS-IS" BASIS,
  7624. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7625. // See the License for the specific language governing permissions and
  7626. // limitations under the License.
  7627. /**
  7628. * @fileoverview Closure user agent detection.
  7629. * @see http://en.wikipedia.org/wiki/User_agent
  7630. * For more information on browser brand, platform, or device see the other
  7631. * sub-namespaces in goog.labs.userAgent (browser, platform, and device).
  7632. *
  7633. */
  7634. goog.provide('goog.labs.userAgent.engine');
  7635. goog.require('goog.array');
  7636. goog.require('goog.labs.userAgent.util');
  7637. goog.require('goog.string');
  7638. /**
  7639. * @return {boolean} Whether the rendering engine is Presto.
  7640. */
  7641. goog.labs.userAgent.engine.isPresto = function() {
  7642. return goog.labs.userAgent.util.matchUserAgent('Presto');
  7643. };
  7644. /**
  7645. * @return {boolean} Whether the rendering engine is Trident.
  7646. */
  7647. goog.labs.userAgent.engine.isTrident = function() {
  7648. // IE only started including the Trident token in IE8.
  7649. return goog.labs.userAgent.util.matchUserAgent('Trident') ||
  7650. goog.labs.userAgent.util.matchUserAgent('MSIE');
  7651. };
  7652. /**
  7653. * @return {boolean} Whether the rendering engine is Edge.
  7654. */
  7655. goog.labs.userAgent.engine.isEdge = function() {
  7656. return goog.labs.userAgent.util.matchUserAgent('Edge');
  7657. };
  7658. /**
  7659. * @return {boolean} Whether the rendering engine is WebKit.
  7660. */
  7661. goog.labs.userAgent.engine.isWebKit = function() {
  7662. return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&
  7663. !goog.labs.userAgent.engine.isEdge();
  7664. };
  7665. /**
  7666. * @return {boolean} Whether the rendering engine is Gecko.
  7667. */
  7668. goog.labs.userAgent.engine.isGecko = function() {
  7669. return goog.labs.userAgent.util.matchUserAgent('Gecko') &&
  7670. !goog.labs.userAgent.engine.isWebKit() &&
  7671. !goog.labs.userAgent.engine.isTrident() &&
  7672. !goog.labs.userAgent.engine.isEdge();
  7673. };
  7674. /**
  7675. * @return {string} The rendering engine's version or empty string if version
  7676. * can't be determined.
  7677. */
  7678. goog.labs.userAgent.engine.getVersion = function() {
  7679. var userAgentString = goog.labs.userAgent.util.getUserAgent();
  7680. if (userAgentString) {
  7681. var tuples = goog.labs.userAgent.util.extractVersionTuples(
  7682. userAgentString);
  7683. var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);
  7684. if (engineTuple) {
  7685. // In Gecko, the version string is either in the browser info or the
  7686. // Firefox version. See Gecko user agent string reference:
  7687. // http://goo.gl/mULqa
  7688. if (engineTuple[0] == 'Gecko') {
  7689. return goog.labs.userAgent.engine.getVersionForKey_(
  7690. tuples, 'Firefox');
  7691. }
  7692. return engineTuple[1];
  7693. }
  7694. // MSIE has only one version identifier, and the Trident version is
  7695. // specified in the parenthetical. IE Edge is covered in the engine tuple
  7696. // detection.
  7697. var browserTuple = tuples[0];
  7698. var info;
  7699. if (browserTuple && (info = browserTuple[2])) {
  7700. var match = /Trident\/([^\s;]+)/.exec(info);
  7701. if (match) {
  7702. return match[1];
  7703. }
  7704. }
  7705. }
  7706. return '';
  7707. };
  7708. /**
  7709. * @param {!Array<!Array<string>>} tuples Extracted version tuples.
  7710. * @return {!Array<string>|undefined} The engine tuple or undefined if not
  7711. * found.
  7712. * @private
  7713. */
  7714. goog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {
  7715. if (!goog.labs.userAgent.engine.isEdge()) {
  7716. return tuples[1];
  7717. }
  7718. for (var i = 0; i < tuples.length; i++) {
  7719. var tuple = tuples[i];
  7720. if (tuple[0] == 'Edge') {
  7721. return tuple;
  7722. }
  7723. }
  7724. };
  7725. /**
  7726. * @param {string|number} version The version to check.
  7727. * @return {boolean} Whether the rendering engine version is higher or the same
  7728. * as the given version.
  7729. */
  7730. goog.labs.userAgent.engine.isVersionOrHigher = function(version) {
  7731. return goog.string.compareVersions(goog.labs.userAgent.engine.getVersion(),
  7732. version) >= 0;
  7733. };
  7734. /**
  7735. * @param {!Array<!Array<string>>} tuples Version tuples.
  7736. * @param {string} key The key to look for.
  7737. * @return {string} The version string of the given key, if present.
  7738. * Otherwise, the empty string.
  7739. * @private
  7740. */
  7741. goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {
  7742. // TODO(nnaze): Move to util if useful elsewhere.
  7743. var pair = goog.array.find(tuples, function(pair) {
  7744. return key == pair[0];
  7745. });
  7746. return pair && pair[1] || '';
  7747. };
  7748. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  7749. //
  7750. // Licensed under the Apache License, Version 2.0 (the "License");
  7751. // you may not use this file except in compliance with the License.
  7752. // You may obtain a copy of the License at
  7753. //
  7754. // http://www.apache.org/licenses/LICENSE-2.0
  7755. //
  7756. // Unless required by applicable law or agreed to in writing, software
  7757. // distributed under the License is distributed on an "AS-IS" BASIS,
  7758. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7759. // See the License for the specific language governing permissions and
  7760. // limitations under the License.
  7761. /**
  7762. * @fileoverview Closure user agent platform detection.
  7763. * @see <a href="http://www.useragentstring.com/">User agent strings</a>
  7764. * For more information on browser brand, rendering engine, or device see the
  7765. * other sub-namespaces in goog.labs.userAgent (browser, engine, and device
  7766. * respectively).
  7767. *
  7768. */
  7769. goog.provide('goog.labs.userAgent.platform');
  7770. goog.require('goog.labs.userAgent.util');
  7771. goog.require('goog.string');
  7772. /**
  7773. * @return {boolean} Whether the platform is Android.
  7774. */
  7775. goog.labs.userAgent.platform.isAndroid = function() {
  7776. return goog.labs.userAgent.util.matchUserAgent('Android');
  7777. };
  7778. /**
  7779. * @return {boolean} Whether the platform is iPod.
  7780. */
  7781. goog.labs.userAgent.platform.isIpod = function() {
  7782. return goog.labs.userAgent.util.matchUserAgent('iPod');
  7783. };
  7784. /**
  7785. * @return {boolean} Whether the platform is iPhone.
  7786. */
  7787. goog.labs.userAgent.platform.isIphone = function() {
  7788. return goog.labs.userAgent.util.matchUserAgent('iPhone') &&
  7789. !goog.labs.userAgent.util.matchUserAgent('iPod') &&
  7790. !goog.labs.userAgent.util.matchUserAgent('iPad');
  7791. };
  7792. /**
  7793. * @return {boolean} Whether the platform is iPad.
  7794. */
  7795. goog.labs.userAgent.platform.isIpad = function() {
  7796. return goog.labs.userAgent.util.matchUserAgent('iPad');
  7797. };
  7798. /**
  7799. * @return {boolean} Whether the platform is iOS.
  7800. */
  7801. goog.labs.userAgent.platform.isIos = function() {
  7802. return goog.labs.userAgent.platform.isIphone() ||
  7803. goog.labs.userAgent.platform.isIpad() ||
  7804. goog.labs.userAgent.platform.isIpod();
  7805. };
  7806. /**
  7807. * @return {boolean} Whether the platform is Mac.
  7808. */
  7809. goog.labs.userAgent.platform.isMacintosh = function() {
  7810. return goog.labs.userAgent.util.matchUserAgent('Macintosh');
  7811. };
  7812. /**
  7813. * Note: ChromeOS is not considered to be Linux as it does not report itself
  7814. * as Linux in the user agent string.
  7815. * @return {boolean} Whether the platform is Linux.
  7816. */
  7817. goog.labs.userAgent.platform.isLinux = function() {
  7818. return goog.labs.userAgent.util.matchUserAgent('Linux');
  7819. };
  7820. /**
  7821. * @return {boolean} Whether the platform is Windows.
  7822. */
  7823. goog.labs.userAgent.platform.isWindows = function() {
  7824. return goog.labs.userAgent.util.matchUserAgent('Windows');
  7825. };
  7826. /**
  7827. * @return {boolean} Whether the platform is ChromeOS.
  7828. */
  7829. goog.labs.userAgent.platform.isChromeOS = function() {
  7830. return goog.labs.userAgent.util.matchUserAgent('CrOS');
  7831. };
  7832. /**
  7833. * The version of the platform. We only determine the version for Windows,
  7834. * Mac, and Chrome OS. It doesn't make much sense on Linux. For Windows, we only
  7835. * look at the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given
  7836. * version 0.0.
  7837. *
  7838. * @return {string} The platform version or empty string if version cannot be
  7839. * determined.
  7840. */
  7841. goog.labs.userAgent.platform.getVersion = function() {
  7842. var userAgentString = goog.labs.userAgent.util.getUserAgent();
  7843. var version = '', re;
  7844. if (goog.labs.userAgent.platform.isWindows()) {
  7845. re = /Windows (?:NT|Phone) ([0-9.]+)/;
  7846. var match = re.exec(userAgentString);
  7847. if (match) {
  7848. version = match[1];
  7849. } else {
  7850. version = '0.0';
  7851. }
  7852. } else if (goog.labs.userAgent.platform.isIos()) {
  7853. re = /(?:iPhone|iPod|iPad|CPU)\s+OS\s+(\S+)/;
  7854. var match = re.exec(userAgentString);
  7855. // Report the version as x.y.z and not x_y_z
  7856. version = match && match[1].replace(/_/g, '.');
  7857. } else if (goog.labs.userAgent.platform.isMacintosh()) {
  7858. re = /Mac OS X ([0-9_.]+)/;
  7859. var match = re.exec(userAgentString);
  7860. // Note: some old versions of Camino do not report an OSX version.
  7861. // Default to 10.
  7862. version = match ? match[1].replace(/_/g, '.') : '10';
  7863. } else if (goog.labs.userAgent.platform.isAndroid()) {
  7864. re = /Android\s+([^\);]+)(\)|;)/;
  7865. var match = re.exec(userAgentString);
  7866. version = match && match[1];
  7867. } else if (goog.labs.userAgent.platform.isChromeOS()) {
  7868. re = /(?:CrOS\s+(?:i686|x86_64)\s+([0-9.]+))/;
  7869. var match = re.exec(userAgentString);
  7870. version = match && match[1];
  7871. }
  7872. return version || '';
  7873. };
  7874. /**
  7875. * @param {string|number} version The version to check.
  7876. * @return {boolean} Whether the browser version is higher or the same as the
  7877. * given version.
  7878. */
  7879. goog.labs.userAgent.platform.isVersionOrHigher = function(version) {
  7880. return goog.string.compareVersions(goog.labs.userAgent.platform.getVersion(),
  7881. version) >= 0;
  7882. };
  7883. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  7884. //
  7885. // Licensed under the Apache License, Version 2.0 (the "License");
  7886. // you may not use this file except in compliance with the License.
  7887. // You may obtain a copy of the License at
  7888. //
  7889. // http://www.apache.org/licenses/LICENSE-2.0
  7890. //
  7891. // Unless required by applicable law or agreed to in writing, software
  7892. // distributed under the License is distributed on an "AS-IS" BASIS,
  7893. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7894. // See the License for the specific language governing permissions and
  7895. // limitations under the License.
  7896. /**
  7897. * @fileoverview Rendering engine detection.
  7898. * @see <a href="http://www.useragentstring.com/">User agent strings</a>
  7899. * For information on the browser brand (such as Safari versus Chrome), see
  7900. * goog.userAgent.product.
  7901. * @author arv@google.com (Erik Arvidsson)
  7902. * @see ../demos/useragent.html
  7903. */
  7904. goog.provide('goog.userAgent');
  7905. goog.require('goog.labs.userAgent.browser');
  7906. goog.require('goog.labs.userAgent.engine');
  7907. goog.require('goog.labs.userAgent.platform');
  7908. goog.require('goog.labs.userAgent.util');
  7909. goog.require('goog.string');
  7910. /**
  7911. * @define {boolean} Whether we know at compile-time that the browser is IE.
  7912. */
  7913. goog.define('goog.userAgent.ASSUME_IE', false);
  7914. /**
  7915. * @define {boolean} Whether we know at compile-time that the browser is EDGE.
  7916. */
  7917. goog.define('goog.userAgent.ASSUME_EDGE', false);
  7918. /**
  7919. * @define {boolean} Whether we know at compile-time that the browser is GECKO.
  7920. */
  7921. goog.define('goog.userAgent.ASSUME_GECKO', false);
  7922. /**
  7923. * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.
  7924. */
  7925. goog.define('goog.userAgent.ASSUME_WEBKIT', false);
  7926. /**
  7927. * @define {boolean} Whether we know at compile-time that the browser is a
  7928. * mobile device running WebKit e.g. iPhone or Android.
  7929. */
  7930. goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);
  7931. /**
  7932. * @define {boolean} Whether we know at compile-time that the browser is OPERA.
  7933. */
  7934. goog.define('goog.userAgent.ASSUME_OPERA', false);
  7935. /**
  7936. * @define {boolean} Whether the
  7937. * {@code goog.userAgent.isVersionOrHigher}
  7938. * function will return true for any version.
  7939. */
  7940. goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);
  7941. /**
  7942. * Whether we know the browser engine at compile-time.
  7943. * @type {boolean}
  7944. * @private
  7945. */
  7946. goog.userAgent.BROWSER_KNOWN_ =
  7947. goog.userAgent.ASSUME_IE ||
  7948. goog.userAgent.ASSUME_EDGE ||
  7949. goog.userAgent.ASSUME_GECKO ||
  7950. goog.userAgent.ASSUME_MOBILE_WEBKIT ||
  7951. goog.userAgent.ASSUME_WEBKIT ||
  7952. goog.userAgent.ASSUME_OPERA;
  7953. /**
  7954. * Returns the userAgent string for the current browser.
  7955. *
  7956. * @return {string} The userAgent string.
  7957. */
  7958. goog.userAgent.getUserAgentString = function() {
  7959. return goog.labs.userAgent.util.getUserAgent();
  7960. };
  7961. /**
  7962. * TODO(nnaze): Change type to "Navigator" and update compilation targets.
  7963. * @return {Object} The native navigator object.
  7964. */
  7965. goog.userAgent.getNavigator = function() {
  7966. // Need a local navigator reference instead of using the global one,
  7967. // to avoid the rare case where they reference different objects.
  7968. // (in a WorkerPool, for example).
  7969. return goog.global['navigator'] || null;
  7970. };
  7971. /**
  7972. * Whether the user agent is Opera.
  7973. * @type {boolean}
  7974. */
  7975. goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?
  7976. goog.userAgent.ASSUME_OPERA :
  7977. goog.labs.userAgent.browser.isOpera();
  7978. /**
  7979. * Whether the user agent is Internet Explorer.
  7980. * @type {boolean}
  7981. */
  7982. goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?
  7983. goog.userAgent.ASSUME_IE :
  7984. goog.labs.userAgent.browser.isIE();
  7985. /**
  7986. * Whether the user agent is Microsoft Edge.
  7987. * @type {boolean}
  7988. */
  7989. goog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?
  7990. goog.userAgent.ASSUME_EDGE :
  7991. goog.labs.userAgent.engine.isEdge();
  7992. /**
  7993. * Whether the user agent is MS Internet Explorer or MS Edge.
  7994. * @type {boolean}
  7995. */
  7996. goog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;
  7997. /**
  7998. * Whether the user agent is Gecko. Gecko is the rendering engine used by
  7999. * Mozilla, Firefox, and others.
  8000. * @type {boolean}
  8001. */
  8002. goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?
  8003. goog.userAgent.ASSUME_GECKO :
  8004. goog.labs.userAgent.engine.isGecko();
  8005. /**
  8006. * Whether the user agent is WebKit. WebKit is the rendering engine that
  8007. * Safari, Android and others use.
  8008. * @type {boolean}
  8009. */
  8010. goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?
  8011. goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :
  8012. goog.labs.userAgent.engine.isWebKit();
  8013. /**
  8014. * Whether the user agent is running on a mobile device.
  8015. *
  8016. * This is a separate function so that the logic can be tested.
  8017. *
  8018. * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().
  8019. *
  8020. * @return {boolean} Whether the user agent is running on a mobile device.
  8021. * @private
  8022. */
  8023. goog.userAgent.isMobile_ = function() {
  8024. return goog.userAgent.WEBKIT &&
  8025. goog.labs.userAgent.util.matchUserAgent('Mobile');
  8026. };
  8027. /**
  8028. * Whether the user agent is running on a mobile device.
  8029. *
  8030. * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent
  8031. * is promoted as the gecko/webkit logic is likely inaccurate.
  8032. *
  8033. * @type {boolean}
  8034. */
  8035. goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT ||
  8036. goog.userAgent.isMobile_();
  8037. /**
  8038. * Used while transitioning code to use WEBKIT instead.
  8039. * @type {boolean}
  8040. * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.
  8041. * TODO(nicksantos): Delete this from goog.userAgent.
  8042. */
  8043. goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
  8044. /**
  8045. * @return {string} the platform (operating system) the user agent is running
  8046. * on. Default to empty string because navigator.platform may not be defined
  8047. * (on Rhino, for example).
  8048. * @private
  8049. */
  8050. goog.userAgent.determinePlatform_ = function() {
  8051. var navigator = goog.userAgent.getNavigator();
  8052. return navigator && navigator.platform || '';
  8053. };
  8054. /**
  8055. * The platform (operating system) the user agent is running on. Default to
  8056. * empty string because navigator.platform may not be defined (on Rhino, for
  8057. * example).
  8058. * @type {string}
  8059. */
  8060. goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
  8061. /**
  8062. * @define {boolean} Whether the user agent is running on a Macintosh operating
  8063. * system.
  8064. */
  8065. goog.define('goog.userAgent.ASSUME_MAC', false);
  8066. /**
  8067. * @define {boolean} Whether the user agent is running on a Windows operating
  8068. * system.
  8069. */
  8070. goog.define('goog.userAgent.ASSUME_WINDOWS', false);
  8071. /**
  8072. * @define {boolean} Whether the user agent is running on a Linux operating
  8073. * system.
  8074. */
  8075. goog.define('goog.userAgent.ASSUME_LINUX', false);
  8076. /**
  8077. * @define {boolean} Whether the user agent is running on a X11 windowing
  8078. * system.
  8079. */
  8080. goog.define('goog.userAgent.ASSUME_X11', false);
  8081. /**
  8082. * @define {boolean} Whether the user agent is running on Android.
  8083. */
  8084. goog.define('goog.userAgent.ASSUME_ANDROID', false);
  8085. /**
  8086. * @define {boolean} Whether the user agent is running on an iPhone.
  8087. */
  8088. goog.define('goog.userAgent.ASSUME_IPHONE', false);
  8089. /**
  8090. * @define {boolean} Whether the user agent is running on an iPad.
  8091. */
  8092. goog.define('goog.userAgent.ASSUME_IPAD', false);
  8093. /**
  8094. * @type {boolean}
  8095. * @private
  8096. */
  8097. goog.userAgent.PLATFORM_KNOWN_ =
  8098. goog.userAgent.ASSUME_MAC ||
  8099. goog.userAgent.ASSUME_WINDOWS ||
  8100. goog.userAgent.ASSUME_LINUX ||
  8101. goog.userAgent.ASSUME_X11 ||
  8102. goog.userAgent.ASSUME_ANDROID ||
  8103. goog.userAgent.ASSUME_IPHONE ||
  8104. goog.userAgent.ASSUME_IPAD;
  8105. /**
  8106. * Whether the user agent is running on a Macintosh operating system.
  8107. * @type {boolean}
  8108. */
  8109. goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?
  8110. goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh();
  8111. /**
  8112. * Whether the user agent is running on a Windows operating system.
  8113. * @type {boolean}
  8114. */
  8115. goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?
  8116. goog.userAgent.ASSUME_WINDOWS :
  8117. goog.labs.userAgent.platform.isWindows();
  8118. /**
  8119. * Whether the user agent is Linux per the legacy behavior of
  8120. * goog.userAgent.LINUX, which considered ChromeOS to also be
  8121. * Linux.
  8122. * @return {boolean}
  8123. * @private
  8124. */
  8125. goog.userAgent.isLegacyLinux_ = function() {
  8126. return goog.labs.userAgent.platform.isLinux() ||
  8127. goog.labs.userAgent.platform.isChromeOS();
  8128. };
  8129. /**
  8130. * Whether the user agent is running on a Linux operating system.
  8131. *
  8132. * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,
  8133. * while goog.labs.userAgent.platform considers ChromeOS and
  8134. * Linux to be different OSes.
  8135. *
  8136. * @type {boolean}
  8137. */
  8138. goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?
  8139. goog.userAgent.ASSUME_LINUX :
  8140. goog.userAgent.isLegacyLinux_();
  8141. /**
  8142. * @return {boolean} Whether the user agent is an X11 windowing system.
  8143. * @private
  8144. */
  8145. goog.userAgent.isX11_ = function() {
  8146. var navigator = goog.userAgent.getNavigator();
  8147. return !!navigator &&
  8148. goog.string.contains(navigator['appVersion'] || '', 'X11');
  8149. };
  8150. /**
  8151. * Whether the user agent is running on a X11 windowing system.
  8152. * @type {boolean}
  8153. */
  8154. goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?
  8155. goog.userAgent.ASSUME_X11 :
  8156. goog.userAgent.isX11_();
  8157. /**
  8158. * Whether the user agent is running on Android.
  8159. * @type {boolean}
  8160. */
  8161. goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?
  8162. goog.userAgent.ASSUME_ANDROID :
  8163. goog.labs.userAgent.platform.isAndroid();
  8164. /**
  8165. * Whether the user agent is running on an iPhone.
  8166. * @type {boolean}
  8167. */
  8168. goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?
  8169. goog.userAgent.ASSUME_IPHONE :
  8170. goog.labs.userAgent.platform.isIphone();
  8171. /**
  8172. * Whether the user agent is running on an iPad.
  8173. * @type {boolean}
  8174. */
  8175. goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?
  8176. goog.userAgent.ASSUME_IPAD :
  8177. goog.labs.userAgent.platform.isIpad();
  8178. /**
  8179. * @return {string} The string that describes the version number of the user
  8180. * agent.
  8181. * Assumes user agent is opera.
  8182. * @private
  8183. */
  8184. goog.userAgent.operaVersion_ = function() {
  8185. var version = goog.global.opera.version;
  8186. try {
  8187. return version();
  8188. } catch (e) {
  8189. return version;
  8190. }
  8191. };
  8192. /**
  8193. * @return {string} The string that describes the version number of the user
  8194. * agent.
  8195. * @private
  8196. */
  8197. goog.userAgent.determineVersion_ = function() {
  8198. // All browsers have different ways to detect the version and they all have
  8199. // different naming schemes.
  8200. if (goog.userAgent.OPERA && goog.global['opera']) {
  8201. return goog.userAgent.operaVersion_();
  8202. }
  8203. // version is a string rather than a number because it may contain 'b', 'a',
  8204. // and so on.
  8205. var version = '';
  8206. var arr = goog.userAgent.getVersionRegexResult_();
  8207. if (arr) {
  8208. version = arr ? arr[1] : '';
  8209. }
  8210. if (goog.userAgent.IE) {
  8211. // IE9 can be in document mode 9 but be reporting an inconsistent user agent
  8212. // version. If it is identifying as a version lower than 9 we take the
  8213. // documentMode as the version instead. IE8 has similar behavior.
  8214. // It is recommended to set the X-UA-Compatible header to ensure that IE9
  8215. // uses documentMode 9.
  8216. var docMode = goog.userAgent.getDocumentMode_();
  8217. if (docMode > parseFloat(version)) {
  8218. return String(docMode);
  8219. }
  8220. }
  8221. return version;
  8222. };
  8223. /**
  8224. * @return {Array|undefined} The version regex matches from parsing the user
  8225. * agent string. These regex statements must be executed inline so they can
  8226. * be compiled out by the closure compiler with the rest of the useragent
  8227. * detection logic when ASSUME_* is specified.
  8228. * @private
  8229. */
  8230. goog.userAgent.getVersionRegexResult_ = function() {
  8231. var userAgent = goog.userAgent.getUserAgentString();
  8232. if (goog.userAgent.GECKO) {
  8233. return /rv\:([^\);]+)(\)|;)/.exec(userAgent);
  8234. }
  8235. if (goog.userAgent.EDGE) {
  8236. return /Edge\/([\d\.]+)/.exec(userAgent);
  8237. }
  8238. if (goog.userAgent.IE) {
  8239. return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(userAgent);
  8240. }
  8241. if (goog.userAgent.WEBKIT) {
  8242. // WebKit/125.4
  8243. return /WebKit\/(\S+)/.exec(userAgent);
  8244. }
  8245. };
  8246. /**
  8247. * @return {number|undefined} Returns the document mode (for testing).
  8248. * @private
  8249. */
  8250. goog.userAgent.getDocumentMode_ = function() {
  8251. // NOTE(user): goog.userAgent may be used in context where there is no DOM.
  8252. var doc = goog.global['document'];
  8253. return doc ? doc['documentMode'] : undefined;
  8254. };
  8255. /**
  8256. * The version of the user agent. This is a string because it might contain
  8257. * 'b' (as in beta) as well as multiple dots.
  8258. * @type {string}
  8259. */
  8260. goog.userAgent.VERSION = goog.userAgent.determineVersion_();
  8261. /**
  8262. * Compares two version numbers.
  8263. *
  8264. * @param {string} v1 Version of first item.
  8265. * @param {string} v2 Version of second item.
  8266. *
  8267. * @return {number} 1 if first argument is higher
  8268. * 0 if arguments are equal
  8269. * -1 if second argument is higher.
  8270. * @deprecated Use goog.string.compareVersions.
  8271. */
  8272. goog.userAgent.compare = function(v1, v2) {
  8273. return goog.string.compareVersions(v1, v2);
  8274. };
  8275. /**
  8276. * Cache for {@link goog.userAgent.isVersionOrHigher}.
  8277. * Calls to compareVersions are surprisingly expensive and, as a browser's
  8278. * version number is unlikely to change during a session, we cache the results.
  8279. * @const
  8280. * @private
  8281. */
  8282. goog.userAgent.isVersionOrHigherCache_ = {};
  8283. /**
  8284. * Whether the user agent version is higher or the same as the given version.
  8285. * NOTE: When checking the version numbers for Firefox and Safari, be sure to
  8286. * use the engine's version, not the browser's version number. For example,
  8287. * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.
  8288. * Opera and Internet Explorer versions match the product release number.<br>
  8289. * @see <a href="http://en.wikipedia.org/wiki/Safari_version_history">
  8290. * Webkit</a>
  8291. * @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a>
  8292. *
  8293. * @param {string|number} version The version to check.
  8294. * @return {boolean} Whether the user agent version is higher or the same as
  8295. * the given version.
  8296. */
  8297. goog.userAgent.isVersionOrHigher = function(version) {
  8298. return goog.userAgent.ASSUME_ANY_VERSION ||
  8299. goog.userAgent.isVersionOrHigherCache_[version] ||
  8300. (goog.userAgent.isVersionOrHigherCache_[version] =
  8301. goog.string.compareVersions(goog.userAgent.VERSION, version) >= 0);
  8302. };
  8303. /**
  8304. * Deprecated alias to {@code goog.userAgent.isVersionOrHigher}.
  8305. * @param {string|number} version The version to check.
  8306. * @return {boolean} Whether the user agent version is higher or the same as
  8307. * the given version.
  8308. * @deprecated Use goog.userAgent.isVersionOrHigher().
  8309. */
  8310. goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;
  8311. /**
  8312. * Whether the IE effective document mode is higher or the same as the given
  8313. * document mode version.
  8314. * NOTE: Only for IE, return false for another browser.
  8315. *
  8316. * @param {number} documentMode The document mode version to check.
  8317. * @return {boolean} Whether the IE effective document mode is higher or the
  8318. * same as the given version.
  8319. */
  8320. goog.userAgent.isDocumentModeOrHigher = function(documentMode) {
  8321. return goog.userAgent.DOCUMENT_MODE >= documentMode;
  8322. };
  8323. /**
  8324. * Deprecated alias to {@code goog.userAgent.isDocumentModeOrHigher}.
  8325. * @param {number} version The version to check.
  8326. * @return {boolean} Whether the IE effective document mode is higher or the
  8327. * same as the given version.
  8328. * @deprecated Use goog.userAgent.isDocumentModeOrHigher().
  8329. */
  8330. goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;
  8331. /**
  8332. * For IE version < 7, documentMode is undefined, so attempt to use the
  8333. * CSS1Compat property to see if we are in standards mode. If we are in
  8334. * standards mode, treat the browser version as the document mode. Otherwise,
  8335. * IE is emulating version 5.
  8336. * @type {number|undefined}
  8337. * @const
  8338. */
  8339. goog.userAgent.DOCUMENT_MODE = (function() {
  8340. var doc = goog.global['document'];
  8341. var mode = goog.userAgent.getDocumentMode_();
  8342. if (!doc || !goog.userAgent.IE) {
  8343. return undefined;
  8344. }
  8345. return mode || (doc['compatMode'] == 'CSS1Compat' ?
  8346. parseInt(goog.userAgent.VERSION, 10) : 5);
  8347. })();
  8348. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  8349. //
  8350. // Licensed under the Apache License, Version 2.0 (the "License");
  8351. // you may not use this file except in compliance with the License.
  8352. // You may obtain a copy of the License at
  8353. //
  8354. // http://www.apache.org/licenses/LICENSE-2.0
  8355. //
  8356. // Unless required by applicable law or agreed to in writing, software
  8357. // distributed under the License is distributed on an "AS-IS" BASIS,
  8358. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8359. // See the License for the specific language governing permissions and
  8360. // limitations under the License.
  8361. /**
  8362. * @fileoverview Browser capability checks for the events package.
  8363. *
  8364. */
  8365. goog.provide('goog.events.BrowserFeature');
  8366. goog.require('goog.userAgent');
  8367. /**
  8368. * Enum of browser capabilities.
  8369. * @enum {boolean}
  8370. */
  8371. goog.events.BrowserFeature = {
  8372. /**
  8373. * Whether the button attribute of the event is W3C compliant. False in
  8374. * Internet Explorer prior to version 9; document-version dependent.
  8375. */
  8376. HAS_W3C_BUTTON: !goog.userAgent.IE ||
  8377. goog.userAgent.isDocumentModeOrHigher(9),
  8378. /**
  8379. * Whether the browser supports full W3C event model.
  8380. */
  8381. HAS_W3C_EVENT_SUPPORT: !goog.userAgent.IE ||
  8382. goog.userAgent.isDocumentModeOrHigher(9),
  8383. /**
  8384. * To prevent default in IE7-8 for certain keydown events we need set the
  8385. * keyCode to -1.
  8386. */
  8387. SET_KEY_CODE_TO_PREVENT_DEFAULT: goog.userAgent.IE &&
  8388. !goog.userAgent.isVersionOrHigher('9'),
  8389. /**
  8390. * Whether the {@code navigator.onLine} property is supported.
  8391. */
  8392. HAS_NAVIGATOR_ONLINE_PROPERTY: !goog.userAgent.WEBKIT ||
  8393. goog.userAgent.isVersionOrHigher('528'),
  8394. /**
  8395. * Whether HTML5 network online/offline events are supported.
  8396. */
  8397. HAS_HTML5_NETWORK_EVENT_SUPPORT:
  8398. goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') ||
  8399. goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') ||
  8400. goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') ||
  8401. goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'),
  8402. /**
  8403. * Whether HTML5 network events fire on document.body, or otherwise the
  8404. * window.
  8405. */
  8406. HTML5_NETWORK_EVENTS_FIRE_ON_BODY:
  8407. goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') ||
  8408. goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),
  8409. /**
  8410. * Whether touch is enabled in the browser.
  8411. */
  8412. TOUCH_ENABLED:
  8413. ('ontouchstart' in goog.global ||
  8414. !!(goog.global['document'] &&
  8415. document.documentElement &&
  8416. 'ontouchstart' in document.documentElement) ||
  8417. // IE10 uses non-standard touch events, so it has a different check.
  8418. !!(goog.global['navigator'] &&
  8419. goog.global['navigator']['msMaxTouchPoints']))
  8420. };
  8421. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  8422. //
  8423. // Licensed under the Apache License, Version 2.0 (the "License");
  8424. // you may not use this file except in compliance with the License.
  8425. // You may obtain a copy of the License at
  8426. //
  8427. // http://www.apache.org/licenses/LICENSE-2.0
  8428. //
  8429. // Unless required by applicable law or agreed to in writing, software
  8430. // distributed under the License is distributed on an "AS-IS" BASIS,
  8431. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8432. // See the License for the specific language governing permissions and
  8433. // limitations under the License.
  8434. /**
  8435. * @fileoverview Definition of the disposable interface. A disposable object
  8436. * has a dispose method to to clean up references and resources.
  8437. * @author nnaze@google.com (Nathan Naze)
  8438. */
  8439. goog.provide('goog.disposable.IDisposable');
  8440. /**
  8441. * Interface for a disposable object. If a instance requires cleanup
  8442. * (references COM objects, DOM notes, or other disposable objects), it should
  8443. * implement this interface (it may subclass goog.Disposable).
  8444. * @interface
  8445. */
  8446. goog.disposable.IDisposable = function() {};
  8447. /**
  8448. * Disposes of the object and its resources.
  8449. * @return {void} Nothing.
  8450. */
  8451. goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
  8452. /**
  8453. * @return {boolean} Whether the object has been disposed of.
  8454. */
  8455. goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
  8456. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  8457. //
  8458. // Licensed under the Apache License, Version 2.0 (the "License");
  8459. // you may not use this file except in compliance with the License.
  8460. // You may obtain a copy of the License at
  8461. //
  8462. // http://www.apache.org/licenses/LICENSE-2.0
  8463. //
  8464. // Unless required by applicable law or agreed to in writing, software
  8465. // distributed under the License is distributed on an "AS-IS" BASIS,
  8466. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8467. // See the License for the specific language governing permissions and
  8468. // limitations under the License.
  8469. /**
  8470. * @fileoverview Implements the disposable interface. The dispose method is used
  8471. * to clean up references and resources.
  8472. * @author arv@google.com (Erik Arvidsson)
  8473. */
  8474. goog.provide('goog.Disposable');
  8475. /** @suppress {extraProvide} */
  8476. goog.provide('goog.dispose');
  8477. /** @suppress {extraProvide} */
  8478. goog.provide('goog.disposeAll');
  8479. goog.require('goog.disposable.IDisposable');
  8480. /**
  8481. * Class that provides the basic implementation for disposable objects. If your
  8482. * class holds one or more references to COM objects, DOM nodes, or other
  8483. * disposable objects, it should extend this class or implement the disposable
  8484. * interface (defined in goog.disposable.IDisposable).
  8485. * @constructor
  8486. * @implements {goog.disposable.IDisposable}
  8487. */
  8488. goog.Disposable = function() {
  8489. if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {
  8490. if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {
  8491. this.creationStack = new Error().stack;
  8492. }
  8493. goog.Disposable.instances_[goog.getUid(this)] = this;
  8494. }
  8495. // Support sealing
  8496. this.disposed_ = this.disposed_;
  8497. this.onDisposeCallbacks_ = this.onDisposeCallbacks_;
  8498. };
  8499. /**
  8500. * @enum {number} Different monitoring modes for Disposable.
  8501. */
  8502. goog.Disposable.MonitoringMode = {
  8503. /**
  8504. * No monitoring.
  8505. */
  8506. OFF: 0,
  8507. /**
  8508. * Creating and disposing the goog.Disposable instances is monitored. All
  8509. * disposable objects need to call the {@code goog.Disposable} base
  8510. * constructor. The PERMANENT mode must be switched on before creating any
  8511. * goog.Disposable instances.
  8512. */
  8513. PERMANENT: 1,
  8514. /**
  8515. * INTERACTIVE mode can be switched on and off on the fly without producing
  8516. * errors. It also doesn't warn if the disposable objects don't call the
  8517. * {@code goog.Disposable} base constructor.
  8518. */
  8519. INTERACTIVE: 2
  8520. };
  8521. /**
  8522. * @define {number} The monitoring mode of the goog.Disposable
  8523. * instances. Default is OFF. Switching on the monitoring is only
  8524. * recommended for debugging because it has a significant impact on
  8525. * performance and memory usage. If switched off, the monitoring code
  8526. * compiles down to 0 bytes.
  8527. */
  8528. goog.define('goog.Disposable.MONITORING_MODE', 0);
  8529. /**
  8530. * @define {boolean} Whether to attach creation stack to each created disposable
  8531. * instance; This is only relevant for when MonitoringMode != OFF.
  8532. */
  8533. goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);
  8534. /**
  8535. * Maps the unique ID of every undisposed {@code goog.Disposable} object to
  8536. * the object itself.
  8537. * @type {!Object<number, !goog.Disposable>}
  8538. * @private
  8539. */
  8540. goog.Disposable.instances_ = {};
  8541. /**
  8542. * @return {!Array<!goog.Disposable>} All {@code goog.Disposable} objects that
  8543. * haven't been disposed of.
  8544. */
  8545. goog.Disposable.getUndisposedObjects = function() {
  8546. var ret = [];
  8547. for (var id in goog.Disposable.instances_) {
  8548. if (goog.Disposable.instances_.hasOwnProperty(id)) {
  8549. ret.push(goog.Disposable.instances_[Number(id)]);
  8550. }
  8551. }
  8552. return ret;
  8553. };
  8554. /**
  8555. * Clears the registry of undisposed objects but doesn't dispose of them.
  8556. */
  8557. goog.Disposable.clearUndisposedObjects = function() {
  8558. goog.Disposable.instances_ = {};
  8559. };
  8560. /**
  8561. * Whether the object has been disposed of.
  8562. * @type {boolean}
  8563. * @private
  8564. */
  8565. goog.Disposable.prototype.disposed_ = false;
  8566. /**
  8567. * Callbacks to invoke when this object is disposed.
  8568. * @type {Array<!Function>}
  8569. * @private
  8570. */
  8571. goog.Disposable.prototype.onDisposeCallbacks_;
  8572. /**
  8573. * If monitoring the goog.Disposable instances is enabled, stores the creation
  8574. * stack trace of the Disposable instance.
  8575. * @const {string}
  8576. */
  8577. goog.Disposable.prototype.creationStack;
  8578. /**
  8579. * @return {boolean} Whether the object has been disposed of.
  8580. * @override
  8581. */
  8582. goog.Disposable.prototype.isDisposed = function() {
  8583. return this.disposed_;
  8584. };
  8585. /**
  8586. * @return {boolean} Whether the object has been disposed of.
  8587. * @deprecated Use {@link #isDisposed} instead.
  8588. */
  8589. goog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;
  8590. /**
  8591. * Disposes of the object. If the object hasn't already been disposed of, calls
  8592. * {@link #disposeInternal}. Classes that extend {@code goog.Disposable} should
  8593. * override {@link #disposeInternal} in order to delete references to COM
  8594. * objects, DOM nodes, and other disposable objects. Reentrant.
  8595. *
  8596. * @return {void} Nothing.
  8597. * @override
  8598. */
  8599. goog.Disposable.prototype.dispose = function() {
  8600. if (!this.disposed_) {
  8601. // Set disposed_ to true first, in case during the chain of disposal this
  8602. // gets disposed recursively.
  8603. this.disposed_ = true;
  8604. this.disposeInternal();
  8605. if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {
  8606. var uid = goog.getUid(this);
  8607. if (goog.Disposable.MONITORING_MODE ==
  8608. goog.Disposable.MonitoringMode.PERMANENT &&
  8609. !goog.Disposable.instances_.hasOwnProperty(uid)) {
  8610. throw Error(this + ' did not call the goog.Disposable base ' +
  8611. 'constructor or was disposed of after a clearUndisposedObjects ' +
  8612. 'call');
  8613. }
  8614. delete goog.Disposable.instances_[uid];
  8615. }
  8616. }
  8617. };
  8618. /**
  8619. * Associates a disposable object with this object so that they will be disposed
  8620. * together.
  8621. * @param {goog.disposable.IDisposable} disposable that will be disposed when
  8622. * this object is disposed.
  8623. */
  8624. goog.Disposable.prototype.registerDisposable = function(disposable) {
  8625. this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));
  8626. };
  8627. /**
  8628. * Invokes a callback function when this object is disposed. Callbacks are
  8629. * invoked in the order in which they were added. If a callback is added to
  8630. * an already disposed Disposable, it will be called immediately.
  8631. * @param {function(this:T):?} callback The callback function.
  8632. * @param {T=} opt_scope An optional scope to call the callback in.
  8633. * @template T
  8634. */
  8635. goog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {
  8636. if (this.disposed_) {
  8637. callback.call(opt_scope);
  8638. return;
  8639. }
  8640. if (!this.onDisposeCallbacks_) {
  8641. this.onDisposeCallbacks_ = [];
  8642. }
  8643. this.onDisposeCallbacks_.push(
  8644. goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback);
  8645. };
  8646. /**
  8647. * Deletes or nulls out any references to COM objects, DOM nodes, or other
  8648. * disposable objects. Classes that extend {@code goog.Disposable} should
  8649. * override this method.
  8650. * Not reentrant. To avoid calling it twice, it must only be called from the
  8651. * subclass' {@code disposeInternal} method. Everywhere else the public
  8652. * {@code dispose} method must be used.
  8653. * For example:
  8654. * <pre>
  8655. * mypackage.MyClass = function() {
  8656. * mypackage.MyClass.base(this, 'constructor');
  8657. * // Constructor logic specific to MyClass.
  8658. * ...
  8659. * };
  8660. * goog.inherits(mypackage.MyClass, goog.Disposable);
  8661. *
  8662. * mypackage.MyClass.prototype.disposeInternal = function() {
  8663. * // Dispose logic specific to MyClass.
  8664. * ...
  8665. * // Call superclass's disposeInternal at the end of the subclass's, like
  8666. * // in C++, to avoid hard-to-catch issues.
  8667. * mypackage.MyClass.base(this, 'disposeInternal');
  8668. * };
  8669. * </pre>
  8670. * @protected
  8671. */
  8672. goog.Disposable.prototype.disposeInternal = function() {
  8673. if (this.onDisposeCallbacks_) {
  8674. while (this.onDisposeCallbacks_.length) {
  8675. this.onDisposeCallbacks_.shift()();
  8676. }
  8677. }
  8678. };
  8679. /**
  8680. * Returns True if we can verify the object is disposed.
  8681. * Calls {@code isDisposed} on the argument if it supports it. If obj
  8682. * is not an object with an isDisposed() method, return false.
  8683. * @param {*} obj The object to investigate.
  8684. * @return {boolean} True if we can verify the object is disposed.
  8685. */
  8686. goog.Disposable.isDisposed = function(obj) {
  8687. if (obj && typeof obj.isDisposed == 'function') {
  8688. return obj.isDisposed();
  8689. }
  8690. return false;
  8691. };
  8692. /**
  8693. * Calls {@code dispose} on the argument if it supports it. If obj is not an
  8694. * object with a dispose() method, this is a no-op.
  8695. * @param {*} obj The object to dispose of.
  8696. */
  8697. goog.dispose = function(obj) {
  8698. if (obj && typeof obj.dispose == 'function') {
  8699. obj.dispose();
  8700. }
  8701. };
  8702. /**
  8703. * Calls {@code dispose} on each member of the list that supports it. (If the
  8704. * member is an ArrayLike, then {@code goog.disposeAll()} will be called
  8705. * recursively on each of its members.) If the member is not an object with a
  8706. * {@code dispose()} method, then it is ignored.
  8707. * @param {...*} var_args The list.
  8708. */
  8709. goog.disposeAll = function(var_args) {
  8710. for (var i = 0, len = arguments.length; i < len; ++i) {
  8711. var disposable = arguments[i];
  8712. if (goog.isArrayLike(disposable)) {
  8713. goog.disposeAll.apply(null, disposable);
  8714. } else {
  8715. goog.dispose(disposable);
  8716. }
  8717. }
  8718. };
  8719. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  8720. //
  8721. // Licensed under the Apache License, Version 2.0 (the "License");
  8722. // you may not use this file except in compliance with the License.
  8723. // You may obtain a copy of the License at
  8724. //
  8725. // http://www.apache.org/licenses/LICENSE-2.0
  8726. //
  8727. // Unless required by applicable law or agreed to in writing, software
  8728. // distributed under the License is distributed on an "AS-IS" BASIS,
  8729. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8730. // See the License for the specific language governing permissions and
  8731. // limitations under the License.
  8732. goog.provide('goog.events.EventId');
  8733. /**
  8734. * A templated class that is used when registering for events. Typical usage:
  8735. * <code>
  8736. * /** @type {goog.events.EventId<MyEventObj>}
  8737. * var myEventId = new goog.events.EventId(
  8738. * goog.events.getUniqueId(('someEvent'));
  8739. *
  8740. * // No need to cast or declare here since the compiler knows the correct
  8741. * // type of 'evt' (MyEventObj).
  8742. * something.listen(myEventId, function(evt) {});
  8743. * </code>
  8744. *
  8745. * @param {string} eventId
  8746. * @template T
  8747. * @constructor
  8748. * @struct
  8749. * @final
  8750. */
  8751. goog.events.EventId = function(eventId) {
  8752. /** @const */ this.id = eventId;
  8753. };
  8754. /**
  8755. * @override
  8756. */
  8757. goog.events.EventId.prototype.toString = function() {
  8758. return this.id;
  8759. };
  8760. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  8761. //
  8762. // Licensed under the Apache License, Version 2.0 (the "License");
  8763. // you may not use this file except in compliance with the License.
  8764. // You may obtain a copy of the License at
  8765. //
  8766. // http://www.apache.org/licenses/LICENSE-2.0
  8767. //
  8768. // Unless required by applicable law or agreed to in writing, software
  8769. // distributed under the License is distributed on an "AS-IS" BASIS,
  8770. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8771. // See the License for the specific language governing permissions and
  8772. // limitations under the License.
  8773. /**
  8774. * @fileoverview A base class for event objects.
  8775. *
  8776. */
  8777. goog.provide('goog.events.Event');
  8778. goog.provide('goog.events.EventLike');
  8779. /**
  8780. * goog.events.Event no longer depends on goog.Disposable. Keep requiring
  8781. * goog.Disposable here to not break projects which assume this dependency.
  8782. * @suppress {extraRequire}
  8783. */
  8784. goog.require('goog.Disposable');
  8785. goog.require('goog.events.EventId');
  8786. /**
  8787. * A typedef for event like objects that are dispatchable via the
  8788. * goog.events.dispatchEvent function. strings are treated as the type for a
  8789. * goog.events.Event. Objects are treated as an extension of a new
  8790. * goog.events.Event with the type property of the object being used as the type
  8791. * of the Event.
  8792. * @typedef {string|Object|goog.events.Event|goog.events.EventId}
  8793. */
  8794. goog.events.EventLike;
  8795. /**
  8796. * A base class for event objects, so that they can support preventDefault and
  8797. * stopPropagation.
  8798. *
  8799. * @param {string|!goog.events.EventId} type Event Type.
  8800. * @param {Object=} opt_target Reference to the object that is the target of
  8801. * this event. It has to implement the {@code EventTarget} interface
  8802. * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.
  8803. * @constructor
  8804. */
  8805. goog.events.Event = function(type, opt_target) {
  8806. /**
  8807. * Event type.
  8808. * @type {string}
  8809. */
  8810. this.type = type instanceof goog.events.EventId ? String(type) : type;
  8811. /**
  8812. * TODO(tbreisacher): The type should probably be
  8813. * EventTarget|goog.events.EventTarget.
  8814. *
  8815. * Target of the event.
  8816. * @type {Object|undefined}
  8817. */
  8818. this.target = opt_target;
  8819. /**
  8820. * Object that had the listener attached.
  8821. * @type {Object|undefined}
  8822. */
  8823. this.currentTarget = this.target;
  8824. /**
  8825. * Whether to cancel the event in internal capture/bubble processing for IE.
  8826. * @type {boolean}
  8827. * @public
  8828. * @suppress {underscore|visibility} Technically public, but referencing this
  8829. * outside this package is strongly discouraged.
  8830. */
  8831. this.propagationStopped_ = false;
  8832. /**
  8833. * Whether the default action has been prevented.
  8834. * This is a property to match the W3C specification at
  8835. * {@link http://www.w3.org/TR/DOM-Level-3-Events/
  8836. * #events-event-type-defaultPrevented}.
  8837. * Must be treated as read-only outside the class.
  8838. * @type {boolean}
  8839. */
  8840. this.defaultPrevented = false;
  8841. /**
  8842. * Return value for in internal capture/bubble processing for IE.
  8843. * @type {boolean}
  8844. * @public
  8845. * @suppress {underscore|visibility} Technically public, but referencing this
  8846. * outside this package is strongly discouraged.
  8847. */
  8848. this.returnValue_ = true;
  8849. };
  8850. /**
  8851. * Stops event propagation.
  8852. */
  8853. goog.events.Event.prototype.stopPropagation = function() {
  8854. this.propagationStopped_ = true;
  8855. };
  8856. /**
  8857. * Prevents the default action, for example a link redirecting to a url.
  8858. */
  8859. goog.events.Event.prototype.preventDefault = function() {
  8860. this.defaultPrevented = true;
  8861. this.returnValue_ = false;
  8862. };
  8863. /**
  8864. * Stops the propagation of the event. It is equivalent to
  8865. * {@code e.stopPropagation()}, but can be used as the callback argument of
  8866. * {@link goog.events.listen} without declaring another function.
  8867. * @param {!goog.events.Event} e An event.
  8868. */
  8869. goog.events.Event.stopPropagation = function(e) {
  8870. e.stopPropagation();
  8871. };
  8872. /**
  8873. * Prevents the default action. It is equivalent to
  8874. * {@code e.preventDefault()}, but can be used as the callback argument of
  8875. * {@link goog.events.listen} without declaring another function.
  8876. * @param {!goog.events.Event} e An event.
  8877. */
  8878. goog.events.Event.preventDefault = function(e) {
  8879. e.preventDefault();
  8880. };
  8881. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  8882. //
  8883. // Licensed under the Apache License, Version 2.0 (the "License");
  8884. // you may not use this file except in compliance with the License.
  8885. // You may obtain a copy of the License at
  8886. //
  8887. // http://www.apache.org/licenses/LICENSE-2.0
  8888. //
  8889. // Unless required by applicable law or agreed to in writing, software
  8890. // distributed under the License is distributed on an "AS-IS" BASIS,
  8891. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8892. // See the License for the specific language governing permissions and
  8893. // limitations under the License.
  8894. /**
  8895. * @fileoverview Event Types.
  8896. *
  8897. * @author arv@google.com (Erik Arvidsson)
  8898. */
  8899. goog.provide('goog.events.EventType');
  8900. goog.require('goog.userAgent');
  8901. /**
  8902. * Returns a prefixed event name for the current browser.
  8903. * @param {string} eventName The name of the event.
  8904. * @return {string} The prefixed event name.
  8905. * @suppress {missingRequire|missingProvide}
  8906. * @private
  8907. */
  8908. goog.events.getVendorPrefixedName_ = function(eventName) {
  8909. return goog.userAgent.WEBKIT ? 'webkit' + eventName :
  8910. (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
  8911. eventName.toLowerCase());
  8912. };
  8913. /**
  8914. * Constants for event names.
  8915. * @enum {string}
  8916. */
  8917. goog.events.EventType = {
  8918. // Mouse events
  8919. CLICK: 'click',
  8920. RIGHTCLICK: 'rightclick',
  8921. DBLCLICK: 'dblclick',
  8922. MOUSEDOWN: 'mousedown',
  8923. MOUSEUP: 'mouseup',
  8924. MOUSEOVER: 'mouseover',
  8925. MOUSEOUT: 'mouseout',
  8926. MOUSEMOVE: 'mousemove',
  8927. MOUSEENTER: 'mouseenter',
  8928. MOUSELEAVE: 'mouseleave',
  8929. // Select start is non-standard.
  8930. // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx.
  8931. SELECTSTART: 'selectstart', // IE, Safari, Chrome
  8932. // Wheel events
  8933. // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
  8934. WHEEL: 'wheel',
  8935. // Key events
  8936. KEYPRESS: 'keypress',
  8937. KEYDOWN: 'keydown',
  8938. KEYUP: 'keyup',
  8939. // Focus
  8940. BLUR: 'blur',
  8941. FOCUS: 'focus',
  8942. DEACTIVATE: 'deactivate', // IE only
  8943. // NOTE: The following two events are not stable in cross-browser usage.
  8944. // WebKit and Opera implement DOMFocusIn/Out.
  8945. // IE implements focusin/out.
  8946. // Gecko implements neither see bug at
  8947. // https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  8948. // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  8949. // http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  8950. // You can use FOCUS in Capture phase until implementations converge.
  8951. FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  8952. FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',
  8953. // Forms
  8954. CHANGE: 'change',
  8955. RESET: 'reset',
  8956. SELECT: 'select',
  8957. SUBMIT: 'submit',
  8958. INPUT: 'input',
  8959. PROPERTYCHANGE: 'propertychange', // IE only
  8960. // Drag and drop
  8961. DRAGSTART: 'dragstart',
  8962. DRAG: 'drag',
  8963. DRAGENTER: 'dragenter',
  8964. DRAGOVER: 'dragover',
  8965. DRAGLEAVE: 'dragleave',
  8966. DROP: 'drop',
  8967. DRAGEND: 'dragend',
  8968. // Touch events
  8969. // Note that other touch events exist, but we should follow the W3C list here.
  8970. // http://www.w3.org/TR/touch-events/#list-of-touchevent-types
  8971. TOUCHSTART: 'touchstart',
  8972. TOUCHMOVE: 'touchmove',
  8973. TOUCHEND: 'touchend',
  8974. TOUCHCANCEL: 'touchcancel',
  8975. // Misc
  8976. BEFOREUNLOAD: 'beforeunload',
  8977. CONSOLEMESSAGE: 'consolemessage',
  8978. CONTEXTMENU: 'contextmenu',
  8979. DOMCONTENTLOADED: 'DOMContentLoaded',
  8980. ERROR: 'error',
  8981. HELP: 'help',
  8982. LOAD: 'load',
  8983. LOSECAPTURE: 'losecapture',
  8984. ORIENTATIONCHANGE: 'orientationchange',
  8985. READYSTATECHANGE: 'readystatechange',
  8986. RESIZE: 'resize',
  8987. SCROLL: 'scroll',
  8988. UNLOAD: 'unload',
  8989. // HTML 5 History events
  8990. // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
  8991. HASHCHANGE: 'hashchange',
  8992. PAGEHIDE: 'pagehide',
  8993. PAGESHOW: 'pageshow',
  8994. POPSTATE: 'popstate',
  8995. // Copy and Paste
  8996. // Support is limited. Make sure it works on your favorite browser
  8997. // before using.
  8998. // http://www.quirksmode.org/dom/events/cutcopypaste.html
  8999. COPY: 'copy',
  9000. PASTE: 'paste',
  9001. CUT: 'cut',
  9002. BEFORECOPY: 'beforecopy',
  9003. BEFORECUT: 'beforecut',
  9004. BEFOREPASTE: 'beforepaste',
  9005. // HTML5 online/offline events.
  9006. // http://www.w3.org/TR/offline-webapps/#related
  9007. ONLINE: 'online',
  9008. OFFLINE: 'offline',
  9009. // HTML 5 worker events
  9010. MESSAGE: 'message',
  9011. CONNECT: 'connect',
  9012. // CSS animation events.
  9013. /** @suppress {missingRequire} */
  9014. ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  9015. /** @suppress {missingRequire} */
  9016. ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  9017. /** @suppress {missingRequire} */
  9018. ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),
  9019. // CSS transition events. Based on the browser support described at:
  9020. // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  9021. /** @suppress {missingRequire} */
  9022. TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),
  9023. // W3C Pointer Events
  9024. // http://www.w3.org/TR/pointerevents/
  9025. POINTERDOWN: 'pointerdown',
  9026. POINTERUP: 'pointerup',
  9027. POINTERCANCEL: 'pointercancel',
  9028. POINTERMOVE: 'pointermove',
  9029. POINTEROVER: 'pointerover',
  9030. POINTEROUT: 'pointerout',
  9031. POINTERENTER: 'pointerenter',
  9032. POINTERLEAVE: 'pointerleave',
  9033. GOTPOINTERCAPTURE: 'gotpointercapture',
  9034. LOSTPOINTERCAPTURE: 'lostpointercapture',
  9035. // IE specific events.
  9036. // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  9037. // Note: these events will be supplanted in IE11.
  9038. MSGESTURECHANGE: 'MSGestureChange',
  9039. MSGESTUREEND: 'MSGestureEnd',
  9040. MSGESTUREHOLD: 'MSGestureHold',
  9041. MSGESTURESTART: 'MSGestureStart',
  9042. MSGESTURETAP: 'MSGestureTap',
  9043. MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  9044. MSINERTIASTART: 'MSInertiaStart',
  9045. MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  9046. MSPOINTERCANCEL: 'MSPointerCancel',
  9047. MSPOINTERDOWN: 'MSPointerDown',
  9048. MSPOINTERENTER: 'MSPointerEnter',
  9049. MSPOINTERHOVER: 'MSPointerHover',
  9050. MSPOINTERLEAVE: 'MSPointerLeave',
  9051. MSPOINTERMOVE: 'MSPointerMove',
  9052. MSPOINTEROUT: 'MSPointerOut',
  9053. MSPOINTEROVER: 'MSPointerOver',
  9054. MSPOINTERUP: 'MSPointerUp',
  9055. // Native IMEs/input tools events.
  9056. TEXT: 'text',
  9057. TEXTINPUT: 'textInput',
  9058. COMPOSITIONSTART: 'compositionstart',
  9059. COMPOSITIONUPDATE: 'compositionupdate',
  9060. COMPOSITIONEND: 'compositionend',
  9061. // Webview tag events
  9062. // See http://developer.chrome.com/dev/apps/webview_tag.html
  9063. EXIT: 'exit',
  9064. LOADABORT: 'loadabort',
  9065. LOADCOMMIT: 'loadcommit',
  9066. LOADREDIRECT: 'loadredirect',
  9067. LOADSTART: 'loadstart',
  9068. LOADSTOP: 'loadstop',
  9069. RESPONSIVE: 'responsive',
  9070. SIZECHANGED: 'sizechanged',
  9071. UNRESPONSIVE: 'unresponsive',
  9072. // HTML5 Page Visibility API. See details at
  9073. // {@code goog.labs.dom.PageVisibilityMonitor}.
  9074. VISIBILITYCHANGE: 'visibilitychange',
  9075. // LocalStorage event.
  9076. STORAGE: 'storage',
  9077. // DOM Level 2 mutation events (deprecated).
  9078. DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  9079. DOMNODEINSERTED: 'DOMNodeInserted',
  9080. DOMNODEREMOVED: 'DOMNodeRemoved',
  9081. DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  9082. DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  9083. DOMATTRMODIFIED: 'DOMAttrModified',
  9084. DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',
  9085. // Print events.
  9086. BEFOREPRINT: 'beforeprint',
  9087. AFTERPRINT: 'afterprint'
  9088. };
  9089. // Copyright 2009 The Closure Library Authors. All Rights Reserved.
  9090. //
  9091. // Licensed under the Apache License, Version 2.0 (the "License");
  9092. // you may not use this file except in compliance with the License.
  9093. // You may obtain a copy of the License at
  9094. //
  9095. // http://www.apache.org/licenses/LICENSE-2.0
  9096. //
  9097. // Unless required by applicable law or agreed to in writing, software
  9098. // distributed under the License is distributed on an "AS-IS" BASIS,
  9099. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9100. // See the License for the specific language governing permissions and
  9101. // limitations under the License.
  9102. /**
  9103. * @fileoverview Useful compiler idioms.
  9104. *
  9105. * @author johnlenz@google.com (John Lenz)
  9106. */
  9107. goog.provide('goog.reflect');
  9108. /**
  9109. * Syntax for object literal casts.
  9110. * @see http://go/jscompiler-renaming
  9111. * @see https://github.com/google/closure-compiler/wiki/Type-Based-Property-Renaming
  9112. *
  9113. * Use this if you have an object literal whose keys need to have the same names
  9114. * as the properties of some class even after they are renamed by the compiler.
  9115. *
  9116. * @param {!Function} type Type to cast to.
  9117. * @param {Object} object Object literal to cast.
  9118. * @return {Object} The object literal.
  9119. */
  9120. goog.reflect.object = function(type, object) {
  9121. return object;
  9122. };
  9123. /**
  9124. * To assert to the compiler that an operation is needed when it would
  9125. * otherwise be stripped. For example:
  9126. * <code>
  9127. * // Force a layout
  9128. * goog.reflect.sinkValue(dialog.offsetHeight);
  9129. * </code>
  9130. * @type {!Function}
  9131. */
  9132. goog.reflect.sinkValue = function(x) {
  9133. goog.reflect.sinkValue[' '](x);
  9134. return x;
  9135. };
  9136. /**
  9137. * The compiler should optimize this function away iff no one ever uses
  9138. * goog.reflect.sinkValue.
  9139. */
  9140. goog.reflect.sinkValue[' '] = goog.nullFunction;
  9141. /**
  9142. * Check if a property can be accessed without throwing an exception.
  9143. * @param {Object} obj The owner of the property.
  9144. * @param {string} prop The property name.
  9145. * @return {boolean} Whether the property is accessible. Will also return true
  9146. * if obj is null.
  9147. */
  9148. goog.reflect.canAccessProperty = function(obj, prop) {
  9149. /** @preserveTry */
  9150. try {
  9151. goog.reflect.sinkValue(obj[prop]);
  9152. return true;
  9153. } catch (e) {}
  9154. return false;
  9155. };
  9156. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  9157. //
  9158. // Licensed under the Apache License, Version 2.0 (the "License");
  9159. // you may not use this file except in compliance with the License.
  9160. // You may obtain a copy of the License at
  9161. //
  9162. // http://www.apache.org/licenses/LICENSE-2.0
  9163. //
  9164. // Unless required by applicable law or agreed to in writing, software
  9165. // distributed under the License is distributed on an "AS-IS" BASIS,
  9166. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9167. // See the License for the specific language governing permissions and
  9168. // limitations under the License.
  9169. /**
  9170. * @fileoverview A patched, standardized event object for browser events.
  9171. *
  9172. * <pre>
  9173. * The patched event object contains the following members:
  9174. * - type {string} Event type, e.g. 'click'
  9175. * - target {Object} The element that actually triggered the event
  9176. * - currentTarget {Object} The element the listener is attached to
  9177. * - relatedTarget {Object} For mouseover and mouseout, the previous object
  9178. * - offsetX {number} X-coordinate relative to target
  9179. * - offsetY {number} Y-coordinate relative to target
  9180. * - clientX {number} X-coordinate relative to viewport
  9181. * - clientY {number} Y-coordinate relative to viewport
  9182. * - screenX {number} X-coordinate relative to the edge of the screen
  9183. * - screenY {number} Y-coordinate relative to the edge of the screen
  9184. * - button {number} Mouse button. Use isButton() to test.
  9185. * - keyCode {number} Key-code
  9186. * - ctrlKey {boolean} Was ctrl key depressed
  9187. * - altKey {boolean} Was alt key depressed
  9188. * - shiftKey {boolean} Was shift key depressed
  9189. * - metaKey {boolean} Was meta key depressed
  9190. * - defaultPrevented {boolean} Whether the default action has been prevented
  9191. * - state {Object} History state object
  9192. *
  9193. * NOTE: The keyCode member contains the raw browser keyCode. For normalized
  9194. * key and character code use {@link goog.events.KeyHandler}.
  9195. * </pre>
  9196. *
  9197. * @author arv@google.com (Erik Arvidsson)
  9198. */
  9199. goog.provide('goog.events.BrowserEvent');
  9200. goog.provide('goog.events.BrowserEvent.MouseButton');
  9201. goog.require('goog.events.BrowserFeature');
  9202. goog.require('goog.events.Event');
  9203. goog.require('goog.events.EventType');
  9204. goog.require('goog.reflect');
  9205. goog.require('goog.userAgent');
  9206. /**
  9207. * Accepts a browser event object and creates a patched, cross browser event
  9208. * object.
  9209. * The content of this object will not be initialized if no event object is
  9210. * provided. If this is the case, init() needs to be invoked separately.
  9211. * @param {Event=} opt_e Browser event object.
  9212. * @param {EventTarget=} opt_currentTarget Current target for event.
  9213. * @constructor
  9214. * @extends {goog.events.Event}
  9215. */
  9216. goog.events.BrowserEvent = function(opt_e, opt_currentTarget) {
  9217. goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');
  9218. /**
  9219. * Target that fired the event.
  9220. * @override
  9221. * @type {Node}
  9222. */
  9223. this.target = null;
  9224. /**
  9225. * Node that had the listener attached.
  9226. * @override
  9227. * @type {Node|undefined}
  9228. */
  9229. this.currentTarget = null;
  9230. /**
  9231. * For mouseover and mouseout events, the related object for the event.
  9232. * @type {Node}
  9233. */
  9234. this.relatedTarget = null;
  9235. /**
  9236. * X-coordinate relative to target.
  9237. * @type {number}
  9238. */
  9239. this.offsetX = 0;
  9240. /**
  9241. * Y-coordinate relative to target.
  9242. * @type {number}
  9243. */
  9244. this.offsetY = 0;
  9245. /**
  9246. * X-coordinate relative to the window.
  9247. * @type {number}
  9248. */
  9249. this.clientX = 0;
  9250. /**
  9251. * Y-coordinate relative to the window.
  9252. * @type {number}
  9253. */
  9254. this.clientY = 0;
  9255. /**
  9256. * X-coordinate relative to the monitor.
  9257. * @type {number}
  9258. */
  9259. this.screenX = 0;
  9260. /**
  9261. * Y-coordinate relative to the monitor.
  9262. * @type {number}
  9263. */
  9264. this.screenY = 0;
  9265. /**
  9266. * Which mouse button was pressed.
  9267. * @type {number}
  9268. */
  9269. this.button = 0;
  9270. /**
  9271. * Keycode of key press.
  9272. * @type {number}
  9273. */
  9274. this.keyCode = 0;
  9275. /**
  9276. * Keycode of key press.
  9277. * @type {number}
  9278. */
  9279. this.charCode = 0;
  9280. /**
  9281. * Whether control was pressed at time of event.
  9282. * @type {boolean}
  9283. */
  9284. this.ctrlKey = false;
  9285. /**
  9286. * Whether alt was pressed at time of event.
  9287. * @type {boolean}
  9288. */
  9289. this.altKey = false;
  9290. /**
  9291. * Whether shift was pressed at time of event.
  9292. * @type {boolean}
  9293. */
  9294. this.shiftKey = false;
  9295. /**
  9296. * Whether the meta key was pressed at time of event.
  9297. * @type {boolean}
  9298. */
  9299. this.metaKey = false;
  9300. /**
  9301. * History state object, only set for PopState events where it's a copy of the
  9302. * state object provided to pushState or replaceState.
  9303. * @type {Object}
  9304. */
  9305. this.state = null;
  9306. /**
  9307. * Whether the default platform modifier key was pressed at time of event.
  9308. * (This is control for all platforms except Mac, where it's Meta.)
  9309. * @type {boolean}
  9310. */
  9311. this.platformModifierKey = false;
  9312. /**
  9313. * The browser event object.
  9314. * @private {Event}
  9315. */
  9316. this.event_ = null;
  9317. if (opt_e) {
  9318. this.init(opt_e, opt_currentTarget);
  9319. }
  9320. };
  9321. goog.inherits(goog.events.BrowserEvent, goog.events.Event);
  9322. /**
  9323. * Normalized button constants for the mouse.
  9324. * @enum {number}
  9325. */
  9326. goog.events.BrowserEvent.MouseButton = {
  9327. LEFT: 0,
  9328. MIDDLE: 1,
  9329. RIGHT: 2
  9330. };
  9331. /**
  9332. * Static data for mapping mouse buttons.
  9333. * @type {!Array<number>}
  9334. */
  9335. goog.events.BrowserEvent.IEButtonMap = [
  9336. 1, // LEFT
  9337. 4, // MIDDLE
  9338. 2 // RIGHT
  9339. ];
  9340. /**
  9341. * Accepts a browser event object and creates a patched, cross browser event
  9342. * object.
  9343. * @param {Event} e Browser event object.
  9344. * @param {EventTarget=} opt_currentTarget Current target for event.
  9345. */
  9346. goog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {
  9347. var type = this.type = e.type;
  9348. /**
  9349. * On touch devices use the first "changed touch" as the relevant touch.
  9350. * @type {Touch}
  9351. */
  9352. var relevantTouch = e.changedTouches ? e.changedTouches[0] : null;
  9353. // TODO(nicksantos): Change this.target to type EventTarget.
  9354. this.target = /** @type {Node} */ (e.target) || e.srcElement;
  9355. // TODO(nicksantos): Change this.currentTarget to type EventTarget.
  9356. this.currentTarget = /** @type {Node} */ (opt_currentTarget);
  9357. var relatedTarget = /** @type {Node} */ (e.relatedTarget);
  9358. if (relatedTarget) {
  9359. // There's a bug in FireFox where sometimes, relatedTarget will be a
  9360. // chrome element, and accessing any property of it will get a permission
  9361. // denied exception. See:
  9362. // https://bugzilla.mozilla.org/show_bug.cgi?id=497780
  9363. if (goog.userAgent.GECKO) {
  9364. if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {
  9365. relatedTarget = null;
  9366. }
  9367. }
  9368. // TODO(arv): Use goog.events.EventType when it has been refactored into its
  9369. // own file.
  9370. } else if (type == goog.events.EventType.MOUSEOVER) {
  9371. relatedTarget = e.fromElement;
  9372. } else if (type == goog.events.EventType.MOUSEOUT) {
  9373. relatedTarget = e.toElement;
  9374. }
  9375. this.relatedTarget = relatedTarget;
  9376. if (!goog.isNull(relevantTouch)) {
  9377. this.clientX = relevantTouch.clientX !== undefined ?
  9378. relevantTouch.clientX : relevantTouch.pageX;
  9379. this.clientY = relevantTouch.clientY !== undefined ?
  9380. relevantTouch.clientY : relevantTouch.pageY;
  9381. this.screenX = relevantTouch.screenX || 0;
  9382. this.screenY = relevantTouch.screenY || 0;
  9383. } else {
  9384. // Webkit emits a lame warning whenever layerX/layerY is accessed.
  9385. // http://code.google.com/p/chromium/issues/detail?id=101733
  9386. this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?
  9387. e.offsetX : e.layerX;
  9388. this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?
  9389. e.offsetY : e.layerY;
  9390. this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;
  9391. this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;
  9392. this.screenX = e.screenX || 0;
  9393. this.screenY = e.screenY || 0;
  9394. }
  9395. this.button = e.button;
  9396. this.keyCode = e.keyCode || 0;
  9397. this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);
  9398. this.ctrlKey = e.ctrlKey;
  9399. this.altKey = e.altKey;
  9400. this.shiftKey = e.shiftKey;
  9401. this.metaKey = e.metaKey;
  9402. this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;
  9403. this.state = e.state;
  9404. this.event_ = e;
  9405. if (e.defaultPrevented) {
  9406. this.preventDefault();
  9407. }
  9408. };
  9409. /**
  9410. * Tests to see which button was pressed during the event. This is really only
  9411. * useful in IE and Gecko browsers. And in IE, it's only useful for
  9412. * mousedown/mouseup events, because click only fires for the left mouse button.
  9413. *
  9414. * Safari 2 only reports the left button being clicked, and uses the value '1'
  9415. * instead of 0. Opera only reports a mousedown event for the middle button, and
  9416. * no mouse events for the right button. Opera has default behavior for left and
  9417. * middle click that can only be overridden via a configuration setting.
  9418. *
  9419. * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.
  9420. *
  9421. * @param {goog.events.BrowserEvent.MouseButton} button The button
  9422. * to test for.
  9423. * @return {boolean} True if button was pressed.
  9424. */
  9425. goog.events.BrowserEvent.prototype.isButton = function(button) {
  9426. if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {
  9427. if (this.type == 'click') {
  9428. return button == goog.events.BrowserEvent.MouseButton.LEFT;
  9429. } else {
  9430. return !!(this.event_.button &
  9431. goog.events.BrowserEvent.IEButtonMap[button]);
  9432. }
  9433. } else {
  9434. return this.event_.button == button;
  9435. }
  9436. };
  9437. /**
  9438. * Whether this has an "action"-producing mouse button.
  9439. *
  9440. * By definition, this includes left-click on windows/linux, and left-click
  9441. * without the ctrl key on Macs.
  9442. *
  9443. * @return {boolean} The result.
  9444. */
  9445. goog.events.BrowserEvent.prototype.isMouseActionButton = function() {
  9446. // Webkit does not ctrl+click to be a right-click, so we
  9447. // normalize it to behave like Gecko and Opera.
  9448. return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&
  9449. !(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);
  9450. };
  9451. /**
  9452. * @override
  9453. */
  9454. goog.events.BrowserEvent.prototype.stopPropagation = function() {
  9455. goog.events.BrowserEvent.superClass_.stopPropagation.call(this);
  9456. if (this.event_.stopPropagation) {
  9457. this.event_.stopPropagation();
  9458. } else {
  9459. this.event_.cancelBubble = true;
  9460. }
  9461. };
  9462. /**
  9463. * @override
  9464. */
  9465. goog.events.BrowserEvent.prototype.preventDefault = function() {
  9466. goog.events.BrowserEvent.superClass_.preventDefault.call(this);
  9467. var be = this.event_;
  9468. if (!be.preventDefault) {
  9469. be.returnValue = false;
  9470. if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {
  9471. /** @preserveTry */
  9472. try {
  9473. // Most keys can be prevented using returnValue. Some special keys
  9474. // require setting the keyCode to -1 as well:
  9475. //
  9476. // In IE7:
  9477. // F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)
  9478. //
  9479. // In IE8:
  9480. // Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)
  9481. //
  9482. // We therefore do this for all function keys as well as when Ctrl key
  9483. // is pressed.
  9484. var VK_F1 = 112;
  9485. var VK_F12 = 123;
  9486. if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {
  9487. be.keyCode = -1;
  9488. }
  9489. } catch (ex) {
  9490. // IE throws an 'access denied' exception when trying to change
  9491. // keyCode in some situations (e.g. srcElement is input[type=file],
  9492. // or srcElement is an anchor tag rewritten by parent's innerHTML).
  9493. // Do nothing in this case.
  9494. }
  9495. }
  9496. } else {
  9497. be.preventDefault();
  9498. }
  9499. };
  9500. /**
  9501. * @return {Event} The underlying browser event object.
  9502. */
  9503. goog.events.BrowserEvent.prototype.getBrowserEvent = function() {
  9504. return this.event_;
  9505. };
  9506. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  9507. //
  9508. // Licensed under the Apache License, Version 2.0 (the "License");
  9509. // you may not use this file except in compliance with the License.
  9510. // You may obtain a copy of the License at
  9511. //
  9512. // http://www.apache.org/licenses/LICENSE-2.0
  9513. //
  9514. // Unless required by applicable law or agreed to in writing, software
  9515. // distributed under the License is distributed on an "AS-IS" BASIS,
  9516. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9517. // See the License for the specific language governing permissions and
  9518. // limitations under the License.
  9519. /**
  9520. * @fileoverview An interface for a listenable JavaScript object.
  9521. * @author chrishenry@google.com (Chris Henry)
  9522. */
  9523. goog.provide('goog.events.Listenable');
  9524. goog.provide('goog.events.ListenableKey');
  9525. /** @suppress {extraRequire} */
  9526. goog.require('goog.events.EventId');
  9527. /**
  9528. * A listenable interface. A listenable is an object with the ability
  9529. * to dispatch/broadcast events to "event listeners" registered via
  9530. * listen/listenOnce.
  9531. *
  9532. * The interface allows for an event propagation mechanism similar
  9533. * to one offered by native browser event targets, such as
  9534. * capture/bubble mechanism, stopping propagation, and preventing
  9535. * default actions. Capture/bubble mechanism depends on the ancestor
  9536. * tree constructed via {@code #getParentEventTarget}; this tree
  9537. * must be directed acyclic graph. The meaning of default action(s)
  9538. * in preventDefault is specific to a particular use case.
  9539. *
  9540. * Implementations that do not support capture/bubble or can not have
  9541. * a parent listenable can simply not implement any ability to set the
  9542. * parent listenable (and have {@code #getParentEventTarget} return
  9543. * null).
  9544. *
  9545. * Implementation of this class can be used with or independently from
  9546. * goog.events.
  9547. *
  9548. * Implementation must call {@code #addImplementation(implClass)}.
  9549. *
  9550. * @interface
  9551. * @see goog.events
  9552. * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html
  9553. */
  9554. goog.events.Listenable = function() {};
  9555. /**
  9556. * An expando property to indicate that an object implements
  9557. * goog.events.Listenable.
  9558. *
  9559. * See addImplementation/isImplementedBy.
  9560. *
  9561. * @type {string}
  9562. * @const
  9563. */
  9564. goog.events.Listenable.IMPLEMENTED_BY_PROP =
  9565. 'closure_listenable_' + ((Math.random() * 1e6) | 0);
  9566. /**
  9567. * Marks a given class (constructor) as an implementation of
  9568. * Listenable, do that we can query that fact at runtime. The class
  9569. * must have already implemented the interface.
  9570. * @param {!Function} cls The class constructor. The corresponding
  9571. * class must have already implemented the interface.
  9572. */
  9573. goog.events.Listenable.addImplementation = function(cls) {
  9574. cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;
  9575. };
  9576. /**
  9577. * @param {Object} obj The object to check.
  9578. * @return {boolean} Whether a given instance implements Listenable. The
  9579. * class/superclass of the instance must call addImplementation.
  9580. */
  9581. goog.events.Listenable.isImplementedBy = function(obj) {
  9582. return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);
  9583. };
  9584. /**
  9585. * Adds an event listener. A listener can only be added once to an
  9586. * object and if it is added again the key for the listener is
  9587. * returned. Note that if the existing listener is a one-off listener
  9588. * (registered via listenOnce), it will no longer be a one-off
  9589. * listener after a call to listen().
  9590. *
  9591. * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
  9592. * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
  9593. * method.
  9594. * @param {boolean=} opt_useCapture Whether to fire in capture phase
  9595. * (defaults to false).
  9596. * @param {SCOPE=} opt_listenerScope Object in whose scope to call the
  9597. * listener.
  9598. * @return {goog.events.ListenableKey} Unique key for the listener.
  9599. * @template SCOPE,EVENTOBJ
  9600. */
  9601. goog.events.Listenable.prototype.listen;
  9602. /**
  9603. * Adds an event listener that is removed automatically after the
  9604. * listener fired once.
  9605. *
  9606. * If an existing listener already exists, listenOnce will do
  9607. * nothing. In particular, if the listener was previously registered
  9608. * via listen(), listenOnce() will not turn the listener into a
  9609. * one-off listener. Similarly, if there is already an existing
  9610. * one-off listener, listenOnce does not modify the listeners (it is
  9611. * still a once listener).
  9612. *
  9613. * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
  9614. * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
  9615. * method.
  9616. * @param {boolean=} opt_useCapture Whether to fire in capture phase
  9617. * (defaults to false).
  9618. * @param {SCOPE=} opt_listenerScope Object in whose scope to call the
  9619. * listener.
  9620. * @return {goog.events.ListenableKey} Unique key for the listener.
  9621. * @template SCOPE,EVENTOBJ
  9622. */
  9623. goog.events.Listenable.prototype.listenOnce;
  9624. /**
  9625. * Removes an event listener which was added with listen() or listenOnce().
  9626. *
  9627. * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
  9628. * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
  9629. * method.
  9630. * @param {boolean=} opt_useCapture Whether to fire in capture phase
  9631. * (defaults to false).
  9632. * @param {SCOPE=} opt_listenerScope Object in whose scope to call
  9633. * the listener.
  9634. * @return {boolean} Whether any listener was removed.
  9635. * @template SCOPE,EVENTOBJ
  9636. */
  9637. goog.events.Listenable.prototype.unlisten;
  9638. /**
  9639. * Removes an event listener which was added with listen() by the key
  9640. * returned by listen().
  9641. *
  9642. * @param {goog.events.ListenableKey} key The key returned by
  9643. * listen() or listenOnce().
  9644. * @return {boolean} Whether any listener was removed.
  9645. */
  9646. goog.events.Listenable.prototype.unlistenByKey;
  9647. /**
  9648. * Dispatches an event (or event like object) and calls all listeners
  9649. * listening for events of this type. The type of the event is decided by the
  9650. * type property on the event object.
  9651. *
  9652. * If any of the listeners returns false OR calls preventDefault then this
  9653. * function will return false. If one of the capture listeners calls
  9654. * stopPropagation, then the bubble listeners won't fire.
  9655. *
  9656. * @param {goog.events.EventLike} e Event object.
  9657. * @return {boolean} If anyone called preventDefault on the event object (or
  9658. * if any of the listeners returns false) this will also return false.
  9659. */
  9660. goog.events.Listenable.prototype.dispatchEvent;
  9661. /**
  9662. * Removes all listeners from this listenable. If type is specified,
  9663. * it will only remove listeners of the particular type. otherwise all
  9664. * registered listeners will be removed.
  9665. *
  9666. * @param {string=} opt_type Type of event to remove, default is to
  9667. * remove all types.
  9668. * @return {number} Number of listeners removed.
  9669. */
  9670. goog.events.Listenable.prototype.removeAllListeners;
  9671. /**
  9672. * Returns the parent of this event target to use for capture/bubble
  9673. * mechanism.
  9674. *
  9675. * NOTE(chrishenry): The name reflects the original implementation of
  9676. * custom event target ({@code goog.events.EventTarget}). We decided
  9677. * that changing the name is not worth it.
  9678. *
  9679. * @return {goog.events.Listenable} The parent EventTarget or null if
  9680. * there is no parent.
  9681. */
  9682. goog.events.Listenable.prototype.getParentEventTarget;
  9683. /**
  9684. * Fires all registered listeners in this listenable for the given
  9685. * type and capture mode, passing them the given eventObject. This
  9686. * does not perform actual capture/bubble. Only implementors of the
  9687. * interface should be using this.
  9688. *
  9689. * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the
  9690. * listeners to fire.
  9691. * @param {boolean} capture The capture mode of the listeners to fire.
  9692. * @param {EVENTOBJ} eventObject The event object to fire.
  9693. * @return {boolean} Whether all listeners succeeded without
  9694. * attempting to prevent default behavior. If any listener returns
  9695. * false or called goog.events.Event#preventDefault, this returns
  9696. * false.
  9697. * @template EVENTOBJ
  9698. */
  9699. goog.events.Listenable.prototype.fireListeners;
  9700. /**
  9701. * Gets all listeners in this listenable for the given type and
  9702. * capture mode.
  9703. *
  9704. * @param {string|!goog.events.EventId} type The type of the listeners to fire.
  9705. * @param {boolean} capture The capture mode of the listeners to fire.
  9706. * @return {!Array<goog.events.ListenableKey>} An array of registered
  9707. * listeners.
  9708. * @template EVENTOBJ
  9709. */
  9710. goog.events.Listenable.prototype.getListeners;
  9711. /**
  9712. * Gets the goog.events.ListenableKey for the event or null if no such
  9713. * listener is in use.
  9714. *
  9715. * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event
  9716. * without the 'on' prefix.
  9717. * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The
  9718. * listener function to get.
  9719. * @param {boolean} capture Whether the listener is a capturing listener.
  9720. * @param {SCOPE=} opt_listenerScope Object in whose scope to call the
  9721. * listener.
  9722. * @return {goog.events.ListenableKey} the found listener or null if not found.
  9723. * @template SCOPE,EVENTOBJ
  9724. */
  9725. goog.events.Listenable.prototype.getListener;
  9726. /**
  9727. * Whether there is any active listeners matching the specified
  9728. * signature. If either the type or capture parameters are
  9729. * unspecified, the function will match on the remaining criteria.
  9730. *
  9731. * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.
  9732. * @param {boolean=} opt_capture Whether to check for capture or bubble
  9733. * listeners.
  9734. * @return {boolean} Whether there is any active listeners matching
  9735. * the requested type and/or capture phase.
  9736. * @template EVENTOBJ
  9737. */
  9738. goog.events.Listenable.prototype.hasListener;
  9739. /**
  9740. * An interface that describes a single registered listener.
  9741. * @interface
  9742. */
  9743. goog.events.ListenableKey = function() {};
  9744. /**
  9745. * Counter used to create a unique key
  9746. * @type {number}
  9747. * @private
  9748. */
  9749. goog.events.ListenableKey.counter_ = 0;
  9750. /**
  9751. * Reserves a key to be used for ListenableKey#key field.
  9752. * @return {number} A number to be used to fill ListenableKey#key
  9753. * field.
  9754. */
  9755. goog.events.ListenableKey.reserveKey = function() {
  9756. return ++goog.events.ListenableKey.counter_;
  9757. };
  9758. /**
  9759. * The source event target.
  9760. * @type {!(Object|goog.events.Listenable|goog.events.EventTarget)}
  9761. */
  9762. goog.events.ListenableKey.prototype.src;
  9763. /**
  9764. * The event type the listener is listening to.
  9765. * @type {string}
  9766. */
  9767. goog.events.ListenableKey.prototype.type;
  9768. /**
  9769. * The listener function.
  9770. * @type {function(?):?|{handleEvent:function(?):?}|null}
  9771. */
  9772. goog.events.ListenableKey.prototype.listener;
  9773. /**
  9774. * Whether the listener works on capture phase.
  9775. * @type {boolean}
  9776. */
  9777. goog.events.ListenableKey.prototype.capture;
  9778. /**
  9779. * The 'this' object for the listener function's scope.
  9780. * @type {Object}
  9781. */
  9782. goog.events.ListenableKey.prototype.handler;
  9783. /**
  9784. * A globally unique number to identify the key.
  9785. * @type {number}
  9786. */
  9787. goog.events.ListenableKey.prototype.key;
  9788. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  9789. //
  9790. // Licensed under the Apache License, Version 2.0 (the "License");
  9791. // you may not use this file except in compliance with the License.
  9792. // You may obtain a copy of the License at
  9793. //
  9794. // http://www.apache.org/licenses/LICENSE-2.0
  9795. //
  9796. // Unless required by applicable law or agreed to in writing, software
  9797. // distributed under the License is distributed on an "AS-IS" BASIS,
  9798. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9799. // See the License for the specific language governing permissions and
  9800. // limitations under the License.
  9801. /**
  9802. * @fileoverview Listener object.
  9803. * @see ../demos/events.html
  9804. */
  9805. goog.provide('goog.events.Listener');
  9806. goog.require('goog.events.ListenableKey');
  9807. /**
  9808. * Simple class that stores information about a listener
  9809. * @param {!Function} listener Callback function.
  9810. * @param {Function} proxy Wrapper for the listener that patches the event.
  9811. * @param {EventTarget|goog.events.Listenable} src Source object for
  9812. * the event.
  9813. * @param {string} type Event type.
  9814. * @param {boolean} capture Whether in capture or bubble phase.
  9815. * @param {Object=} opt_handler Object in whose context to execute the callback.
  9816. * @implements {goog.events.ListenableKey}
  9817. * @constructor
  9818. */
  9819. goog.events.Listener = function(
  9820. listener, proxy, src, type, capture, opt_handler) {
  9821. if (goog.events.Listener.ENABLE_MONITORING) {
  9822. this.creationStack = new Error().stack;
  9823. }
  9824. /**
  9825. * Callback function.
  9826. * @type {Function}
  9827. */
  9828. this.listener = listener;
  9829. /**
  9830. * A wrapper over the original listener. This is used solely to
  9831. * handle native browser events (it is used to simulate the capture
  9832. * phase and to patch the event object).
  9833. * @type {Function}
  9834. */
  9835. this.proxy = proxy;
  9836. /**
  9837. * Object or node that callback is listening to
  9838. * @type {EventTarget|goog.events.Listenable}
  9839. */
  9840. this.src = src;
  9841. /**
  9842. * The event type.
  9843. * @const {string}
  9844. */
  9845. this.type = type;
  9846. /**
  9847. * Whether the listener is being called in the capture or bubble phase
  9848. * @const {boolean}
  9849. */
  9850. this.capture = !!capture;
  9851. /**
  9852. * Optional object whose context to execute the listener in
  9853. * @type {Object|undefined}
  9854. */
  9855. this.handler = opt_handler;
  9856. /**
  9857. * The key of the listener.
  9858. * @const {number}
  9859. * @override
  9860. */
  9861. this.key = goog.events.ListenableKey.reserveKey();
  9862. /**
  9863. * Whether to remove the listener after it has been called.
  9864. * @type {boolean}
  9865. */
  9866. this.callOnce = false;
  9867. /**
  9868. * Whether the listener has been removed.
  9869. * @type {boolean}
  9870. */
  9871. this.removed = false;
  9872. };
  9873. /**
  9874. * @define {boolean} Whether to enable the monitoring of the
  9875. * goog.events.Listener instances. Switching on the monitoring is only
  9876. * recommended for debugging because it has a significant impact on
  9877. * performance and memory usage. If switched off, the monitoring code
  9878. * compiles down to 0 bytes.
  9879. */
  9880. goog.define('goog.events.Listener.ENABLE_MONITORING', false);
  9881. /**
  9882. * If monitoring the goog.events.Listener instances is enabled, stores the
  9883. * creation stack trace of the Disposable instance.
  9884. * @type {string}
  9885. */
  9886. goog.events.Listener.prototype.creationStack;
  9887. /**
  9888. * Marks this listener as removed. This also remove references held by
  9889. * this listener object (such as listener and event source).
  9890. */
  9891. goog.events.Listener.prototype.markAsRemoved = function() {
  9892. this.removed = true;
  9893. this.listener = null;
  9894. this.proxy = null;
  9895. this.src = null;
  9896. this.handler = null;
  9897. };
  9898. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  9899. //
  9900. // Licensed under the Apache License, Version 2.0 (the "License");
  9901. // you may not use this file except in compliance with the License.
  9902. // You may obtain a copy of the License at
  9903. //
  9904. // http://www.apache.org/licenses/LICENSE-2.0
  9905. //
  9906. // Unless required by applicable law or agreed to in writing, software
  9907. // distributed under the License is distributed on an "AS-IS" BASIS,
  9908. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9909. // See the License for the specific language governing permissions and
  9910. // limitations under the License.
  9911. /**
  9912. * @fileoverview A map of listeners that provides utility functions to
  9913. * deal with listeners on an event target. Used by
  9914. * {@code goog.events.EventTarget}.
  9915. *
  9916. * WARNING: Do not use this class from outside goog.events package.
  9917. *
  9918. * @visibility {//closure/goog/bin/sizetests:__pkg__}
  9919. * @visibility {//closure/goog/events:__pkg__}
  9920. * @visibility {//closure/goog/labs/events:__pkg__}
  9921. */
  9922. goog.provide('goog.events.ListenerMap');
  9923. goog.require('goog.array');
  9924. goog.require('goog.events.Listener');
  9925. goog.require('goog.object');
  9926. /**
  9927. * Creates a new listener map.
  9928. * @param {EventTarget|goog.events.Listenable} src The src object.
  9929. * @constructor
  9930. * @final
  9931. */
  9932. goog.events.ListenerMap = function(src) {
  9933. /** @type {EventTarget|goog.events.Listenable} */
  9934. this.src = src;
  9935. /**
  9936. * Maps of event type to an array of listeners.
  9937. * @type {Object<string, !Array<!goog.events.Listener>>}
  9938. */
  9939. this.listeners = {};
  9940. /**
  9941. * The count of types in this map that have registered listeners.
  9942. * @private {number}
  9943. */
  9944. this.typeCount_ = 0;
  9945. };
  9946. /**
  9947. * @return {number} The count of event types in this map that actually
  9948. * have registered listeners.
  9949. */
  9950. goog.events.ListenerMap.prototype.getTypeCount = function() {
  9951. return this.typeCount_;
  9952. };
  9953. /**
  9954. * @return {number} Total number of registered listeners.
  9955. */
  9956. goog.events.ListenerMap.prototype.getListenerCount = function() {
  9957. var count = 0;
  9958. for (var type in this.listeners) {
  9959. count += this.listeners[type].length;
  9960. }
  9961. return count;
  9962. };
  9963. /**
  9964. * Adds an event listener. A listener can only be added once to an
  9965. * object and if it is added again the key for the listener is
  9966. * returned.
  9967. *
  9968. * Note that a one-off listener will not change an existing listener,
  9969. * if any. On the other hand a normal listener will change existing
  9970. * one-off listener to become a normal listener.
  9971. *
  9972. * @param {string|!goog.events.EventId} type The listener event type.
  9973. * @param {!Function} listener This listener callback method.
  9974. * @param {boolean} callOnce Whether the listener is a one-off
  9975. * listener.
  9976. * @param {boolean=} opt_useCapture The capture mode of the listener.
  9977. * @param {Object=} opt_listenerScope Object in whose scope to call the
  9978. * listener.
  9979. * @return {goog.events.ListenableKey} Unique key for the listener.
  9980. */
  9981. goog.events.ListenerMap.prototype.add = function(
  9982. type, listener, callOnce, opt_useCapture, opt_listenerScope) {
  9983. var typeStr = type.toString();
  9984. var listenerArray = this.listeners[typeStr];
  9985. if (!listenerArray) {
  9986. listenerArray = this.listeners[typeStr] = [];
  9987. this.typeCount_++;
  9988. }
  9989. var listenerObj;
  9990. var index = goog.events.ListenerMap.findListenerIndex_(
  9991. listenerArray, listener, opt_useCapture, opt_listenerScope);
  9992. if (index > -1) {
  9993. listenerObj = listenerArray[index];
  9994. if (!callOnce) {
  9995. // Ensure that, if there is an existing callOnce listener, it is no
  9996. // longer a callOnce listener.
  9997. listenerObj.callOnce = false;
  9998. }
  9999. } else {
  10000. listenerObj = new goog.events.Listener(
  10001. listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);
  10002. listenerObj.callOnce = callOnce;
  10003. listenerArray.push(listenerObj);
  10004. }
  10005. return listenerObj;
  10006. };
  10007. /**
  10008. * Removes a matching listener.
  10009. * @param {string|!goog.events.EventId} type The listener event type.
  10010. * @param {!Function} listener This listener callback method.
  10011. * @param {boolean=} opt_useCapture The capture mode of the listener.
  10012. * @param {Object=} opt_listenerScope Object in whose scope to call the
  10013. * listener.
  10014. * @return {boolean} Whether any listener was removed.
  10015. */
  10016. goog.events.ListenerMap.prototype.remove = function(
  10017. type, listener, opt_useCapture, opt_listenerScope) {
  10018. var typeStr = type.toString();
  10019. if (!(typeStr in this.listeners)) {
  10020. return false;
  10021. }
  10022. var listenerArray = this.listeners[typeStr];
  10023. var index = goog.events.ListenerMap.findListenerIndex_(
  10024. listenerArray, listener, opt_useCapture, opt_listenerScope);
  10025. if (index > -1) {
  10026. var listenerObj = listenerArray[index];
  10027. listenerObj.markAsRemoved();
  10028. goog.array.removeAt(listenerArray, index);
  10029. if (listenerArray.length == 0) {
  10030. delete this.listeners[typeStr];
  10031. this.typeCount_--;
  10032. }
  10033. return true;
  10034. }
  10035. return false;
  10036. };
  10037. /**
  10038. * Removes the given listener object.
  10039. * @param {goog.events.ListenableKey} listener The listener to remove.
  10040. * @return {boolean} Whether the listener is removed.
  10041. */
  10042. goog.events.ListenerMap.prototype.removeByKey = function(listener) {
  10043. var type = listener.type;
  10044. if (!(type in this.listeners)) {
  10045. return false;
  10046. }
  10047. var removed = goog.array.remove(this.listeners[type], listener);
  10048. if (removed) {
  10049. listener.markAsRemoved();
  10050. if (this.listeners[type].length == 0) {
  10051. delete this.listeners[type];
  10052. this.typeCount_--;
  10053. }
  10054. }
  10055. return removed;
  10056. };
  10057. /**
  10058. * Removes all listeners from this map. If opt_type is provided, only
  10059. * listeners that match the given type are removed.
  10060. * @param {string|!goog.events.EventId=} opt_type Type of event to remove.
  10061. * @return {number} Number of listeners removed.
  10062. */
  10063. goog.events.ListenerMap.prototype.removeAll = function(opt_type) {
  10064. var typeStr = opt_type && opt_type.toString();
  10065. var count = 0;
  10066. for (var type in this.listeners) {
  10067. if (!typeStr || type == typeStr) {
  10068. var listenerArray = this.listeners[type];
  10069. for (var i = 0; i < listenerArray.length; i++) {
  10070. ++count;
  10071. listenerArray[i].markAsRemoved();
  10072. }
  10073. delete this.listeners[type];
  10074. this.typeCount_--;
  10075. }
  10076. }
  10077. return count;
  10078. };
  10079. /**
  10080. * Gets all listeners that match the given type and capture mode. The
  10081. * returned array is a copy (but the listener objects are not).
  10082. * @param {string|!goog.events.EventId} type The type of the listeners
  10083. * to retrieve.
  10084. * @param {boolean} capture The capture mode of the listeners to retrieve.
  10085. * @return {!Array<goog.events.ListenableKey>} An array of matching
  10086. * listeners.
  10087. */
  10088. goog.events.ListenerMap.prototype.getListeners = function(type, capture) {
  10089. var listenerArray = this.listeners[type.toString()];
  10090. var rv = [];
  10091. if (listenerArray) {
  10092. for (var i = 0; i < listenerArray.length; ++i) {
  10093. var listenerObj = listenerArray[i];
  10094. if (listenerObj.capture == capture) {
  10095. rv.push(listenerObj);
  10096. }
  10097. }
  10098. }
  10099. return rv;
  10100. };
  10101. /**
  10102. * Gets the goog.events.ListenableKey for the event or null if no such
  10103. * listener is in use.
  10104. *
  10105. * @param {string|!goog.events.EventId} type The type of the listener
  10106. * to retrieve.
  10107. * @param {!Function} listener The listener function to get.
  10108. * @param {boolean} capture Whether the listener is a capturing listener.
  10109. * @param {Object=} opt_listenerScope Object in whose scope to call the
  10110. * listener.
  10111. * @return {goog.events.ListenableKey} the found listener or null if not found.
  10112. */
  10113. goog.events.ListenerMap.prototype.getListener = function(
  10114. type, listener, capture, opt_listenerScope) {
  10115. var listenerArray = this.listeners[type.toString()];
  10116. var i = -1;
  10117. if (listenerArray) {
  10118. i = goog.events.ListenerMap.findListenerIndex_(
  10119. listenerArray, listener, capture, opt_listenerScope);
  10120. }
  10121. return i > -1 ? listenerArray[i] : null;
  10122. };
  10123. /**
  10124. * Whether there is a matching listener. If either the type or capture
  10125. * parameters are unspecified, the function will match on the
  10126. * remaining criteria.
  10127. *
  10128. * @param {string|!goog.events.EventId=} opt_type The type of the listener.
  10129. * @param {boolean=} opt_capture The capture mode of the listener.
  10130. * @return {boolean} Whether there is an active listener matching
  10131. * the requested type and/or capture phase.
  10132. */
  10133. goog.events.ListenerMap.prototype.hasListener = function(
  10134. opt_type, opt_capture) {
  10135. var hasType = goog.isDef(opt_type);
  10136. var typeStr = hasType ? opt_type.toString() : '';
  10137. var hasCapture = goog.isDef(opt_capture);
  10138. return goog.object.some(
  10139. this.listeners, function(listenerArray, type) {
  10140. for (var i = 0; i < listenerArray.length; ++i) {
  10141. if ((!hasType || listenerArray[i].type == typeStr) &&
  10142. (!hasCapture || listenerArray[i].capture == opt_capture)) {
  10143. return true;
  10144. }
  10145. }
  10146. return false;
  10147. });
  10148. };
  10149. /**
  10150. * Finds the index of a matching goog.events.Listener in the given
  10151. * listenerArray.
  10152. * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.
  10153. * @param {!Function} listener The listener function.
  10154. * @param {boolean=} opt_useCapture The capture flag for the listener.
  10155. * @param {Object=} opt_listenerScope The listener scope.
  10156. * @return {number} The index of the matching listener within the
  10157. * listenerArray.
  10158. * @private
  10159. */
  10160. goog.events.ListenerMap.findListenerIndex_ = function(
  10161. listenerArray, listener, opt_useCapture, opt_listenerScope) {
  10162. for (var i = 0; i < listenerArray.length; ++i) {
  10163. var listenerObj = listenerArray[i];
  10164. if (!listenerObj.removed &&
  10165. listenerObj.listener == listener &&
  10166. listenerObj.capture == !!opt_useCapture &&
  10167. listenerObj.handler == opt_listenerScope) {
  10168. return i;
  10169. }
  10170. }
  10171. return -1;
  10172. };
  10173. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  10174. //
  10175. // Licensed under the Apache License, Version 2.0 (the "License");
  10176. // you may not use this file except in compliance with the License.
  10177. // You may obtain a copy of the License at
  10178. //
  10179. // http://www.apache.org/licenses/LICENSE-2.0
  10180. //
  10181. // Unless required by applicable law or agreed to in writing, software
  10182. // distributed under the License is distributed on an "AS-IS" BASIS,
  10183. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10184. // See the License for the specific language governing permissions and
  10185. // limitations under the License.
  10186. /**
  10187. * @fileoverview An event manager for both native browser event
  10188. * targets and custom JavaScript event targets
  10189. * ({@code goog.events.Listenable}). This provides an abstraction
  10190. * over browsers' event systems.
  10191. *
  10192. * It also provides a simulation of W3C event model's capture phase in
  10193. * Internet Explorer (IE 8 and below). Caveat: the simulation does not
  10194. * interact well with listeners registered directly on the elements
  10195. * (bypassing goog.events) or even with listeners registered via
  10196. * goog.events in a separate JS binary. In these cases, we provide
  10197. * no ordering guarantees.
  10198. *
  10199. * The listeners will receive a "patched" event object. Such event object
  10200. * contains normalized values for certain event properties that differs in
  10201. * different browsers.
  10202. *
  10203. * Example usage:
  10204. * <pre>
  10205. * goog.events.listen(myNode, 'click', function(e) { alert('woo') });
  10206. * goog.events.listen(myNode, 'mouseover', mouseHandler, true);
  10207. * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);
  10208. * goog.events.removeAll(myNode);
  10209. * </pre>
  10210. *
  10211. * in IE and event object patching]
  10212. * @author arv@google.com (Erik Arvidsson)
  10213. *
  10214. * @see ../demos/events.html
  10215. * @see ../demos/event-propagation.html
  10216. * @see ../demos/stopevent.html
  10217. */
  10218. // IMPLEMENTATION NOTES:
  10219. // goog.events stores an auxiliary data structure on each EventTarget
  10220. // source being listened on. This allows us to take advantage of GC,
  10221. // having the data structure GC'd when the EventTarget is GC'd. This
  10222. // GC behavior is equivalent to using W3C DOM Events directly.
  10223. goog.provide('goog.events');
  10224. goog.provide('goog.events.CaptureSimulationMode');
  10225. goog.provide('goog.events.Key');
  10226. goog.provide('goog.events.ListenableType');
  10227. goog.require('goog.asserts');
  10228. goog.require('goog.debug.entryPointRegistry');
  10229. goog.require('goog.events.BrowserEvent');
  10230. goog.require('goog.events.BrowserFeature');
  10231. goog.require('goog.events.Listenable');
  10232. goog.require('goog.events.ListenerMap');
  10233. goog.forwardDeclare('goog.debug.ErrorHandler');
  10234. goog.forwardDeclare('goog.events.EventWrapper');
  10235. /**
  10236. * @typedef {number|goog.events.ListenableKey}
  10237. */
  10238. goog.events.Key;
  10239. /**
  10240. * @typedef {EventTarget|goog.events.Listenable}
  10241. */
  10242. goog.events.ListenableType;
  10243. /**
  10244. * Property name on a native event target for the listener map
  10245. * associated with the event target.
  10246. * @private @const {string}
  10247. */
  10248. goog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);
  10249. /**
  10250. * String used to prepend to IE event types.
  10251. * @const
  10252. * @private
  10253. */
  10254. goog.events.onString_ = 'on';
  10255. /**
  10256. * Map of computed "on<eventname>" strings for IE event types. Caching
  10257. * this removes an extra object allocation in goog.events.listen which
  10258. * improves IE6 performance.
  10259. * @const
  10260. * @dict
  10261. * @private
  10262. */
  10263. goog.events.onStringMap_ = {};
  10264. /**
  10265. * @enum {number} Different capture simulation mode for IE8-.
  10266. */
  10267. goog.events.CaptureSimulationMode = {
  10268. /**
  10269. * Does not perform capture simulation. Will asserts in IE8- when you
  10270. * add capture listeners.
  10271. */
  10272. OFF_AND_FAIL: 0,
  10273. /**
  10274. * Does not perform capture simulation, silently ignore capture
  10275. * listeners.
  10276. */
  10277. OFF_AND_SILENT: 1,
  10278. /**
  10279. * Performs capture simulation.
  10280. */
  10281. ON: 2
  10282. };
  10283. /**
  10284. * @define {number} The capture simulation mode for IE8-. By default,
  10285. * this is ON.
  10286. */
  10287. goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);
  10288. /**
  10289. * Estimated count of total native listeners.
  10290. * @private {number}
  10291. */
  10292. goog.events.listenerCountEstimate_ = 0;
  10293. /**
  10294. * Adds an event listener for a specific event on a native event
  10295. * target (such as a DOM element) or an object that has implemented
  10296. * {@link goog.events.Listenable}. A listener can only be added once
  10297. * to an object and if it is added again the key for the listener is
  10298. * returned. Note that if the existing listener is a one-off listener
  10299. * (registered via listenOnce), it will no longer be a one-off
  10300. * listener after a call to listen().
  10301. *
  10302. * @param {EventTarget|goog.events.Listenable} src The node to listen
  10303. * to events on.
  10304. * @param {string|Array<string>|
  10305. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  10306. * type Event type or array of event types.
  10307. * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}
  10308. * listener Callback method, or an object with a handleEvent function.
  10309. * WARNING: passing an Object is now softly deprecated.
  10310. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
  10311. * false).
  10312. * @param {T=} opt_handler Element in whose scope to call the listener.
  10313. * @return {goog.events.Key} Unique key for the listener.
  10314. * @template T,EVENTOBJ
  10315. */
  10316. goog.events.listen = function(src, type, listener, opt_capt, opt_handler) {
  10317. if (goog.isArray(type)) {
  10318. for (var i = 0; i < type.length; i++) {
  10319. goog.events.listen(src, type[i], listener, opt_capt, opt_handler);
  10320. }
  10321. return null;
  10322. }
  10323. listener = goog.events.wrapListener(listener);
  10324. if (goog.events.Listenable.isImplementedBy(src)) {
  10325. return src.listen(
  10326. /** @type {string|!goog.events.EventId} */ (type),
  10327. listener, opt_capt, opt_handler);
  10328. } else {
  10329. return goog.events.listen_(
  10330. /** @type {!EventTarget} */ (src),
  10331. /** @type {string|!goog.events.EventId} */ (type),
  10332. listener, /* callOnce */ false, opt_capt, opt_handler);
  10333. }
  10334. };
  10335. /**
  10336. * Adds an event listener for a specific event on a native event
  10337. * target. A listener can only be added once to an object and if it
  10338. * is added again the key for the listener is returned.
  10339. *
  10340. * Note that a one-off listener will not change an existing listener,
  10341. * if any. On the other hand a normal listener will change existing
  10342. * one-off listener to become a normal listener.
  10343. *
  10344. * @param {EventTarget} src The node to listen to events on.
  10345. * @param {string|!goog.events.EventId} type Event type.
  10346. * @param {!Function} listener Callback function.
  10347. * @param {boolean} callOnce Whether the listener is a one-off
  10348. * listener or otherwise.
  10349. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
  10350. * false).
  10351. * @param {Object=} opt_handler Element in whose scope to call the listener.
  10352. * @return {goog.events.ListenableKey} Unique key for the listener.
  10353. * @private
  10354. */
  10355. goog.events.listen_ = function(
  10356. src, type, listener, callOnce, opt_capt, opt_handler) {
  10357. if (!type) {
  10358. throw Error('Invalid event type');
  10359. }
  10360. var capture = !!opt_capt;
  10361. if (capture && !goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {
  10362. if (goog.events.CAPTURE_SIMULATION_MODE ==
  10363. goog.events.CaptureSimulationMode.OFF_AND_FAIL) {
  10364. goog.asserts.fail('Can not register capture listener in IE8-.');
  10365. return null;
  10366. } else if (goog.events.CAPTURE_SIMULATION_MODE ==
  10367. goog.events.CaptureSimulationMode.OFF_AND_SILENT) {
  10368. return null;
  10369. }
  10370. }
  10371. var listenerMap = goog.events.getListenerMap_(src);
  10372. if (!listenerMap) {
  10373. src[goog.events.LISTENER_MAP_PROP_] = listenerMap =
  10374. new goog.events.ListenerMap(src);
  10375. }
  10376. var listenerObj = listenerMap.add(
  10377. type, listener, callOnce, opt_capt, opt_handler);
  10378. // If the listenerObj already has a proxy, it has been set up
  10379. // previously. We simply return.
  10380. if (listenerObj.proxy) {
  10381. return listenerObj;
  10382. }
  10383. var proxy = goog.events.getProxy();
  10384. listenerObj.proxy = proxy;
  10385. proxy.src = src;
  10386. proxy.listener = listenerObj;
  10387. // Attach the proxy through the browser's API
  10388. if (src.addEventListener) {
  10389. src.addEventListener(type.toString(), proxy, capture);
  10390. } else if (src.attachEvent) {
  10391. // The else if above used to be an unconditional else. It would call
  10392. // exception on IE11, spoiling the day of some callers. The previous
  10393. // incarnation of this code, from 2007, indicates that it replaced an
  10394. // earlier still version that caused excess allocations on IE6.
  10395. src.attachEvent(goog.events.getOnString_(type.toString()), proxy);
  10396. } else {
  10397. throw Error('addEventListener and attachEvent are unavailable.');
  10398. }
  10399. goog.events.listenerCountEstimate_++;
  10400. return listenerObj;
  10401. };
  10402. /**
  10403. * Helper function for returning a proxy function.
  10404. * @return {!Function} A new or reused function object.
  10405. */
  10406. goog.events.getProxy = function() {
  10407. var proxyCallbackFunction = goog.events.handleBrowserEvent_;
  10408. // Use a local var f to prevent one allocation.
  10409. var f = goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ?
  10410. function(eventObject) {
  10411. return proxyCallbackFunction.call(f.src, f.listener, eventObject);
  10412. } :
  10413. function(eventObject) {
  10414. var v = proxyCallbackFunction.call(f.src, f.listener, eventObject);
  10415. // NOTE(chrishenry): In IE, we hack in a capture phase. However, if
  10416. // there is inline event handler which tries to prevent default (for
  10417. // example <a href="..." onclick="return false">...</a>) in a
  10418. // descendant element, the prevent default will be overridden
  10419. // by this listener if this listener were to return true. Hence, we
  10420. // return undefined.
  10421. if (!v) return v;
  10422. };
  10423. return f;
  10424. };
  10425. /**
  10426. * Adds an event listener for a specific event on a native event
  10427. * target (such as a DOM element) or an object that has implemented
  10428. * {@link goog.events.Listenable}. After the event has fired the event
  10429. * listener is removed from the target.
  10430. *
  10431. * If an existing listener already exists, listenOnce will do
  10432. * nothing. In particular, if the listener was previously registered
  10433. * via listen(), listenOnce() will not turn the listener into a
  10434. * one-off listener. Similarly, if there is already an existing
  10435. * one-off listener, listenOnce does not modify the listeners (it is
  10436. * still a once listener).
  10437. *
  10438. * @param {EventTarget|goog.events.Listenable} src The node to listen
  10439. * to events on.
  10440. * @param {string|Array<string>|
  10441. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  10442. * type Event type or array of event types.
  10443. * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}
  10444. * listener Callback method.
  10445. * @param {boolean=} opt_capt Fire in capture phase?.
  10446. * @param {T=} opt_handler Element in whose scope to call the listener.
  10447. * @return {goog.events.Key} Unique key for the listener.
  10448. * @template T,EVENTOBJ
  10449. */
  10450. goog.events.listenOnce = function(src, type, listener, opt_capt, opt_handler) {
  10451. if (goog.isArray(type)) {
  10452. for (var i = 0; i < type.length; i++) {
  10453. goog.events.listenOnce(src, type[i], listener, opt_capt, opt_handler);
  10454. }
  10455. return null;
  10456. }
  10457. listener = goog.events.wrapListener(listener);
  10458. if (goog.events.Listenable.isImplementedBy(src)) {
  10459. return src.listenOnce(
  10460. /** @type {string|!goog.events.EventId} */ (type),
  10461. listener, opt_capt, opt_handler);
  10462. } else {
  10463. return goog.events.listen_(
  10464. /** @type {!EventTarget} */ (src),
  10465. /** @type {string|!goog.events.EventId} */ (type),
  10466. listener, /* callOnce */ true, opt_capt, opt_handler);
  10467. }
  10468. };
  10469. /**
  10470. * Adds an event listener with a specific event wrapper on a DOM Node or an
  10471. * object that has implemented {@link goog.events.Listenable}. A listener can
  10472. * only be added once to an object.
  10473. *
  10474. * @param {EventTarget|goog.events.Listenable} src The target to
  10475. * listen to events on.
  10476. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  10477. * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener
  10478. * Callback method, or an object with a handleEvent function.
  10479. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
  10480. * false).
  10481. * @param {T=} opt_handler Element in whose scope to call the listener.
  10482. * @template T
  10483. */
  10484. goog.events.listenWithWrapper = function(src, wrapper, listener, opt_capt,
  10485. opt_handler) {
  10486. wrapper.listen(src, listener, opt_capt, opt_handler);
  10487. };
  10488. /**
  10489. * Removes an event listener which was added with listen().
  10490. *
  10491. * @param {EventTarget|goog.events.Listenable} src The target to stop
  10492. * listening to events on.
  10493. * @param {string|Array<string>|
  10494. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  10495. * type Event type or array of event types to unlisten to.
  10496. * @param {function(?):?|{handleEvent:function(?):?}|null} listener The
  10497. * listener function to remove.
  10498. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines
  10499. * whether the listener is fired during the capture or bubble phase of the
  10500. * event.
  10501. * @param {Object=} opt_handler Element in whose scope to call the listener.
  10502. * @return {?boolean} indicating whether the listener was there to remove.
  10503. * @template EVENTOBJ
  10504. */
  10505. goog.events.unlisten = function(src, type, listener, opt_capt, opt_handler) {
  10506. if (goog.isArray(type)) {
  10507. for (var i = 0; i < type.length; i++) {
  10508. goog.events.unlisten(src, type[i], listener, opt_capt, opt_handler);
  10509. }
  10510. return null;
  10511. }
  10512. listener = goog.events.wrapListener(listener);
  10513. if (goog.events.Listenable.isImplementedBy(src)) {
  10514. return src.unlisten(
  10515. /** @type {string|!goog.events.EventId} */ (type),
  10516. listener, opt_capt, opt_handler);
  10517. }
  10518. if (!src) {
  10519. // TODO(chrishenry): We should tighten the API to only accept
  10520. // non-null objects, or add an assertion here.
  10521. return false;
  10522. }
  10523. var capture = !!opt_capt;
  10524. var listenerMap = goog.events.getListenerMap_(
  10525. /** @type {!EventTarget} */ (src));
  10526. if (listenerMap) {
  10527. var listenerObj = listenerMap.getListener(
  10528. /** @type {string|!goog.events.EventId} */ (type),
  10529. listener, capture, opt_handler);
  10530. if (listenerObj) {
  10531. return goog.events.unlistenByKey(listenerObj);
  10532. }
  10533. }
  10534. return false;
  10535. };
  10536. /**
  10537. * Removes an event listener which was added with listen() by the key
  10538. * returned by listen().
  10539. *
  10540. * @param {goog.events.Key} key The key returned by listen() for this
  10541. * event listener.
  10542. * @return {boolean} indicating whether the listener was there to remove.
  10543. */
  10544. goog.events.unlistenByKey = function(key) {
  10545. // TODO(chrishenry): Remove this check when tests that rely on this
  10546. // are fixed.
  10547. if (goog.isNumber(key)) {
  10548. return false;
  10549. }
  10550. var listener = key;
  10551. if (!listener || listener.removed) {
  10552. return false;
  10553. }
  10554. var src = listener.src;
  10555. if (goog.events.Listenable.isImplementedBy(src)) {
  10556. return src.unlistenByKey(listener);
  10557. }
  10558. var type = listener.type;
  10559. var proxy = listener.proxy;
  10560. if (src.removeEventListener) {
  10561. src.removeEventListener(type, proxy, listener.capture);
  10562. } else if (src.detachEvent) {
  10563. src.detachEvent(goog.events.getOnString_(type), proxy);
  10564. }
  10565. goog.events.listenerCountEstimate_--;
  10566. var listenerMap = goog.events.getListenerMap_(
  10567. /** @type {!EventTarget} */ (src));
  10568. // TODO(chrishenry): Try to remove this conditional and execute the
  10569. // first branch always. This should be safe.
  10570. if (listenerMap) {
  10571. listenerMap.removeByKey(listener);
  10572. if (listenerMap.getTypeCount() == 0) {
  10573. // Null the src, just because this is simple to do (and useful
  10574. // for IE <= 7).
  10575. listenerMap.src = null;
  10576. // We don't use delete here because IE does not allow delete
  10577. // on a window object.
  10578. src[goog.events.LISTENER_MAP_PROP_] = null;
  10579. }
  10580. } else {
  10581. listener.markAsRemoved();
  10582. }
  10583. return true;
  10584. };
  10585. /**
  10586. * Removes an event listener which was added with listenWithWrapper().
  10587. *
  10588. * @param {EventTarget|goog.events.Listenable} src The target to stop
  10589. * listening to events on.
  10590. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  10591. * @param {function(?):?|{handleEvent:function(?):?}|null} listener The
  10592. * listener function to remove.
  10593. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines
  10594. * whether the listener is fired during the capture or bubble phase of the
  10595. * event.
  10596. * @param {Object=} opt_handler Element in whose scope to call the listener.
  10597. */
  10598. goog.events.unlistenWithWrapper = function(src, wrapper, listener, opt_capt,
  10599. opt_handler) {
  10600. wrapper.unlisten(src, listener, opt_capt, opt_handler);
  10601. };
  10602. /**
  10603. * Removes all listeners from an object. You can also optionally
  10604. * remove listeners of a particular type.
  10605. *
  10606. * @param {Object|undefined} obj Object to remove listeners from. Must be an
  10607. * EventTarget or a goog.events.Listenable.
  10608. * @param {string|!goog.events.EventId=} opt_type Type of event to remove.
  10609. * Default is all types.
  10610. * @return {number} Number of listeners removed.
  10611. */
  10612. goog.events.removeAll = function(obj, opt_type) {
  10613. // TODO(chrishenry): Change the type of obj to
  10614. // (!EventTarget|!goog.events.Listenable).
  10615. if (!obj) {
  10616. return 0;
  10617. }
  10618. if (goog.events.Listenable.isImplementedBy(obj)) {
  10619. return obj.removeAllListeners(opt_type);
  10620. }
  10621. var listenerMap = goog.events.getListenerMap_(
  10622. /** @type {!EventTarget} */ (obj));
  10623. if (!listenerMap) {
  10624. return 0;
  10625. }
  10626. var count = 0;
  10627. var typeStr = opt_type && opt_type.toString();
  10628. for (var type in listenerMap.listeners) {
  10629. if (!typeStr || type == typeStr) {
  10630. // Clone so that we don't need to worry about unlistenByKey
  10631. // changing the content of the ListenerMap.
  10632. var listeners = listenerMap.listeners[type].concat();
  10633. for (var i = 0; i < listeners.length; ++i) {
  10634. if (goog.events.unlistenByKey(listeners[i])) {
  10635. ++count;
  10636. }
  10637. }
  10638. }
  10639. }
  10640. return count;
  10641. };
  10642. /**
  10643. * Gets the listeners for a given object, type and capture phase.
  10644. *
  10645. * @param {Object} obj Object to get listeners for.
  10646. * @param {string|!goog.events.EventId} type Event type.
  10647. * @param {boolean} capture Capture phase?.
  10648. * @return {Array<goog.events.Listener>} Array of listener objects.
  10649. */
  10650. goog.events.getListeners = function(obj, type, capture) {
  10651. if (goog.events.Listenable.isImplementedBy(obj)) {
  10652. return obj.getListeners(type, capture);
  10653. } else {
  10654. if (!obj) {
  10655. // TODO(chrishenry): We should tighten the API to accept
  10656. // !EventTarget|goog.events.Listenable, and add an assertion here.
  10657. return [];
  10658. }
  10659. var listenerMap = goog.events.getListenerMap_(
  10660. /** @type {!EventTarget} */ (obj));
  10661. return listenerMap ? listenerMap.getListeners(type, capture) : [];
  10662. }
  10663. };
  10664. /**
  10665. * Gets the goog.events.Listener for the event or null if no such listener is
  10666. * in use.
  10667. *
  10668. * @param {EventTarget|goog.events.Listenable} src The target from
  10669. * which to get listeners.
  10670. * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.
  10671. * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The
  10672. * listener function to get.
  10673. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines
  10674. * whether the listener is fired during the
  10675. * capture or bubble phase of the event.
  10676. * @param {Object=} opt_handler Element in whose scope to call the listener.
  10677. * @return {goog.events.ListenableKey} the found listener or null if not found.
  10678. * @template EVENTOBJ
  10679. */
  10680. goog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {
  10681. // TODO(chrishenry): Change type from ?string to string, or add assertion.
  10682. type = /** @type {string} */ (type);
  10683. listener = goog.events.wrapListener(listener);
  10684. var capture = !!opt_capt;
  10685. if (goog.events.Listenable.isImplementedBy(src)) {
  10686. return src.getListener(type, listener, capture, opt_handler);
  10687. }
  10688. if (!src) {
  10689. // TODO(chrishenry): We should tighten the API to only accept
  10690. // non-null objects, or add an assertion here.
  10691. return null;
  10692. }
  10693. var listenerMap = goog.events.getListenerMap_(
  10694. /** @type {!EventTarget} */ (src));
  10695. if (listenerMap) {
  10696. return listenerMap.getListener(type, listener, capture, opt_handler);
  10697. }
  10698. return null;
  10699. };
  10700. /**
  10701. * Returns whether an event target has any active listeners matching the
  10702. * specified signature. If either the type or capture parameters are
  10703. * unspecified, the function will match on the remaining criteria.
  10704. *
  10705. * @param {EventTarget|goog.events.Listenable} obj Target to get
  10706. * listeners for.
  10707. * @param {string|!goog.events.EventId=} opt_type Event type.
  10708. * @param {boolean=} opt_capture Whether to check for capture or bubble-phase
  10709. * listeners.
  10710. * @return {boolean} Whether an event target has one or more listeners matching
  10711. * the requested type and/or capture phase.
  10712. */
  10713. goog.events.hasListener = function(obj, opt_type, opt_capture) {
  10714. if (goog.events.Listenable.isImplementedBy(obj)) {
  10715. return obj.hasListener(opt_type, opt_capture);
  10716. }
  10717. var listenerMap = goog.events.getListenerMap_(
  10718. /** @type {!EventTarget} */ (obj));
  10719. return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);
  10720. };
  10721. /**
  10722. * Provides a nice string showing the normalized event objects public members
  10723. * @param {Object} e Event Object.
  10724. * @return {string} String of the public members of the normalized event object.
  10725. */
  10726. goog.events.expose = function(e) {
  10727. var str = [];
  10728. for (var key in e) {
  10729. if (e[key] && e[key].id) {
  10730. str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');
  10731. } else {
  10732. str.push(key + ' = ' + e[key]);
  10733. }
  10734. }
  10735. return str.join('\n');
  10736. };
  10737. /**
  10738. * Returns a string with on prepended to the specified type. This is used for IE
  10739. * which expects "on" to be prepended. This function caches the string in order
  10740. * to avoid extra allocations in steady state.
  10741. * @param {string} type Event type.
  10742. * @return {string} The type string with 'on' prepended.
  10743. * @private
  10744. */
  10745. goog.events.getOnString_ = function(type) {
  10746. if (type in goog.events.onStringMap_) {
  10747. return goog.events.onStringMap_[type];
  10748. }
  10749. return goog.events.onStringMap_[type] = goog.events.onString_ + type;
  10750. };
  10751. /**
  10752. * Fires an object's listeners of a particular type and phase
  10753. *
  10754. * @param {Object} obj Object whose listeners to call.
  10755. * @param {string|!goog.events.EventId} type Event type.
  10756. * @param {boolean} capture Which event phase.
  10757. * @param {Object} eventObject Event object to be passed to listener.
  10758. * @return {boolean} True if all listeners returned true else false.
  10759. */
  10760. goog.events.fireListeners = function(obj, type, capture, eventObject) {
  10761. if (goog.events.Listenable.isImplementedBy(obj)) {
  10762. return obj.fireListeners(type, capture, eventObject);
  10763. }
  10764. return goog.events.fireListeners_(obj, type, capture, eventObject);
  10765. };
  10766. /**
  10767. * Fires an object's listeners of a particular type and phase.
  10768. * @param {Object} obj Object whose listeners to call.
  10769. * @param {string|!goog.events.EventId} type Event type.
  10770. * @param {boolean} capture Which event phase.
  10771. * @param {Object} eventObject Event object to be passed to listener.
  10772. * @return {boolean} True if all listeners returned true else false.
  10773. * @private
  10774. */
  10775. goog.events.fireListeners_ = function(obj, type, capture, eventObject) {
  10776. /** @type {boolean} */
  10777. var retval = true;
  10778. var listenerMap = goog.events.getListenerMap_(
  10779. /** @type {EventTarget} */ (obj));
  10780. if (listenerMap) {
  10781. // TODO(chrishenry): Original code avoids array creation when there
  10782. // is no listener, so we do the same. If this optimization turns
  10783. // out to be not required, we can replace this with
  10784. // listenerMap.getListeners(type, capture) instead, which is simpler.
  10785. var listenerArray = listenerMap.listeners[type.toString()];
  10786. if (listenerArray) {
  10787. listenerArray = listenerArray.concat();
  10788. for (var i = 0; i < listenerArray.length; i++) {
  10789. var listener = listenerArray[i];
  10790. // We might not have a listener if the listener was removed.
  10791. if (listener && listener.capture == capture && !listener.removed) {
  10792. var result = goog.events.fireListener(listener, eventObject);
  10793. retval = retval && (result !== false);
  10794. }
  10795. }
  10796. }
  10797. }
  10798. return retval;
  10799. };
  10800. /**
  10801. * Fires a listener with a set of arguments
  10802. *
  10803. * @param {goog.events.Listener} listener The listener object to call.
  10804. * @param {Object} eventObject The event object to pass to the listener.
  10805. * @return {boolean} Result of listener.
  10806. */
  10807. goog.events.fireListener = function(listener, eventObject) {
  10808. var listenerFn = listener.listener;
  10809. var listenerHandler = listener.handler || listener.src;
  10810. if (listener.callOnce) {
  10811. goog.events.unlistenByKey(listener);
  10812. }
  10813. return listenerFn.call(listenerHandler, eventObject);
  10814. };
  10815. /**
  10816. * Gets the total number of listeners currently in the system.
  10817. * @return {number} Number of listeners.
  10818. * @deprecated This returns estimated count, now that Closure no longer
  10819. * stores a central listener registry. We still return an estimation
  10820. * to keep existing listener-related tests passing. In the near future,
  10821. * this function will be removed.
  10822. */
  10823. goog.events.getTotalListenerCount = function() {
  10824. return goog.events.listenerCountEstimate_;
  10825. };
  10826. /**
  10827. * Dispatches an event (or event like object) and calls all listeners
  10828. * listening for events of this type. The type of the event is decided by the
  10829. * type property on the event object.
  10830. *
  10831. * If any of the listeners returns false OR calls preventDefault then this
  10832. * function will return false. If one of the capture listeners calls
  10833. * stopPropagation, then the bubble listeners won't fire.
  10834. *
  10835. * @param {goog.events.Listenable} src The event target.
  10836. * @param {goog.events.EventLike} e Event object.
  10837. * @return {boolean} If anyone called preventDefault on the event object (or
  10838. * if any of the handlers returns false) this will also return false.
  10839. * If there are no handlers, or if all handlers return true, this returns
  10840. * true.
  10841. */
  10842. goog.events.dispatchEvent = function(src, e) {
  10843. goog.asserts.assert(
  10844. goog.events.Listenable.isImplementedBy(src),
  10845. 'Can not use goog.events.dispatchEvent with ' +
  10846. 'non-goog.events.Listenable instance.');
  10847. return src.dispatchEvent(e);
  10848. };
  10849. /**
  10850. * Installs exception protection for the browser event entry point using the
  10851. * given error handler.
  10852. *
  10853. * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
  10854. * protect the entry point.
  10855. */
  10856. goog.events.protectBrowserEventEntryPoint = function(errorHandler) {
  10857. goog.events.handleBrowserEvent_ = errorHandler.protectEntryPoint(
  10858. goog.events.handleBrowserEvent_);
  10859. };
  10860. /**
  10861. * Handles an event and dispatches it to the correct listeners. This
  10862. * function is a proxy for the real listener the user specified.
  10863. *
  10864. * @param {goog.events.Listener} listener The listener object.
  10865. * @param {Event=} opt_evt Optional event object that gets passed in via the
  10866. * native event handlers.
  10867. * @return {boolean} Result of the event handler.
  10868. * @this {EventTarget} The object or Element that fired the event.
  10869. * @private
  10870. */
  10871. goog.events.handleBrowserEvent_ = function(listener, opt_evt) {
  10872. if (listener.removed) {
  10873. return true;
  10874. }
  10875. // Synthesize event propagation if the browser does not support W3C
  10876. // event model.
  10877. if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {
  10878. var ieEvent = opt_evt ||
  10879. /** @type {Event} */ (goog.getObjectByName('window.event'));
  10880. var evt = new goog.events.BrowserEvent(ieEvent, this);
  10881. /** @type {boolean} */
  10882. var retval = true;
  10883. if (goog.events.CAPTURE_SIMULATION_MODE ==
  10884. goog.events.CaptureSimulationMode.ON) {
  10885. // If we have not marked this event yet, we should perform capture
  10886. // simulation.
  10887. if (!goog.events.isMarkedIeEvent_(ieEvent)) {
  10888. goog.events.markIeEvent_(ieEvent);
  10889. var ancestors = [];
  10890. for (var parent = evt.currentTarget; parent;
  10891. parent = parent.parentNode) {
  10892. ancestors.push(parent);
  10893. }
  10894. // Fire capture listeners.
  10895. var type = listener.type;
  10896. for (var i = ancestors.length - 1; !evt.propagationStopped_ && i >= 0;
  10897. i--) {
  10898. evt.currentTarget = ancestors[i];
  10899. var result = goog.events.fireListeners_(ancestors[i], type, true, evt);
  10900. retval = retval && result;
  10901. }
  10902. // Fire bubble listeners.
  10903. //
  10904. // We can technically rely on IE to perform bubble event
  10905. // propagation. However, it turns out that IE fires events in
  10906. // opposite order of attachEvent registration, which broke
  10907. // some code and tests that rely on the order. (While W3C DOM
  10908. // Level 2 Events TR leaves the event ordering unspecified,
  10909. // modern browsers and W3C DOM Level 3 Events Working Draft
  10910. // actually specify the order as the registration order.)
  10911. for (var i = 0; !evt.propagationStopped_ && i < ancestors.length; i++) {
  10912. evt.currentTarget = ancestors[i];
  10913. var result = goog.events.fireListeners_(ancestors[i], type, false, evt);
  10914. retval = retval && result;
  10915. }
  10916. }
  10917. } else {
  10918. retval = goog.events.fireListener(listener, evt);
  10919. }
  10920. return retval;
  10921. }
  10922. // Otherwise, simply fire the listener.
  10923. return goog.events.fireListener(
  10924. listener, new goog.events.BrowserEvent(opt_evt, this));
  10925. };
  10926. /**
  10927. * This is used to mark the IE event object so we do not do the Closure pass
  10928. * twice for a bubbling event.
  10929. * @param {Event} e The IE browser event.
  10930. * @private
  10931. */
  10932. goog.events.markIeEvent_ = function(e) {
  10933. // Only the keyCode and the returnValue can be changed. We use keyCode for
  10934. // non keyboard events.
  10935. // event.returnValue is a bit more tricky. It is undefined by default. A
  10936. // boolean false prevents the default action. In a window.onbeforeunload and
  10937. // the returnValue is non undefined it will be alerted. However, we will only
  10938. // modify the returnValue for keyboard events. We can get a problem if non
  10939. // closure events sets the keyCode or the returnValue
  10940. var useReturnValue = false;
  10941. if (e.keyCode == 0) {
  10942. // We cannot change the keyCode in case that srcElement is input[type=file].
  10943. // We could test that that is the case but that would allocate 3 objects.
  10944. // If we use try/catch we will only allocate extra objects in the case of a
  10945. // failure.
  10946. /** @preserveTry */
  10947. try {
  10948. e.keyCode = -1;
  10949. return;
  10950. } catch (ex) {
  10951. useReturnValue = true;
  10952. }
  10953. }
  10954. if (useReturnValue ||
  10955. /** @type {boolean|undefined} */ (e.returnValue) == undefined) {
  10956. e.returnValue = true;
  10957. }
  10958. };
  10959. /**
  10960. * This is used to check if an IE event has already been handled by the Closure
  10961. * system so we do not do the Closure pass twice for a bubbling event.
  10962. * @param {Event} e The IE browser event.
  10963. * @return {boolean} True if the event object has been marked.
  10964. * @private
  10965. */
  10966. goog.events.isMarkedIeEvent_ = function(e) {
  10967. return e.keyCode < 0 || e.returnValue != undefined;
  10968. };
  10969. /**
  10970. * Counter to create unique event ids.
  10971. * @private {number}
  10972. */
  10973. goog.events.uniqueIdCounter_ = 0;
  10974. /**
  10975. * Creates a unique event id.
  10976. *
  10977. * @param {string} identifier The identifier.
  10978. * @return {string} A unique identifier.
  10979. * @idGenerator
  10980. */
  10981. goog.events.getUniqueId = function(identifier) {
  10982. return identifier + '_' + goog.events.uniqueIdCounter_++;
  10983. };
  10984. /**
  10985. * @param {EventTarget} src The source object.
  10986. * @return {goog.events.ListenerMap} A listener map for the given
  10987. * source object, or null if none exists.
  10988. * @private
  10989. */
  10990. goog.events.getListenerMap_ = function(src) {
  10991. var listenerMap = src[goog.events.LISTENER_MAP_PROP_];
  10992. // IE serializes the property as well (e.g. when serializing outer
  10993. // HTML). So we must check that the value is of the correct type.
  10994. return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;
  10995. };
  10996. /**
  10997. * Expando property for listener function wrapper for Object with
  10998. * handleEvent.
  10999. * @private @const {string}
  11000. */
  11001. goog.events.LISTENER_WRAPPER_PROP_ = '__closure_events_fn_' +
  11002. ((Math.random() * 1e9) >>> 0);
  11003. /**
  11004. * @param {Object|Function} listener The listener function or an
  11005. * object that contains handleEvent method.
  11006. * @return {!Function} Either the original function or a function that
  11007. * calls obj.handleEvent. If the same listener is passed to this
  11008. * function more than once, the same function is guaranteed to be
  11009. * returned.
  11010. */
  11011. goog.events.wrapListener = function(listener) {
  11012. goog.asserts.assert(listener, 'Listener can not be null.');
  11013. if (goog.isFunction(listener)) {
  11014. return listener;
  11015. }
  11016. goog.asserts.assert(
  11017. listener.handleEvent, 'An object listener must have handleEvent method.');
  11018. if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {
  11019. listener[goog.events.LISTENER_WRAPPER_PROP_] =
  11020. function(e) { return listener.handleEvent(e); };
  11021. }
  11022. return listener[goog.events.LISTENER_WRAPPER_PROP_];
  11023. };
  11024. // Register the browser event handler as an entry point, so that
  11025. // it can be monitored for exception handling, etc.
  11026. goog.debug.entryPointRegistry.register(
  11027. /**
  11028. * @param {function(!Function): !Function} transformer The transforming
  11029. * function.
  11030. */
  11031. function(transformer) {
  11032. goog.events.handleBrowserEvent_ = transformer(
  11033. goog.events.handleBrowserEvent_);
  11034. });
  11035. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  11036. //
  11037. // Licensed under the Apache License, Version 2.0 (the "License");
  11038. // you may not use this file except in compliance with the License.
  11039. // You may obtain a copy of the License at
  11040. //
  11041. // http://www.apache.org/licenses/LICENSE-2.0
  11042. //
  11043. // Unless required by applicable law or agreed to in writing, software
  11044. // distributed under the License is distributed on an "AS-IS" BASIS,
  11045. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11046. // See the License for the specific language governing permissions and
  11047. // limitations under the License.
  11048. /**
  11049. * @fileoverview A disposable implementation of a custom
  11050. * listenable/event target. See also: documentation for
  11051. * {@code goog.events.Listenable}.
  11052. *
  11053. * @author arv@google.com (Erik Arvidsson) [Original implementation]
  11054. * @see ../demos/eventtarget.html
  11055. * @see goog.events.Listenable
  11056. */
  11057. goog.provide('goog.events.EventTarget');
  11058. goog.require('goog.Disposable');
  11059. goog.require('goog.asserts');
  11060. goog.require('goog.events');
  11061. goog.require('goog.events.Event');
  11062. goog.require('goog.events.Listenable');
  11063. goog.require('goog.events.ListenerMap');
  11064. goog.require('goog.object');
  11065. /**
  11066. * An implementation of {@code goog.events.Listenable} with full W3C
  11067. * EventTarget-like support (capture/bubble mechanism, stopping event
  11068. * propagation, preventing default actions).
  11069. *
  11070. * You may subclass this class to turn your class into a Listenable.
  11071. *
  11072. * Unless propagation is stopped, an event dispatched by an
  11073. * EventTarget will bubble to the parent returned by
  11074. * {@code getParentEventTarget}. To set the parent, call
  11075. * {@code setParentEventTarget}. Subclasses that don't support
  11076. * changing the parent can override the setter to throw an error.
  11077. *
  11078. * Example usage:
  11079. * <pre>
  11080. * var source = new goog.events.EventTarget();
  11081. * function handleEvent(e) {
  11082. * alert('Type: ' + e.type + '; Target: ' + e.target);
  11083. * }
  11084. * source.listen('foo', handleEvent);
  11085. * // Or: goog.events.listen(source, 'foo', handleEvent);
  11086. * ...
  11087. * source.dispatchEvent('foo'); // will call handleEvent
  11088. * ...
  11089. * source.unlisten('foo', handleEvent);
  11090. * // Or: goog.events.unlisten(source, 'foo', handleEvent);
  11091. * </pre>
  11092. *
  11093. * @constructor
  11094. * @extends {goog.Disposable}
  11095. * @implements {goog.events.Listenable}
  11096. */
  11097. goog.events.EventTarget = function() {
  11098. goog.Disposable.call(this);
  11099. /**
  11100. * Maps of event type to an array of listeners.
  11101. * @private {!goog.events.ListenerMap}
  11102. */
  11103. this.eventTargetListeners_ = new goog.events.ListenerMap(this);
  11104. /**
  11105. * The object to use for event.target. Useful when mixing in an
  11106. * EventTarget to another object.
  11107. * @private {!Object}
  11108. */
  11109. this.actualEventTarget_ = this;
  11110. /**
  11111. * Parent event target, used during event bubbling.
  11112. *
  11113. * TODO(chrishenry): Change this to goog.events.Listenable. This
  11114. * currently breaks people who expect getParentEventTarget to return
  11115. * goog.events.EventTarget.
  11116. *
  11117. * @private {goog.events.EventTarget}
  11118. */
  11119. this.parentEventTarget_ = null;
  11120. };
  11121. goog.inherits(goog.events.EventTarget, goog.Disposable);
  11122. goog.events.Listenable.addImplementation(goog.events.EventTarget);
  11123. /**
  11124. * An artificial cap on the number of ancestors you can have. This is mainly
  11125. * for loop detection.
  11126. * @const {number}
  11127. * @private
  11128. */
  11129. goog.events.EventTarget.MAX_ANCESTORS_ = 1000;
  11130. /**
  11131. * Returns the parent of this event target to use for bubbling.
  11132. *
  11133. * @return {goog.events.EventTarget} The parent EventTarget or null if
  11134. * there is no parent.
  11135. * @override
  11136. */
  11137. goog.events.EventTarget.prototype.getParentEventTarget = function() {
  11138. return this.parentEventTarget_;
  11139. };
  11140. /**
  11141. * Sets the parent of this event target to use for capture/bubble
  11142. * mechanism.
  11143. * @param {goog.events.EventTarget} parent Parent listenable (null if none).
  11144. */
  11145. goog.events.EventTarget.prototype.setParentEventTarget = function(parent) {
  11146. this.parentEventTarget_ = parent;
  11147. };
  11148. /**
  11149. * Adds an event listener to the event target. The same handler can only be
  11150. * added once per the type. Even if you add the same handler multiple times
  11151. * using the same type then it will only be called once when the event is
  11152. * dispatched.
  11153. *
  11154. * @param {string} type The type of the event to listen for.
  11155. * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function
  11156. * to handle the event. The handler can also be an object that implements
  11157. * the handleEvent method which takes the event object as argument.
  11158. * @param {boolean=} opt_capture In DOM-compliant browsers, this determines
  11159. * whether the listener is fired during the capture or bubble phase
  11160. * of the event.
  11161. * @param {Object=} opt_handlerScope Object in whose scope to call
  11162. * the listener.
  11163. * @deprecated Use {@code #listen} instead, when possible. Otherwise, use
  11164. * {@code goog.events.listen} if you are passing Object
  11165. * (instead of Function) as handler.
  11166. */
  11167. goog.events.EventTarget.prototype.addEventListener = function(
  11168. type, handler, opt_capture, opt_handlerScope) {
  11169. goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);
  11170. };
  11171. /**
  11172. * Removes an event listener from the event target. The handler must be the
  11173. * same object as the one added. If the handler has not been added then
  11174. * nothing is done.
  11175. *
  11176. * @param {string} type The type of the event to listen for.
  11177. * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function
  11178. * to handle the event. The handler can also be an object that implements
  11179. * the handleEvent method which takes the event object as argument.
  11180. * @param {boolean=} opt_capture In DOM-compliant browsers, this determines
  11181. * whether the listener is fired during the capture or bubble phase
  11182. * of the event.
  11183. * @param {Object=} opt_handlerScope Object in whose scope to call
  11184. * the listener.
  11185. * @deprecated Use {@code #unlisten} instead, when possible. Otherwise, use
  11186. * {@code goog.events.unlisten} if you are passing Object
  11187. * (instead of Function) as handler.
  11188. */
  11189. goog.events.EventTarget.prototype.removeEventListener = function(
  11190. type, handler, opt_capture, opt_handlerScope) {
  11191. goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);
  11192. };
  11193. /** @override */
  11194. goog.events.EventTarget.prototype.dispatchEvent = function(e) {
  11195. this.assertInitialized_();
  11196. var ancestorsTree, ancestor = this.getParentEventTarget();
  11197. if (ancestor) {
  11198. ancestorsTree = [];
  11199. var ancestorCount = 1;
  11200. for (; ancestor; ancestor = ancestor.getParentEventTarget()) {
  11201. ancestorsTree.push(ancestor);
  11202. goog.asserts.assert(
  11203. (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),
  11204. 'infinite loop');
  11205. }
  11206. }
  11207. return goog.events.EventTarget.dispatchEventInternal_(
  11208. this.actualEventTarget_, e, ancestorsTree);
  11209. };
  11210. /**
  11211. * Removes listeners from this object. Classes that extend EventTarget may
  11212. * need to override this method in order to remove references to DOM Elements
  11213. * and additional listeners.
  11214. * @override
  11215. */
  11216. goog.events.EventTarget.prototype.disposeInternal = function() {
  11217. goog.events.EventTarget.superClass_.disposeInternal.call(this);
  11218. this.removeAllListeners();
  11219. this.parentEventTarget_ = null;
  11220. };
  11221. /** @override */
  11222. goog.events.EventTarget.prototype.listen = function(
  11223. type, listener, opt_useCapture, opt_listenerScope) {
  11224. this.assertInitialized_();
  11225. return this.eventTargetListeners_.add(
  11226. String(type), listener, false /* callOnce */, opt_useCapture,
  11227. opt_listenerScope);
  11228. };
  11229. /** @override */
  11230. goog.events.EventTarget.prototype.listenOnce = function(
  11231. type, listener, opt_useCapture, opt_listenerScope) {
  11232. return this.eventTargetListeners_.add(
  11233. String(type), listener, true /* callOnce */, opt_useCapture,
  11234. opt_listenerScope);
  11235. };
  11236. /** @override */
  11237. goog.events.EventTarget.prototype.unlisten = function(
  11238. type, listener, opt_useCapture, opt_listenerScope) {
  11239. return this.eventTargetListeners_.remove(
  11240. String(type), listener, opt_useCapture, opt_listenerScope);
  11241. };
  11242. /** @override */
  11243. goog.events.EventTarget.prototype.unlistenByKey = function(key) {
  11244. return this.eventTargetListeners_.removeByKey(key);
  11245. };
  11246. /** @override */
  11247. goog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {
  11248. // TODO(chrishenry): Previously, removeAllListeners can be called on
  11249. // uninitialized EventTarget, so we preserve that behavior. We
  11250. // should remove this when usages that rely on that fact are purged.
  11251. if (!this.eventTargetListeners_) {
  11252. return 0;
  11253. }
  11254. return this.eventTargetListeners_.removeAll(opt_type);
  11255. };
  11256. /** @override */
  11257. goog.events.EventTarget.prototype.fireListeners = function(
  11258. type, capture, eventObject) {
  11259. // TODO(chrishenry): Original code avoids array creation when there
  11260. // is no listener, so we do the same. If this optimization turns
  11261. // out to be not required, we can replace this with
  11262. // getListeners(type, capture) instead, which is simpler.
  11263. var listenerArray = this.eventTargetListeners_.listeners[String(type)];
  11264. if (!listenerArray) {
  11265. return true;
  11266. }
  11267. listenerArray = listenerArray.concat();
  11268. var rv = true;
  11269. for (var i = 0; i < listenerArray.length; ++i) {
  11270. var listener = listenerArray[i];
  11271. // We might not have a listener if the listener was removed.
  11272. if (listener && !listener.removed && listener.capture == capture) {
  11273. var listenerFn = listener.listener;
  11274. var listenerHandler = listener.handler || listener.src;
  11275. if (listener.callOnce) {
  11276. this.unlistenByKey(listener);
  11277. }
  11278. rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;
  11279. }
  11280. }
  11281. return rv && eventObject.returnValue_ != false;
  11282. };
  11283. /** @override */
  11284. goog.events.EventTarget.prototype.getListeners = function(type, capture) {
  11285. return this.eventTargetListeners_.getListeners(String(type), capture);
  11286. };
  11287. /** @override */
  11288. goog.events.EventTarget.prototype.getListener = function(
  11289. type, listener, capture, opt_listenerScope) {
  11290. return this.eventTargetListeners_.getListener(
  11291. String(type), listener, capture, opt_listenerScope);
  11292. };
  11293. /** @override */
  11294. goog.events.EventTarget.prototype.hasListener = function(
  11295. opt_type, opt_capture) {
  11296. var id = goog.isDef(opt_type) ? String(opt_type) : undefined;
  11297. return this.eventTargetListeners_.hasListener(id, opt_capture);
  11298. };
  11299. /**
  11300. * Sets the target to be used for {@code event.target} when firing
  11301. * event. Mainly used for testing. For example, see
  11302. * {@code goog.testing.events.mixinListenable}.
  11303. * @param {!Object} target The target.
  11304. */
  11305. goog.events.EventTarget.prototype.setTargetForTesting = function(target) {
  11306. this.actualEventTarget_ = target;
  11307. };
  11308. /**
  11309. * Asserts that the event target instance is initialized properly.
  11310. * @private
  11311. */
  11312. goog.events.EventTarget.prototype.assertInitialized_ = function() {
  11313. goog.asserts.assert(
  11314. this.eventTargetListeners_,
  11315. 'Event target is not initialized. Did you call the superclass ' +
  11316. '(goog.events.EventTarget) constructor?');
  11317. };
  11318. /**
  11319. * Dispatches the given event on the ancestorsTree.
  11320. *
  11321. * @param {!Object} target The target to dispatch on.
  11322. * @param {goog.events.Event|Object|string} e The event object.
  11323. * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors
  11324. * tree of the target, in reverse order from the closest ancestor
  11325. * to the root event target. May be null if the target has no ancestor.
  11326. * @return {boolean} If anyone called preventDefault on the event object (or
  11327. * if any of the listeners returns false) this will also return false.
  11328. * @private
  11329. */
  11330. goog.events.EventTarget.dispatchEventInternal_ = function(
  11331. target, e, opt_ancestorsTree) {
  11332. var type = e.type || /** @type {string} */ (e);
  11333. // If accepting a string or object, create a custom event object so that
  11334. // preventDefault and stopPropagation work with the event.
  11335. if (goog.isString(e)) {
  11336. e = new goog.events.Event(e, target);
  11337. } else if (!(e instanceof goog.events.Event)) {
  11338. var oldEvent = e;
  11339. e = new goog.events.Event(type, target);
  11340. goog.object.extend(e, oldEvent);
  11341. } else {
  11342. e.target = e.target || target;
  11343. }
  11344. var rv = true, currentTarget;
  11345. // Executes all capture listeners on the ancestors, if any.
  11346. if (opt_ancestorsTree) {
  11347. for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;
  11348. i--) {
  11349. currentTarget = e.currentTarget = opt_ancestorsTree[i];
  11350. rv = currentTarget.fireListeners(type, true, e) && rv;
  11351. }
  11352. }
  11353. // Executes capture and bubble listeners on the target.
  11354. if (!e.propagationStopped_) {
  11355. currentTarget = e.currentTarget = target;
  11356. rv = currentTarget.fireListeners(type, true, e) && rv;
  11357. if (!e.propagationStopped_) {
  11358. rv = currentTarget.fireListeners(type, false, e) && rv;
  11359. }
  11360. }
  11361. // Executes all bubble listeners on the ancestors, if any.
  11362. if (opt_ancestorsTree) {
  11363. for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {
  11364. currentTarget = e.currentTarget = opt_ancestorsTree[i];
  11365. rv = currentTarget.fireListeners(type, false, e) && rv;
  11366. }
  11367. }
  11368. return rv;
  11369. };
  11370. goog.provide('ol.Observable');
  11371. goog.require('goog.events');
  11372. goog.require('goog.events.EventTarget');
  11373. goog.require('goog.events.EventType');
  11374. /**
  11375. * @classdesc
  11376. * Abstract base class; normally only used for creating subclasses and not
  11377. * instantiated in apps.
  11378. * An event target providing convenient methods for listener registration
  11379. * and unregistration. A generic `change` event is always available through
  11380. * {@link ol.Observable#changed}.
  11381. *
  11382. * @constructor
  11383. * @extends {goog.events.EventTarget}
  11384. * @fires change
  11385. * @struct
  11386. * @api stable
  11387. */
  11388. ol.Observable = function() {
  11389. goog.base(this);
  11390. /**
  11391. * @private
  11392. * @type {number}
  11393. */
  11394. this.revision_ = 0;
  11395. };
  11396. goog.inherits(ol.Observable, goog.events.EventTarget);
  11397. /**
  11398. * Removes an event listener using the key returned by `on()` or `once()`.
  11399. * @param {goog.events.Key} key The key returned by `on()` or `once()`.
  11400. * @api stable
  11401. */
  11402. ol.Observable.unByKey = function(key) {
  11403. goog.events.unlistenByKey(key);
  11404. };
  11405. /**
  11406. * Increases the revision counter and dispatches a 'change' event.
  11407. * @api
  11408. */
  11409. ol.Observable.prototype.changed = function() {
  11410. ++this.revision_;
  11411. this.dispatchEvent(goog.events.EventType.CHANGE);
  11412. };
  11413. /**
  11414. * Triggered when the revision counter is increased.
  11415. * @event change
  11416. * @api
  11417. */
  11418. /**
  11419. * Get the version number for this object. Each time the object is modified,
  11420. * its version number will be incremented.
  11421. * @return {number} Revision.
  11422. * @api
  11423. */
  11424. ol.Observable.prototype.getRevision = function() {
  11425. return this.revision_;
  11426. };
  11427. /**
  11428. * Listen for a certain type of event.
  11429. * @param {string|Array.<string>} type The event type or array of event types.
  11430. * @param {function(?): ?} listener The listener function.
  11431. * @param {Object=} opt_this The object to use as `this` in `listener`.
  11432. * @return {goog.events.Key} Unique key for the listener.
  11433. * @api stable
  11434. */
  11435. ol.Observable.prototype.on = function(type, listener, opt_this) {
  11436. return goog.events.listen(this, type, listener, false, opt_this);
  11437. };
  11438. /**
  11439. * Listen once for a certain type of event.
  11440. * @param {string|Array.<string>} type The event type or array of event types.
  11441. * @param {function(?): ?} listener The listener function.
  11442. * @param {Object=} opt_this The object to use as `this` in `listener`.
  11443. * @return {goog.events.Key} Unique key for the listener.
  11444. * @api stable
  11445. */
  11446. ol.Observable.prototype.once = function(type, listener, opt_this) {
  11447. return goog.events.listenOnce(this, type, listener, false, opt_this);
  11448. };
  11449. /**
  11450. * Unlisten for a certain type of event.
  11451. * @param {string|Array.<string>} type The event type or array of event types.
  11452. * @param {function(?): ?} listener The listener function.
  11453. * @param {Object=} opt_this The object which was used as `this` by the
  11454. * `listener`.
  11455. * @api stable
  11456. */
  11457. ol.Observable.prototype.un = function(type, listener, opt_this) {
  11458. goog.events.unlisten(this, type, listener, false, opt_this);
  11459. };
  11460. /**
  11461. * Removes an event listener using the key returned by `on()` or `once()`.
  11462. * Note that using the {@link ol.Observable.unByKey} static function is to
  11463. * be preferred.
  11464. * @param {goog.events.Key} key The key returned by `on()` or `once()`.
  11465. * @function
  11466. * @api stable
  11467. */
  11468. ol.Observable.prototype.unByKey = ol.Observable.unByKey;
  11469. goog.provide('ol.Object');
  11470. goog.provide('ol.ObjectEvent');
  11471. goog.provide('ol.ObjectEventType');
  11472. goog.require('goog.events');
  11473. goog.require('goog.events.Event');
  11474. goog.require('ol.Observable');
  11475. /**
  11476. * @enum {string}
  11477. */
  11478. ol.ObjectEventType = {
  11479. /**
  11480. * Triggered when a property is changed.
  11481. * @event ol.ObjectEvent#propertychange
  11482. * @api stable
  11483. */
  11484. PROPERTYCHANGE: 'propertychange'
  11485. };
  11486. /**
  11487. * @classdesc
  11488. * Events emitted by {@link ol.Object} instances are instances of this type.
  11489. *
  11490. * @param {string} type The event type.
  11491. * @param {string} key The property name.
  11492. * @param {*} oldValue The old value for `key`.
  11493. * @extends {goog.events.Event}
  11494. * @implements {oli.ObjectEvent}
  11495. * @constructor
  11496. */
  11497. ol.ObjectEvent = function(type, key, oldValue) {
  11498. goog.base(this, type);
  11499. /**
  11500. * The name of the property whose value is changing.
  11501. * @type {string}
  11502. * @api stable
  11503. */
  11504. this.key = key;
  11505. /**
  11506. * The old value. To get the new value use `e.target.get(e.key)` where
  11507. * `e` is the event object.
  11508. * @type {*}
  11509. * @api stable
  11510. */
  11511. this.oldValue = oldValue;
  11512. };
  11513. goog.inherits(ol.ObjectEvent, goog.events.Event);
  11514. /**
  11515. * @classdesc
  11516. * Abstract base class; normally only used for creating subclasses and not
  11517. * instantiated in apps.
  11518. * Most non-trivial classes inherit from this.
  11519. *
  11520. * This extends {@link ol.Observable} with observable properties, where each
  11521. * property is observable as well as the object as a whole.
  11522. *
  11523. * Classes that inherit from this have pre-defined properties, to which you can
  11524. * add your owns. The pre-defined properties are listed in this documentation as
  11525. * 'Observable Properties', and have their own accessors; for example,
  11526. * {@link ol.Map} has a `target` property, accessed with `getTarget()` and
  11527. * changed with `setTarget()`. Not all properties are however settable. There
  11528. * are also general-purpose accessors `get()` and `set()`. For example,
  11529. * `get('target')` is equivalent to `getTarget()`.
  11530. *
  11531. * The `set` accessors trigger a change event, and you can monitor this by
  11532. * registering a listener. For example, {@link ol.View} has a `center`
  11533. * property, so `view.on('change:center', function(evt) {...});` would call the
  11534. * function whenever the value of the center property changes. Within the
  11535. * function, `evt.target` would be the view, so `evt.target.getCenter()` would
  11536. * return the new center.
  11537. *
  11538. * You can add your own observable properties with
  11539. * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`.
  11540. * You can listen for changes on that property value with
  11541. * `object.on('change:prop', listener)`. You can get a list of all
  11542. * properties with {@link ol.Object#getProperties object.getProperties()}.
  11543. *
  11544. * Note that the observable properties are separate from standard JS properties.
  11545. * You can, for example, give your map object a title with
  11546. * `map.title='New title'` and with `map.set('title', 'Another title')`. The
  11547. * first will be a `hasOwnProperty`; the second will appear in
  11548. * `getProperties()`. Only the second is observable.
  11549. *
  11550. * Properties can be deleted by using the unset method. E.g.
  11551. * object.unset('foo').
  11552. *
  11553. * @constructor
  11554. * @extends {ol.Observable}
  11555. * @param {Object.<string, *>=} opt_values An object with key-value pairs.
  11556. * @fires ol.ObjectEvent
  11557. * @api
  11558. */
  11559. ol.Object = function(opt_values) {
  11560. goog.base(this);
  11561. // Call goog.getUid to ensure that the order of objects' ids is the same as
  11562. // the order in which they were created. This also helps to ensure that
  11563. // object properties are always added in the same order, which helps many
  11564. // JavaScript engines generate faster code.
  11565. goog.getUid(this);
  11566. /**
  11567. * @private
  11568. * @type {!Object.<string, *>}
  11569. */
  11570. this.values_ = {};
  11571. if (opt_values !== undefined) {
  11572. this.setProperties(opt_values);
  11573. }
  11574. };
  11575. goog.inherits(ol.Object, ol.Observable);
  11576. /**
  11577. * @private
  11578. * @type {Object.<string, string>}
  11579. */
  11580. ol.Object.changeEventTypeCache_ = {};
  11581. /**
  11582. * @param {string} key Key name.
  11583. * @return {string} Change name.
  11584. */
  11585. ol.Object.getChangeEventType = function(key) {
  11586. return ol.Object.changeEventTypeCache_.hasOwnProperty(key) ?
  11587. ol.Object.changeEventTypeCache_[key] :
  11588. (ol.Object.changeEventTypeCache_[key] = 'change:' + key);
  11589. };
  11590. /**
  11591. * Gets a value.
  11592. * @param {string} key Key name.
  11593. * @return {*} Value.
  11594. * @api stable
  11595. */
  11596. ol.Object.prototype.get = function(key) {
  11597. var value;
  11598. if (this.values_.hasOwnProperty(key)) {
  11599. value = this.values_[key];
  11600. }
  11601. return value;
  11602. };
  11603. /**
  11604. * Get a list of object property names.
  11605. * @return {Array.<string>} List of property names.
  11606. * @api stable
  11607. */
  11608. ol.Object.prototype.getKeys = function() {
  11609. return Object.keys(this.values_);
  11610. };
  11611. /**
  11612. * Get an object of all property names and values.
  11613. * @return {Object.<string, *>} Object.
  11614. * @api stable
  11615. */
  11616. ol.Object.prototype.getProperties = function() {
  11617. var properties = {};
  11618. var key;
  11619. for (key in this.values_) {
  11620. properties[key] = this.values_[key];
  11621. }
  11622. return properties;
  11623. };
  11624. /**
  11625. * @param {string} key Key name.
  11626. * @param {*} oldValue Old value.
  11627. */
  11628. ol.Object.prototype.notify = function(key, oldValue) {
  11629. var eventType;
  11630. eventType = ol.Object.getChangeEventType(key);
  11631. this.dispatchEvent(new ol.ObjectEvent(eventType, key, oldValue));
  11632. eventType = ol.ObjectEventType.PROPERTYCHANGE;
  11633. this.dispatchEvent(new ol.ObjectEvent(eventType, key, oldValue));
  11634. };
  11635. /**
  11636. * Sets a value.
  11637. * @param {string} key Key name.
  11638. * @param {*} value Value.
  11639. * @api stable
  11640. */
  11641. ol.Object.prototype.set = function(key, value) {
  11642. var oldValue = this.values_[key];
  11643. this.values_[key] = value;
  11644. this.notify(key, oldValue);
  11645. };
  11646. /**
  11647. * Sets a collection of key-value pairs. Note that this changes any existing
  11648. * properties and adds new ones (it does not remove any existing properties).
  11649. * @param {Object.<string, *>} values Values.
  11650. * @api stable
  11651. */
  11652. ol.Object.prototype.setProperties = function(values) {
  11653. var key;
  11654. for (key in values) {
  11655. this.set(key, values[key]);
  11656. }
  11657. };
  11658. /**
  11659. * Unsets a property.
  11660. * @param {string} key Key name.
  11661. * @api stable
  11662. */
  11663. ol.Object.prototype.unset = function(key) {
  11664. if (key in this.values_) {
  11665. var oldValue = this.values_[key];
  11666. delete this.values_[key];
  11667. this.notify(key, oldValue);
  11668. }
  11669. };
  11670. goog.provide('ol.Size');
  11671. goog.provide('ol.size');
  11672. goog.require('goog.asserts');
  11673. /**
  11674. * An array of numbers representing a size: `[width, height]`.
  11675. * @typedef {Array.<number>}
  11676. * @api stable
  11677. */
  11678. ol.Size;
  11679. /**
  11680. * Returns a buffered size.
  11681. * @param {ol.Size} size Size.
  11682. * @param {number} buffer Buffer.
  11683. * @param {ol.Size=} opt_size Optional reusable size array.
  11684. * @return {ol.Size}
  11685. */
  11686. ol.size.buffer = function(size, buffer, opt_size) {
  11687. if (opt_size === undefined) {
  11688. opt_size = [0, 0];
  11689. }
  11690. opt_size[0] = size[0] + 2 * buffer;
  11691. opt_size[1] = size[1] + 2 * buffer;
  11692. return opt_size;
  11693. };
  11694. /**
  11695. * Compares sizes for equality.
  11696. * @param {ol.Size} a Size.
  11697. * @param {ol.Size} b Size.
  11698. * @return {boolean} Equals.
  11699. */
  11700. ol.size.equals = function(a, b) {
  11701. return a[0] == b[0] && a[1] == b[1];
  11702. };
  11703. /**
  11704. * Determines if a size has a positive area.
  11705. * @param {ol.Size} size The size to test.
  11706. * @return {boolean} The size has a positive area.
  11707. */
  11708. ol.size.hasArea = function(size) {
  11709. return size[0] > 0 && size[1] > 0;
  11710. };
  11711. /**
  11712. * Returns a size scaled by a ratio. The result will be an array of integers.
  11713. * @param {ol.Size} size Size.
  11714. * @param {number} ratio Ratio.
  11715. * @param {ol.Size=} opt_size Optional reusable size array.
  11716. * @return {ol.Size}
  11717. */
  11718. ol.size.scale = function(size, ratio, opt_size) {
  11719. if (opt_size === undefined) {
  11720. opt_size = [0, 0];
  11721. }
  11722. opt_size[0] = (size[0] * ratio + 0.5) | 0;
  11723. opt_size[1] = (size[1] * ratio + 0.5) | 0;
  11724. return opt_size;
  11725. };
  11726. /**
  11727. * Returns an `ol.Size` array for the passed in number (meaning: square) or
  11728. * `ol.Size` array.
  11729. * (meaning: non-square),
  11730. * @param {number|ol.Size} size Width and height.
  11731. * @param {ol.Size=} opt_size Optional reusable size array.
  11732. * @return {ol.Size} Size.
  11733. * @api stable
  11734. */
  11735. ol.size.toSize = function(size, opt_size) {
  11736. if (goog.isArray(size)) {
  11737. return size;
  11738. } else {
  11739. goog.asserts.assert(goog.isNumber(size));
  11740. if (opt_size === undefined) {
  11741. opt_size = [size, size];
  11742. } else {
  11743. opt_size[0] = size;
  11744. opt_size[1] = size;
  11745. }
  11746. return opt_size;
  11747. }
  11748. };
  11749. goog.provide('ol.Coordinate');
  11750. goog.provide('ol.CoordinateFormatType');
  11751. goog.provide('ol.coordinate');
  11752. goog.require('goog.math');
  11753. goog.require('goog.string');
  11754. /**
  11755. * A function that takes a {@link ol.Coordinate} and transforms it into a
  11756. * `{string}`.
  11757. *
  11758. * @typedef {function((ol.Coordinate|undefined)): string}
  11759. * @api stable
  11760. */
  11761. ol.CoordinateFormatType;
  11762. /**
  11763. * An array of numbers representing an xy coordinate. Example: `[16, 48]`.
  11764. * @typedef {Array.<number>} ol.Coordinate
  11765. * @api stable
  11766. */
  11767. ol.Coordinate;
  11768. /**
  11769. * Add `delta` to `coordinate`. `coordinate` is modified in place and returned
  11770. * by the function.
  11771. *
  11772. * Example:
  11773. *
  11774. * var coord = [7.85, 47.983333];
  11775. * ol.coordinate.add(coord, [-2, 4]);
  11776. * // coord is now [5.85, 51.983333]
  11777. *
  11778. * @param {ol.Coordinate} coordinate Coordinate.
  11779. * @param {ol.Coordinate} delta Delta.
  11780. * @return {ol.Coordinate} The input coordinate adjusted by the given delta.
  11781. * @api stable
  11782. */
  11783. ol.coordinate.add = function(coordinate, delta) {
  11784. coordinate[0] += delta[0];
  11785. coordinate[1] += delta[1];
  11786. return coordinate;
  11787. };
  11788. /**
  11789. * Calculates the point closest to the passed coordinate on the passed segment.
  11790. * This is the foot of the perpendicular of the coordinate to the segment when
  11791. * the foot is on the segment, or the closest segment coordinate when the foot
  11792. * is outside the segment.
  11793. *
  11794. * @param {ol.Coordinate} coordinate The coordinate.
  11795. * @param {Array.<ol.Coordinate>} segment The two coordinates of the segment.
  11796. * @return {ol.Coordinate} The foot of the perpendicular of the coordinate to
  11797. * the segment.
  11798. */
  11799. ol.coordinate.closestOnSegment = function(coordinate, segment) {
  11800. var x0 = coordinate[0];
  11801. var y0 = coordinate[1];
  11802. var start = segment[0];
  11803. var end = segment[1];
  11804. var x1 = start[0];
  11805. var y1 = start[1];
  11806. var x2 = end[0];
  11807. var y2 = end[1];
  11808. var dx = x2 - x1;
  11809. var dy = y2 - y1;
  11810. var along = (dx === 0 && dy === 0) ? 0 :
  11811. ((dx * (x0 - x1)) + (dy * (y0 - y1))) / ((dx * dx + dy * dy) || 0);
  11812. var x, y;
  11813. if (along <= 0) {
  11814. x = x1;
  11815. y = y1;
  11816. } else if (along >= 1) {
  11817. x = x2;
  11818. y = y2;
  11819. } else {
  11820. x = x1 + along * dx;
  11821. y = y1 + along * dy;
  11822. }
  11823. return [x, y];
  11824. };
  11825. /**
  11826. * Returns a {@link ol.CoordinateFormatType} function that can be used to format
  11827. * a {ol.Coordinate} to a string.
  11828. *
  11829. * Example without specifying the fractional digits:
  11830. *
  11831. * var coord = [7.85, 47.983333];
  11832. * var stringifyFunc = ol.coordinate.createStringXY();
  11833. * var out = stringifyFunc(coord);
  11834. * // out is now '8, 48'
  11835. *
  11836. * Example with explicitly specifying 2 fractional digits:
  11837. *
  11838. * var coord = [7.85, 47.983333];
  11839. * var stringifyFunc = ol.coordinate.createStringXY(2);
  11840. * var out = stringifyFunc(coord);
  11841. * // out is now '7.85, 47.98'
  11842. *
  11843. * @param {number=} opt_fractionDigits The number of digits to include
  11844. * after the decimal point. Default is `0`.
  11845. * @return {ol.CoordinateFormatType} Coordinate format.
  11846. * @api stable
  11847. */
  11848. ol.coordinate.createStringXY = function(opt_fractionDigits) {
  11849. return (
  11850. /**
  11851. * @param {ol.Coordinate|undefined} coordinate Coordinate.
  11852. * @return {string} String XY.
  11853. */
  11854. function(coordinate) {
  11855. return ol.coordinate.toStringXY(coordinate, opt_fractionDigits);
  11856. });
  11857. };
  11858. /**
  11859. * @private
  11860. * @param {number} degrees Degrees.
  11861. * @param {string} hemispheres Hemispheres.
  11862. * @return {string} String.
  11863. */
  11864. ol.coordinate.degreesToStringHDMS_ = function(degrees, hemispheres) {
  11865. var normalizedDegrees = goog.math.modulo(degrees + 180, 360) - 180;
  11866. var x = Math.abs(Math.round(3600 * normalizedDegrees));
  11867. return Math.floor(x / 3600) + '\u00b0 ' +
  11868. goog.string.padNumber(Math.floor((x / 60) % 60), 2) + '\u2032 ' +
  11869. goog.string.padNumber(Math.floor(x % 60), 2) + '\u2033 ' +
  11870. hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0);
  11871. };
  11872. /**
  11873. * Transforms the given {@link ol.Coordinate} to a string using the given string
  11874. * template. The strings `{x}` and `{y}` in the template will be replaced with
  11875. * the first and second coordinate values respectively.
  11876. *
  11877. * Example without specifying the fractional digits:
  11878. *
  11879. * var coord = [7.85, 47.983333];
  11880. * var template = 'Coordinate is ({x}|{y}).';
  11881. * var out = ol.coordinate.format(coord, template);
  11882. * // out is now 'Coordinate is (8|48).'
  11883. *
  11884. * Example explicitly specifying the fractional digits:
  11885. *
  11886. * var coord = [7.85, 47.983333];
  11887. * var template = 'Coordinate is ({x}|{y}).';
  11888. * var out = ol.coordinate.format(coord, template, 2);
  11889. * // out is now 'Coordinate is (7.85|47.98).'
  11890. *
  11891. * @param {ol.Coordinate|undefined} coordinate Coordinate.
  11892. * @param {string} template A template string with `{x}` and `{y}` placeholders
  11893. * that will be replaced by first and second coordinate values.
  11894. * @param {number=} opt_fractionDigits The number of digits to include
  11895. * after the decimal point. Default is `0`.
  11896. * @return {string} Formatted coordinate.
  11897. * @api stable
  11898. */
  11899. ol.coordinate.format = function(coordinate, template, opt_fractionDigits) {
  11900. if (coordinate) {
  11901. return template
  11902. .replace('{x}', coordinate[0].toFixed(opt_fractionDigits))
  11903. .replace('{y}', coordinate[1].toFixed(opt_fractionDigits));
  11904. } else {
  11905. return '';
  11906. }
  11907. };
  11908. /**
  11909. * @param {ol.Coordinate} coordinate1 First coordinate.
  11910. * @param {ol.Coordinate} coordinate2 Second coordinate.
  11911. * @return {boolean} Whether the passed coordinates are equal.
  11912. */
  11913. ol.coordinate.equals = function(coordinate1, coordinate2) {
  11914. var equals = true;
  11915. for (var i = coordinate1.length - 1; i >= 0; --i) {
  11916. if (coordinate1[i] != coordinate2[i]) {
  11917. equals = false;
  11918. break;
  11919. }
  11920. }
  11921. return equals;
  11922. };
  11923. /**
  11924. * Rotate `coordinate` by `angle`. `coordinate` is modified in place and
  11925. * returned by the function.
  11926. *
  11927. * Example:
  11928. *
  11929. * var coord = [7.85, 47.983333];
  11930. * var rotateRadians = Math.PI / 2; // 90 degrees
  11931. * ol.coordinate.rotate(coord, rotateRadians);
  11932. * // coord is now [-47.983333, 7.85]
  11933. *
  11934. * @param {ol.Coordinate} coordinate Coordinate.
  11935. * @param {number} angle Angle in radian.
  11936. * @return {ol.Coordinate} Coordinate.
  11937. * @api stable
  11938. */
  11939. ol.coordinate.rotate = function(coordinate, angle) {
  11940. var cosAngle = Math.cos(angle);
  11941. var sinAngle = Math.sin(angle);
  11942. var x = coordinate[0] * cosAngle - coordinate[1] * sinAngle;
  11943. var y = coordinate[1] * cosAngle + coordinate[0] * sinAngle;
  11944. coordinate[0] = x;
  11945. coordinate[1] = y;
  11946. return coordinate;
  11947. };
  11948. /**
  11949. * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned
  11950. * by the function.
  11951. *
  11952. * Example:
  11953. *
  11954. * var coord = [7.85, 47.983333];
  11955. * var scale = 1.2;
  11956. * ol.coordinate.scale(coord, scale);
  11957. * // coord is now [9.42, 57.5799996]
  11958. *
  11959. * @param {ol.Coordinate} coordinate Coordinate.
  11960. * @param {number} scale Scale factor.
  11961. * @return {ol.Coordinate} Coordinate.
  11962. */
  11963. ol.coordinate.scale = function(coordinate, scale) {
  11964. coordinate[0] *= scale;
  11965. coordinate[1] *= scale;
  11966. return coordinate;
  11967. };
  11968. /**
  11969. * Subtract `delta` to `coordinate`. `coordinate` is modified in place and
  11970. * returned by the function.
  11971. *
  11972. * @param {ol.Coordinate} coordinate Coordinate.
  11973. * @param {ol.Coordinate} delta Delta.
  11974. * @return {ol.Coordinate} Coordinate.
  11975. */
  11976. ol.coordinate.sub = function(coordinate, delta) {
  11977. coordinate[0] -= delta[0];
  11978. coordinate[1] -= delta[1];
  11979. return coordinate;
  11980. };
  11981. /**
  11982. * @param {ol.Coordinate} coord1 First coordinate.
  11983. * @param {ol.Coordinate} coord2 Second coordinate.
  11984. * @return {number} Squared distance between coord1 and coord2.
  11985. */
  11986. ol.coordinate.squaredDistance = function(coord1, coord2) {
  11987. var dx = coord1[0] - coord2[0];
  11988. var dy = coord1[1] - coord2[1];
  11989. return dx * dx + dy * dy;
  11990. };
  11991. /**
  11992. * Calculate the squared distance from a coordinate to a line segment.
  11993. *
  11994. * @param {ol.Coordinate} coordinate Coordinate of the point.
  11995. * @param {Array.<ol.Coordinate>} segment Line segment (2 coordinates).
  11996. * @return {number} Squared distance from the point to the line segment.
  11997. */
  11998. ol.coordinate.squaredDistanceToSegment = function(coordinate, segment) {
  11999. return ol.coordinate.squaredDistance(coordinate,
  12000. ol.coordinate.closestOnSegment(coordinate, segment));
  12001. };
  12002. /**
  12003. * Format a geographic coordinate with the hemisphere, degrees, minutes, and
  12004. * seconds.
  12005. *
  12006. * Example:
  12007. *
  12008. * var coord = [7.85, 47.983333];
  12009. * var out = ol.coordinate.toStringHDMS(coord);
  12010. * // out is now '47° 59′ 0″ N 7° 51′ 0″ E'
  12011. *
  12012. * @param {ol.Coordinate|undefined} coordinate Coordinate.
  12013. * @return {string} Hemisphere, degrees, minutes and seconds.
  12014. * @api stable
  12015. */
  12016. ol.coordinate.toStringHDMS = function(coordinate) {
  12017. if (coordinate) {
  12018. return ol.coordinate.degreesToStringHDMS_(coordinate[1], 'NS') + ' ' +
  12019. ol.coordinate.degreesToStringHDMS_(coordinate[0], 'EW');
  12020. } else {
  12021. return '';
  12022. }
  12023. };
  12024. /**
  12025. * Format a coordinate as a comma delimited string.
  12026. *
  12027. * Example without specifying fractional digits:
  12028. *
  12029. * var coord = [7.85, 47.983333];
  12030. * var out = ol.coordinate.toStringXY(coord);
  12031. * // out is now '8, 48'
  12032. *
  12033. * Example explicitly specifying 1 fractional digit:
  12034. *
  12035. * var coord = [7.85, 47.983333];
  12036. * var out = ol.coordinate.toStringXY(coord, 1);
  12037. * // out is now '7.8, 48.0'
  12038. *
  12039. * @param {ol.Coordinate|undefined} coordinate Coordinate.
  12040. * @param {number=} opt_fractionDigits The number of digits to include
  12041. * after the decimal point. Default is `0`.
  12042. * @return {string} XY.
  12043. * @api stable
  12044. */
  12045. ol.coordinate.toStringXY = function(coordinate, opt_fractionDigits) {
  12046. return ol.coordinate.format(coordinate, '{x}, {y}', opt_fractionDigits);
  12047. };
  12048. /**
  12049. * Create an ol.Coordinate from an Array and take into account axis order.
  12050. *
  12051. * Examples:
  12052. *
  12053. * var northCoord = ol.coordinate.fromProjectedArray([1, 2], 'n');
  12054. * // northCoord is now [2, 1]
  12055. *
  12056. * var eastCoord = ol.coordinate.fromProjectedArray([1, 2], 'e');
  12057. * // eastCoord is now [1, 2]
  12058. *
  12059. * @param {Array} array The array with coordinates.
  12060. * @param {string} axis the axis info.
  12061. * @return {ol.Coordinate} The coordinate created.
  12062. */
  12063. ol.coordinate.fromProjectedArray = function(array, axis) {
  12064. var firstAxis = axis.charAt(0);
  12065. if (firstAxis === 'n' || firstAxis === 's') {
  12066. return [array[1], array[0]];
  12067. } else {
  12068. return array;
  12069. }
  12070. };
  12071. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  12072. //
  12073. // Licensed under the Apache License, Version 2.0 (the "License");
  12074. // you may not use this file except in compliance with the License.
  12075. // You may obtain a copy of the License at
  12076. //
  12077. // http://www.apache.org/licenses/LICENSE-2.0
  12078. //
  12079. // Unless required by applicable law or agreed to in writing, software
  12080. // distributed under the License is distributed on an "AS-IS" BASIS,
  12081. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12082. // See the License for the specific language governing permissions and
  12083. // limitations under the License.
  12084. /**
  12085. * @fileoverview Supplies a Float32Array implementation that implements
  12086. * most of the Float32Array spec and that can be used when a built-in
  12087. * implementation is not available.
  12088. *
  12089. * Note that if no existing Float32Array implementation is found then
  12090. * this class and all its public properties are exported as Float32Array.
  12091. *
  12092. * Adding support for the other TypedArray classes here does not make sense
  12093. * since this vector math library only needs Float32Array.
  12094. *
  12095. */
  12096. goog.provide('goog.vec.Float32Array');
  12097. /**
  12098. * Constructs a new Float32Array. The new array is initialized to all zeros.
  12099. *
  12100. * @param {goog.vec.Float32Array|Array|ArrayBuffer|number} p0
  12101. * The length of the array, or an array to initialize the contents of the
  12102. * new Float32Array.
  12103. * @constructor
  12104. * @final
  12105. */
  12106. goog.vec.Float32Array = function(p0) {
  12107. this.length = /** @type {number} */ (p0.length || p0);
  12108. for (var i = 0; i < this.length; i++) {
  12109. this[i] = p0[i] || 0;
  12110. }
  12111. };
  12112. /**
  12113. * The number of bytes in an element (as defined by the Typed Array
  12114. * specification).
  12115. *
  12116. * @type {number}
  12117. */
  12118. goog.vec.Float32Array.BYTES_PER_ELEMENT = 4;
  12119. /**
  12120. * The number of bytes in an element (as defined by the Typed Array
  12121. * specification).
  12122. *
  12123. * @type {number}
  12124. */
  12125. goog.vec.Float32Array.prototype.BYTES_PER_ELEMENT = 4;
  12126. /**
  12127. * Sets elements of the array.
  12128. * @param {Array<number>|Float32Array} values The array of values.
  12129. * @param {number=} opt_offset The offset in this array to start.
  12130. */
  12131. goog.vec.Float32Array.prototype.set = function(values, opt_offset) {
  12132. opt_offset = opt_offset || 0;
  12133. for (var i = 0; i < values.length && opt_offset + i < this.length; i++) {
  12134. this[opt_offset + i] = values[i];
  12135. }
  12136. };
  12137. /**
  12138. * Creates a string representation of this array.
  12139. * @return {string} The string version of this array.
  12140. * @override
  12141. */
  12142. goog.vec.Float32Array.prototype.toString = Array.prototype.join;
  12143. /**
  12144. * Note that we cannot implement the subarray() or (deprecated) slice()
  12145. * methods properly since doing so would require being able to overload
  12146. * the [] operator which is not possible in javascript. So we leave
  12147. * them unimplemented. Any attempt to call these methods will just result
  12148. * in a javascript error since we leave them undefined.
  12149. */
  12150. /**
  12151. * If no existing Float32Array implementation is found then we export
  12152. * goog.vec.Float32Array as Float32Array.
  12153. */
  12154. if (typeof Float32Array == 'undefined') {
  12155. goog.exportProperty(goog.vec.Float32Array, 'BYTES_PER_ELEMENT',
  12156. goog.vec.Float32Array.BYTES_PER_ELEMENT);
  12157. goog.exportProperty(goog.vec.Float32Array.prototype, 'BYTES_PER_ELEMENT',
  12158. goog.vec.Float32Array.prototype.BYTES_PER_ELEMENT);
  12159. goog.exportProperty(goog.vec.Float32Array.prototype, 'set',
  12160. goog.vec.Float32Array.prototype.set);
  12161. goog.exportProperty(goog.vec.Float32Array.prototype, 'toString',
  12162. goog.vec.Float32Array.prototype.toString);
  12163. goog.exportSymbol('Float32Array', goog.vec.Float32Array);
  12164. }
  12165. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  12166. //
  12167. // Licensed under the Apache License, Version 2.0 (the "License");
  12168. // you may not use this file except in compliance with the License.
  12169. // You may obtain a copy of the License at
  12170. //
  12171. // http://www.apache.org/licenses/LICENSE-2.0
  12172. //
  12173. // Unless required by applicable law or agreed to in writing, software
  12174. // distributed under the License is distributed on an "AS-IS" BASIS,
  12175. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12176. // See the License for the specific language governing permissions and
  12177. // limitations under the License.
  12178. /**
  12179. * @fileoverview Supplies a Float64Array implementation that implements
  12180. * most of the Float64Array spec and that can be used when a built-in
  12181. * implementation is not available.
  12182. *
  12183. * Note that if no existing Float64Array implementation is found then this
  12184. * class and all its public properties are exported as Float64Array.
  12185. *
  12186. * Adding support for the other TypedArray classes here does not make sense
  12187. * since this vector math library only needs Float32Array and Float64Array.
  12188. *
  12189. */
  12190. goog.provide('goog.vec.Float64Array');
  12191. /**
  12192. * Constructs a new Float64Array. The new array is initialized to all zeros.
  12193. *
  12194. * @param {goog.vec.Float64Array|Array|ArrayBuffer|number} p0
  12195. * The length of the array, or an array to initialize the contents of the
  12196. * new Float64Array.
  12197. * @constructor
  12198. * @final
  12199. */
  12200. goog.vec.Float64Array = function(p0) {
  12201. this.length = /** @type {number} */ (p0.length || p0);
  12202. for (var i = 0; i < this.length; i++) {
  12203. this[i] = p0[i] || 0;
  12204. }
  12205. };
  12206. /**
  12207. * The number of bytes in an element (as defined by the Typed Array
  12208. * specification).
  12209. *
  12210. * @type {number}
  12211. */
  12212. goog.vec.Float64Array.BYTES_PER_ELEMENT = 8;
  12213. /**
  12214. * The number of bytes in an element (as defined by the Typed Array
  12215. * specification).
  12216. *
  12217. * @type {number}
  12218. */
  12219. goog.vec.Float64Array.prototype.BYTES_PER_ELEMENT = 8;
  12220. /**
  12221. * Sets elements of the array.
  12222. * @param {Array<number>|Float64Array} values The array of values.
  12223. * @param {number=} opt_offset The offset in this array to start.
  12224. */
  12225. goog.vec.Float64Array.prototype.set = function(values, opt_offset) {
  12226. opt_offset = opt_offset || 0;
  12227. for (var i = 0; i < values.length && opt_offset + i < this.length; i++) {
  12228. this[opt_offset + i] = values[i];
  12229. }
  12230. };
  12231. /**
  12232. * Creates a string representation of this array.
  12233. * @return {string} The string version of this array.
  12234. * @override
  12235. */
  12236. goog.vec.Float64Array.prototype.toString = Array.prototype.join;
  12237. /**
  12238. * Note that we cannot implement the subarray() or (deprecated) slice()
  12239. * methods properly since doing so would require being able to overload
  12240. * the [] operator which is not possible in javascript. So we leave
  12241. * them unimplemented. Any attempt to call these methods will just result
  12242. * in a javascript error since we leave them undefined.
  12243. */
  12244. /**
  12245. * If no existing Float64Array implementation is found then we export
  12246. * goog.vec.Float64Array as Float64Array.
  12247. */
  12248. if (typeof Float64Array == 'undefined') {
  12249. try {
  12250. goog.exportProperty(goog.vec.Float64Array, 'BYTES_PER_ELEMENT',
  12251. goog.vec.Float64Array.BYTES_PER_ELEMENT);
  12252. } catch (float64ArrayError) {
  12253. // Do nothing. This code is in place to fix b/7225850, in which an error
  12254. // is incorrectly thrown for Google TV on an old Chrome.
  12255. // TODO(user): remove after that version is retired.
  12256. }
  12257. goog.exportProperty(goog.vec.Float64Array.prototype, 'BYTES_PER_ELEMENT',
  12258. goog.vec.Float64Array.prototype.BYTES_PER_ELEMENT);
  12259. goog.exportProperty(goog.vec.Float64Array.prototype, 'set',
  12260. goog.vec.Float64Array.prototype.set);
  12261. goog.exportProperty(goog.vec.Float64Array.prototype, 'toString',
  12262. goog.vec.Float64Array.prototype.toString);
  12263. goog.exportSymbol('Float64Array', goog.vec.Float64Array);
  12264. }
  12265. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  12266. //
  12267. // Licensed under the Apache License, Version 2.0 (the "License");
  12268. // you may not use this file except in compliance with the License.
  12269. // You may obtain a copy of the License at
  12270. //
  12271. // http://www.apache.org/licenses/LICENSE-2.0
  12272. //
  12273. // Unless required by applicable law or agreed to in writing, software
  12274. // distributed under the License is distributed on an "AS-IS" BASIS,
  12275. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12276. // See the License for the specific language governing permissions and
  12277. // limitations under the License.
  12278. /**
  12279. * @fileoverview Supplies global data types and constants for the vector math
  12280. * library.
  12281. */
  12282. goog.provide('goog.vec');
  12283. goog.provide('goog.vec.AnyType');
  12284. goog.provide('goog.vec.ArrayType');
  12285. goog.provide('goog.vec.Float32');
  12286. goog.provide('goog.vec.Float64');
  12287. goog.provide('goog.vec.Number');
  12288. /**
  12289. * On platforms that don't have native Float32Array or Float64Array support we
  12290. * use a javascript implementation so that this math library can be used on all
  12291. * platforms.
  12292. * @suppress {extraRequire}
  12293. */
  12294. goog.require('goog.vec.Float32Array');
  12295. /** @suppress {extraRequire} */
  12296. goog.require('goog.vec.Float64Array');
  12297. // All vector and matrix operations are based upon arrays of numbers using
  12298. // either Float32Array, Float64Array, or a standard Javascript Array of
  12299. // Numbers.
  12300. /** @typedef {!Float32Array} */
  12301. goog.vec.Float32;
  12302. /** @typedef {!Float64Array} */
  12303. goog.vec.Float64;
  12304. /** @typedef {!Array<number>} */
  12305. goog.vec.Number;
  12306. /** @typedef {!goog.vec.Float32|!goog.vec.Float64|!goog.vec.Number} */
  12307. goog.vec.AnyType;
  12308. /**
  12309. * @deprecated Use AnyType.
  12310. * @typedef {!Float32Array|!Array<number>}
  12311. */
  12312. goog.vec.ArrayType;
  12313. /**
  12314. * For graphics work, 6 decimal places of accuracy are typically all that is
  12315. * required.
  12316. *
  12317. * @type {number}
  12318. * @const
  12319. */
  12320. goog.vec.EPSILON = 1e-6;
  12321. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  12322. //
  12323. // Licensed under the Apache License, Version 2.0 (the "License");
  12324. // you may not use this file except in compliance with the License.
  12325. // You may obtain a copy of the License at
  12326. //
  12327. // http://www.apache.org/licenses/LICENSE-2.0
  12328. //
  12329. // Unless required by applicable law or agreed to in writing, software
  12330. // distributed under the License is distributed on an "AS-IS" BASIS,
  12331. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12332. // See the License for the specific language governing permissions and
  12333. // limitations under the License.
  12334. /**
  12335. * @fileoverview Supplies 3 element vectors that are compatible with WebGL.
  12336. * Each element is a float32 since that is typically the desired size of a
  12337. * 3-vector in the GPU. The API is structured to avoid unnecessary memory
  12338. * allocations. The last parameter will typically be the output vector and
  12339. * an object can be both an input and output parameter to all methods except
  12340. * where noted.
  12341. *
  12342. */
  12343. goog.provide('goog.vec.Vec3');
  12344. /** @suppress {extraRequire} */
  12345. goog.require('goog.vec');
  12346. /** @typedef {goog.vec.Float32} */ goog.vec.Vec3.Float32;
  12347. /** @typedef {goog.vec.Float64} */ goog.vec.Vec3.Float64;
  12348. /** @typedef {goog.vec.Number} */ goog.vec.Vec3.Number;
  12349. /** @typedef {goog.vec.AnyType} */ goog.vec.Vec3.AnyType;
  12350. // The following two types are deprecated - use the above types instead.
  12351. /** @typedef {Float32Array} */ goog.vec.Vec3.Type;
  12352. /** @typedef {goog.vec.ArrayType} */ goog.vec.Vec3.Vec3Like;
  12353. /**
  12354. * Creates a 3 element vector of Float32. The array is initialized to zero.
  12355. *
  12356. * @return {!goog.vec.Vec3.Float32} The new 3 element array.
  12357. */
  12358. goog.vec.Vec3.createFloat32 = function() {
  12359. return new Float32Array(3);
  12360. };
  12361. /**
  12362. * Creates a 3 element vector of Float64. The array is initialized to zero.
  12363. *
  12364. * @return {!goog.vec.Vec3.Float64} The new 3 element array.
  12365. */
  12366. goog.vec.Vec3.createFloat64 = function() {
  12367. return new Float64Array(3);
  12368. };
  12369. /**
  12370. * Creates a 3 element vector of Number. The array is initialized to zero.
  12371. *
  12372. * @return {!goog.vec.Vec3.Number} The new 3 element array.
  12373. */
  12374. goog.vec.Vec3.createNumber = function() {
  12375. var a = new Array(3);
  12376. goog.vec.Vec3.setFromValues(a, 0, 0, 0);
  12377. return a;
  12378. };
  12379. /**
  12380. * Creates a 3 element vector of Float32Array. The array is initialized to zero.
  12381. *
  12382. * @deprecated Use createFloat32.
  12383. * @return {!goog.vec.Vec3.Type} The new 3 element array.
  12384. */
  12385. goog.vec.Vec3.create = function() {
  12386. return new Float32Array(3);
  12387. };
  12388. /**
  12389. * Creates a new 3 element FLoat32 vector initialized with the value from the
  12390. * given array.
  12391. *
  12392. * @param {goog.vec.Vec3.AnyType} vec The source 3 element array.
  12393. * @return {!goog.vec.Vec3.Float32} The new 3 element array.
  12394. */
  12395. goog.vec.Vec3.createFloat32FromArray = function(vec) {
  12396. var newVec = goog.vec.Vec3.createFloat32();
  12397. goog.vec.Vec3.setFromArray(newVec, vec);
  12398. return newVec;
  12399. };
  12400. /**
  12401. * Creates a new 3 element Float32 vector initialized with the supplied values.
  12402. *
  12403. * @param {number} v0 The value for element at index 0.
  12404. * @param {number} v1 The value for element at index 1.
  12405. * @param {number} v2 The value for element at index 2.
  12406. * @return {!goog.vec.Vec3.Float32} The new vector.
  12407. */
  12408. goog.vec.Vec3.createFloat32FromValues = function(v0, v1, v2) {
  12409. var a = goog.vec.Vec3.createFloat32();
  12410. goog.vec.Vec3.setFromValues(a, v0, v1, v2);
  12411. return a;
  12412. };
  12413. /**
  12414. * Creates a clone of the given 3 element Float32 vector.
  12415. *
  12416. * @param {goog.vec.Vec3.Float32} vec The source 3 element vector.
  12417. * @return {!goog.vec.Vec3.Float32} The new cloned vector.
  12418. */
  12419. goog.vec.Vec3.cloneFloat32 = goog.vec.Vec3.createFloat32FromArray;
  12420. /**
  12421. * Creates a new 3 element Float64 vector initialized with the value from the
  12422. * given array.
  12423. *
  12424. * @param {goog.vec.Vec3.AnyType} vec The source 3 element array.
  12425. * @return {!goog.vec.Vec3.Float64} The new 3 element array.
  12426. */
  12427. goog.vec.Vec3.createFloat64FromArray = function(vec) {
  12428. var newVec = goog.vec.Vec3.createFloat64();
  12429. goog.vec.Vec3.setFromArray(newVec, vec);
  12430. return newVec;
  12431. };
  12432. /**
  12433. * Creates a new 3 element Float64 vector initialized with the supplied values.
  12434. *
  12435. * @param {number} v0 The value for element at index 0.
  12436. * @param {number} v1 The value for element at index 1.
  12437. * @param {number} v2 The value for element at index 2.
  12438. * @return {!goog.vec.Vec3.Float64} The new vector.
  12439. */
  12440. goog.vec.Vec3.createFloat64FromValues = function(v0, v1, v2) {
  12441. var vec = goog.vec.Vec3.createFloat64();
  12442. goog.vec.Vec3.setFromValues(vec, v0, v1, v2);
  12443. return vec;
  12444. };
  12445. /**
  12446. * Creates a clone of the given 3 element vector.
  12447. *
  12448. * @param {goog.vec.Vec3.Float64} vec The source 3 element vector.
  12449. * @return {!goog.vec.Vec3.Float64} The new cloned vector.
  12450. */
  12451. goog.vec.Vec3.cloneFloat64 = goog.vec.Vec3.createFloat64FromArray;
  12452. /**
  12453. * Creates a new 3 element vector initialized with the value from the given
  12454. * array.
  12455. *
  12456. * @deprecated Use createFloat32FromArray.
  12457. * @param {goog.vec.Vec3.Vec3Like} vec The source 3 element array.
  12458. * @return {!goog.vec.Vec3.Type} The new 3 element array.
  12459. */
  12460. goog.vec.Vec3.createFromArray = function(vec) {
  12461. var newVec = goog.vec.Vec3.create();
  12462. goog.vec.Vec3.setFromArray(newVec, vec);
  12463. return newVec;
  12464. };
  12465. /**
  12466. * Creates a new 3 element vector initialized with the supplied values.
  12467. *
  12468. * @deprecated Use createFloat32FromValues.
  12469. * @param {number} v0 The value for element at index 0.
  12470. * @param {number} v1 The value for element at index 1.
  12471. * @param {number} v2 The value for element at index 2.
  12472. * @return {!goog.vec.Vec3.Type} The new vector.
  12473. */
  12474. goog.vec.Vec3.createFromValues = function(v0, v1, v2) {
  12475. var vec = goog.vec.Vec3.create();
  12476. goog.vec.Vec3.setFromValues(vec, v0, v1, v2);
  12477. return vec;
  12478. };
  12479. /**
  12480. * Creates a clone of the given 3 element vector.
  12481. *
  12482. * @deprecated Use cloneFloat32.
  12483. * @param {goog.vec.Vec3.Vec3Like} vec The source 3 element vector.
  12484. * @return {!goog.vec.Vec3.Type} The new cloned vector.
  12485. */
  12486. goog.vec.Vec3.clone = function(vec) {
  12487. var newVec = goog.vec.Vec3.create();
  12488. goog.vec.Vec3.setFromArray(newVec, vec);
  12489. return newVec;
  12490. };
  12491. /**
  12492. * Initializes the vector with the given values.
  12493. *
  12494. * @param {goog.vec.Vec3.AnyType} vec The vector to receive the values.
  12495. * @param {number} v0 The value for element at index 0.
  12496. * @param {number} v1 The value for element at index 1.
  12497. * @param {number} v2 The value for element at index 2.
  12498. * @return {!goog.vec.Vec3.AnyType} Return vec so that operations can be
  12499. * chained together.
  12500. */
  12501. goog.vec.Vec3.setFromValues = function(vec, v0, v1, v2) {
  12502. vec[0] = v0;
  12503. vec[1] = v1;
  12504. vec[2] = v2;
  12505. return vec;
  12506. };
  12507. /**
  12508. * Initializes the vector with the given array of values.
  12509. *
  12510. * @param {goog.vec.Vec3.AnyType} vec The vector to receive the
  12511. * values.
  12512. * @param {goog.vec.Vec3.AnyType} values The array of values.
  12513. * @return {!goog.vec.Vec3.AnyType} Return vec so that operations can be
  12514. * chained together.
  12515. */
  12516. goog.vec.Vec3.setFromArray = function(vec, values) {
  12517. vec[0] = values[0];
  12518. vec[1] = values[1];
  12519. vec[2] = values[2];
  12520. return vec;
  12521. };
  12522. /**
  12523. * Performs a component-wise addition of vec0 and vec1 together storing the
  12524. * result into resultVec.
  12525. *
  12526. * @param {goog.vec.Vec3.AnyType} vec0 The first addend.
  12527. * @param {goog.vec.Vec3.AnyType} vec1 The second addend.
  12528. * @param {goog.vec.Vec3.AnyType} resultVec The vector to
  12529. * receive the result. May be vec0 or vec1.
  12530. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12531. * chained together.
  12532. */
  12533. goog.vec.Vec3.add = function(vec0, vec1, resultVec) {
  12534. resultVec[0] = vec0[0] + vec1[0];
  12535. resultVec[1] = vec0[1] + vec1[1];
  12536. resultVec[2] = vec0[2] + vec1[2];
  12537. return resultVec;
  12538. };
  12539. /**
  12540. * Performs a component-wise subtraction of vec1 from vec0 storing the
  12541. * result into resultVec.
  12542. *
  12543. * @param {goog.vec.Vec3.AnyType} vec0 The minuend.
  12544. * @param {goog.vec.Vec3.AnyType} vec1 The subtrahend.
  12545. * @param {goog.vec.Vec3.AnyType} resultVec The vector to
  12546. * receive the result. May be vec0 or vec1.
  12547. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12548. * chained together.
  12549. */
  12550. goog.vec.Vec3.subtract = function(vec0, vec1, resultVec) {
  12551. resultVec[0] = vec0[0] - vec1[0];
  12552. resultVec[1] = vec0[1] - vec1[1];
  12553. resultVec[2] = vec0[2] - vec1[2];
  12554. return resultVec;
  12555. };
  12556. /**
  12557. * Negates vec0, storing the result into resultVec.
  12558. *
  12559. * @param {goog.vec.Vec3.AnyType} vec0 The vector to negate.
  12560. * @param {goog.vec.Vec3.AnyType} resultVec The vector to
  12561. * receive the result. May be vec0.
  12562. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12563. * chained together.
  12564. */
  12565. goog.vec.Vec3.negate = function(vec0, resultVec) {
  12566. resultVec[0] = -vec0[0];
  12567. resultVec[1] = -vec0[1];
  12568. resultVec[2] = -vec0[2];
  12569. return resultVec;
  12570. };
  12571. /**
  12572. * Takes the absolute value of each component of vec0 storing the result in
  12573. * resultVec.
  12574. *
  12575. * @param {goog.vec.Vec3.AnyType} vec0 The source vector.
  12576. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the result.
  12577. * May be vec0.
  12578. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12579. * chained together.
  12580. */
  12581. goog.vec.Vec3.abs = function(vec0, resultVec) {
  12582. resultVec[0] = Math.abs(vec0[0]);
  12583. resultVec[1] = Math.abs(vec0[1]);
  12584. resultVec[2] = Math.abs(vec0[2]);
  12585. return resultVec;
  12586. };
  12587. /**
  12588. * Multiplies each component of vec0 with scalar storing the product into
  12589. * resultVec.
  12590. *
  12591. * @param {goog.vec.Vec3.AnyType} vec0 The source vector.
  12592. * @param {number} scalar The value to multiply with each component of vec0.
  12593. * @param {goog.vec.Vec3.AnyType} resultVec The vector to
  12594. * receive the result. May be vec0.
  12595. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12596. * chained together.
  12597. */
  12598. goog.vec.Vec3.scale = function(vec0, scalar, resultVec) {
  12599. resultVec[0] = vec0[0] * scalar;
  12600. resultVec[1] = vec0[1] * scalar;
  12601. resultVec[2] = vec0[2] * scalar;
  12602. return resultVec;
  12603. };
  12604. /**
  12605. * Returns the magnitudeSquared of the given vector.
  12606. *
  12607. * @param {goog.vec.Vec3.AnyType} vec0 The vector.
  12608. * @return {number} The magnitude of the vector.
  12609. */
  12610. goog.vec.Vec3.magnitudeSquared = function(vec0) {
  12611. var x = vec0[0], y = vec0[1], z = vec0[2];
  12612. return x * x + y * y + z * z;
  12613. };
  12614. /**
  12615. * Returns the magnitude of the given vector.
  12616. *
  12617. * @param {goog.vec.Vec3.AnyType} vec0 The vector.
  12618. * @return {number} The magnitude of the vector.
  12619. */
  12620. goog.vec.Vec3.magnitude = function(vec0) {
  12621. var x = vec0[0], y = vec0[1], z = vec0[2];
  12622. return Math.sqrt(x * x + y * y + z * z);
  12623. };
  12624. /**
  12625. * Normalizes the given vector storing the result into resultVec.
  12626. *
  12627. * @param {goog.vec.Vec3.AnyType} vec0 The vector to normalize.
  12628. * @param {goog.vec.Vec3.AnyType} resultVec The vector to
  12629. * receive the result. May be vec0.
  12630. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12631. * chained together.
  12632. */
  12633. goog.vec.Vec3.normalize = function(vec0, resultVec) {
  12634. var ilen = 1 / goog.vec.Vec3.magnitude(vec0);
  12635. resultVec[0] = vec0[0] * ilen;
  12636. resultVec[1] = vec0[1] * ilen;
  12637. resultVec[2] = vec0[2] * ilen;
  12638. return resultVec;
  12639. };
  12640. /**
  12641. * Returns the scalar product of vectors v0 and v1.
  12642. *
  12643. * @param {goog.vec.Vec3.AnyType} v0 The first vector.
  12644. * @param {goog.vec.Vec3.AnyType} v1 The second vector.
  12645. * @return {number} The scalar product.
  12646. */
  12647. goog.vec.Vec3.dot = function(v0, v1) {
  12648. return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2];
  12649. };
  12650. /**
  12651. * Computes the vector (cross) product of v0 and v1 storing the result into
  12652. * resultVec.
  12653. *
  12654. * @param {goog.vec.Vec3.AnyType} v0 The first vector.
  12655. * @param {goog.vec.Vec3.AnyType} v1 The second vector.
  12656. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
  12657. * results. May be either v0 or v1.
  12658. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12659. * chained together.
  12660. */
  12661. goog.vec.Vec3.cross = function(v0, v1, resultVec) {
  12662. var x0 = v0[0], y0 = v0[1], z0 = v0[2];
  12663. var x1 = v1[0], y1 = v1[1], z1 = v1[2];
  12664. resultVec[0] = y0 * z1 - z0 * y1;
  12665. resultVec[1] = z0 * x1 - x0 * z1;
  12666. resultVec[2] = x0 * y1 - y0 * x1;
  12667. return resultVec;
  12668. };
  12669. /**
  12670. * Returns the squared distance between two points.
  12671. *
  12672. * @param {goog.vec.Vec3.AnyType} vec0 First point.
  12673. * @param {goog.vec.Vec3.AnyType} vec1 Second point.
  12674. * @return {number} The squared distance between the points.
  12675. */
  12676. goog.vec.Vec3.distanceSquared = function(vec0, vec1) {
  12677. var x = vec0[0] - vec1[0];
  12678. var y = vec0[1] - vec1[1];
  12679. var z = vec0[2] - vec1[2];
  12680. return x * x + y * y + z * z;
  12681. };
  12682. /**
  12683. * Returns the distance between two points.
  12684. *
  12685. * @param {goog.vec.Vec3.AnyType} vec0 First point.
  12686. * @param {goog.vec.Vec3.AnyType} vec1 Second point.
  12687. * @return {number} The distance between the points.
  12688. */
  12689. goog.vec.Vec3.distance = function(vec0, vec1) {
  12690. return Math.sqrt(goog.vec.Vec3.distanceSquared(vec0, vec1));
  12691. };
  12692. /**
  12693. * Returns a unit vector pointing from one point to another.
  12694. * If the input points are equal then the result will be all zeros.
  12695. *
  12696. * @param {goog.vec.Vec3.AnyType} vec0 Origin point.
  12697. * @param {goog.vec.Vec3.AnyType} vec1 Target point.
  12698. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
  12699. * results (may be vec0 or vec1).
  12700. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12701. * chained together.
  12702. */
  12703. goog.vec.Vec3.direction = function(vec0, vec1, resultVec) {
  12704. var x = vec1[0] - vec0[0];
  12705. var y = vec1[1] - vec0[1];
  12706. var z = vec1[2] - vec0[2];
  12707. var d = Math.sqrt(x * x + y * y + z * z);
  12708. if (d) {
  12709. d = 1 / d;
  12710. resultVec[0] = x * d;
  12711. resultVec[1] = y * d;
  12712. resultVec[2] = z * d;
  12713. } else {
  12714. resultVec[0] = resultVec[1] = resultVec[2] = 0;
  12715. }
  12716. return resultVec;
  12717. };
  12718. /**
  12719. * Linearly interpolate from vec0 to v1 according to f. The value of f should be
  12720. * in the range [0..1] otherwise the results are undefined.
  12721. *
  12722. * @param {goog.vec.Vec3.AnyType} v0 The first vector.
  12723. * @param {goog.vec.Vec3.AnyType} v1 The second vector.
  12724. * @param {number} f The interpolation factor.
  12725. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
  12726. * results (may be v0 or v1).
  12727. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12728. * chained together.
  12729. */
  12730. goog.vec.Vec3.lerp = function(v0, v1, f, resultVec) {
  12731. var x = v0[0], y = v0[1], z = v0[2];
  12732. resultVec[0] = (v1[0] - x) * f + x;
  12733. resultVec[1] = (v1[1] - y) * f + y;
  12734. resultVec[2] = (v1[2] - z) * f + z;
  12735. return resultVec;
  12736. };
  12737. /**
  12738. * Compares the components of vec0 with the components of another vector or
  12739. * scalar, storing the larger values in resultVec.
  12740. *
  12741. * @param {goog.vec.Vec3.AnyType} vec0 The source vector.
  12742. * @param {goog.vec.Vec3.AnyType|number} limit The limit vector or scalar.
  12743. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
  12744. * results (may be vec0 or limit).
  12745. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12746. * chained together.
  12747. */
  12748. goog.vec.Vec3.max = function(vec0, limit, resultVec) {
  12749. if (goog.isNumber(limit)) {
  12750. resultVec[0] = Math.max(vec0[0], limit);
  12751. resultVec[1] = Math.max(vec0[1], limit);
  12752. resultVec[2] = Math.max(vec0[2], limit);
  12753. } else {
  12754. resultVec[0] = Math.max(vec0[0], limit[0]);
  12755. resultVec[1] = Math.max(vec0[1], limit[1]);
  12756. resultVec[2] = Math.max(vec0[2], limit[2]);
  12757. }
  12758. return resultVec;
  12759. };
  12760. /**
  12761. * Compares the components of vec0 with the components of another vector or
  12762. * scalar, storing the smaller values in resultVec.
  12763. *
  12764. * @param {goog.vec.Vec3.AnyType} vec0 The source vector.
  12765. * @param {goog.vec.Vec3.AnyType|number} limit The limit vector or scalar.
  12766. * @param {goog.vec.Vec3.AnyType} resultVec The vector to receive the
  12767. * results (may be vec0 or limit).
  12768. * @return {!goog.vec.Vec3.AnyType} Return resultVec so that operations can be
  12769. * chained together.
  12770. */
  12771. goog.vec.Vec3.min = function(vec0, limit, resultVec) {
  12772. if (goog.isNumber(limit)) {
  12773. resultVec[0] = Math.min(vec0[0], limit);
  12774. resultVec[1] = Math.min(vec0[1], limit);
  12775. resultVec[2] = Math.min(vec0[2], limit);
  12776. } else {
  12777. resultVec[0] = Math.min(vec0[0], limit[0]);
  12778. resultVec[1] = Math.min(vec0[1], limit[1]);
  12779. resultVec[2] = Math.min(vec0[2], limit[2]);
  12780. }
  12781. return resultVec;
  12782. };
  12783. /**
  12784. * Returns true if the components of v0 are equal to the components of v1.
  12785. *
  12786. * @param {goog.vec.Vec3.AnyType} v0 The first vector.
  12787. * @param {goog.vec.Vec3.AnyType} v1 The second vector.
  12788. * @return {boolean} True if the vectors are equal, false otherwise.
  12789. */
  12790. goog.vec.Vec3.equals = function(v0, v1) {
  12791. return v0.length == v1.length &&
  12792. v0[0] == v1[0] && v0[1] == v1[1] && v0[2] == v1[2];
  12793. };
  12794. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  12795. //
  12796. // Licensed under the Apache License, Version 2.0 (the "License");
  12797. // you may not use this file except in compliance with the License.
  12798. // You may obtain a copy of the License at
  12799. //
  12800. // http://www.apache.org/licenses/LICENSE-2.0
  12801. //
  12802. // Unless required by applicable law or agreed to in writing, software
  12803. // distributed under the License is distributed on an "AS-IS" BASIS,
  12804. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12805. // See the License for the specific language governing permissions and
  12806. // limitations under the License.
  12807. /**
  12808. * @fileoverview Supplies 4 element vectors that are compatible with WebGL.
  12809. * Each element is a float32 since that is typically the desired size of a
  12810. * 4-vector in the GPU. The API is structured to avoid unnecessary memory
  12811. * allocations. The last parameter will typically be the output vector and
  12812. * an object can be both an input and output parameter to all methods except
  12813. * where noted.
  12814. *
  12815. */
  12816. goog.provide('goog.vec.Vec4');
  12817. /** @suppress {extraRequire} */
  12818. goog.require('goog.vec');
  12819. /** @typedef {goog.vec.Float32} */ goog.vec.Vec4.Float32;
  12820. /** @typedef {goog.vec.Float64} */ goog.vec.Vec4.Float64;
  12821. /** @typedef {goog.vec.Number} */ goog.vec.Vec4.Number;
  12822. /** @typedef {goog.vec.AnyType} */ goog.vec.Vec4.AnyType;
  12823. // The following two types are deprecated - use the above types instead.
  12824. /** @typedef {Float32Array} */ goog.vec.Vec4.Type;
  12825. /** @typedef {goog.vec.ArrayType} */ goog.vec.Vec4.Vec4Like;
  12826. /**
  12827. * Creates a 4 element vector of Float32. The array is initialized to zero.
  12828. *
  12829. * @return {!goog.vec.Vec4.Float32} The new 3 element array.
  12830. */
  12831. goog.vec.Vec4.createFloat32 = function() {
  12832. return new Float32Array(4);
  12833. };
  12834. /**
  12835. * Creates a 4 element vector of Float64. The array is initialized to zero.
  12836. *
  12837. * @return {!goog.vec.Vec4.Float64} The new 4 element array.
  12838. */
  12839. goog.vec.Vec4.createFloat64 = function() {
  12840. return new Float64Array(4);
  12841. };
  12842. /**
  12843. * Creates a 4 element vector of Number. The array is initialized to zero.
  12844. *
  12845. * @return {!goog.vec.Vec4.Number} The new 4 element array.
  12846. */
  12847. goog.vec.Vec4.createNumber = function() {
  12848. var v = new Array(4);
  12849. goog.vec.Vec4.setFromValues(v, 0, 0, 0, 0);
  12850. return v;
  12851. };
  12852. /**
  12853. * Creates a 4 element vector of Float32Array. The array is initialized to zero.
  12854. *
  12855. * @deprecated Use createFloat32.
  12856. * @return {!goog.vec.Vec4.Type} The new 4 element array.
  12857. */
  12858. goog.vec.Vec4.create = function() {
  12859. return new Float32Array(4);
  12860. };
  12861. /**
  12862. * Creates a new 4 element vector initialized with the value from the given
  12863. * array.
  12864. *
  12865. * @deprecated Use createFloat32FromArray.
  12866. * @param {goog.vec.Vec4.Vec4Like} vec The source 4 element array.
  12867. * @return {!goog.vec.Vec4.Type} The new 4 element array.
  12868. */
  12869. goog.vec.Vec4.createFromArray = function(vec) {
  12870. var newVec = goog.vec.Vec4.create();
  12871. goog.vec.Vec4.setFromArray(newVec, vec);
  12872. return newVec;
  12873. };
  12874. /**
  12875. * Creates a new 4 element FLoat32 vector initialized with the value from the
  12876. * given array.
  12877. *
  12878. * @param {goog.vec.Vec4.AnyType} vec The source 3 element array.
  12879. * @return {!goog.vec.Vec4.Float32} The new 3 element array.
  12880. */
  12881. goog.vec.Vec4.createFloat32FromArray = function(vec) {
  12882. var newVec = goog.vec.Vec4.createFloat32();
  12883. goog.vec.Vec4.setFromArray(newVec, vec);
  12884. return newVec;
  12885. };
  12886. /**
  12887. * Creates a new 4 element Float32 vector initialized with the supplied values.
  12888. *
  12889. * @param {number} v0 The value for element at index 0.
  12890. * @param {number} v1 The value for element at index 1.
  12891. * @param {number} v2 The value for element at index 2.
  12892. * @param {number} v3 The value for element at index 3.
  12893. * @return {!goog.vec.Vec4.Float32} The new vector.
  12894. */
  12895. goog.vec.Vec4.createFloat32FromValues = function(v0, v1, v2, v3) {
  12896. var vec = goog.vec.Vec4.createFloat32();
  12897. goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
  12898. return vec;
  12899. };
  12900. /**
  12901. * Creates a clone of the given 4 element Float32 vector.
  12902. *
  12903. * @param {goog.vec.Vec4.Float32} vec The source 3 element vector.
  12904. * @return {!goog.vec.Vec4.Float32} The new cloned vector.
  12905. */
  12906. goog.vec.Vec4.cloneFloat32 = goog.vec.Vec4.createFloat32FromArray;
  12907. /**
  12908. * Creates a new 4 element Float64 vector initialized with the value from the
  12909. * given array.
  12910. *
  12911. * @param {goog.vec.Vec4.AnyType} vec The source 4 element array.
  12912. * @return {!goog.vec.Vec4.Float64} The new 4 element array.
  12913. */
  12914. goog.vec.Vec4.createFloat64FromArray = function(vec) {
  12915. var newVec = goog.vec.Vec4.createFloat64();
  12916. goog.vec.Vec4.setFromArray(newVec, vec);
  12917. return newVec;
  12918. };
  12919. /**
  12920. * Creates a new 4 element Float64 vector initialized with the supplied values.
  12921. *
  12922. * @param {number} v0 The value for element at index 0.
  12923. * @param {number} v1 The value for element at index 1.
  12924. * @param {number} v2 The value for element at index 2.
  12925. * @param {number} v3 The value for element at index 3.
  12926. * @return {!goog.vec.Vec4.Float64} The new vector.
  12927. */
  12928. goog.vec.Vec4.createFloat64FromValues = function(v0, v1, v2, v3) {
  12929. var vec = goog.vec.Vec4.createFloat64();
  12930. goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
  12931. return vec;
  12932. };
  12933. /**
  12934. * Creates a clone of the given 4 element vector.
  12935. *
  12936. * @param {goog.vec.Vec4.Float64} vec The source 4 element vector.
  12937. * @return {!goog.vec.Vec4.Float64} The new cloned vector.
  12938. */
  12939. goog.vec.Vec4.cloneFloat64 = goog.vec.Vec4.createFloat64FromArray;
  12940. /**
  12941. * Creates a new 4 element vector initialized with the supplied values.
  12942. *
  12943. * @deprecated Use createFloat32FromValues.
  12944. * @param {number} v0 The value for element at index 0.
  12945. * @param {number} v1 The value for element at index 1.
  12946. * @param {number} v2 The value for element at index 2.
  12947. * @param {number} v3 The value for element at index 3.
  12948. * @return {!goog.vec.Vec4.Type} The new vector.
  12949. */
  12950. goog.vec.Vec4.createFromValues = function(v0, v1, v2, v3) {
  12951. var vec = goog.vec.Vec4.create();
  12952. goog.vec.Vec4.setFromValues(vec, v0, v1, v2, v3);
  12953. return vec;
  12954. };
  12955. /**
  12956. * Creates a clone of the given 4 element vector.
  12957. *
  12958. * @deprecated Use cloneFloat32.
  12959. * @param {goog.vec.Vec4.Vec4Like} vec The source 4 element vector.
  12960. * @return {!goog.vec.Vec4.Type} The new cloned vector.
  12961. */
  12962. goog.vec.Vec4.clone = goog.vec.Vec4.createFromArray;
  12963. /**
  12964. * Initializes the vector with the given values.
  12965. *
  12966. * @param {goog.vec.Vec4.AnyType} vec The vector to receive the values.
  12967. * @param {number} v0 The value for element at index 0.
  12968. * @param {number} v1 The value for element at index 1.
  12969. * @param {number} v2 The value for element at index 2.
  12970. * @param {number} v3 The value for element at index 3.
  12971. * @return {!goog.vec.Vec4.AnyType} Return vec so that operations can be
  12972. * chained together.
  12973. */
  12974. goog.vec.Vec4.setFromValues = function(vec, v0, v1, v2, v3) {
  12975. vec[0] = v0;
  12976. vec[1] = v1;
  12977. vec[2] = v2;
  12978. vec[3] = v3;
  12979. return vec;
  12980. };
  12981. /**
  12982. * Initializes the vector with the given array of values.
  12983. *
  12984. * @param {goog.vec.Vec4.AnyType} vec The vector to receive the
  12985. * values.
  12986. * @param {goog.vec.Vec4.AnyType} values The array of values.
  12987. * @return {!goog.vec.Vec4.AnyType} Return vec so that operations can be
  12988. * chained together.
  12989. */
  12990. goog.vec.Vec4.setFromArray = function(vec, values) {
  12991. vec[0] = values[0];
  12992. vec[1] = values[1];
  12993. vec[2] = values[2];
  12994. vec[3] = values[3];
  12995. return vec;
  12996. };
  12997. /**
  12998. * Performs a component-wise addition of vec0 and vec1 together storing the
  12999. * result into resultVec.
  13000. *
  13001. * @param {goog.vec.Vec4.AnyType} vec0 The first addend.
  13002. * @param {goog.vec.Vec4.AnyType} vec1 The second addend.
  13003. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  13004. * receive the result. May be vec0 or vec1.
  13005. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13006. * chained together.
  13007. */
  13008. goog.vec.Vec4.add = function(vec0, vec1, resultVec) {
  13009. resultVec[0] = vec0[0] + vec1[0];
  13010. resultVec[1] = vec0[1] + vec1[1];
  13011. resultVec[2] = vec0[2] + vec1[2];
  13012. resultVec[3] = vec0[3] + vec1[3];
  13013. return resultVec;
  13014. };
  13015. /**
  13016. * Performs a component-wise subtraction of vec1 from vec0 storing the
  13017. * result into resultVec.
  13018. *
  13019. * @param {goog.vec.Vec4.AnyType} vec0 The minuend.
  13020. * @param {goog.vec.Vec4.AnyType} vec1 The subtrahend.
  13021. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  13022. * receive the result. May be vec0 or vec1.
  13023. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13024. * chained together.
  13025. */
  13026. goog.vec.Vec4.subtract = function(vec0, vec1, resultVec) {
  13027. resultVec[0] = vec0[0] - vec1[0];
  13028. resultVec[1] = vec0[1] - vec1[1];
  13029. resultVec[2] = vec0[2] - vec1[2];
  13030. resultVec[3] = vec0[3] - vec1[3];
  13031. return resultVec;
  13032. };
  13033. /**
  13034. * Negates vec0, storing the result into resultVec.
  13035. *
  13036. * @param {goog.vec.Vec4.AnyType} vec0 The vector to negate.
  13037. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  13038. * receive the result. May be vec0.
  13039. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13040. * chained together.
  13041. */
  13042. goog.vec.Vec4.negate = function(vec0, resultVec) {
  13043. resultVec[0] = -vec0[0];
  13044. resultVec[1] = -vec0[1];
  13045. resultVec[2] = -vec0[2];
  13046. resultVec[3] = -vec0[3];
  13047. return resultVec;
  13048. };
  13049. /**
  13050. * Takes the absolute value of each component of vec0 storing the result in
  13051. * resultVec.
  13052. *
  13053. * @param {goog.vec.Vec4.AnyType} vec0 The source vector.
  13054. * @param {goog.vec.Vec4.AnyType} resultVec The vector to receive the result.
  13055. * May be vec0.
  13056. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13057. * chained together.
  13058. */
  13059. goog.vec.Vec4.abs = function(vec0, resultVec) {
  13060. resultVec[0] = Math.abs(vec0[0]);
  13061. resultVec[1] = Math.abs(vec0[1]);
  13062. resultVec[2] = Math.abs(vec0[2]);
  13063. resultVec[3] = Math.abs(vec0[3]);
  13064. return resultVec;
  13065. };
  13066. /**
  13067. * Multiplies each component of vec0 with scalar storing the product into
  13068. * resultVec.
  13069. *
  13070. * @param {goog.vec.Vec4.AnyType} vec0 The source vector.
  13071. * @param {number} scalar The value to multiply with each component of vec0.
  13072. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  13073. * receive the result. May be vec0.
  13074. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13075. * chained together.
  13076. */
  13077. goog.vec.Vec4.scale = function(vec0, scalar, resultVec) {
  13078. resultVec[0] = vec0[0] * scalar;
  13079. resultVec[1] = vec0[1] * scalar;
  13080. resultVec[2] = vec0[2] * scalar;
  13081. resultVec[3] = vec0[3] * scalar;
  13082. return resultVec;
  13083. };
  13084. /**
  13085. * Returns the magnitudeSquared of the given vector.
  13086. *
  13087. * @param {goog.vec.Vec4.AnyType} vec0 The vector.
  13088. * @return {number} The magnitude of the vector.
  13089. */
  13090. goog.vec.Vec4.magnitudeSquared = function(vec0) {
  13091. var x = vec0[0], y = vec0[1], z = vec0[2], w = vec0[3];
  13092. return x * x + y * y + z * z + w * w;
  13093. };
  13094. /**
  13095. * Returns the magnitude of the given vector.
  13096. *
  13097. * @param {goog.vec.Vec4.AnyType} vec0 The vector.
  13098. * @return {number} The magnitude of the vector.
  13099. */
  13100. goog.vec.Vec4.magnitude = function(vec0) {
  13101. var x = vec0[0], y = vec0[1], z = vec0[2], w = vec0[3];
  13102. return Math.sqrt(x * x + y * y + z * z + w * w);
  13103. };
  13104. /**
  13105. * Normalizes the given vector storing the result into resultVec.
  13106. *
  13107. * @param {goog.vec.Vec4.AnyType} vec0 The vector to normalize.
  13108. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  13109. * receive the result. May be vec0.
  13110. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13111. * chained together.
  13112. */
  13113. goog.vec.Vec4.normalize = function(vec0, resultVec) {
  13114. var ilen = 1 / goog.vec.Vec4.magnitude(vec0);
  13115. resultVec[0] = vec0[0] * ilen;
  13116. resultVec[1] = vec0[1] * ilen;
  13117. resultVec[2] = vec0[2] * ilen;
  13118. resultVec[3] = vec0[3] * ilen;
  13119. return resultVec;
  13120. };
  13121. /**
  13122. * Returns the scalar product of vectors v0 and v1.
  13123. *
  13124. * @param {goog.vec.Vec4.AnyType} v0 The first vector.
  13125. * @param {goog.vec.Vec4.AnyType} v1 The second vector.
  13126. * @return {number} The scalar product.
  13127. */
  13128. goog.vec.Vec4.dot = function(v0, v1) {
  13129. return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2] + v0[3] * v1[3];
  13130. };
  13131. /**
  13132. * Linearly interpolate from v0 to v1 according to f. The value of f should be
  13133. * in the range [0..1] otherwise the results are undefined.
  13134. *
  13135. * @param {goog.vec.Vec4.AnyType} v0 The first vector.
  13136. * @param {goog.vec.Vec4.AnyType} v1 The second vector.
  13137. * @param {number} f The interpolation factor.
  13138. * @param {goog.vec.Vec4.AnyType} resultVec The vector to receive the
  13139. * results (may be v0 or v1).
  13140. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13141. * chained together.
  13142. */
  13143. goog.vec.Vec4.lerp = function(v0, v1, f, resultVec) {
  13144. var x = v0[0], y = v0[1], z = v0[2], w = v0[3];
  13145. resultVec[0] = (v1[0] - x) * f + x;
  13146. resultVec[1] = (v1[1] - y) * f + y;
  13147. resultVec[2] = (v1[2] - z) * f + z;
  13148. resultVec[3] = (v1[3] - w) * f + w;
  13149. return resultVec;
  13150. };
  13151. /**
  13152. * Compares the components of vec0 with the components of another vector or
  13153. * scalar, storing the larger values in resultVec.
  13154. *
  13155. * @param {goog.vec.Vec4.AnyType} vec0 The source vector.
  13156. * @param {goog.vec.Vec4.AnyType|number} limit The limit vector or scalar.
  13157. * @param {goog.vec.Vec4.AnyType} resultVec The vector to receive the
  13158. * results (may be vec0 or limit).
  13159. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13160. * chained together.
  13161. */
  13162. goog.vec.Vec4.max = function(vec0, limit, resultVec) {
  13163. if (goog.isNumber(limit)) {
  13164. resultVec[0] = Math.max(vec0[0], limit);
  13165. resultVec[1] = Math.max(vec0[1], limit);
  13166. resultVec[2] = Math.max(vec0[2], limit);
  13167. resultVec[3] = Math.max(vec0[3], limit);
  13168. } else {
  13169. resultVec[0] = Math.max(vec0[0], limit[0]);
  13170. resultVec[1] = Math.max(vec0[1], limit[1]);
  13171. resultVec[2] = Math.max(vec0[2], limit[2]);
  13172. resultVec[3] = Math.max(vec0[3], limit[3]);
  13173. }
  13174. return resultVec;
  13175. };
  13176. /**
  13177. * Compares the components of vec0 with the components of another vector or
  13178. * scalar, storing the smaller values in resultVec.
  13179. *
  13180. * @param {goog.vec.Vec4.AnyType} vec0 The source vector.
  13181. * @param {goog.vec.Vec4.AnyType|number} limit The limit vector or scalar.
  13182. * @param {goog.vec.Vec4.AnyType} resultVec The vector to receive the
  13183. * results (may be vec0 or limit).
  13184. * @return {!goog.vec.Vec4.AnyType} Return resultVec so that operations can be
  13185. * chained together.
  13186. */
  13187. goog.vec.Vec4.min = function(vec0, limit, resultVec) {
  13188. if (goog.isNumber(limit)) {
  13189. resultVec[0] = Math.min(vec0[0], limit);
  13190. resultVec[1] = Math.min(vec0[1], limit);
  13191. resultVec[2] = Math.min(vec0[2], limit);
  13192. resultVec[3] = Math.min(vec0[3], limit);
  13193. } else {
  13194. resultVec[0] = Math.min(vec0[0], limit[0]);
  13195. resultVec[1] = Math.min(vec0[1], limit[1]);
  13196. resultVec[2] = Math.min(vec0[2], limit[2]);
  13197. resultVec[3] = Math.min(vec0[3], limit[3]);
  13198. }
  13199. return resultVec;
  13200. };
  13201. /**
  13202. * Returns true if the components of v0 are equal to the components of v1.
  13203. *
  13204. * @param {goog.vec.Vec4.AnyType} v0 The first vector.
  13205. * @param {goog.vec.Vec4.AnyType} v1 The second vector.
  13206. * @return {boolean} True if the vectors are equal, false otherwise.
  13207. */
  13208. goog.vec.Vec4.equals = function(v0, v1) {
  13209. return v0.length == v1.length &&
  13210. v0[0] == v1[0] && v0[1] == v1[1] && v0[2] == v1[2] && v0[3] == v1[3];
  13211. };
  13212. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  13213. //
  13214. // Licensed under the Apache License, Version 2.0 (the "License");
  13215. // you may not use this file except in compliance with the License.
  13216. // You may obtain a copy of the License at
  13217. //
  13218. // http://www.apache.org/licenses/LICENSE-2.0
  13219. //
  13220. // Unless required by applicable law or agreed to in writing, software
  13221. // distributed under the License is distributed on an "AS-IS" BASIS,
  13222. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13223. // See the License for the specific language governing permissions and
  13224. // limitations under the License.
  13225. /**
  13226. * @fileoverview Implements 4x4 matrices and their related functions which are
  13227. * compatible with WebGL. The API is structured to avoid unnecessary memory
  13228. * allocations. The last parameter will typically be the output vector and
  13229. * an object can be both an input and output parameter to all methods except
  13230. * where noted. Matrix operations follow the mathematical form when multiplying
  13231. * vectors as follows: resultVec = matrix * vec.
  13232. *
  13233. * The matrices are stored in column-major order.
  13234. *
  13235. */
  13236. goog.provide('goog.vec.Mat4');
  13237. goog.require('goog.vec');
  13238. goog.require('goog.vec.Vec3');
  13239. goog.require('goog.vec.Vec4');
  13240. /** @typedef {goog.vec.Float32} */ goog.vec.Mat4.Float32;
  13241. /** @typedef {goog.vec.Float64} */ goog.vec.Mat4.Float64;
  13242. /** @typedef {goog.vec.Number} */ goog.vec.Mat4.Number;
  13243. /** @typedef {goog.vec.AnyType} */ goog.vec.Mat4.AnyType;
  13244. // The following two types are deprecated - use the above types instead.
  13245. /** @typedef {!Float32Array} */ goog.vec.Mat4.Type;
  13246. /** @typedef {goog.vec.ArrayType} */ goog.vec.Mat4.Mat4Like;
  13247. /**
  13248. * Creates the array representation of a 4x4 matrix of Float32.
  13249. * The use of the array directly instead of a class reduces overhead.
  13250. * The returned matrix is cleared to all zeros.
  13251. *
  13252. * @return {!goog.vec.Mat4.Float32} The new matrix.
  13253. */
  13254. goog.vec.Mat4.createFloat32 = function() {
  13255. return new Float32Array(16);
  13256. };
  13257. /**
  13258. * Creates the array representation of a 4x4 matrix of Float64.
  13259. * The returned matrix is cleared to all zeros.
  13260. *
  13261. * @return {!goog.vec.Mat4.Float64} The new matrix.
  13262. */
  13263. goog.vec.Mat4.createFloat64 = function() {
  13264. return new Float64Array(16);
  13265. };
  13266. /**
  13267. * Creates the array representation of a 4x4 matrix of Number.
  13268. * The returned matrix is cleared to all zeros.
  13269. *
  13270. * @return {!goog.vec.Mat4.Number} The new matrix.
  13271. */
  13272. goog.vec.Mat4.createNumber = function() {
  13273. var a = new Array(16);
  13274. goog.vec.Mat4.setFromValues(a,
  13275. 0, 0, 0, 0,
  13276. 0, 0, 0, 0,
  13277. 0, 0, 0, 0,
  13278. 0, 0, 0, 0);
  13279. return a;
  13280. };
  13281. /**
  13282. * Creates the array representation of a 4x4 matrix of Float32.
  13283. * The returned matrix is cleared to all zeros.
  13284. *
  13285. * @deprecated Use createFloat32.
  13286. * @return {!goog.vec.Mat4.Type} The new matrix.
  13287. */
  13288. goog.vec.Mat4.create = function() {
  13289. return goog.vec.Mat4.createFloat32();
  13290. };
  13291. /**
  13292. * Creates a 4x4 identity matrix of Float32.
  13293. *
  13294. * @return {!goog.vec.Mat4.Float32} The new 16 element array.
  13295. */
  13296. goog.vec.Mat4.createFloat32Identity = function() {
  13297. var mat = goog.vec.Mat4.createFloat32();
  13298. mat[0] = mat[5] = mat[10] = mat[15] = 1;
  13299. return mat;
  13300. };
  13301. /**
  13302. * Creates a 4x4 identity matrix of Float64.
  13303. *
  13304. * @return {!goog.vec.Mat4.Float64} The new 16 element array.
  13305. */
  13306. goog.vec.Mat4.createFloat64Identity = function() {
  13307. var mat = goog.vec.Mat4.createFloat64();
  13308. mat[0] = mat[5] = mat[10] = mat[15] = 1;
  13309. return mat;
  13310. };
  13311. /**
  13312. * Creates a 4x4 identity matrix of Number.
  13313. * The returned matrix is cleared to all zeros.
  13314. *
  13315. * @return {!goog.vec.Mat4.Number} The new 16 element array.
  13316. */
  13317. goog.vec.Mat4.createNumberIdentity = function() {
  13318. var a = new Array(16);
  13319. goog.vec.Mat4.setFromValues(a,
  13320. 1, 0, 0, 0,
  13321. 0, 1, 0, 0,
  13322. 0, 0, 1, 0,
  13323. 0, 0, 0, 1);
  13324. return a;
  13325. };
  13326. /**
  13327. * Creates the array representation of a 4x4 matrix of Float32.
  13328. * The returned matrix is cleared to all zeros.
  13329. *
  13330. * @deprecated Use createFloat32Identity.
  13331. * @return {!goog.vec.Mat4.Type} The new 16 element array.
  13332. */
  13333. goog.vec.Mat4.createIdentity = function() {
  13334. return goog.vec.Mat4.createFloat32Identity();
  13335. };
  13336. /**
  13337. * Creates a 4x4 matrix of Float32 initialized from the given array.
  13338. *
  13339. * @param {goog.vec.Mat4.AnyType} matrix The array containing the
  13340. * matrix values in column major order.
  13341. * @return {!goog.vec.Mat4.Float32} The new, 16 element array.
  13342. */
  13343. goog.vec.Mat4.createFloat32FromArray = function(matrix) {
  13344. var newMatrix = goog.vec.Mat4.createFloat32();
  13345. goog.vec.Mat4.setFromArray(newMatrix, matrix);
  13346. return newMatrix;
  13347. };
  13348. /**
  13349. * Creates a 4x4 matrix of Float32 initialized from the given values.
  13350. *
  13351. * @param {number} v00 The values at (0, 0).
  13352. * @param {number} v10 The values at (1, 0).
  13353. * @param {number} v20 The values at (2, 0).
  13354. * @param {number} v30 The values at (3, 0).
  13355. * @param {number} v01 The values at (0, 1).
  13356. * @param {number} v11 The values at (1, 1).
  13357. * @param {number} v21 The values at (2, 1).
  13358. * @param {number} v31 The values at (3, 1).
  13359. * @param {number} v02 The values at (0, 2).
  13360. * @param {number} v12 The values at (1, 2).
  13361. * @param {number} v22 The values at (2, 2).
  13362. * @param {number} v32 The values at (3, 2).
  13363. * @param {number} v03 The values at (0, 3).
  13364. * @param {number} v13 The values at (1, 3).
  13365. * @param {number} v23 The values at (2, 3).
  13366. * @param {number} v33 The values at (3, 3).
  13367. * @return {!goog.vec.Mat4.Float32} The new, 16 element array.
  13368. */
  13369. goog.vec.Mat4.createFloat32FromValues = function(
  13370. v00, v10, v20, v30,
  13371. v01, v11, v21, v31,
  13372. v02, v12, v22, v32,
  13373. v03, v13, v23, v33) {
  13374. var newMatrix = goog.vec.Mat4.createFloat32();
  13375. goog.vec.Mat4.setFromValues(
  13376. newMatrix, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
  13377. v03, v13, v23, v33);
  13378. return newMatrix;
  13379. };
  13380. /**
  13381. * Creates a clone of a 4x4 matrix of Float32.
  13382. *
  13383. * @param {goog.vec.Mat4.Float32} matrix The source 4x4 matrix.
  13384. * @return {!goog.vec.Mat4.Float32} The new 4x4 element matrix.
  13385. */
  13386. goog.vec.Mat4.cloneFloat32 = goog.vec.Mat4.createFloat32FromArray;
  13387. /**
  13388. * Creates a 4x4 matrix of Float64 initialized from the given array.
  13389. *
  13390. * @param {goog.vec.Mat4.AnyType} matrix The array containing the
  13391. * matrix values in column major order.
  13392. * @return {!goog.vec.Mat4.Float64} The new, nine element array.
  13393. */
  13394. goog.vec.Mat4.createFloat64FromArray = function(matrix) {
  13395. var newMatrix = goog.vec.Mat4.createFloat64();
  13396. goog.vec.Mat4.setFromArray(newMatrix, matrix);
  13397. return newMatrix;
  13398. };
  13399. /**
  13400. * Creates a 4x4 matrix of Float64 initialized from the given values.
  13401. *
  13402. * @param {number} v00 The values at (0, 0).
  13403. * @param {number} v10 The values at (1, 0).
  13404. * @param {number} v20 The values at (2, 0).
  13405. * @param {number} v30 The values at (3, 0).
  13406. * @param {number} v01 The values at (0, 1).
  13407. * @param {number} v11 The values at (1, 1).
  13408. * @param {number} v21 The values at (2, 1).
  13409. * @param {number} v31 The values at (3, 1).
  13410. * @param {number} v02 The values at (0, 2).
  13411. * @param {number} v12 The values at (1, 2).
  13412. * @param {number} v22 The values at (2, 2).
  13413. * @param {number} v32 The values at (3, 2).
  13414. * @param {number} v03 The values at (0, 3).
  13415. * @param {number} v13 The values at (1, 3).
  13416. * @param {number} v23 The values at (2, 3).
  13417. * @param {number} v33 The values at (3, 3).
  13418. * @return {!goog.vec.Mat4.Float64} The new, 16 element array.
  13419. */
  13420. goog.vec.Mat4.createFloat64FromValues = function(
  13421. v00, v10, v20, v30,
  13422. v01, v11, v21, v31,
  13423. v02, v12, v22, v32,
  13424. v03, v13, v23, v33) {
  13425. var newMatrix = goog.vec.Mat4.createFloat64();
  13426. goog.vec.Mat4.setFromValues(
  13427. newMatrix, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
  13428. v03, v13, v23, v33);
  13429. return newMatrix;
  13430. };
  13431. /**
  13432. * Creates a clone of a 4x4 matrix of Float64.
  13433. *
  13434. * @param {goog.vec.Mat4.Float64} matrix The source 4x4 matrix.
  13435. * @return {!goog.vec.Mat4.Float64} The new 4x4 element matrix.
  13436. */
  13437. goog.vec.Mat4.cloneFloat64 = goog.vec.Mat4.createFloat64FromArray;
  13438. /**
  13439. * Creates a 4x4 matrix of Float32 initialized from the given array.
  13440. *
  13441. * @deprecated Use createFloat32FromArray.
  13442. * @param {goog.vec.Mat4.Mat4Like} matrix The array containing the
  13443. * matrix values in column major order.
  13444. * @return {!goog.vec.Mat4.Type} The new, nine element array.
  13445. */
  13446. goog.vec.Mat4.createFromArray = function(matrix) {
  13447. var newMatrix = goog.vec.Mat4.createFloat32();
  13448. goog.vec.Mat4.setFromArray(newMatrix, matrix);
  13449. return newMatrix;
  13450. };
  13451. /**
  13452. * Creates a 4x4 matrix of Float32 initialized from the given values.
  13453. *
  13454. * @deprecated Use createFloat32FromValues.
  13455. * @param {number} v00 The values at (0, 0).
  13456. * @param {number} v10 The values at (1, 0).
  13457. * @param {number} v20 The values at (2, 0).
  13458. * @param {number} v30 The values at (3, 0).
  13459. * @param {number} v01 The values at (0, 1).
  13460. * @param {number} v11 The values at (1, 1).
  13461. * @param {number} v21 The values at (2, 1).
  13462. * @param {number} v31 The values at (3, 1).
  13463. * @param {number} v02 The values at (0, 2).
  13464. * @param {number} v12 The values at (1, 2).
  13465. * @param {number} v22 The values at (2, 2).
  13466. * @param {number} v32 The values at (3, 2).
  13467. * @param {number} v03 The values at (0, 3).
  13468. * @param {number} v13 The values at (1, 3).
  13469. * @param {number} v23 The values at (2, 3).
  13470. * @param {number} v33 The values at (3, 3).
  13471. * @return {!goog.vec.Mat4.Type} The new, 16 element array.
  13472. */
  13473. goog.vec.Mat4.createFromValues = function(
  13474. v00, v10, v20, v30,
  13475. v01, v11, v21, v31,
  13476. v02, v12, v22, v32,
  13477. v03, v13, v23, v33) {
  13478. return goog.vec.Mat4.createFloat32FromValues(
  13479. v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
  13480. v03, v13, v23, v33);
  13481. };
  13482. /**
  13483. * Creates a clone of a 4x4 matrix of Float32.
  13484. *
  13485. * @deprecated Use cloneFloat32.
  13486. * @param {goog.vec.Mat4.Mat4Like} matrix The source 4x4 matrix.
  13487. * @return {!goog.vec.Mat4.Type} The new 4x4 element matrix.
  13488. */
  13489. goog.vec.Mat4.clone = goog.vec.Mat4.createFromArray;
  13490. /**
  13491. * Retrieves the element at the requested row and column.
  13492. *
  13493. * @param {goog.vec.Mat4.AnyType} mat The matrix containing the
  13494. * value to retrieve.
  13495. * @param {number} row The row index.
  13496. * @param {number} column The column index.
  13497. * @return {number} The element value at the requested row, column indices.
  13498. */
  13499. goog.vec.Mat4.getElement = function(mat, row, column) {
  13500. return mat[row + column * 4];
  13501. };
  13502. /**
  13503. * Sets the element at the requested row and column.
  13504. *
  13505. * @param {goog.vec.Mat4.AnyType} mat The matrix to set the value on.
  13506. * @param {number} row The row index.
  13507. * @param {number} column The column index.
  13508. * @param {number} value The value to set at the requested row, column.
  13509. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13510. * chained together.
  13511. */
  13512. goog.vec.Mat4.setElement = function(mat, row, column, value) {
  13513. mat[row + column * 4] = value;
  13514. return mat;
  13515. };
  13516. /**
  13517. * Initializes the matrix from the set of values. Note the values supplied are
  13518. * in column major order.
  13519. *
  13520. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the
  13521. * values.
  13522. * @param {number} v00 The values at (0, 0).
  13523. * @param {number} v10 The values at (1, 0).
  13524. * @param {number} v20 The values at (2, 0).
  13525. * @param {number} v30 The values at (3, 0).
  13526. * @param {number} v01 The values at (0, 1).
  13527. * @param {number} v11 The values at (1, 1).
  13528. * @param {number} v21 The values at (2, 1).
  13529. * @param {number} v31 The values at (3, 1).
  13530. * @param {number} v02 The values at (0, 2).
  13531. * @param {number} v12 The values at (1, 2).
  13532. * @param {number} v22 The values at (2, 2).
  13533. * @param {number} v32 The values at (3, 2).
  13534. * @param {number} v03 The values at (0, 3).
  13535. * @param {number} v13 The values at (1, 3).
  13536. * @param {number} v23 The values at (2, 3).
  13537. * @param {number} v33 The values at (3, 3).
  13538. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13539. * chained together.
  13540. */
  13541. goog.vec.Mat4.setFromValues = function(
  13542. mat, v00, v10, v20, v30, v01, v11, v21, v31, v02, v12, v22, v32,
  13543. v03, v13, v23, v33) {
  13544. mat[0] = v00;
  13545. mat[1] = v10;
  13546. mat[2] = v20;
  13547. mat[3] = v30;
  13548. mat[4] = v01;
  13549. mat[5] = v11;
  13550. mat[6] = v21;
  13551. mat[7] = v31;
  13552. mat[8] = v02;
  13553. mat[9] = v12;
  13554. mat[10] = v22;
  13555. mat[11] = v32;
  13556. mat[12] = v03;
  13557. mat[13] = v13;
  13558. mat[14] = v23;
  13559. mat[15] = v33;
  13560. return mat;
  13561. };
  13562. /**
  13563. * Sets the matrix from the array of values stored in column major order.
  13564. *
  13565. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13566. * @param {goog.vec.Mat4.AnyType} values The column major ordered
  13567. * array of values to store in the matrix.
  13568. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13569. * chained together.
  13570. */
  13571. goog.vec.Mat4.setFromArray = function(mat, values) {
  13572. mat[0] = values[0];
  13573. mat[1] = values[1];
  13574. mat[2] = values[2];
  13575. mat[3] = values[3];
  13576. mat[4] = values[4];
  13577. mat[5] = values[5];
  13578. mat[6] = values[6];
  13579. mat[7] = values[7];
  13580. mat[8] = values[8];
  13581. mat[9] = values[9];
  13582. mat[10] = values[10];
  13583. mat[11] = values[11];
  13584. mat[12] = values[12];
  13585. mat[13] = values[13];
  13586. mat[14] = values[14];
  13587. mat[15] = values[15];
  13588. return mat;
  13589. };
  13590. /**
  13591. * Sets the matrix from the array of values stored in row major order.
  13592. *
  13593. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13594. * @param {goog.vec.Mat4.AnyType} values The row major ordered array of
  13595. * values to store in the matrix.
  13596. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13597. * chained together.
  13598. */
  13599. goog.vec.Mat4.setFromRowMajorArray = function(mat, values) {
  13600. mat[0] = values[0];
  13601. mat[1] = values[4];
  13602. mat[2] = values[8];
  13603. mat[3] = values[12];
  13604. mat[4] = values[1];
  13605. mat[5] = values[5];
  13606. mat[6] = values[9];
  13607. mat[7] = values[13];
  13608. mat[8] = values[2];
  13609. mat[9] = values[6];
  13610. mat[10] = values[10];
  13611. mat[11] = values[14];
  13612. mat[12] = values[3];
  13613. mat[13] = values[7];
  13614. mat[14] = values[11];
  13615. mat[15] = values[15];
  13616. return mat;
  13617. };
  13618. /**
  13619. * Sets the diagonal values of the matrix from the given values.
  13620. *
  13621. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13622. * @param {number} v00 The values for (0, 0).
  13623. * @param {number} v11 The values for (1, 1).
  13624. * @param {number} v22 The values for (2, 2).
  13625. * @param {number} v33 The values for (3, 3).
  13626. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13627. * chained together.
  13628. */
  13629. goog.vec.Mat4.setDiagonalValues = function(mat, v00, v11, v22, v33) {
  13630. mat[0] = v00;
  13631. mat[5] = v11;
  13632. mat[10] = v22;
  13633. mat[15] = v33;
  13634. return mat;
  13635. };
  13636. /**
  13637. * Sets the diagonal values of the matrix from the given vector.
  13638. *
  13639. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13640. * @param {goog.vec.Vec4.AnyType} vec The vector containing the values.
  13641. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13642. * chained together.
  13643. */
  13644. goog.vec.Mat4.setDiagonal = function(mat, vec) {
  13645. mat[0] = vec[0];
  13646. mat[5] = vec[1];
  13647. mat[10] = vec[2];
  13648. mat[15] = vec[3];
  13649. return mat;
  13650. };
  13651. /**
  13652. * Gets the diagonal values of the matrix into the given vector.
  13653. *
  13654. * @param {goog.vec.Mat4.AnyType} mat The matrix containing the values.
  13655. * @param {goog.vec.Vec4.AnyType} vec The vector to receive the values.
  13656. * @param {number=} opt_diagonal Which diagonal to get. A value of 0 selects the
  13657. * main diagonal, a positive number selects a super diagonal and a negative
  13658. * number selects a sub diagonal.
  13659. * @return {goog.vec.Vec4.AnyType} return vec so that operations can be
  13660. * chained together.
  13661. */
  13662. goog.vec.Mat4.getDiagonal = function(mat, vec, opt_diagonal) {
  13663. if (!opt_diagonal) {
  13664. // This is the most common case, so we avoid the for loop.
  13665. vec[0] = mat[0];
  13666. vec[1] = mat[5];
  13667. vec[2] = mat[10];
  13668. vec[3] = mat[15];
  13669. } else {
  13670. var offset = opt_diagonal > 0 ? 4 * opt_diagonal : -opt_diagonal;
  13671. for (var i = 0; i < 4 - Math.abs(opt_diagonal); i++) {
  13672. vec[i] = mat[offset + 5 * i];
  13673. }
  13674. }
  13675. return vec;
  13676. };
  13677. /**
  13678. * Sets the specified column with the supplied values.
  13679. *
  13680. * @param {goog.vec.Mat4.AnyType} mat The matrix to recieve the values.
  13681. * @param {number} column The column index to set the values on.
  13682. * @param {number} v0 The value for row 0.
  13683. * @param {number} v1 The value for row 1.
  13684. * @param {number} v2 The value for row 2.
  13685. * @param {number} v3 The value for row 3.
  13686. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13687. * chained together.
  13688. */
  13689. goog.vec.Mat4.setColumnValues = function(mat, column, v0, v1, v2, v3) {
  13690. var i = column * 4;
  13691. mat[i] = v0;
  13692. mat[i + 1] = v1;
  13693. mat[i + 2] = v2;
  13694. mat[i + 3] = v3;
  13695. return mat;
  13696. };
  13697. /**
  13698. * Sets the specified column with the value from the supplied vector.
  13699. *
  13700. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13701. * @param {number} column The column index to set the values on.
  13702. * @param {goog.vec.Vec4.AnyType} vec The vector of elements for the column.
  13703. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13704. * chained together.
  13705. */
  13706. goog.vec.Mat4.setColumn = function(mat, column, vec) {
  13707. var i = column * 4;
  13708. mat[i] = vec[0];
  13709. mat[i + 1] = vec[1];
  13710. mat[i + 2] = vec[2];
  13711. mat[i + 3] = vec[3];
  13712. return mat;
  13713. };
  13714. /**
  13715. * Retrieves the specified column from the matrix into the given vector.
  13716. *
  13717. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the values.
  13718. * @param {number} column The column to get the values from.
  13719. * @param {goog.vec.Vec4.AnyType} vec The vector of elements to
  13720. * receive the column.
  13721. * @return {goog.vec.Vec4.AnyType} return vec so that operations can be
  13722. * chained together.
  13723. */
  13724. goog.vec.Mat4.getColumn = function(mat, column, vec) {
  13725. var i = column * 4;
  13726. vec[0] = mat[i];
  13727. vec[1] = mat[i + 1];
  13728. vec[2] = mat[i + 2];
  13729. vec[3] = mat[i + 3];
  13730. return vec;
  13731. };
  13732. /**
  13733. * Sets the columns of the matrix from the given vectors.
  13734. *
  13735. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13736. * @param {goog.vec.Vec4.AnyType} vec0 The values for column 0.
  13737. * @param {goog.vec.Vec4.AnyType} vec1 The values for column 1.
  13738. * @param {goog.vec.Vec4.AnyType} vec2 The values for column 2.
  13739. * @param {goog.vec.Vec4.AnyType} vec3 The values for column 3.
  13740. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13741. * chained together.
  13742. */
  13743. goog.vec.Mat4.setColumns = function(mat, vec0, vec1, vec2, vec3) {
  13744. goog.vec.Mat4.setColumn(mat, 0, vec0);
  13745. goog.vec.Mat4.setColumn(mat, 1, vec1);
  13746. goog.vec.Mat4.setColumn(mat, 2, vec2);
  13747. goog.vec.Mat4.setColumn(mat, 3, vec3);
  13748. return mat;
  13749. };
  13750. /**
  13751. * Retrieves the column values from the given matrix into the given vectors.
  13752. *
  13753. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the columns.
  13754. * @param {goog.vec.Vec4.AnyType} vec0 The vector to receive column 0.
  13755. * @param {goog.vec.Vec4.AnyType} vec1 The vector to receive column 1.
  13756. * @param {goog.vec.Vec4.AnyType} vec2 The vector to receive column 2.
  13757. * @param {goog.vec.Vec4.AnyType} vec3 The vector to receive column 3.
  13758. */
  13759. goog.vec.Mat4.getColumns = function(mat, vec0, vec1, vec2, vec3) {
  13760. goog.vec.Mat4.getColumn(mat, 0, vec0);
  13761. goog.vec.Mat4.getColumn(mat, 1, vec1);
  13762. goog.vec.Mat4.getColumn(mat, 2, vec2);
  13763. goog.vec.Mat4.getColumn(mat, 3, vec3);
  13764. };
  13765. /**
  13766. * Sets the row values from the supplied values.
  13767. *
  13768. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13769. * @param {number} row The index of the row to receive the values.
  13770. * @param {number} v0 The value for column 0.
  13771. * @param {number} v1 The value for column 1.
  13772. * @param {number} v2 The value for column 2.
  13773. * @param {number} v3 The value for column 3.
  13774. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13775. * chained together.
  13776. */
  13777. goog.vec.Mat4.setRowValues = function(mat, row, v0, v1, v2, v3) {
  13778. mat[row] = v0;
  13779. mat[row + 4] = v1;
  13780. mat[row + 8] = v2;
  13781. mat[row + 12] = v3;
  13782. return mat;
  13783. };
  13784. /**
  13785. * Sets the row values from the supplied vector.
  13786. *
  13787. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the row values.
  13788. * @param {number} row The index of the row.
  13789. * @param {goog.vec.Vec4.AnyType} vec The vector containing the values.
  13790. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13791. * chained together.
  13792. */
  13793. goog.vec.Mat4.setRow = function(mat, row, vec) {
  13794. mat[row] = vec[0];
  13795. mat[row + 4] = vec[1];
  13796. mat[row + 8] = vec[2];
  13797. mat[row + 12] = vec[3];
  13798. return mat;
  13799. };
  13800. /**
  13801. * Retrieves the row values into the given vector.
  13802. *
  13803. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the values.
  13804. * @param {number} row The index of the row supplying the values.
  13805. * @param {goog.vec.Vec4.AnyType} vec The vector to receive the row.
  13806. * @return {goog.vec.Vec4.AnyType} return vec so that operations can be
  13807. * chained together.
  13808. */
  13809. goog.vec.Mat4.getRow = function(mat, row, vec) {
  13810. vec[0] = mat[row];
  13811. vec[1] = mat[row + 4];
  13812. vec[2] = mat[row + 8];
  13813. vec[3] = mat[row + 12];
  13814. return vec;
  13815. };
  13816. /**
  13817. * Sets the rows of the matrix from the supplied vectors.
  13818. *
  13819. * @param {goog.vec.Mat4.AnyType} mat The matrix to receive the values.
  13820. * @param {goog.vec.Vec4.AnyType} vec0 The values for row 0.
  13821. * @param {goog.vec.Vec4.AnyType} vec1 The values for row 1.
  13822. * @param {goog.vec.Vec4.AnyType} vec2 The values for row 2.
  13823. * @param {goog.vec.Vec4.AnyType} vec3 The values for row 3.
  13824. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  13825. * chained together.
  13826. */
  13827. goog.vec.Mat4.setRows = function(mat, vec0, vec1, vec2, vec3) {
  13828. goog.vec.Mat4.setRow(mat, 0, vec0);
  13829. goog.vec.Mat4.setRow(mat, 1, vec1);
  13830. goog.vec.Mat4.setRow(mat, 2, vec2);
  13831. goog.vec.Mat4.setRow(mat, 3, vec3);
  13832. return mat;
  13833. };
  13834. /**
  13835. * Retrieves the rows of the matrix into the supplied vectors.
  13836. *
  13837. * @param {goog.vec.Mat4.AnyType} mat The matrix to supply the values.
  13838. * @param {goog.vec.Vec4.AnyType} vec0 The vector to receive row 0.
  13839. * @param {goog.vec.Vec4.AnyType} vec1 The vector to receive row 1.
  13840. * @param {goog.vec.Vec4.AnyType} vec2 The vector to receive row 2.
  13841. * @param {goog.vec.Vec4.AnyType} vec3 The vector to receive row 3.
  13842. */
  13843. goog.vec.Mat4.getRows = function(mat, vec0, vec1, vec2, vec3) {
  13844. goog.vec.Mat4.getRow(mat, 0, vec0);
  13845. goog.vec.Mat4.getRow(mat, 1, vec1);
  13846. goog.vec.Mat4.getRow(mat, 2, vec2);
  13847. goog.vec.Mat4.getRow(mat, 3, vec3);
  13848. };
  13849. /**
  13850. * Makes the given 4x4 matrix the zero matrix.
  13851. *
  13852. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  13853. * @return {!goog.vec.Mat4.AnyType} return mat so operations can be chained.
  13854. */
  13855. goog.vec.Mat4.makeZero = function(mat) {
  13856. mat[0] = 0;
  13857. mat[1] = 0;
  13858. mat[2] = 0;
  13859. mat[3] = 0;
  13860. mat[4] = 0;
  13861. mat[5] = 0;
  13862. mat[6] = 0;
  13863. mat[7] = 0;
  13864. mat[8] = 0;
  13865. mat[9] = 0;
  13866. mat[10] = 0;
  13867. mat[11] = 0;
  13868. mat[12] = 0;
  13869. mat[13] = 0;
  13870. mat[14] = 0;
  13871. mat[15] = 0;
  13872. return mat;
  13873. };
  13874. /**
  13875. * Makes the given 4x4 matrix the identity matrix.
  13876. *
  13877. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  13878. * @return {goog.vec.Mat4.AnyType} return mat so operations can be chained.
  13879. */
  13880. goog.vec.Mat4.makeIdentity = function(mat) {
  13881. mat[0] = 1;
  13882. mat[1] = 0;
  13883. mat[2] = 0;
  13884. mat[3] = 0;
  13885. mat[4] = 0;
  13886. mat[5] = 1;
  13887. mat[6] = 0;
  13888. mat[7] = 0;
  13889. mat[8] = 0;
  13890. mat[9] = 0;
  13891. mat[10] = 1;
  13892. mat[11] = 0;
  13893. mat[12] = 0;
  13894. mat[13] = 0;
  13895. mat[14] = 0;
  13896. mat[15] = 1;
  13897. return mat;
  13898. };
  13899. /**
  13900. * Performs a per-component addition of the matrix mat0 and mat1, storing
  13901. * the result into resultMat.
  13902. *
  13903. * @param {goog.vec.Mat4.AnyType} mat0 The first addend.
  13904. * @param {goog.vec.Mat4.AnyType} mat1 The second addend.
  13905. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to
  13906. * receive the results (may be either mat0 or mat1).
  13907. * @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
  13908. * chained together.
  13909. */
  13910. goog.vec.Mat4.addMat = function(mat0, mat1, resultMat) {
  13911. resultMat[0] = mat0[0] + mat1[0];
  13912. resultMat[1] = mat0[1] + mat1[1];
  13913. resultMat[2] = mat0[2] + mat1[2];
  13914. resultMat[3] = mat0[3] + mat1[3];
  13915. resultMat[4] = mat0[4] + mat1[4];
  13916. resultMat[5] = mat0[5] + mat1[5];
  13917. resultMat[6] = mat0[6] + mat1[6];
  13918. resultMat[7] = mat0[7] + mat1[7];
  13919. resultMat[8] = mat0[8] + mat1[8];
  13920. resultMat[9] = mat0[9] + mat1[9];
  13921. resultMat[10] = mat0[10] + mat1[10];
  13922. resultMat[11] = mat0[11] + mat1[11];
  13923. resultMat[12] = mat0[12] + mat1[12];
  13924. resultMat[13] = mat0[13] + mat1[13];
  13925. resultMat[14] = mat0[14] + mat1[14];
  13926. resultMat[15] = mat0[15] + mat1[15];
  13927. return resultMat;
  13928. };
  13929. /**
  13930. * Performs a per-component subtraction of the matrix mat0 and mat1,
  13931. * storing the result into resultMat.
  13932. *
  13933. * @param {goog.vec.Mat4.AnyType} mat0 The minuend.
  13934. * @param {goog.vec.Mat4.AnyType} mat1 The subtrahend.
  13935. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
  13936. * the results (may be either mat0 or mat1).
  13937. * @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
  13938. * chained together.
  13939. */
  13940. goog.vec.Mat4.subMat = function(mat0, mat1, resultMat) {
  13941. resultMat[0] = mat0[0] - mat1[0];
  13942. resultMat[1] = mat0[1] - mat1[1];
  13943. resultMat[2] = mat0[2] - mat1[2];
  13944. resultMat[3] = mat0[3] - mat1[3];
  13945. resultMat[4] = mat0[4] - mat1[4];
  13946. resultMat[5] = mat0[5] - mat1[5];
  13947. resultMat[6] = mat0[6] - mat1[6];
  13948. resultMat[7] = mat0[7] - mat1[7];
  13949. resultMat[8] = mat0[8] - mat1[8];
  13950. resultMat[9] = mat0[9] - mat1[9];
  13951. resultMat[10] = mat0[10] - mat1[10];
  13952. resultMat[11] = mat0[11] - mat1[11];
  13953. resultMat[12] = mat0[12] - mat1[12];
  13954. resultMat[13] = mat0[13] - mat1[13];
  13955. resultMat[14] = mat0[14] - mat1[14];
  13956. resultMat[15] = mat0[15] - mat1[15];
  13957. return resultMat;
  13958. };
  13959. /**
  13960. * Multiplies matrix mat with the given scalar, storing the result
  13961. * into resultMat.
  13962. *
  13963. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  13964. * @param {number} scalar The scalar value to multiply to each element of mat.
  13965. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
  13966. * the results (may be mat).
  13967. * @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
  13968. * chained together.
  13969. */
  13970. goog.vec.Mat4.multScalar = function(mat, scalar, resultMat) {
  13971. resultMat[0] = mat[0] * scalar;
  13972. resultMat[1] = mat[1] * scalar;
  13973. resultMat[2] = mat[2] * scalar;
  13974. resultMat[3] = mat[3] * scalar;
  13975. resultMat[4] = mat[4] * scalar;
  13976. resultMat[5] = mat[5] * scalar;
  13977. resultMat[6] = mat[6] * scalar;
  13978. resultMat[7] = mat[7] * scalar;
  13979. resultMat[8] = mat[8] * scalar;
  13980. resultMat[9] = mat[9] * scalar;
  13981. resultMat[10] = mat[10] * scalar;
  13982. resultMat[11] = mat[11] * scalar;
  13983. resultMat[12] = mat[12] * scalar;
  13984. resultMat[13] = mat[13] * scalar;
  13985. resultMat[14] = mat[14] * scalar;
  13986. resultMat[15] = mat[15] * scalar;
  13987. return resultMat;
  13988. };
  13989. /**
  13990. * Multiplies the two matrices mat0 and mat1 using matrix multiplication,
  13991. * storing the result into resultMat.
  13992. *
  13993. * @param {goog.vec.Mat4.AnyType} mat0 The first (left hand) matrix.
  13994. * @param {goog.vec.Mat4.AnyType} mat1 The second (right hand) matrix.
  13995. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
  13996. * the results (may be either mat0 or mat1).
  13997. * @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
  13998. * chained together.
  13999. */
  14000. goog.vec.Mat4.multMat = function(mat0, mat1, resultMat) {
  14001. var a00 = mat0[0], a10 = mat0[1], a20 = mat0[2], a30 = mat0[3];
  14002. var a01 = mat0[4], a11 = mat0[5], a21 = mat0[6], a31 = mat0[7];
  14003. var a02 = mat0[8], a12 = mat0[9], a22 = mat0[10], a32 = mat0[11];
  14004. var a03 = mat0[12], a13 = mat0[13], a23 = mat0[14], a33 = mat0[15];
  14005. var b00 = mat1[0], b10 = mat1[1], b20 = mat1[2], b30 = mat1[3];
  14006. var b01 = mat1[4], b11 = mat1[5], b21 = mat1[6], b31 = mat1[7];
  14007. var b02 = mat1[8], b12 = mat1[9], b22 = mat1[10], b32 = mat1[11];
  14008. var b03 = mat1[12], b13 = mat1[13], b23 = mat1[14], b33 = mat1[15];
  14009. resultMat[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;
  14010. resultMat[1] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;
  14011. resultMat[2] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;
  14012. resultMat[3] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;
  14013. resultMat[4] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;
  14014. resultMat[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;
  14015. resultMat[6] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;
  14016. resultMat[7] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;
  14017. resultMat[8] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;
  14018. resultMat[9] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;
  14019. resultMat[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;
  14020. resultMat[11] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;
  14021. resultMat[12] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;
  14022. resultMat[13] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;
  14023. resultMat[14] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;
  14024. resultMat[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;
  14025. return resultMat;
  14026. };
  14027. /**
  14028. * Transposes the given matrix mat storing the result into resultMat.
  14029. *
  14030. * @param {goog.vec.Mat4.AnyType} mat The matrix to transpose.
  14031. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
  14032. * the results (may be mat).
  14033. * @return {goog.vec.Mat4.AnyType} return resultMat so that operations can be
  14034. * chained together.
  14035. */
  14036. goog.vec.Mat4.transpose = function(mat, resultMat) {
  14037. if (resultMat == mat) {
  14038. var a10 = mat[1], a20 = mat[2], a30 = mat[3];
  14039. var a21 = mat[6], a31 = mat[7];
  14040. var a32 = mat[11];
  14041. resultMat[1] = mat[4];
  14042. resultMat[2] = mat[8];
  14043. resultMat[3] = mat[12];
  14044. resultMat[4] = a10;
  14045. resultMat[6] = mat[9];
  14046. resultMat[7] = mat[13];
  14047. resultMat[8] = a20;
  14048. resultMat[9] = a21;
  14049. resultMat[11] = mat[14];
  14050. resultMat[12] = a30;
  14051. resultMat[13] = a31;
  14052. resultMat[14] = a32;
  14053. } else {
  14054. resultMat[0] = mat[0];
  14055. resultMat[1] = mat[4];
  14056. resultMat[2] = mat[8];
  14057. resultMat[3] = mat[12];
  14058. resultMat[4] = mat[1];
  14059. resultMat[5] = mat[5];
  14060. resultMat[6] = mat[9];
  14061. resultMat[7] = mat[13];
  14062. resultMat[8] = mat[2];
  14063. resultMat[9] = mat[6];
  14064. resultMat[10] = mat[10];
  14065. resultMat[11] = mat[14];
  14066. resultMat[12] = mat[3];
  14067. resultMat[13] = mat[7];
  14068. resultMat[14] = mat[11];
  14069. resultMat[15] = mat[15];
  14070. }
  14071. return resultMat;
  14072. };
  14073. /**
  14074. * Computes the determinant of the matrix.
  14075. *
  14076. * @param {goog.vec.Mat4.AnyType} mat The matrix to compute the matrix for.
  14077. * @return {number} The determinant of the matrix.
  14078. */
  14079. goog.vec.Mat4.determinant = function(mat) {
  14080. var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
  14081. var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
  14082. var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
  14083. var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
  14084. var a0 = m00 * m11 - m10 * m01;
  14085. var a1 = m00 * m21 - m20 * m01;
  14086. var a2 = m00 * m31 - m30 * m01;
  14087. var a3 = m10 * m21 - m20 * m11;
  14088. var a4 = m10 * m31 - m30 * m11;
  14089. var a5 = m20 * m31 - m30 * m21;
  14090. var b0 = m02 * m13 - m12 * m03;
  14091. var b1 = m02 * m23 - m22 * m03;
  14092. var b2 = m02 * m33 - m32 * m03;
  14093. var b3 = m12 * m23 - m22 * m13;
  14094. var b4 = m12 * m33 - m32 * m13;
  14095. var b5 = m22 * m33 - m32 * m23;
  14096. return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
  14097. };
  14098. /**
  14099. * Computes the inverse of mat storing the result into resultMat. If the
  14100. * inverse is defined, this function returns true, false otherwise.
  14101. *
  14102. * @param {goog.vec.Mat4.AnyType} mat The matrix to invert.
  14103. * @param {goog.vec.Mat4.AnyType} resultMat The matrix to receive
  14104. * the result (may be mat).
  14105. * @return {boolean} True if the inverse is defined. If false is returned,
  14106. * resultMat is not modified.
  14107. */
  14108. goog.vec.Mat4.invert = function(mat, resultMat) {
  14109. var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
  14110. var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
  14111. var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
  14112. var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
  14113. var a0 = m00 * m11 - m10 * m01;
  14114. var a1 = m00 * m21 - m20 * m01;
  14115. var a2 = m00 * m31 - m30 * m01;
  14116. var a3 = m10 * m21 - m20 * m11;
  14117. var a4 = m10 * m31 - m30 * m11;
  14118. var a5 = m20 * m31 - m30 * m21;
  14119. var b0 = m02 * m13 - m12 * m03;
  14120. var b1 = m02 * m23 - m22 * m03;
  14121. var b2 = m02 * m33 - m32 * m03;
  14122. var b3 = m12 * m23 - m22 * m13;
  14123. var b4 = m12 * m33 - m32 * m13;
  14124. var b5 = m22 * m33 - m32 * m23;
  14125. var det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
  14126. if (det == 0) {
  14127. return false;
  14128. }
  14129. var idet = 1.0 / det;
  14130. resultMat[0] = (m11 * b5 - m21 * b4 + m31 * b3) * idet;
  14131. resultMat[1] = (-m10 * b5 + m20 * b4 - m30 * b3) * idet;
  14132. resultMat[2] = (m13 * a5 - m23 * a4 + m33 * a3) * idet;
  14133. resultMat[3] = (-m12 * a5 + m22 * a4 - m32 * a3) * idet;
  14134. resultMat[4] = (-m01 * b5 + m21 * b2 - m31 * b1) * idet;
  14135. resultMat[5] = (m00 * b5 - m20 * b2 + m30 * b1) * idet;
  14136. resultMat[6] = (-m03 * a5 + m23 * a2 - m33 * a1) * idet;
  14137. resultMat[7] = (m02 * a5 - m22 * a2 + m32 * a1) * idet;
  14138. resultMat[8] = (m01 * b4 - m11 * b2 + m31 * b0) * idet;
  14139. resultMat[9] = (-m00 * b4 + m10 * b2 - m30 * b0) * idet;
  14140. resultMat[10] = (m03 * a4 - m13 * a2 + m33 * a0) * idet;
  14141. resultMat[11] = (-m02 * a4 + m12 * a2 - m32 * a0) * idet;
  14142. resultMat[12] = (-m01 * b3 + m11 * b1 - m21 * b0) * idet;
  14143. resultMat[13] = (m00 * b3 - m10 * b1 + m20 * b0) * idet;
  14144. resultMat[14] = (-m03 * a3 + m13 * a1 - m23 * a0) * idet;
  14145. resultMat[15] = (m02 * a3 - m12 * a1 + m22 * a0) * idet;
  14146. return true;
  14147. };
  14148. /**
  14149. * Returns true if the components of mat0 are equal to the components of mat1.
  14150. *
  14151. * @param {goog.vec.Mat4.AnyType} mat0 The first matrix.
  14152. * @param {goog.vec.Mat4.AnyType} mat1 The second matrix.
  14153. * @return {boolean} True if the the two matrices are equivalent.
  14154. */
  14155. goog.vec.Mat4.equals = function(mat0, mat1) {
  14156. return mat0.length == mat1.length &&
  14157. mat0[0] == mat1[0] &&
  14158. mat0[1] == mat1[1] &&
  14159. mat0[2] == mat1[2] &&
  14160. mat0[3] == mat1[3] &&
  14161. mat0[4] == mat1[4] &&
  14162. mat0[5] == mat1[5] &&
  14163. mat0[6] == mat1[6] &&
  14164. mat0[7] == mat1[7] &&
  14165. mat0[8] == mat1[8] &&
  14166. mat0[9] == mat1[9] &&
  14167. mat0[10] == mat1[10] &&
  14168. mat0[11] == mat1[11] &&
  14169. mat0[12] == mat1[12] &&
  14170. mat0[13] == mat1[13] &&
  14171. mat0[14] == mat1[14] &&
  14172. mat0[15] == mat1[15];
  14173. };
  14174. /**
  14175. * Transforms the given vector with the given matrix storing the resulting,
  14176. * transformed vector into resultVec. The input vector is multiplied against the
  14177. * upper 3x4 matrix omitting the projective component.
  14178. *
  14179. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
  14180. * @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
  14181. * @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector to
  14182. * receive the results (may be vec).
  14183. * @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
  14184. * chained together.
  14185. */
  14186. goog.vec.Mat4.multVec3 = function(mat, vec, resultVec) {
  14187. var x = vec[0], y = vec[1], z = vec[2];
  14188. resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
  14189. resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
  14190. resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
  14191. return resultVec;
  14192. };
  14193. /**
  14194. * Transforms the given vector with the given matrix storing the resulting,
  14195. * transformed vector into resultVec. The input vector is multiplied against the
  14196. * upper 3x3 matrix omitting the projective component and translation
  14197. * components.
  14198. *
  14199. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
  14200. * @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
  14201. * @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector to
  14202. * receive the results (may be vec).
  14203. * @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
  14204. * chained together.
  14205. */
  14206. goog.vec.Mat4.multVec3NoTranslate = function(mat, vec, resultVec) {
  14207. var x = vec[0], y = vec[1], z = vec[2];
  14208. resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8];
  14209. resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9];
  14210. resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10];
  14211. return resultVec;
  14212. };
  14213. /**
  14214. * Transforms the given vector with the given matrix storing the resulting,
  14215. * transformed vector into resultVec. The input vector is multiplied against the
  14216. * full 4x4 matrix with the homogeneous divide applied to reduce the 4 element
  14217. * vector to a 3 element vector.
  14218. *
  14219. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
  14220. * @param {goog.vec.Vec3.AnyType} vec The 3 element vector to transform.
  14221. * @param {goog.vec.Vec3.AnyType} resultVec The 3 element vector
  14222. * to receive the results (may be vec).
  14223. * @return {goog.vec.Vec3.AnyType} return resultVec so that operations can be
  14224. * chained together.
  14225. */
  14226. goog.vec.Mat4.multVec3Projective = function(mat, vec, resultVec) {
  14227. var x = vec[0], y = vec[1], z = vec[2];
  14228. var invw = 1 / (x * mat[3] + y * mat[7] + z * mat[11] + mat[15]);
  14229. resultVec[0] = (x * mat[0] + y * mat[4] + z * mat[8] + mat[12]) * invw;
  14230. resultVec[1] = (x * mat[1] + y * mat[5] + z * mat[9] + mat[13]) * invw;
  14231. resultVec[2] = (x * mat[2] + y * mat[6] + z * mat[10] + mat[14]) * invw;
  14232. return resultVec;
  14233. };
  14234. /**
  14235. * Transforms the given vector with the given matrix storing the resulting,
  14236. * transformed vector into resultVec.
  14237. *
  14238. * @param {goog.vec.Mat4.AnyType} mat The matrix supplying the transformation.
  14239. * @param {goog.vec.Vec4.AnyType} vec The vector to transform.
  14240. * @param {goog.vec.Vec4.AnyType} resultVec The vector to
  14241. * receive the results (may be vec).
  14242. * @return {goog.vec.Vec4.AnyType} return resultVec so that operations can be
  14243. * chained together.
  14244. */
  14245. goog.vec.Mat4.multVec4 = function(mat, vec, resultVec) {
  14246. var x = vec[0], y = vec[1], z = vec[2], w = vec[3];
  14247. resultVec[0] = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
  14248. resultVec[1] = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
  14249. resultVec[2] = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
  14250. resultVec[3] = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
  14251. return resultVec;
  14252. };
  14253. /**
  14254. * Makes the given 4x4 matrix a translation matrix with x, y and z
  14255. * translation factors.
  14256. *
  14257. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14258. * @param {number} x The translation along the x axis.
  14259. * @param {number} y The translation along the y axis.
  14260. * @param {number} z The translation along the z axis.
  14261. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14262. * chained.
  14263. */
  14264. goog.vec.Mat4.makeTranslate = function(mat, x, y, z) {
  14265. goog.vec.Mat4.makeIdentity(mat);
  14266. return goog.vec.Mat4.setColumnValues(mat, 3, x, y, z, 1);
  14267. };
  14268. /**
  14269. * Makes the given 4x4 matrix as a scale matrix with x, y and z scale factors.
  14270. *
  14271. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14272. * @param {number} x The scale along the x axis.
  14273. * @param {number} y The scale along the y axis.
  14274. * @param {number} z The scale along the z axis.
  14275. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14276. * chained.
  14277. */
  14278. goog.vec.Mat4.makeScale = function(mat, x, y, z) {
  14279. goog.vec.Mat4.makeIdentity(mat);
  14280. return goog.vec.Mat4.setDiagonalValues(mat, x, y, z, 1);
  14281. };
  14282. /**
  14283. * Makes the given 4x4 matrix a rotation matrix with the given rotation
  14284. * angle about the axis defined by the vector (ax, ay, az).
  14285. *
  14286. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14287. * @param {number} angle The rotation angle in radians.
  14288. * @param {number} ax The x component of the rotation axis.
  14289. * @param {number} ay The y component of the rotation axis.
  14290. * @param {number} az The z component of the rotation axis.
  14291. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14292. * chained.
  14293. */
  14294. goog.vec.Mat4.makeRotate = function(mat, angle, ax, ay, az) {
  14295. var c = Math.cos(angle);
  14296. var d = 1 - c;
  14297. var s = Math.sin(angle);
  14298. return goog.vec.Mat4.setFromValues(mat,
  14299. ax * ax * d + c,
  14300. ax * ay * d + az * s,
  14301. ax * az * d - ay * s,
  14302. 0,
  14303. ax * ay * d - az * s,
  14304. ay * ay * d + c,
  14305. ay * az * d + ax * s,
  14306. 0,
  14307. ax * az * d + ay * s,
  14308. ay * az * d - ax * s,
  14309. az * az * d + c,
  14310. 0,
  14311. 0, 0, 0, 1);
  14312. };
  14313. /**
  14314. * Makes the given 4x4 matrix a rotation matrix with the given rotation
  14315. * angle about the X axis.
  14316. *
  14317. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14318. * @param {number} angle The rotation angle in radians.
  14319. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14320. * chained.
  14321. */
  14322. goog.vec.Mat4.makeRotateX = function(mat, angle) {
  14323. var c = Math.cos(angle);
  14324. var s = Math.sin(angle);
  14325. return goog.vec.Mat4.setFromValues(
  14326. mat, 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1);
  14327. };
  14328. /**
  14329. * Makes the given 4x4 matrix a rotation matrix with the given rotation
  14330. * angle about the Y axis.
  14331. *
  14332. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14333. * @param {number} angle The rotation angle in radians.
  14334. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14335. * chained.
  14336. */
  14337. goog.vec.Mat4.makeRotateY = function(mat, angle) {
  14338. var c = Math.cos(angle);
  14339. var s = Math.sin(angle);
  14340. return goog.vec.Mat4.setFromValues(
  14341. mat, c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1);
  14342. };
  14343. /**
  14344. * Makes the given 4x4 matrix a rotation matrix with the given rotation
  14345. * angle about the Z axis.
  14346. *
  14347. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14348. * @param {number} angle The rotation angle in radians.
  14349. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14350. * chained.
  14351. */
  14352. goog.vec.Mat4.makeRotateZ = function(mat, angle) {
  14353. var c = Math.cos(angle);
  14354. var s = Math.sin(angle);
  14355. return goog.vec.Mat4.setFromValues(
  14356. mat, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  14357. };
  14358. /**
  14359. * Makes the given 4x4 matrix a perspective projection matrix.
  14360. *
  14361. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14362. * @param {number} left The coordinate of the left clipping plane.
  14363. * @param {number} right The coordinate of the right clipping plane.
  14364. * @param {number} bottom The coordinate of the bottom clipping plane.
  14365. * @param {number} top The coordinate of the top clipping plane.
  14366. * @param {number} near The distance to the near clipping plane.
  14367. * @param {number} far The distance to the far clipping plane.
  14368. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14369. * chained.
  14370. */
  14371. goog.vec.Mat4.makeFrustum = function(mat, left, right, bottom, top, near, far) {
  14372. var x = (2 * near) / (right - left);
  14373. var y = (2 * near) / (top - bottom);
  14374. var a = (right + left) / (right - left);
  14375. var b = (top + bottom) / (top - bottom);
  14376. var c = -(far + near) / (far - near);
  14377. var d = -(2 * far * near) / (far - near);
  14378. return goog.vec.Mat4.setFromValues(mat,
  14379. x, 0, 0, 0,
  14380. 0, y, 0, 0,
  14381. a, b, c, -1,
  14382. 0, 0, d, 0
  14383. );
  14384. };
  14385. /**
  14386. * Makse the given 4x4 matrix perspective projection matrix given a
  14387. * field of view and aspect ratio.
  14388. *
  14389. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14390. * @param {number} fovy The field of view along the y (vertical) axis in
  14391. * radians.
  14392. * @param {number} aspect The x (width) to y (height) aspect ratio.
  14393. * @param {number} near The distance to the near clipping plane.
  14394. * @param {number} far The distance to the far clipping plane.
  14395. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14396. * chained.
  14397. */
  14398. goog.vec.Mat4.makePerspective = function(mat, fovy, aspect, near, far) {
  14399. var angle = fovy / 2;
  14400. var dz = far - near;
  14401. var sinAngle = Math.sin(angle);
  14402. if (dz == 0 || sinAngle == 0 || aspect == 0) {
  14403. return mat;
  14404. }
  14405. var cot = Math.cos(angle) / sinAngle;
  14406. return goog.vec.Mat4.setFromValues(mat,
  14407. cot / aspect, 0, 0, 0,
  14408. 0, cot, 0, 0,
  14409. 0, 0, -(far + near) / dz, -1,
  14410. 0, 0, -(2 * near * far) / dz, 0
  14411. );
  14412. };
  14413. /**
  14414. * Makes the given 4x4 matrix an orthographic projection matrix.
  14415. *
  14416. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14417. * @param {number} left The coordinate of the left clipping plane.
  14418. * @param {number} right The coordinate of the right clipping plane.
  14419. * @param {number} bottom The coordinate of the bottom clipping plane.
  14420. * @param {number} top The coordinate of the top clipping plane.
  14421. * @param {number} near The distance to the near clipping plane.
  14422. * @param {number} far The distance to the far clipping plane.
  14423. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14424. * chained.
  14425. */
  14426. goog.vec.Mat4.makeOrtho = function(mat, left, right, bottom, top, near, far) {
  14427. var x = 2 / (right - left);
  14428. var y = 2 / (top - bottom);
  14429. var z = -2 / (far - near);
  14430. var a = -(right + left) / (right - left);
  14431. var b = -(top + bottom) / (top - bottom);
  14432. var c = -(far + near) / (far - near);
  14433. return goog.vec.Mat4.setFromValues(mat,
  14434. x, 0, 0, 0,
  14435. 0, y, 0, 0,
  14436. 0, 0, z, 0,
  14437. a, b, c, 1
  14438. );
  14439. };
  14440. /**
  14441. * Makes the given 4x4 matrix a modelview matrix of a camera so that
  14442. * the camera is 'looking at' the given center point.
  14443. *
  14444. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14445. * @param {goog.vec.Vec3.AnyType} eyePt The position of the eye point
  14446. * (camera origin).
  14447. * @param {goog.vec.Vec3.AnyType} centerPt The point to aim the camera at.
  14448. * @param {goog.vec.Vec3.AnyType} worldUpVec The vector that identifies
  14449. * the up direction for the camera.
  14450. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14451. * chained.
  14452. */
  14453. goog.vec.Mat4.makeLookAt = function(mat, eyePt, centerPt, worldUpVec) {
  14454. // Compute the direction vector from the eye point to the center point and
  14455. // normalize.
  14456. var fwdVec = goog.vec.Mat4.tmpVec4_[0];
  14457. goog.vec.Vec3.subtract(centerPt, eyePt, fwdVec);
  14458. goog.vec.Vec3.normalize(fwdVec, fwdVec);
  14459. fwdVec[3] = 0;
  14460. // Compute the side vector from the forward vector and the input up vector.
  14461. var sideVec = goog.vec.Mat4.tmpVec4_[1];
  14462. goog.vec.Vec3.cross(fwdVec, worldUpVec, sideVec);
  14463. goog.vec.Vec3.normalize(sideVec, sideVec);
  14464. sideVec[3] = 0;
  14465. // Now the up vector to form the orthonormal basis.
  14466. var upVec = goog.vec.Mat4.tmpVec4_[2];
  14467. goog.vec.Vec3.cross(sideVec, fwdVec, upVec);
  14468. goog.vec.Vec3.normalize(upVec, upVec);
  14469. upVec[3] = 0;
  14470. // Update the view matrix with the new orthonormal basis and position the
  14471. // camera at the given eye point.
  14472. goog.vec.Vec3.negate(fwdVec, fwdVec);
  14473. goog.vec.Mat4.setRow(mat, 0, sideVec);
  14474. goog.vec.Mat4.setRow(mat, 1, upVec);
  14475. goog.vec.Mat4.setRow(mat, 2, fwdVec);
  14476. goog.vec.Mat4.setRowValues(mat, 3, 0, 0, 0, 1);
  14477. goog.vec.Mat4.translate(
  14478. mat, -eyePt[0], -eyePt[1], -eyePt[2]);
  14479. return mat;
  14480. };
  14481. /**
  14482. * Decomposes a matrix into the lookAt vectors eyePt, fwdVec and worldUpVec.
  14483. * The matrix represents the modelview matrix of a camera. It is the inverse
  14484. * of lookAt except for the output of the fwdVec instead of centerPt.
  14485. * The centerPt itself cannot be recovered from a modelview matrix.
  14486. *
  14487. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14488. * @param {goog.vec.Vec3.AnyType} eyePt The position of the eye point
  14489. * (camera origin).
  14490. * @param {goog.vec.Vec3.AnyType} fwdVec The vector describing where
  14491. * the camera points to.
  14492. * @param {goog.vec.Vec3.AnyType} worldUpVec The vector that
  14493. * identifies the up direction for the camera.
  14494. * @return {boolean} True if the method succeeds, false otherwise.
  14495. * The method can only fail if the inverse of viewMatrix is not defined.
  14496. */
  14497. goog.vec.Mat4.toLookAt = function(mat, eyePt, fwdVec, worldUpVec) {
  14498. // Get eye of the camera.
  14499. var matInverse = goog.vec.Mat4.tmpMat4_[0];
  14500. if (!goog.vec.Mat4.invert(mat, matInverse)) {
  14501. // The input matrix does not have a valid inverse.
  14502. return false;
  14503. }
  14504. if (eyePt) {
  14505. eyePt[0] = matInverse[12];
  14506. eyePt[1] = matInverse[13];
  14507. eyePt[2] = matInverse[14];
  14508. }
  14509. // Get forward vector from the definition of lookAt.
  14510. if (fwdVec || worldUpVec) {
  14511. if (!fwdVec) {
  14512. fwdVec = goog.vec.Mat4.tmpVec3_[0];
  14513. }
  14514. fwdVec[0] = -mat[2];
  14515. fwdVec[1] = -mat[6];
  14516. fwdVec[2] = -mat[10];
  14517. // Normalize forward vector.
  14518. goog.vec.Vec3.normalize(fwdVec, fwdVec);
  14519. }
  14520. if (worldUpVec) {
  14521. // Get side vector from the definition of gluLookAt.
  14522. var side = goog.vec.Mat4.tmpVec3_[1];
  14523. side[0] = mat[0];
  14524. side[1] = mat[4];
  14525. side[2] = mat[8];
  14526. // Compute up vector as a up = side x forward.
  14527. goog.vec.Vec3.cross(side, fwdVec, worldUpVec);
  14528. // Normalize up vector.
  14529. goog.vec.Vec3.normalize(worldUpVec, worldUpVec);
  14530. }
  14531. return true;
  14532. };
  14533. /**
  14534. * Makes the given 4x4 matrix a rotation matrix given Euler angles using
  14535. * the ZXZ convention.
  14536. * Given the euler angles [theta1, theta2, theta3], the rotation is defined as
  14537. * rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
  14538. * with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
  14539. * rotation_x(theta) means rotation around the X axis of theta radians,
  14540. *
  14541. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14542. * @param {number} theta1 The angle of rotation around the Z axis in radians.
  14543. * @param {number} theta2 The angle of rotation around the X axis in radians.
  14544. * @param {number} theta3 The angle of rotation around the Z axis in radians.
  14545. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14546. * chained.
  14547. */
  14548. goog.vec.Mat4.makeEulerZXZ = function(mat, theta1, theta2, theta3) {
  14549. var c1 = Math.cos(theta1);
  14550. var s1 = Math.sin(theta1);
  14551. var c2 = Math.cos(theta2);
  14552. var s2 = Math.sin(theta2);
  14553. var c3 = Math.cos(theta3);
  14554. var s3 = Math.sin(theta3);
  14555. mat[0] = c1 * c3 - c2 * s1 * s3;
  14556. mat[1] = c2 * c1 * s3 + c3 * s1;
  14557. mat[2] = s3 * s2;
  14558. mat[3] = 0;
  14559. mat[4] = -c1 * s3 - c3 * c2 * s1;
  14560. mat[5] = c1 * c2 * c3 - s1 * s3;
  14561. mat[6] = c3 * s2;
  14562. mat[7] = 0;
  14563. mat[8] = s2 * s1;
  14564. mat[9] = -c1 * s2;
  14565. mat[10] = c2;
  14566. mat[11] = 0;
  14567. mat[12] = 0;
  14568. mat[13] = 0;
  14569. mat[14] = 0;
  14570. mat[15] = 1;
  14571. return mat;
  14572. };
  14573. /**
  14574. * Decomposes a rotation matrix into Euler angles using the ZXZ convention so
  14575. * that rotation = rotation_z(theta1) * rotation_x(theta2) * rotation_z(theta3),
  14576. * with theta1 in [0, 2 * pi], theta2 in [0, pi] and theta3 in [0, 2 * pi].
  14577. * rotation_x(theta) means rotation around the X axis of theta radians.
  14578. *
  14579. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14580. * @param {goog.vec.Vec3.AnyType} euler The ZXZ Euler angles in
  14581. * radians as [theta1, theta2, theta3].
  14582. * @param {boolean=} opt_theta2IsNegative Whether theta2 is in [-pi, 0] instead
  14583. * of the default [0, pi].
  14584. * @return {goog.vec.Vec4.AnyType} return euler so that operations can be
  14585. * chained together.
  14586. */
  14587. goog.vec.Mat4.toEulerZXZ = function(mat, euler, opt_theta2IsNegative) {
  14588. // There is an ambiguity in the sign of sinTheta2 because of the sqrt.
  14589. var sinTheta2 = Math.sqrt(mat[2] * mat[2] + mat[6] * mat[6]);
  14590. // By default we explicitely constrain theta2 to be in [0, pi],
  14591. // so sinTheta2 is always positive. We can change the behavior and specify
  14592. // theta2 to be negative in [-pi, 0] with opt_Theta2IsNegative.
  14593. var signTheta2 = opt_theta2IsNegative ? -1 : 1;
  14594. if (sinTheta2 > goog.vec.EPSILON) {
  14595. euler[2] = Math.atan2(mat[2] * signTheta2, mat[6] * signTheta2);
  14596. euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[10]);
  14597. euler[0] = Math.atan2(mat[8] * signTheta2, -mat[9] * signTheta2);
  14598. } else {
  14599. // There is also an arbitrary choice for theta1 = 0 or theta2 = 0 here.
  14600. // We assume theta1 = 0 as some applications do not allow the camera to roll
  14601. // (i.e. have theta1 != 0).
  14602. euler[0] = 0;
  14603. euler[1] = Math.atan2(sinTheta2 * signTheta2, mat[10]);
  14604. euler[2] = Math.atan2(mat[1], mat[0]);
  14605. }
  14606. // Atan2 outputs angles in [-pi, pi] so we bring them back to [0, 2 * pi].
  14607. euler[0] = (euler[0] + Math.PI * 2) % (Math.PI * 2);
  14608. euler[2] = (euler[2] + Math.PI * 2) % (Math.PI * 2);
  14609. // For theta2 we want the angle to be in [0, pi] or [-pi, 0] depending on
  14610. // signTheta2.
  14611. euler[1] = ((euler[1] * signTheta2 + Math.PI * 2) % (Math.PI * 2)) *
  14612. signTheta2;
  14613. return euler;
  14614. };
  14615. /**
  14616. * Translates the given matrix by x,y,z. Equvialent to:
  14617. * goog.vec.Mat4.multMat(
  14618. * mat,
  14619. * goog.vec.Mat4.makeTranslate(goog.vec.Mat4.create(), x, y, z),
  14620. * mat);
  14621. *
  14622. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14623. * @param {number} x The translation along the x axis.
  14624. * @param {number} y The translation along the y axis.
  14625. * @param {number} z The translation along the z axis.
  14626. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14627. * chained.
  14628. */
  14629. goog.vec.Mat4.translate = function(mat, x, y, z) {
  14630. return goog.vec.Mat4.setColumnValues(
  14631. mat, 3,
  14632. mat[0] * x + mat[4] * y + mat[8] * z + mat[12],
  14633. mat[1] * x + mat[5] * y + mat[9] * z + mat[13],
  14634. mat[2] * x + mat[6] * y + mat[10] * z + mat[14],
  14635. mat[3] * x + mat[7] * y + mat[11] * z + mat[15]);
  14636. };
  14637. /**
  14638. * Scales the given matrix by x,y,z. Equivalent to:
  14639. * goog.vec.Mat4.multMat(
  14640. * mat,
  14641. * goog.vec.Mat4.makeScale(goog.vec.Mat4.create(), x, y, z),
  14642. * mat);
  14643. *
  14644. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14645. * @param {number} x The x scale factor.
  14646. * @param {number} y The y scale factor.
  14647. * @param {number} z The z scale factor.
  14648. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14649. * chained.
  14650. */
  14651. goog.vec.Mat4.scale = function(mat, x, y, z) {
  14652. return goog.vec.Mat4.setFromValues(
  14653. mat,
  14654. mat[0] * x, mat[1] * x, mat[2] * x, mat[3] * x,
  14655. mat[4] * y, mat[5] * y, mat[6] * y, mat[7] * y,
  14656. mat[8] * z, mat[9] * z, mat[10] * z, mat[11] * z,
  14657. mat[12], mat[13], mat[14], mat[15]);
  14658. };
  14659. /**
  14660. * Rotate the given matrix by angle about the x,y,z axis. Equivalent to:
  14661. * goog.vec.Mat4.multMat(
  14662. * mat,
  14663. * goog.vec.Mat4.makeRotate(goog.vec.Mat4.create(), angle, x, y, z),
  14664. * mat);
  14665. *
  14666. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14667. * @param {number} angle The angle in radians.
  14668. * @param {number} x The x component of the rotation axis.
  14669. * @param {number} y The y component of the rotation axis.
  14670. * @param {number} z The z component of the rotation axis.
  14671. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14672. * chained.
  14673. */
  14674. goog.vec.Mat4.rotate = function(mat, angle, x, y, z) {
  14675. var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
  14676. var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
  14677. var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
  14678. var m03 = mat[12], m13 = mat[13], m23 = mat[14], m33 = mat[15];
  14679. var cosAngle = Math.cos(angle);
  14680. var sinAngle = Math.sin(angle);
  14681. var diffCosAngle = 1 - cosAngle;
  14682. var r00 = x * x * diffCosAngle + cosAngle;
  14683. var r10 = x * y * diffCosAngle + z * sinAngle;
  14684. var r20 = x * z * diffCosAngle - y * sinAngle;
  14685. var r01 = x * y * diffCosAngle - z * sinAngle;
  14686. var r11 = y * y * diffCosAngle + cosAngle;
  14687. var r21 = y * z * diffCosAngle + x * sinAngle;
  14688. var r02 = x * z * diffCosAngle + y * sinAngle;
  14689. var r12 = y * z * diffCosAngle - x * sinAngle;
  14690. var r22 = z * z * diffCosAngle + cosAngle;
  14691. return goog.vec.Mat4.setFromValues(
  14692. mat,
  14693. m00 * r00 + m01 * r10 + m02 * r20,
  14694. m10 * r00 + m11 * r10 + m12 * r20,
  14695. m20 * r00 + m21 * r10 + m22 * r20,
  14696. m30 * r00 + m31 * r10 + m32 * r20,
  14697. m00 * r01 + m01 * r11 + m02 * r21,
  14698. m10 * r01 + m11 * r11 + m12 * r21,
  14699. m20 * r01 + m21 * r11 + m22 * r21,
  14700. m30 * r01 + m31 * r11 + m32 * r21,
  14701. m00 * r02 + m01 * r12 + m02 * r22,
  14702. m10 * r02 + m11 * r12 + m12 * r22,
  14703. m20 * r02 + m21 * r12 + m22 * r22,
  14704. m30 * r02 + m31 * r12 + m32 * r22,
  14705. m03, m13, m23, m33);
  14706. };
  14707. /**
  14708. * Rotate the given matrix by angle about the x axis. Equivalent to:
  14709. * goog.vec.Mat4.multMat(
  14710. * mat,
  14711. * goog.vec.Mat4.makeRotateX(goog.vec.Mat4.create(), angle),
  14712. * mat);
  14713. *
  14714. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14715. * @param {number} angle The angle in radians.
  14716. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14717. * chained.
  14718. */
  14719. goog.vec.Mat4.rotateX = function(mat, angle) {
  14720. var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
  14721. var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
  14722. var c = Math.cos(angle);
  14723. var s = Math.sin(angle);
  14724. mat[4] = m01 * c + m02 * s;
  14725. mat[5] = m11 * c + m12 * s;
  14726. mat[6] = m21 * c + m22 * s;
  14727. mat[7] = m31 * c + m32 * s;
  14728. mat[8] = m01 * -s + m02 * c;
  14729. mat[9] = m11 * -s + m12 * c;
  14730. mat[10] = m21 * -s + m22 * c;
  14731. mat[11] = m31 * -s + m32 * c;
  14732. return mat;
  14733. };
  14734. /**
  14735. * Rotate the given matrix by angle about the y axis. Equivalent to:
  14736. * goog.vec.Mat4.multMat(
  14737. * mat,
  14738. * goog.vec.Mat4.makeRotateY(goog.vec.Mat4.create(), angle),
  14739. * mat);
  14740. *
  14741. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14742. * @param {number} angle The angle in radians.
  14743. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14744. * chained.
  14745. */
  14746. goog.vec.Mat4.rotateY = function(mat, angle) {
  14747. var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
  14748. var m02 = mat[8], m12 = mat[9], m22 = mat[10], m32 = mat[11];
  14749. var c = Math.cos(angle);
  14750. var s = Math.sin(angle);
  14751. mat[0] = m00 * c + m02 * -s;
  14752. mat[1] = m10 * c + m12 * -s;
  14753. mat[2] = m20 * c + m22 * -s;
  14754. mat[3] = m30 * c + m32 * -s;
  14755. mat[8] = m00 * s + m02 * c;
  14756. mat[9] = m10 * s + m12 * c;
  14757. mat[10] = m20 * s + m22 * c;
  14758. mat[11] = m30 * s + m32 * c;
  14759. return mat;
  14760. };
  14761. /**
  14762. * Rotate the given matrix by angle about the z axis. Equivalent to:
  14763. * goog.vec.Mat4.multMat(
  14764. * mat,
  14765. * goog.vec.Mat4.makeRotateZ(goog.vec.Mat4.create(), angle),
  14766. * mat);
  14767. *
  14768. * @param {goog.vec.Mat4.AnyType} mat The matrix.
  14769. * @param {number} angle The angle in radians.
  14770. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14771. * chained.
  14772. */
  14773. goog.vec.Mat4.rotateZ = function(mat, angle) {
  14774. var m00 = mat[0], m10 = mat[1], m20 = mat[2], m30 = mat[3];
  14775. var m01 = mat[4], m11 = mat[5], m21 = mat[6], m31 = mat[7];
  14776. var c = Math.cos(angle);
  14777. var s = Math.sin(angle);
  14778. mat[0] = m00 * c + m01 * s;
  14779. mat[1] = m10 * c + m11 * s;
  14780. mat[2] = m20 * c + m21 * s;
  14781. mat[3] = m30 * c + m31 * s;
  14782. mat[4] = m00 * -s + m01 * c;
  14783. mat[5] = m10 * -s + m11 * c;
  14784. mat[6] = m20 * -s + m21 * c;
  14785. mat[7] = m30 * -s + m31 * c;
  14786. return mat;
  14787. };
  14788. /**
  14789. * Retrieves the translation component of the transformation matrix.
  14790. *
  14791. * @param {goog.vec.Mat4.AnyType} mat The transformation matrix.
  14792. * @param {goog.vec.Vec3.AnyType} translation The vector for storing the
  14793. * result.
  14794. * @return {goog.vec.Mat4.AnyType} return mat so that operations can be
  14795. * chained.
  14796. */
  14797. goog.vec.Mat4.getTranslation = function(mat, translation) {
  14798. translation[0] = mat[12];
  14799. translation[1] = mat[13];
  14800. translation[2] = mat[14];
  14801. return translation;
  14802. };
  14803. /**
  14804. * @type {!Array<!goog.vec.Vec3.Type>}
  14805. * @private
  14806. */
  14807. goog.vec.Mat4.tmpVec3_ = [
  14808. goog.vec.Vec3.createFloat64(),
  14809. goog.vec.Vec3.createFloat64()
  14810. ];
  14811. /**
  14812. * @type {!Array<!goog.vec.Vec4.Type>}
  14813. * @private
  14814. */
  14815. goog.vec.Mat4.tmpVec4_ = [
  14816. goog.vec.Vec4.createFloat64(),
  14817. goog.vec.Vec4.createFloat64(),
  14818. goog.vec.Vec4.createFloat64()
  14819. ];
  14820. /**
  14821. * @type {!Array<!goog.vec.Mat4.Type>}
  14822. * @private
  14823. */
  14824. goog.vec.Mat4.tmpMat4_ = [
  14825. goog.vec.Mat4.createFloat64()
  14826. ];
  14827. goog.provide('ol.TransformFunction');
  14828. /**
  14829. * A transform function accepts an array of input coordinate values, an optional
  14830. * output array, and an optional dimension (default should be 2). The function
  14831. * transforms the input coordinate values, populates the output array, and
  14832. * returns the output array.
  14833. *
  14834. * @typedef {function(Array.<number>, Array.<number>=, number=): Array.<number>}
  14835. * @api stable
  14836. */
  14837. ol.TransformFunction;
  14838. goog.provide('ol.Extent');
  14839. goog.provide('ol.extent');
  14840. goog.provide('ol.extent.Corner');
  14841. goog.provide('ol.extent.Relationship');
  14842. goog.require('goog.asserts');
  14843. goog.require('goog.vec.Mat4');
  14844. goog.require('ol.Coordinate');
  14845. goog.require('ol.Size');
  14846. goog.require('ol.TransformFunction');
  14847. /**
  14848. * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`.
  14849. * @typedef {Array.<number>}
  14850. * @api stable
  14851. */
  14852. ol.Extent;
  14853. /**
  14854. * Extent corner.
  14855. * @enum {string}
  14856. */
  14857. ol.extent.Corner = {
  14858. BOTTOM_LEFT: 'bottom-left',
  14859. BOTTOM_RIGHT: 'bottom-right',
  14860. TOP_LEFT: 'top-left',
  14861. TOP_RIGHT: 'top-right'
  14862. };
  14863. /**
  14864. * Relationship to an extent.
  14865. * @enum {number}
  14866. */
  14867. ol.extent.Relationship = {
  14868. UNKNOWN: 0,
  14869. INTERSECTING: 1,
  14870. ABOVE: 2,
  14871. RIGHT: 4,
  14872. BELOW: 8,
  14873. LEFT: 16
  14874. };
  14875. /**
  14876. * Build an extent that includes all given coordinates.
  14877. *
  14878. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  14879. * @return {ol.Extent} Bounding extent.
  14880. * @api stable
  14881. */
  14882. ol.extent.boundingExtent = function(coordinates) {
  14883. var extent = ol.extent.createEmpty();
  14884. for (var i = 0, ii = coordinates.length; i < ii; ++i) {
  14885. ol.extent.extendCoordinate(extent, coordinates[i]);
  14886. }
  14887. return extent;
  14888. };
  14889. /**
  14890. * @param {Array.<number>} xs Xs.
  14891. * @param {Array.<number>} ys Ys.
  14892. * @param {ol.Extent=} opt_extent Destination extent.
  14893. * @private
  14894. * @return {ol.Extent} Extent.
  14895. */
  14896. ol.extent.boundingExtentXYs_ = function(xs, ys, opt_extent) {
  14897. goog.asserts.assert(xs.length > 0, 'xs length should be larger than 0');
  14898. goog.asserts.assert(ys.length > 0, 'ys length should be larger than 0');
  14899. var minX = Math.min.apply(null, xs);
  14900. var minY = Math.min.apply(null, ys);
  14901. var maxX = Math.max.apply(null, xs);
  14902. var maxY = Math.max.apply(null, ys);
  14903. return ol.extent.createOrUpdate(minX, minY, maxX, maxY, opt_extent);
  14904. };
  14905. /**
  14906. * Return extent increased by the provided value.
  14907. * @param {ol.Extent} extent Extent.
  14908. * @param {number} value The amount by which the extent should be buffered.
  14909. * @param {ol.Extent=} opt_extent Extent.
  14910. * @return {ol.Extent} Extent.
  14911. * @api stable
  14912. */
  14913. ol.extent.buffer = function(extent, value, opt_extent) {
  14914. if (opt_extent) {
  14915. opt_extent[0] = extent[0] - value;
  14916. opt_extent[1] = extent[1] - value;
  14917. opt_extent[2] = extent[2] + value;
  14918. opt_extent[3] = extent[3] + value;
  14919. return opt_extent;
  14920. } else {
  14921. return [
  14922. extent[0] - value,
  14923. extent[1] - value,
  14924. extent[2] + value,
  14925. extent[3] + value
  14926. ];
  14927. }
  14928. };
  14929. /**
  14930. * Creates a clone of an extent.
  14931. *
  14932. * @param {ol.Extent} extent Extent to clone.
  14933. * @param {ol.Extent=} opt_extent Extent.
  14934. * @return {ol.Extent} The clone.
  14935. */
  14936. ol.extent.clone = function(extent, opt_extent) {
  14937. if (opt_extent) {
  14938. opt_extent[0] = extent[0];
  14939. opt_extent[1] = extent[1];
  14940. opt_extent[2] = extent[2];
  14941. opt_extent[3] = extent[3];
  14942. return opt_extent;
  14943. } else {
  14944. return extent.slice();
  14945. }
  14946. };
  14947. /**
  14948. * @param {ol.Extent} extent Extent.
  14949. * @param {number} x X.
  14950. * @param {number} y Y.
  14951. * @return {number} Closest squared distance.
  14952. */
  14953. ol.extent.closestSquaredDistanceXY = function(extent, x, y) {
  14954. var dx, dy;
  14955. if (x < extent[0]) {
  14956. dx = extent[0] - x;
  14957. } else if (extent[2] < x) {
  14958. dx = x - extent[2];
  14959. } else {
  14960. dx = 0;
  14961. }
  14962. if (y < extent[1]) {
  14963. dy = extent[1] - y;
  14964. } else if (extent[3] < y) {
  14965. dy = y - extent[3];
  14966. } else {
  14967. dy = 0;
  14968. }
  14969. return dx * dx + dy * dy;
  14970. };
  14971. /**
  14972. * Check if the passed coordinate is contained or on the edge of the extent.
  14973. *
  14974. * @param {ol.Extent} extent Extent.
  14975. * @param {ol.Coordinate} coordinate Coordinate.
  14976. * @return {boolean} The coordinate is contained in the extent.
  14977. * @api stable
  14978. */
  14979. ol.extent.containsCoordinate = function(extent, coordinate) {
  14980. return ol.extent.containsXY(extent, coordinate[0], coordinate[1]);
  14981. };
  14982. /**
  14983. * Check if one extent contains another.
  14984. *
  14985. * An extent is deemed contained if it lies completely within the other extent,
  14986. * including if they share one or more edges.
  14987. *
  14988. * @param {ol.Extent} extent1 Extent 1.
  14989. * @param {ol.Extent} extent2 Extent 2.
  14990. * @return {boolean} The second extent is contained by or on the edge of the
  14991. * first.
  14992. * @api stable
  14993. */
  14994. ol.extent.containsExtent = function(extent1, extent2) {
  14995. return extent1[0] <= extent2[0] && extent2[2] <= extent1[2] &&
  14996. extent1[1] <= extent2[1] && extent2[3] <= extent1[3];
  14997. };
  14998. /**
  14999. * Check if the passed coordinate is contained or on the edge of the extent.
  15000. *
  15001. * @param {ol.Extent} extent Extent.
  15002. * @param {number} x X coordinate.
  15003. * @param {number} y Y coordinate.
  15004. * @return {boolean} The x, y values are contained in the extent.
  15005. * @api stable
  15006. */
  15007. ol.extent.containsXY = function(extent, x, y) {
  15008. return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3];
  15009. };
  15010. /**
  15011. * Get the relationship between a coordinate and extent.
  15012. * @param {ol.Extent} extent The extent.
  15013. * @param {ol.Coordinate} coordinate The coordinate.
  15014. * @return {number} The relationship (bitwise compare with
  15015. * ol.extent.Relationship).
  15016. */
  15017. ol.extent.coordinateRelationship = function(extent, coordinate) {
  15018. var minX = extent[0];
  15019. var minY = extent[1];
  15020. var maxX = extent[2];
  15021. var maxY = extent[3];
  15022. var x = coordinate[0];
  15023. var y = coordinate[1];
  15024. var relationship = ol.extent.Relationship.UNKNOWN;
  15025. if (x < minX) {
  15026. relationship = relationship | ol.extent.Relationship.LEFT;
  15027. } else if (x > maxX) {
  15028. relationship = relationship | ol.extent.Relationship.RIGHT;
  15029. }
  15030. if (y < minY) {
  15031. relationship = relationship | ol.extent.Relationship.BELOW;
  15032. } else if (y > maxY) {
  15033. relationship = relationship | ol.extent.Relationship.ABOVE;
  15034. }
  15035. if (relationship === ol.extent.Relationship.UNKNOWN) {
  15036. relationship = ol.extent.Relationship.INTERSECTING;
  15037. }
  15038. return relationship;
  15039. };
  15040. /**
  15041. * Create an empty extent.
  15042. * @return {ol.Extent} Empty extent.
  15043. * @api stable
  15044. */
  15045. ol.extent.createEmpty = function() {
  15046. return [Infinity, Infinity, -Infinity, -Infinity];
  15047. };
  15048. /**
  15049. * Create a new extent or update the provided extent.
  15050. * @param {number} minX Minimum X.
  15051. * @param {number} minY Minimum Y.
  15052. * @param {number} maxX Maximum X.
  15053. * @param {number} maxY Maximum Y.
  15054. * @param {ol.Extent=} opt_extent Destination extent.
  15055. * @return {ol.Extent} Extent.
  15056. */
  15057. ol.extent.createOrUpdate = function(minX, minY, maxX, maxY, opt_extent) {
  15058. if (opt_extent) {
  15059. opt_extent[0] = minX;
  15060. opt_extent[1] = minY;
  15061. opt_extent[2] = maxX;
  15062. opt_extent[3] = maxY;
  15063. return opt_extent;
  15064. } else {
  15065. return [minX, minY, maxX, maxY];
  15066. }
  15067. };
  15068. /**
  15069. * Create a new empty extent or make the provided one empty.
  15070. * @param {ol.Extent=} opt_extent Extent.
  15071. * @return {ol.Extent} Extent.
  15072. */
  15073. ol.extent.createOrUpdateEmpty = function(opt_extent) {
  15074. return ol.extent.createOrUpdate(
  15075. Infinity, Infinity, -Infinity, -Infinity, opt_extent);
  15076. };
  15077. /**
  15078. * @param {ol.Coordinate} coordinate Coordinate.
  15079. * @param {ol.Extent=} opt_extent Extent.
  15080. * @return {ol.Extent} Extent.
  15081. */
  15082. ol.extent.createOrUpdateFromCoordinate = function(coordinate, opt_extent) {
  15083. var x = coordinate[0];
  15084. var y = coordinate[1];
  15085. return ol.extent.createOrUpdate(x, y, x, y, opt_extent);
  15086. };
  15087. /**
  15088. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  15089. * @param {ol.Extent=} opt_extent Extent.
  15090. * @return {ol.Extent} Extent.
  15091. */
  15092. ol.extent.createOrUpdateFromCoordinates = function(coordinates, opt_extent) {
  15093. var extent = ol.extent.createOrUpdateEmpty(opt_extent);
  15094. return ol.extent.extendCoordinates(extent, coordinates);
  15095. };
  15096. /**
  15097. * @param {Array.<number>} flatCoordinates Flat coordinates.
  15098. * @param {number} offset Offset.
  15099. * @param {number} end End.
  15100. * @param {number} stride Stride.
  15101. * @param {ol.Extent=} opt_extent Extent.
  15102. * @return {ol.Extent} Extent.
  15103. */
  15104. ol.extent.createOrUpdateFromFlatCoordinates =
  15105. function(flatCoordinates, offset, end, stride, opt_extent) {
  15106. var extent = ol.extent.createOrUpdateEmpty(opt_extent);
  15107. return ol.extent.extendFlatCoordinates(
  15108. extent, flatCoordinates, offset, end, stride);
  15109. };
  15110. /**
  15111. * @param {Array.<Array.<ol.Coordinate>>} rings Rings.
  15112. * @param {ol.Extent=} opt_extent Extent.
  15113. * @return {ol.Extent} Extent.
  15114. */
  15115. ol.extent.createOrUpdateFromRings = function(rings, opt_extent) {
  15116. var extent = ol.extent.createOrUpdateEmpty(opt_extent);
  15117. return ol.extent.extendRings(extent, rings);
  15118. };
  15119. /**
  15120. * Empty an extent in place.
  15121. * @param {ol.Extent} extent Extent.
  15122. * @return {ol.Extent} Extent.
  15123. */
  15124. ol.extent.empty = function(extent) {
  15125. extent[0] = extent[1] = Infinity;
  15126. extent[2] = extent[3] = -Infinity;
  15127. return extent;
  15128. };
  15129. /**
  15130. * Determine if two extents are equivalent.
  15131. * @param {ol.Extent} extent1 Extent 1.
  15132. * @param {ol.Extent} extent2 Extent 2.
  15133. * @return {boolean} The two extents are equivalent.
  15134. * @api stable
  15135. */
  15136. ol.extent.equals = function(extent1, extent2) {
  15137. return extent1[0] == extent2[0] && extent1[2] == extent2[2] &&
  15138. extent1[1] == extent2[1] && extent1[3] == extent2[3];
  15139. };
  15140. /**
  15141. * Modify an extent to include another extent.
  15142. * @param {ol.Extent} extent1 The extent to be modified.
  15143. * @param {ol.Extent} extent2 The extent that will be included in the first.
  15144. * @return {ol.Extent} A reference to the first (extended) extent.
  15145. * @api stable
  15146. */
  15147. ol.extent.extend = function(extent1, extent2) {
  15148. if (extent2[0] < extent1[0]) {
  15149. extent1[0] = extent2[0];
  15150. }
  15151. if (extent2[2] > extent1[2]) {
  15152. extent1[2] = extent2[2];
  15153. }
  15154. if (extent2[1] < extent1[1]) {
  15155. extent1[1] = extent2[1];
  15156. }
  15157. if (extent2[3] > extent1[3]) {
  15158. extent1[3] = extent2[3];
  15159. }
  15160. return extent1;
  15161. };
  15162. /**
  15163. * @param {ol.Extent} extent Extent.
  15164. * @param {ol.Coordinate} coordinate Coordinate.
  15165. */
  15166. ol.extent.extendCoordinate = function(extent, coordinate) {
  15167. if (coordinate[0] < extent[0]) {
  15168. extent[0] = coordinate[0];
  15169. }
  15170. if (coordinate[0] > extent[2]) {
  15171. extent[2] = coordinate[0];
  15172. }
  15173. if (coordinate[1] < extent[1]) {
  15174. extent[1] = coordinate[1];
  15175. }
  15176. if (coordinate[1] > extent[3]) {
  15177. extent[3] = coordinate[1];
  15178. }
  15179. };
  15180. /**
  15181. * @param {ol.Extent} extent Extent.
  15182. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  15183. * @return {ol.Extent} Extent.
  15184. */
  15185. ol.extent.extendCoordinates = function(extent, coordinates) {
  15186. var i, ii;
  15187. for (i = 0, ii = coordinates.length; i < ii; ++i) {
  15188. ol.extent.extendCoordinate(extent, coordinates[i]);
  15189. }
  15190. return extent;
  15191. };
  15192. /**
  15193. * @param {ol.Extent} extent Extent.
  15194. * @param {Array.<number>} flatCoordinates Flat coordinates.
  15195. * @param {number} offset Offset.
  15196. * @param {number} end End.
  15197. * @param {number} stride Stride.
  15198. * @return {ol.Extent} Extent.
  15199. */
  15200. ol.extent.extendFlatCoordinates =
  15201. function(extent, flatCoordinates, offset, end, stride) {
  15202. for (; offset < end; offset += stride) {
  15203. ol.extent.extendXY(
  15204. extent, flatCoordinates[offset], flatCoordinates[offset + 1]);
  15205. }
  15206. return extent;
  15207. };
  15208. /**
  15209. * @param {ol.Extent} extent Extent.
  15210. * @param {Array.<Array.<ol.Coordinate>>} rings Rings.
  15211. * @return {ol.Extent} Extent.
  15212. */
  15213. ol.extent.extendRings = function(extent, rings) {
  15214. var i, ii;
  15215. for (i = 0, ii = rings.length; i < ii; ++i) {
  15216. ol.extent.extendCoordinates(extent, rings[i]);
  15217. }
  15218. return extent;
  15219. };
  15220. /**
  15221. * @param {ol.Extent} extent Extent.
  15222. * @param {number} x X.
  15223. * @param {number} y Y.
  15224. */
  15225. ol.extent.extendXY = function(extent, x, y) {
  15226. extent[0] = Math.min(extent[0], x);
  15227. extent[1] = Math.min(extent[1], y);
  15228. extent[2] = Math.max(extent[2], x);
  15229. extent[3] = Math.max(extent[3], y);
  15230. };
  15231. /**
  15232. * This function calls `callback` for each corner of the extent. If the
  15233. * callback returns a truthy value the function returns that value
  15234. * immediately. Otherwise the function returns `false`.
  15235. * @param {ol.Extent} extent Extent.
  15236. * @param {function(this:T, ol.Coordinate): S} callback Callback.
  15237. * @param {T=} opt_this Value to use as `this` when executing `callback`.
  15238. * @return {S|boolean} Value.
  15239. * @template S, T
  15240. */
  15241. ol.extent.forEachCorner = function(extent, callback, opt_this) {
  15242. var val;
  15243. val = callback.call(opt_this, ol.extent.getBottomLeft(extent));
  15244. if (val) {
  15245. return val;
  15246. }
  15247. val = callback.call(opt_this, ol.extent.getBottomRight(extent));
  15248. if (val) {
  15249. return val;
  15250. }
  15251. val = callback.call(opt_this, ol.extent.getTopRight(extent));
  15252. if (val) {
  15253. return val;
  15254. }
  15255. val = callback.call(opt_this, ol.extent.getTopLeft(extent));
  15256. if (val) {
  15257. return val;
  15258. }
  15259. return false;
  15260. };
  15261. /**
  15262. * @param {ol.Extent} extent Extent.
  15263. * @return {number} Area.
  15264. */
  15265. ol.extent.getArea = function(extent) {
  15266. var area = 0;
  15267. if (!ol.extent.isEmpty(extent)) {
  15268. area = ol.extent.getWidth(extent) * ol.extent.getHeight(extent);
  15269. }
  15270. return area;
  15271. };
  15272. /**
  15273. * Get the bottom left coordinate of an extent.
  15274. * @param {ol.Extent} extent Extent.
  15275. * @return {ol.Coordinate} Bottom left coordinate.
  15276. * @api stable
  15277. */
  15278. ol.extent.getBottomLeft = function(extent) {
  15279. return [extent[0], extent[1]];
  15280. };
  15281. /**
  15282. * Get the bottom right coordinate of an extent.
  15283. * @param {ol.Extent} extent Extent.
  15284. * @return {ol.Coordinate} Bottom right coordinate.
  15285. * @api stable
  15286. */
  15287. ol.extent.getBottomRight = function(extent) {
  15288. return [extent[2], extent[1]];
  15289. };
  15290. /**
  15291. * Get the center coordinate of an extent.
  15292. * @param {ol.Extent} extent Extent.
  15293. * @return {ol.Coordinate} Center.
  15294. * @api stable
  15295. */
  15296. ol.extent.getCenter = function(extent) {
  15297. return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];
  15298. };
  15299. /**
  15300. * Get a corner coordinate of an extent.
  15301. * @param {ol.Extent} extent Extent.
  15302. * @param {ol.extent.Corner} corner Corner.
  15303. * @return {ol.Coordinate} Corner coordinate.
  15304. */
  15305. ol.extent.getCorner = function(extent, corner) {
  15306. var coordinate;
  15307. if (corner === ol.extent.Corner.BOTTOM_LEFT) {
  15308. coordinate = ol.extent.getBottomLeft(extent);
  15309. } else if (corner === ol.extent.Corner.BOTTOM_RIGHT) {
  15310. coordinate = ol.extent.getBottomRight(extent);
  15311. } else if (corner === ol.extent.Corner.TOP_LEFT) {
  15312. coordinate = ol.extent.getTopLeft(extent);
  15313. } else if (corner === ol.extent.Corner.TOP_RIGHT) {
  15314. coordinate = ol.extent.getTopRight(extent);
  15315. } else {
  15316. goog.asserts.fail('Invalid corner: %s', corner);
  15317. }
  15318. goog.asserts.assert(coordinate, 'coordinate should be defined');
  15319. return coordinate;
  15320. };
  15321. /**
  15322. * @param {ol.Extent} extent1 Extent 1.
  15323. * @param {ol.Extent} extent2 Extent 2.
  15324. * @return {number} Enlarged area.
  15325. */
  15326. ol.extent.getEnlargedArea = function(extent1, extent2) {
  15327. var minX = Math.min(extent1[0], extent2[0]);
  15328. var minY = Math.min(extent1[1], extent2[1]);
  15329. var maxX = Math.max(extent1[2], extent2[2]);
  15330. var maxY = Math.max(extent1[3], extent2[3]);
  15331. return (maxX - minX) * (maxY - minY);
  15332. };
  15333. /**
  15334. * @param {ol.Coordinate} center Center.
  15335. * @param {number} resolution Resolution.
  15336. * @param {number} rotation Rotation.
  15337. * @param {ol.Size} size Size.
  15338. * @param {ol.Extent=} opt_extent Destination extent.
  15339. * @return {ol.Extent} Extent.
  15340. */
  15341. ol.extent.getForViewAndSize =
  15342. function(center, resolution, rotation, size, opt_extent) {
  15343. var dx = resolution * size[0] / 2;
  15344. var dy = resolution * size[1] / 2;
  15345. var cosRotation = Math.cos(rotation);
  15346. var sinRotation = Math.sin(rotation);
  15347. /** @type {Array.<number>} */
  15348. var xs = [-dx, -dx, dx, dx];
  15349. /** @type {Array.<number>} */
  15350. var ys = [-dy, dy, -dy, dy];
  15351. var i, x, y;
  15352. for (i = 0; i < 4; ++i) {
  15353. x = xs[i];
  15354. y = ys[i];
  15355. xs[i] = center[0] + x * cosRotation - y * sinRotation;
  15356. ys[i] = center[1] + x * sinRotation + y * cosRotation;
  15357. }
  15358. return ol.extent.boundingExtentXYs_(xs, ys, opt_extent);
  15359. };
  15360. /**
  15361. * Get the height of an extent.
  15362. * @param {ol.Extent} extent Extent.
  15363. * @return {number} Height.
  15364. * @api stable
  15365. */
  15366. ol.extent.getHeight = function(extent) {
  15367. return extent[3] - extent[1];
  15368. };
  15369. /**
  15370. * @param {ol.Extent} extent1 Extent 1.
  15371. * @param {ol.Extent} extent2 Extent 2.
  15372. * @return {number} Intersection area.
  15373. */
  15374. ol.extent.getIntersectionArea = function(extent1, extent2) {
  15375. var intersection = ol.extent.getIntersection(extent1, extent2);
  15376. return ol.extent.getArea(intersection);
  15377. };
  15378. /**
  15379. * Get the intersection of two extents.
  15380. * @param {ol.Extent} extent1 Extent 1.
  15381. * @param {ol.Extent} extent2 Extent 2.
  15382. * @param {ol.Extent=} opt_extent Optional extent to populate with intersection.
  15383. * @return {ol.Extent} Intersecting extent.
  15384. * @api stable
  15385. */
  15386. ol.extent.getIntersection = function(extent1, extent2, opt_extent) {
  15387. var intersection = opt_extent ? opt_extent : ol.extent.createEmpty();
  15388. if (ol.extent.intersects(extent1, extent2)) {
  15389. if (extent1[0] > extent2[0]) {
  15390. intersection[0] = extent1[0];
  15391. } else {
  15392. intersection[0] = extent2[0];
  15393. }
  15394. if (extent1[1] > extent2[1]) {
  15395. intersection[1] = extent1[1];
  15396. } else {
  15397. intersection[1] = extent2[1];
  15398. }
  15399. if (extent1[2] < extent2[2]) {
  15400. intersection[2] = extent1[2];
  15401. } else {
  15402. intersection[2] = extent2[2];
  15403. }
  15404. if (extent1[3] < extent2[3]) {
  15405. intersection[3] = extent1[3];
  15406. } else {
  15407. intersection[3] = extent2[3];
  15408. }
  15409. }
  15410. return intersection;
  15411. };
  15412. /**
  15413. * @param {ol.Extent} extent Extent.
  15414. * @return {number} Margin.
  15415. */
  15416. ol.extent.getMargin = function(extent) {
  15417. return ol.extent.getWidth(extent) + ol.extent.getHeight(extent);
  15418. };
  15419. /**
  15420. * Get the size (width, height) of an extent.
  15421. * @param {ol.Extent} extent The extent.
  15422. * @return {ol.Size} The extent size.
  15423. * @api stable
  15424. */
  15425. ol.extent.getSize = function(extent) {
  15426. return [extent[2] - extent[0], extent[3] - extent[1]];
  15427. };
  15428. /**
  15429. * Get the top left coordinate of an extent.
  15430. * @param {ol.Extent} extent Extent.
  15431. * @return {ol.Coordinate} Top left coordinate.
  15432. * @api stable
  15433. */
  15434. ol.extent.getTopLeft = function(extent) {
  15435. return [extent[0], extent[3]];
  15436. };
  15437. /**
  15438. * Get the top right coordinate of an extent.
  15439. * @param {ol.Extent} extent Extent.
  15440. * @return {ol.Coordinate} Top right coordinate.
  15441. * @api stable
  15442. */
  15443. ol.extent.getTopRight = function(extent) {
  15444. return [extent[2], extent[3]];
  15445. };
  15446. /**
  15447. * Get the width of an extent.
  15448. * @param {ol.Extent} extent Extent.
  15449. * @return {number} Width.
  15450. * @api stable
  15451. */
  15452. ol.extent.getWidth = function(extent) {
  15453. return extent[2] - extent[0];
  15454. };
  15455. /**
  15456. * Determine if one extent intersects another.
  15457. * @param {ol.Extent} extent1 Extent 1.
  15458. * @param {ol.Extent} extent2 Extent.
  15459. * @return {boolean} The two extents intersect.
  15460. * @api stable
  15461. */
  15462. ol.extent.intersects = function(extent1, extent2) {
  15463. return extent1[0] <= extent2[2] &&
  15464. extent1[2] >= extent2[0] &&
  15465. extent1[1] <= extent2[3] &&
  15466. extent1[3] >= extent2[1];
  15467. };
  15468. /**
  15469. * Determine if an extent is empty.
  15470. * @param {ol.Extent} extent Extent.
  15471. * @return {boolean} Is empty.
  15472. * @api stable
  15473. */
  15474. ol.extent.isEmpty = function(extent) {
  15475. return extent[2] < extent[0] || extent[3] < extent[1];
  15476. };
  15477. /**
  15478. * @param {ol.Extent} extent Extent.
  15479. * @return {boolean} Is infinite.
  15480. */
  15481. ol.extent.isInfinite = function(extent) {
  15482. return extent[0] == -Infinity || extent[1] == -Infinity ||
  15483. extent[2] == Infinity || extent[3] == Infinity;
  15484. };
  15485. /**
  15486. * @param {ol.Extent} extent Extent.
  15487. * @param {ol.Coordinate} coordinate Coordinate.
  15488. * @return {ol.Coordinate} Coordinate.
  15489. */
  15490. ol.extent.normalize = function(extent, coordinate) {
  15491. return [
  15492. (coordinate[0] - extent[0]) / (extent[2] - extent[0]),
  15493. (coordinate[1] - extent[1]) / (extent[3] - extent[1])
  15494. ];
  15495. };
  15496. /**
  15497. * @param {ol.Extent} extent Extent.
  15498. * @param {ol.Extent=} opt_extent Extent.
  15499. * @return {ol.Extent} Extent.
  15500. */
  15501. ol.extent.returnOrUpdate = function(extent, opt_extent) {
  15502. if (opt_extent) {
  15503. opt_extent[0] = extent[0];
  15504. opt_extent[1] = extent[1];
  15505. opt_extent[2] = extent[2];
  15506. opt_extent[3] = extent[3];
  15507. return opt_extent;
  15508. } else {
  15509. return extent;
  15510. }
  15511. };
  15512. /**
  15513. * @param {ol.Extent} extent Extent.
  15514. * @param {number} value Value.
  15515. */
  15516. ol.extent.scaleFromCenter = function(extent, value) {
  15517. var deltaX = ((extent[2] - extent[0]) / 2) * (value - 1);
  15518. var deltaY = ((extent[3] - extent[1]) / 2) * (value - 1);
  15519. extent[0] -= deltaX;
  15520. extent[2] += deltaX;
  15521. extent[1] -= deltaY;
  15522. extent[3] += deltaY;
  15523. };
  15524. /**
  15525. * Determine if the segment between two coordinates intersects (crosses,
  15526. * touches, or is contained by) the provided extent.
  15527. * @param {ol.Extent} extent The extent.
  15528. * @param {ol.Coordinate} start Segment start coordinate.
  15529. * @param {ol.Coordinate} end Segment end coordinate.
  15530. * @return {boolean} The segment intersects the extent.
  15531. */
  15532. ol.extent.intersectsSegment = function(extent, start, end) {
  15533. var intersects = false;
  15534. var startRel = ol.extent.coordinateRelationship(extent, start);
  15535. var endRel = ol.extent.coordinateRelationship(extent, end);
  15536. if (startRel === ol.extent.Relationship.INTERSECTING ||
  15537. endRel === ol.extent.Relationship.INTERSECTING) {
  15538. intersects = true;
  15539. } else {
  15540. var minX = extent[0];
  15541. var minY = extent[1];
  15542. var maxX = extent[2];
  15543. var maxY = extent[3];
  15544. var startX = start[0];
  15545. var startY = start[1];
  15546. var endX = end[0];
  15547. var endY = end[1];
  15548. var slope = (endY - startY) / (endX - startX);
  15549. var x, y;
  15550. if (!!(endRel & ol.extent.Relationship.ABOVE) &&
  15551. !(startRel & ol.extent.Relationship.ABOVE)) {
  15552. // potentially intersects top
  15553. x = endX - ((endY - maxY) / slope);
  15554. intersects = x >= minX && x <= maxX;
  15555. }
  15556. if (!intersects && !!(endRel & ol.extent.Relationship.RIGHT) &&
  15557. !(startRel & ol.extent.Relationship.RIGHT)) {
  15558. // potentially intersects right
  15559. y = endY - ((endX - maxX) * slope);
  15560. intersects = y >= minY && y <= maxY;
  15561. }
  15562. if (!intersects && !!(endRel & ol.extent.Relationship.BELOW) &&
  15563. !(startRel & ol.extent.Relationship.BELOW)) {
  15564. // potentially intersects bottom
  15565. x = endX - ((endY - minY) / slope);
  15566. intersects = x >= minX && x <= maxX;
  15567. }
  15568. if (!intersects && !!(endRel & ol.extent.Relationship.LEFT) &&
  15569. !(startRel & ol.extent.Relationship.LEFT)) {
  15570. // potentially intersects left
  15571. y = endY - ((endX - minX) * slope);
  15572. intersects = y >= minY && y <= maxY;
  15573. }
  15574. }
  15575. return intersects;
  15576. };
  15577. /**
  15578. * @param {ol.Extent} extent1 Extent 1.
  15579. * @param {ol.Extent} extent2 Extent 2.
  15580. * @return {boolean} Touches.
  15581. */
  15582. ol.extent.touches = function(extent1, extent2) {
  15583. var intersects = ol.extent.intersects(extent1, extent2);
  15584. return intersects &&
  15585. (extent1[0] == extent2[2] || extent1[2] == extent2[0] ||
  15586. extent1[1] == extent2[3] || extent1[3] == extent2[1]);
  15587. };
  15588. /**
  15589. * Apply a transform function to the extent.
  15590. * @param {ol.Extent} extent Extent.
  15591. * @param {ol.TransformFunction} transformFn Transform function. Called with
  15592. * [minX, minY, maxX, maxY] extent coordinates.
  15593. * @param {ol.Extent=} opt_extent Destination extent.
  15594. * @return {ol.Extent} Extent.
  15595. * @api stable
  15596. */
  15597. ol.extent.applyTransform = function(extent, transformFn, opt_extent) {
  15598. var coordinates = [
  15599. extent[0], extent[1],
  15600. extent[0], extent[3],
  15601. extent[2], extent[1],
  15602. extent[2], extent[3]
  15603. ];
  15604. transformFn(coordinates, coordinates, 2);
  15605. var xs = [coordinates[0], coordinates[2], coordinates[4], coordinates[6]];
  15606. var ys = [coordinates[1], coordinates[3], coordinates[5], coordinates[7]];
  15607. return ol.extent.boundingExtentXYs_(xs, ys, opt_extent);
  15608. };
  15609. /**
  15610. * Apply a 2d transform to an extent.
  15611. * @param {ol.Extent} extent Input extent.
  15612. * @param {goog.vec.Mat4.Number} transform The transform matrix.
  15613. * @param {ol.Extent=} opt_extent Optional extent for return values.
  15614. * @return {ol.Extent} The transformed extent.
  15615. */
  15616. ol.extent.transform2D = function(extent, transform, opt_extent) {
  15617. var dest = opt_extent ? opt_extent : [];
  15618. var m00 = goog.vec.Mat4.getElement(transform, 0, 0);
  15619. var m10 = goog.vec.Mat4.getElement(transform, 1, 0);
  15620. var m01 = goog.vec.Mat4.getElement(transform, 0, 1);
  15621. var m11 = goog.vec.Mat4.getElement(transform, 1, 1);
  15622. var m03 = goog.vec.Mat4.getElement(transform, 0, 3);
  15623. var m13 = goog.vec.Mat4.getElement(transform, 1, 3);
  15624. var xi = [0, 2, 0, 2];
  15625. var yi = [1, 1, 3, 3];
  15626. var xs = [];
  15627. var ys = [];
  15628. var i, x, y;
  15629. for (i = 0; i < 4; ++i) {
  15630. x = extent[xi[i]];
  15631. y = extent[yi[i]];
  15632. xs[i] = m00 * x + m01 * y + m03;
  15633. ys[i] = m10 * x + m11 * y + m13;
  15634. }
  15635. dest[0] = Math.min.apply(null, xs);
  15636. dest[1] = Math.min.apply(null, ys);
  15637. dest[2] = Math.max.apply(null, xs);
  15638. dest[3] = Math.max.apply(null, ys);
  15639. return dest;
  15640. };
  15641. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  15642. //
  15643. // Licensed under the Apache License, Version 2.0 (the "License");
  15644. // you may not use this file except in compliance with the License.
  15645. // You may obtain a copy of the License at
  15646. //
  15647. // http://www.apache.org/licenses/LICENSE-2.0
  15648. //
  15649. // Unless required by applicable law or agreed to in writing, software
  15650. // distributed under the License is distributed on an "AS-IS" BASIS,
  15651. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15652. // See the License for the specific language governing permissions and
  15653. // limitations under the License.
  15654. /**
  15655. * @fileoverview Utilities for creating functions. Loosely inspired by the
  15656. * java classes: http://goo.gl/GM0Hmu and http://goo.gl/6k7nI8.
  15657. *
  15658. * @author nicksantos@google.com (Nick Santos)
  15659. */
  15660. goog.provide('goog.functions');
  15661. /**
  15662. * Creates a function that always returns the same value.
  15663. * @param {T} retValue The value to return.
  15664. * @return {function():T} The new function.
  15665. * @template T
  15666. */
  15667. goog.functions.constant = function(retValue) {
  15668. return function() {
  15669. return retValue;
  15670. };
  15671. };
  15672. /**
  15673. * Always returns false.
  15674. * @type {function(...): boolean}
  15675. */
  15676. goog.functions.FALSE = goog.functions.constant(false);
  15677. /**
  15678. * Always returns true.
  15679. * @type {function(...): boolean}
  15680. */
  15681. goog.functions.TRUE = goog.functions.constant(true);
  15682. /**
  15683. * Always returns NULL.
  15684. * @type {function(...): null}
  15685. */
  15686. goog.functions.NULL = goog.functions.constant(null);
  15687. /**
  15688. * A simple function that returns the first argument of whatever is passed
  15689. * into it.
  15690. * @param {T=} opt_returnValue The single value that will be returned.
  15691. * @param {...*} var_args Optional trailing arguments. These are ignored.
  15692. * @return {T} The first argument passed in, or undefined if nothing was passed.
  15693. * @template T
  15694. */
  15695. goog.functions.identity = function(opt_returnValue, var_args) {
  15696. return opt_returnValue;
  15697. };
  15698. /**
  15699. * Creates a function that always throws an error with the given message.
  15700. * @param {string} message The error message.
  15701. * @return {!Function} The error-throwing function.
  15702. */
  15703. goog.functions.error = function(message) {
  15704. return function() {
  15705. throw Error(message);
  15706. };
  15707. };
  15708. /**
  15709. * Creates a function that throws the given object.
  15710. * @param {*} err An object to be thrown.
  15711. * @return {!Function} The error-throwing function.
  15712. */
  15713. goog.functions.fail = function(err) {
  15714. return function() {
  15715. throw err;
  15716. }
  15717. };
  15718. /**
  15719. * Given a function, create a function that keeps opt_numArgs arguments and
  15720. * silently discards all additional arguments.
  15721. * @param {Function} f The original function.
  15722. * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.
  15723. * @return {!Function} A version of f that only keeps the first opt_numArgs
  15724. * arguments.
  15725. */
  15726. goog.functions.lock = function(f, opt_numArgs) {
  15727. opt_numArgs = opt_numArgs || 0;
  15728. return function() {
  15729. return f.apply(this, Array.prototype.slice.call(arguments, 0, opt_numArgs));
  15730. };
  15731. };
  15732. /**
  15733. * Creates a function that returns its nth argument.
  15734. * @param {number} n The position of the return argument.
  15735. * @return {!Function} A new function.
  15736. */
  15737. goog.functions.nth = function(n) {
  15738. return function() {
  15739. return arguments[n];
  15740. };
  15741. };
  15742. /**
  15743. * Given a function, create a new function that swallows its return value
  15744. * and replaces it with a new one.
  15745. * @param {Function} f A function.
  15746. * @param {T} retValue A new return value.
  15747. * @return {function(...?):T} A new function.
  15748. * @template T
  15749. */
  15750. goog.functions.withReturnValue = function(f, retValue) {
  15751. return goog.functions.sequence(f, goog.functions.constant(retValue));
  15752. };
  15753. /**
  15754. * Creates a function that returns whether its arguement equals the given value.
  15755. *
  15756. * Example:
  15757. * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));
  15758. *
  15759. * @param {*} value The value to compare to.
  15760. * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)
  15761. * comparison rather than a strict (===) one. Defaults to false.
  15762. * @return {function(*):boolean} The new function.
  15763. */
  15764. goog.functions.equalTo = function(value, opt_useLooseComparison) {
  15765. return function(other) {
  15766. return opt_useLooseComparison ? (value == other) : (value === other);
  15767. };
  15768. };
  15769. /**
  15770. * Creates the composition of the functions passed in.
  15771. * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).
  15772. * @param {function(...?):T} fn The final function.
  15773. * @param {...Function} var_args A list of functions.
  15774. * @return {function(...?):T} The composition of all inputs.
  15775. * @template T
  15776. */
  15777. goog.functions.compose = function(fn, var_args) {
  15778. var functions = arguments;
  15779. var length = functions.length;
  15780. return function() {
  15781. var result;
  15782. if (length) {
  15783. result = functions[length - 1].apply(this, arguments);
  15784. }
  15785. for (var i = length - 2; i >= 0; i--) {
  15786. result = functions[i].call(this, result);
  15787. }
  15788. return result;
  15789. };
  15790. };
  15791. /**
  15792. * Creates a function that calls the functions passed in in sequence, and
  15793. * returns the value of the last function. For example,
  15794. * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).
  15795. * @param {...Function} var_args A list of functions.
  15796. * @return {!Function} A function that calls all inputs in sequence.
  15797. */
  15798. goog.functions.sequence = function(var_args) {
  15799. var functions = arguments;
  15800. var length = functions.length;
  15801. return function() {
  15802. var result;
  15803. for (var i = 0; i < length; i++) {
  15804. result = functions[i].apply(this, arguments);
  15805. }
  15806. return result;
  15807. };
  15808. };
  15809. /**
  15810. * Creates a function that returns true if each of its components evaluates
  15811. * to true. The components are evaluated in order, and the evaluation will be
  15812. * short-circuited as soon as a function returns false.
  15813. * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).
  15814. * @param {...Function} var_args A list of functions.
  15815. * @return {function(...?):boolean} A function that ANDs its component
  15816. * functions.
  15817. */
  15818. goog.functions.and = function(var_args) {
  15819. var functions = arguments;
  15820. var length = functions.length;
  15821. return function() {
  15822. for (var i = 0; i < length; i++) {
  15823. if (!functions[i].apply(this, arguments)) {
  15824. return false;
  15825. }
  15826. }
  15827. return true;
  15828. };
  15829. };
  15830. /**
  15831. * Creates a function that returns true if any of its components evaluates
  15832. * to true. The components are evaluated in order, and the evaluation will be
  15833. * short-circuited as soon as a function returns true.
  15834. * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).
  15835. * @param {...Function} var_args A list of functions.
  15836. * @return {function(...?):boolean} A function that ORs its component
  15837. * functions.
  15838. */
  15839. goog.functions.or = function(var_args) {
  15840. var functions = arguments;
  15841. var length = functions.length;
  15842. return function() {
  15843. for (var i = 0; i < length; i++) {
  15844. if (functions[i].apply(this, arguments)) {
  15845. return true;
  15846. }
  15847. }
  15848. return false;
  15849. };
  15850. };
  15851. /**
  15852. * Creates a function that returns the Boolean opposite of a provided function.
  15853. * For example, (goog.functions.not(f))(x) is equivalent to !f(x).
  15854. * @param {!Function} f The original function.
  15855. * @return {function(...?):boolean} A function that delegates to f and returns
  15856. * opposite.
  15857. */
  15858. goog.functions.not = function(f) {
  15859. return function() {
  15860. return !f.apply(this, arguments);
  15861. };
  15862. };
  15863. /**
  15864. * Generic factory function to construct an object given the constructor
  15865. * and the arguments. Intended to be bound to create object factories.
  15866. *
  15867. * Example:
  15868. *
  15869. * var factory = goog.partial(goog.functions.create, Class);
  15870. *
  15871. * @param {function(new:T, ...)} constructor The constructor for the Object.
  15872. * @param {...*} var_args The arguments to be passed to the constructor.
  15873. * @return {T} A new instance of the class given in {@code constructor}.
  15874. * @template T
  15875. */
  15876. goog.functions.create = function(constructor, var_args) {
  15877. /**
  15878. * @constructor
  15879. * @final
  15880. */
  15881. var temp = function() {};
  15882. temp.prototype = constructor.prototype;
  15883. // obj will have constructor's prototype in its chain and
  15884. // 'obj instanceof constructor' will be true.
  15885. var obj = new temp();
  15886. // obj is initialized by constructor.
  15887. // arguments is only array-like so lacks shift(), but can be used with
  15888. // the Array prototype function.
  15889. constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
  15890. return obj;
  15891. };
  15892. /**
  15893. * @define {boolean} Whether the return value cache should be used.
  15894. * This should only be used to disable caches when testing.
  15895. */
  15896. goog.define('goog.functions.CACHE_RETURN_VALUE', true);
  15897. /**
  15898. * Gives a wrapper function that caches the return value of a parameterless
  15899. * function when first called.
  15900. *
  15901. * When called for the first time, the given function is called and its
  15902. * return value is cached (thus this is only appropriate for idempotent
  15903. * functions). Subsequent calls will return the cached return value. This
  15904. * allows the evaluation of expensive functions to be delayed until first used.
  15905. *
  15906. * To cache the return values of functions with parameters, see goog.memoize.
  15907. *
  15908. * @param {!function():T} fn A function to lazily evaluate.
  15909. * @return {!function():T} A wrapped version the function.
  15910. * @template T
  15911. */
  15912. goog.functions.cacheReturnValue = function(fn) {
  15913. var called = false;
  15914. var value;
  15915. return function() {
  15916. if (!goog.functions.CACHE_RETURN_VALUE) {
  15917. return fn();
  15918. }
  15919. if (!called) {
  15920. value = fn();
  15921. called = true;
  15922. }
  15923. return value;
  15924. }
  15925. };
  15926. /**
  15927. * Wraps a function to allow it to be called, at most, once. All
  15928. * additional calls are no-ops.
  15929. *
  15930. * This is particularly useful for initialization functions
  15931. * that should be called, at most, once.
  15932. *
  15933. * @param {function():*} f Function to call.
  15934. * @return {function():undefined} Wrapped function.
  15935. */
  15936. goog.functions.once = function(f) {
  15937. // Keep a reference to the function that we null out when we're done with
  15938. // it -- that way, the function can be GC'd when we're done with it.
  15939. var inner = f;
  15940. return function() {
  15941. if (inner) {
  15942. var tmp = inner;
  15943. inner = null;
  15944. tmp();
  15945. }
  15946. };
  15947. };
  15948. /**
  15949. * Wraps a function to allow it to be called, at most, once for each sequence of
  15950. * calls fired repeatedly so long as they are fired less than a specified
  15951. * interval apart (in milliseconds). Whether it receives one signal or multiple,
  15952. * it will always wait until a full interval has elapsed since the last signal
  15953. * before performing the action.
  15954. *
  15955. * This is particularly useful for bulking up repeated user actions (e.g. only
  15956. * refreshing a view once a user finishes typing rather than updating with every
  15957. * keystroke). For more stateful debouncing with support for pausing, resuming,
  15958. * and canceling debounced actions, use {@code goog.async.Debouncer}.
  15959. *
  15960. * @param {function(this:SCOPE):*} f Function to call.
  15961. * @param {number} interval Interval over which to debounce. The function will
  15962. * only be called after the full interval has elapsed since the last call.
  15963. * @param {SCOPE=} opt_scope Object in whose scope to call the function.
  15964. * @return {function():undefined} Wrapped function.
  15965. * @template SCOPE
  15966. */
  15967. goog.functions.debounce = function(f, interval, opt_scope) {
  15968. if (opt_scope) {
  15969. f = goog.bind(f, opt_scope);
  15970. }
  15971. var timeout = null;
  15972. return function() {
  15973. goog.global.clearTimeout(timeout);
  15974. timeout = goog.global.setTimeout(f, interval);
  15975. };
  15976. };
  15977. /**
  15978. * Wraps a function to allow it to be called, at most, once per interval
  15979. * (specified in milliseconds). If it is called multiple times while it is
  15980. * waiting, it will only perform the action once at the end of the interval.
  15981. *
  15982. * This is particularly useful for limiting repeated user requests (e.g.
  15983. * preventing a user from spamming a server with frequent view refreshes). For
  15984. * more stateful throttling with support for pausing, resuming, and canceling
  15985. * throttled actions, use {@code goog.async.Throttle}.
  15986. *
  15987. * @param {function(this:SCOPE):*} f Function to call.
  15988. * @param {number} interval Interval over which to throttle. The function can
  15989. * only be called once per interval.
  15990. * @param {SCOPE=} opt_scope Object in whose scope to call the function.
  15991. * @return {function():undefined} Wrapped function.
  15992. * @template SCOPE
  15993. */
  15994. goog.functions.throttle = function(f, interval, opt_scope) {
  15995. if (opt_scope) {
  15996. f = goog.bind(f, opt_scope);
  15997. }
  15998. var timeout = null;
  15999. var shouldFire = false;
  16000. var fire = function() {
  16001. timeout = goog.global.setTimeout(handleTimeout, interval);
  16002. f();
  16003. };
  16004. var handleTimeout = function() {
  16005. timeout = null;
  16006. if (shouldFire) {
  16007. shouldFire = false;
  16008. fire();
  16009. }
  16010. };
  16011. return function() {
  16012. if (!timeout) {
  16013. fire();
  16014. } else {
  16015. shouldFire = true;
  16016. }
  16017. };
  16018. };
  16019. /**
  16020. * @license
  16021. * Latitude/longitude spherical geodesy formulae taken from
  16022. * http://www.movable-type.co.uk/scripts/latlong.html
  16023. * Licensed under CC-BY-3.0.
  16024. */
  16025. goog.provide('ol.Sphere');
  16026. goog.require('goog.math');
  16027. /**
  16028. * @classdesc
  16029. * Class to create objects that can be used with {@link
  16030. * ol.geom.Polygon.circular}.
  16031. *
  16032. * For example to create a sphere whose radius is equal to the semi-major
  16033. * axis of the WGS84 ellipsoid:
  16034. *
  16035. * ```js
  16036. * var wgs84Sphere= new ol.Sphere(6378137);
  16037. * ```
  16038. *
  16039. * @constructor
  16040. * @param {number} radius Radius.
  16041. * @api
  16042. */
  16043. ol.Sphere = function(radius) {
  16044. /**
  16045. * @type {number}
  16046. */
  16047. this.radius = radius;
  16048. };
  16049. /**
  16050. * Returns the geodesic area for a list of coordinates.
  16051. *
  16052. * [Reference](http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409)
  16053. * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
  16054. * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
  16055. * Laboratory, Pasadena, CA, June 2007
  16056. *
  16057. * @param {Array.<ol.Coordinate>} coordinates List of coordinates of a linear
  16058. * ring. If the ring is oriented clockwise, the area will be positive,
  16059. * otherwise it will be negative.
  16060. * @return {number} Area.
  16061. * @api
  16062. */
  16063. ol.Sphere.prototype.geodesicArea = function(coordinates) {
  16064. var area = 0, len = coordinates.length;
  16065. var x1 = coordinates[len - 1][0];
  16066. var y1 = coordinates[len - 1][1];
  16067. for (var i = 0; i < len; i++) {
  16068. var x2 = coordinates[i][0], y2 = coordinates[i][1];
  16069. area += goog.math.toRadians(x2 - x1) *
  16070. (2 + Math.sin(goog.math.toRadians(y1)) +
  16071. Math.sin(goog.math.toRadians(y2)));
  16072. x1 = x2;
  16073. y1 = y2;
  16074. }
  16075. return area * this.radius * this.radius / 2.0;
  16076. };
  16077. /**
  16078. * Returns the distance from c1 to c2 using the haversine formula.
  16079. *
  16080. * @param {ol.Coordinate} c1 Coordinate 1.
  16081. * @param {ol.Coordinate} c2 Coordinate 2.
  16082. * @return {number} Haversine distance.
  16083. * @api
  16084. */
  16085. ol.Sphere.prototype.haversineDistance = function(c1, c2) {
  16086. var lat1 = goog.math.toRadians(c1[1]);
  16087. var lat2 = goog.math.toRadians(c2[1]);
  16088. var deltaLatBy2 = (lat2 - lat1) / 2;
  16089. var deltaLonBy2 = goog.math.toRadians(c2[0] - c1[0]) / 2;
  16090. var a = Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +
  16091. Math.sin(deltaLonBy2) * Math.sin(deltaLonBy2) *
  16092. Math.cos(lat1) * Math.cos(lat2);
  16093. return 2 * this.radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  16094. };
  16095. /**
  16096. * Returns the coordinate at the given distance and bearing from `c1`.
  16097. *
  16098. * @param {ol.Coordinate} c1 The origin point (`[lon, lat]` in degrees).
  16099. * @param {number} distance The great-circle distance between the origin
  16100. * point and the target point.
  16101. * @param {number} bearing The bearing (in radians).
  16102. * @return {ol.Coordinate} The target point.
  16103. */
  16104. ol.Sphere.prototype.offset = function(c1, distance, bearing) {
  16105. var lat1 = goog.math.toRadians(c1[1]);
  16106. var lon1 = goog.math.toRadians(c1[0]);
  16107. var dByR = distance / this.radius;
  16108. var lat = Math.asin(
  16109. Math.sin(lat1) * Math.cos(dByR) +
  16110. Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing));
  16111. var lon = lon1 + Math.atan2(
  16112. Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),
  16113. Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat));
  16114. return [goog.math.toDegrees(lon), goog.math.toDegrees(lat)];
  16115. };
  16116. goog.provide('ol.sphere.NORMAL');
  16117. goog.require('ol.Sphere');
  16118. /**
  16119. * The normal sphere.
  16120. * @const
  16121. * @type {ol.Sphere}
  16122. */
  16123. ol.sphere.NORMAL = new ol.Sphere(6370997);
  16124. goog.provide('ol.proj');
  16125. goog.provide('ol.proj.METERS_PER_UNIT');
  16126. goog.provide('ol.proj.Projection');
  16127. goog.provide('ol.proj.ProjectionLike');
  16128. goog.provide('ol.proj.Units');
  16129. goog.require('goog.asserts');
  16130. goog.require('goog.object');
  16131. goog.require('ol');
  16132. goog.require('ol.Extent');
  16133. goog.require('ol.TransformFunction');
  16134. goog.require('ol.extent');
  16135. goog.require('ol.sphere.NORMAL');
  16136. /**
  16137. * A projection as {@link ol.proj.Projection}, SRS identifier string or
  16138. * undefined.
  16139. * @typedef {ol.proj.Projection|string|undefined} ol.proj.ProjectionLike
  16140. * @api stable
  16141. */
  16142. ol.proj.ProjectionLike;
  16143. /**
  16144. * Projection units: `'degrees'`, `'ft'`, `'m'`, `'pixels'`, or `'us-ft'`.
  16145. * @enum {string}
  16146. * @api stable
  16147. */
  16148. ol.proj.Units = {
  16149. DEGREES: 'degrees',
  16150. FEET: 'ft',
  16151. METERS: 'm',
  16152. PIXELS: 'pixels',
  16153. USFEET: 'us-ft'
  16154. };
  16155. /**
  16156. * Meters per unit lookup table.
  16157. * @const
  16158. * @type {Object.<ol.proj.Units, number>}
  16159. * @api stable
  16160. */
  16161. ol.proj.METERS_PER_UNIT = {};
  16162. ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES] =
  16163. 2 * Math.PI * ol.sphere.NORMAL.radius / 360;
  16164. ol.proj.METERS_PER_UNIT[ol.proj.Units.FEET] = 0.3048;
  16165. ol.proj.METERS_PER_UNIT[ol.proj.Units.METERS] = 1;
  16166. ol.proj.METERS_PER_UNIT[ol.proj.Units.USFEET] = 1200 / 3937;
  16167. /**
  16168. * @classdesc
  16169. * Projection definition class. One of these is created for each projection
  16170. * supported in the application and stored in the {@link ol.proj} namespace.
  16171. * You can use these in applications, but this is not required, as API params
  16172. * and options use {@link ol.proj.ProjectionLike} which means the simple string
  16173. * code will suffice.
  16174. *
  16175. * You can use {@link ol.proj.get} to retrieve the object for a particular
  16176. * projection.
  16177. *
  16178. * The library includes definitions for `EPSG:4326` and `EPSG:3857`, together
  16179. * with the following aliases:
  16180. * * `EPSG:4326`: CRS:84, urn:ogc:def:crs:EPSG:6.6:4326,
  16181. * urn:ogc:def:crs:OGC:1.3:CRS84, urn:ogc:def:crs:OGC:2:84,
  16182. * http://www.opengis.net/gml/srs/epsg.xml#4326,
  16183. * urn:x-ogc:def:crs:EPSG:4326
  16184. * * `EPSG:3857`: EPSG:102100, EPSG:102113, EPSG:900913,
  16185. * urn:ogc:def:crs:EPSG:6.18:3:3857,
  16186. * http://www.opengis.net/gml/srs/epsg.xml#3857
  16187. *
  16188. * If you use proj4js, aliases can be added using `proj4.defs()`; see
  16189. * [documentation](https://github.com/proj4js/proj4js).
  16190. *
  16191. * @constructor
  16192. * @param {olx.ProjectionOptions} options Projection options.
  16193. * @struct
  16194. * @api stable
  16195. */
  16196. ol.proj.Projection = function(options) {
  16197. /**
  16198. * @private
  16199. * @type {string}
  16200. */
  16201. this.code_ = options.code;
  16202. /**
  16203. * @private
  16204. * @type {ol.proj.Units}
  16205. */
  16206. this.units_ = /** @type {ol.proj.Units} */ (options.units);
  16207. /**
  16208. * @private
  16209. * @type {ol.Extent}
  16210. */
  16211. this.extent_ = options.extent !== undefined ? options.extent : null;
  16212. /**
  16213. * @private
  16214. * @type {ol.Extent}
  16215. */
  16216. this.worldExtent_ = options.worldExtent !== undefined ?
  16217. options.worldExtent : null;
  16218. /**
  16219. * @private
  16220. * @type {string}
  16221. */
  16222. this.axisOrientation_ = options.axisOrientation !== undefined ?
  16223. options.axisOrientation : 'enu';
  16224. /**
  16225. * @private
  16226. * @type {boolean}
  16227. */
  16228. this.global_ = options.global !== undefined ? options.global : false;
  16229. /**
  16230. * @private
  16231. * @type {boolean}
  16232. */
  16233. this.canWrapX_ = !!(this.global_ && this.extent_);
  16234. /**
  16235. * @private
  16236. * @type {function(number, ol.Coordinate):number}
  16237. */
  16238. this.getPointResolutionFunc_ = options.getPointResolution !== undefined ?
  16239. options.getPointResolution : this.getPointResolution_;
  16240. /**
  16241. * @private
  16242. * @type {ol.tilegrid.TileGrid}
  16243. */
  16244. this.defaultTileGrid_ = null;
  16245. var projections = ol.proj.projections_;
  16246. var code = options.code;
  16247. goog.asserts.assert(code !== undefined,
  16248. 'Option "code" is required for constructing instance');
  16249. if (ol.ENABLE_PROJ4JS && typeof proj4 == 'function' &&
  16250. projections[code] === undefined) {
  16251. var def = proj4.defs(code);
  16252. if (def !== undefined) {
  16253. if (def.axis !== undefined && options.axisOrientation === undefined) {
  16254. this.axisOrientation_ = def.axis;
  16255. }
  16256. if (options.units === undefined) {
  16257. var units = def.units;
  16258. if (def.to_meter !== undefined) {
  16259. if (units === undefined ||
  16260. ol.proj.METERS_PER_UNIT[units] === undefined) {
  16261. units = def.to_meter.toString();
  16262. ol.proj.METERS_PER_UNIT[units] = def.to_meter;
  16263. }
  16264. }
  16265. this.units_ = units;
  16266. }
  16267. var currentCode, currentDef, currentProj, proj4Transform;
  16268. for (currentCode in projections) {
  16269. currentDef = proj4.defs(currentCode);
  16270. if (currentDef !== undefined) {
  16271. currentProj = ol.proj.get(currentCode);
  16272. if (currentDef === def) {
  16273. ol.proj.addEquivalentProjections([currentProj, this]);
  16274. } else {
  16275. proj4Transform = proj4(currentCode, code);
  16276. ol.proj.addCoordinateTransforms(currentProj, this,
  16277. proj4Transform.forward, proj4Transform.inverse);
  16278. }
  16279. }
  16280. }
  16281. }
  16282. }
  16283. };
  16284. /**
  16285. * @return {boolean} The projection is suitable for wrapping the x-axis
  16286. */
  16287. ol.proj.Projection.prototype.canWrapX = function() {
  16288. return this.canWrapX_;
  16289. };
  16290. /**
  16291. * Get the code for this projection, e.g. 'EPSG:4326'.
  16292. * @return {string} Code.
  16293. * @api stable
  16294. */
  16295. ol.proj.Projection.prototype.getCode = function() {
  16296. return this.code_;
  16297. };
  16298. /**
  16299. * Get the validity extent for this projection.
  16300. * @return {ol.Extent} Extent.
  16301. * @api stable
  16302. */
  16303. ol.proj.Projection.prototype.getExtent = function() {
  16304. return this.extent_;
  16305. };
  16306. /**
  16307. * Get the units of this projection.
  16308. * @return {ol.proj.Units} Units.
  16309. * @api stable
  16310. */
  16311. ol.proj.Projection.prototype.getUnits = function() {
  16312. return this.units_;
  16313. };
  16314. /**
  16315. * Get the amount of meters per unit of this projection. If the projection is
  16316. * not configured with a units identifier, the return is `undefined`.
  16317. * @return {number|undefined} Meters.
  16318. * @api stable
  16319. */
  16320. ol.proj.Projection.prototype.getMetersPerUnit = function() {
  16321. return ol.proj.METERS_PER_UNIT[this.units_];
  16322. };
  16323. /**
  16324. * Get the world extent for this projection.
  16325. * @return {ol.Extent} Extent.
  16326. * @api
  16327. */
  16328. ol.proj.Projection.prototype.getWorldExtent = function() {
  16329. return this.worldExtent_;
  16330. };
  16331. /**
  16332. * Get the axis orientation of this projection.
  16333. * Example values are:
  16334. * enu - the default easting, northing, elevation.
  16335. * neu - northing, easting, up - useful for "lat/long" geographic coordinates,
  16336. * or south orientated transverse mercator.
  16337. * wnu - westing, northing, up - some planetary coordinate systems have
  16338. * "west positive" coordinate systems
  16339. * @return {string} Axis orientation.
  16340. */
  16341. ol.proj.Projection.prototype.getAxisOrientation = function() {
  16342. return this.axisOrientation_;
  16343. };
  16344. /**
  16345. * Is this projection a global projection which spans the whole world?
  16346. * @return {boolean} Whether the projection is global.
  16347. * @api stable
  16348. */
  16349. ol.proj.Projection.prototype.isGlobal = function() {
  16350. return this.global_;
  16351. };
  16352. /**
  16353. * Set if the projection is a global projection which spans the whole world
  16354. * @param {boolean} global Whether the projection is global.
  16355. * @api stable
  16356. */
  16357. ol.proj.Projection.prototype.setGlobal = function(global) {
  16358. this.global_ = global;
  16359. this.canWrapX_ = !!(global && this.extent_);
  16360. };
  16361. /**
  16362. * @return {ol.tilegrid.TileGrid} The default tile grid.
  16363. */
  16364. ol.proj.Projection.prototype.getDefaultTileGrid = function() {
  16365. return this.defaultTileGrid_;
  16366. };
  16367. /**
  16368. * @param {ol.tilegrid.TileGrid} tileGrid The default tile grid.
  16369. */
  16370. ol.proj.Projection.prototype.setDefaultTileGrid = function(tileGrid) {
  16371. this.defaultTileGrid_ = tileGrid;
  16372. };
  16373. /**
  16374. * Set the validity extent for this projection.
  16375. * @param {ol.Extent} extent Extent.
  16376. * @api stable
  16377. */
  16378. ol.proj.Projection.prototype.setExtent = function(extent) {
  16379. this.extent_ = extent;
  16380. this.canWrapX_ = !!(this.global_ && extent);
  16381. };
  16382. /**
  16383. * Set the world extent for this projection.
  16384. * @param {ol.Extent} worldExtent World extent
  16385. * [minlon, minlat, maxlon, maxlat].
  16386. * @api
  16387. */
  16388. ol.proj.Projection.prototype.setWorldExtent = function(worldExtent) {
  16389. this.worldExtent_ = worldExtent;
  16390. };
  16391. /**
  16392. * Set the getPointResolution function for this projection.
  16393. * @param {function(number, ol.Coordinate):number} func Function
  16394. * @api
  16395. */
  16396. ol.proj.Projection.prototype.setGetPointResolution = function(func) {
  16397. this.getPointResolutionFunc_ = func;
  16398. };
  16399. /**
  16400. * Default version.
  16401. * Get the resolution of the point in degrees or distance units.
  16402. * For projections with degrees as the unit this will simply return the
  16403. * provided resolution. For other projections the point resolution is
  16404. * estimated by transforming the 'point' pixel to EPSG:4326,
  16405. * measuring its width and height on the normal sphere,
  16406. * and taking the average of the width and height.
  16407. * @param {number} resolution Nominal resolution in projection units.
  16408. * @param {ol.Coordinate} point Point to find adjusted resolution at.
  16409. * @return {number} Point resolution at point in projection units.
  16410. * @private
  16411. */
  16412. ol.proj.Projection.prototype.getPointResolution_ = function(resolution, point) {
  16413. var units = this.getUnits();
  16414. if (units == ol.proj.Units.DEGREES) {
  16415. return resolution;
  16416. } else {
  16417. // Estimate point resolution by transforming the center pixel to EPSG:4326,
  16418. // measuring its width and height on the normal sphere, and taking the
  16419. // average of the width and height.
  16420. var toEPSG4326 = ol.proj.getTransformFromProjections(
  16421. this, ol.proj.get('EPSG:4326'));
  16422. var vertices = [
  16423. point[0] - resolution / 2, point[1],
  16424. point[0] + resolution / 2, point[1],
  16425. point[0], point[1] - resolution / 2,
  16426. point[0], point[1] + resolution / 2
  16427. ];
  16428. vertices = toEPSG4326(vertices, vertices, 2);
  16429. var width = ol.sphere.NORMAL.haversineDistance(
  16430. vertices.slice(0, 2), vertices.slice(2, 4));
  16431. var height = ol.sphere.NORMAL.haversineDistance(
  16432. vertices.slice(4, 6), vertices.slice(6, 8));
  16433. var pointResolution = (width + height) / 2;
  16434. var metersPerUnit = this.getMetersPerUnit();
  16435. if (metersPerUnit !== undefined) {
  16436. pointResolution /= metersPerUnit;
  16437. }
  16438. return pointResolution;
  16439. }
  16440. };
  16441. /**
  16442. * Get the resolution of the point in degrees or distance units.
  16443. * For projections with degrees as the unit this will simply return the
  16444. * provided resolution. The default for other projections is to estimate
  16445. * the point resolution by transforming the 'point' pixel to EPSG:4326,
  16446. * measuring its width and height on the normal sphere,
  16447. * and taking the average of the width and height.
  16448. * An alternative implementation may be given when constructing a
  16449. * projection. For many local projections,
  16450. * such a custom function will return the resolution unchanged.
  16451. * @param {number} resolution Resolution in projection units.
  16452. * @param {ol.Coordinate} point Point.
  16453. * @return {number} Point resolution in projection units.
  16454. * @api
  16455. */
  16456. ol.proj.Projection.prototype.getPointResolution = function(resolution, point) {
  16457. return this.getPointResolutionFunc_(resolution, point);
  16458. };
  16459. /**
  16460. * @private
  16461. * @type {Object.<string, ol.proj.Projection>}
  16462. */
  16463. ol.proj.projections_ = {};
  16464. /**
  16465. * @private
  16466. * @type {Object.<string, Object.<string, ol.TransformFunction>>}
  16467. */
  16468. ol.proj.transforms_ = {};
  16469. /**
  16470. * Registers transformation functions that don't alter coordinates. Those allow
  16471. * to transform between projections with equal meaning.
  16472. *
  16473. * @param {Array.<ol.proj.Projection>} projections Projections.
  16474. * @api
  16475. */
  16476. ol.proj.addEquivalentProjections = function(projections) {
  16477. ol.proj.addProjections(projections);
  16478. projections.forEach(function(source) {
  16479. projections.forEach(function(destination) {
  16480. if (source !== destination) {
  16481. ol.proj.addTransform(source, destination, ol.proj.cloneTransform);
  16482. }
  16483. });
  16484. });
  16485. };
  16486. /**
  16487. * Registers transformation functions to convert coordinates in any projection
  16488. * in projection1 to any projection in projection2.
  16489. *
  16490. * @param {Array.<ol.proj.Projection>} projections1 Projections with equal
  16491. * meaning.
  16492. * @param {Array.<ol.proj.Projection>} projections2 Projections with equal
  16493. * meaning.
  16494. * @param {ol.TransformFunction} forwardTransform Transformation from any
  16495. * projection in projection1 to any projection in projection2.
  16496. * @param {ol.TransformFunction} inverseTransform Transform from any projection
  16497. * in projection2 to any projection in projection1..
  16498. */
  16499. ol.proj.addEquivalentTransforms =
  16500. function(projections1, projections2, forwardTransform, inverseTransform) {
  16501. projections1.forEach(function(projection1) {
  16502. projections2.forEach(function(projection2) {
  16503. ol.proj.addTransform(projection1, projection2, forwardTransform);
  16504. ol.proj.addTransform(projection2, projection1, inverseTransform);
  16505. });
  16506. });
  16507. };
  16508. /**
  16509. * Add a Projection object to the list of supported projections that can be
  16510. * looked up by their code.
  16511. *
  16512. * @param {ol.proj.Projection} projection Projection instance.
  16513. * @api stable
  16514. */
  16515. ol.proj.addProjection = function(projection) {
  16516. ol.proj.projections_[projection.getCode()] = projection;
  16517. ol.proj.addTransform(projection, projection, ol.proj.cloneTransform);
  16518. };
  16519. /**
  16520. * @param {Array.<ol.proj.Projection>} projections Projections.
  16521. */
  16522. ol.proj.addProjections = function(projections) {
  16523. var addedProjections = [];
  16524. projections.forEach(function(projection) {
  16525. addedProjections.push(ol.proj.addProjection(projection));
  16526. });
  16527. };
  16528. /**
  16529. * FIXME empty description for jsdoc
  16530. */
  16531. ol.proj.clearAllProjections = function() {
  16532. ol.proj.projections_ = {};
  16533. ol.proj.transforms_ = {};
  16534. };
  16535. /**
  16536. * @param {ol.proj.Projection|string|undefined} projection Projection.
  16537. * @param {string} defaultCode Default code.
  16538. * @return {ol.proj.Projection} Projection.
  16539. */
  16540. ol.proj.createProjection = function(projection, defaultCode) {
  16541. if (!projection) {
  16542. return ol.proj.get(defaultCode);
  16543. } else if (goog.isString(projection)) {
  16544. return ol.proj.get(projection);
  16545. } else {
  16546. goog.asserts.assertInstanceof(projection, ol.proj.Projection,
  16547. 'projection should be an ol.proj.Projection');
  16548. return projection;
  16549. }
  16550. };
  16551. /**
  16552. * Registers a conversion function to convert coordinates from the source
  16553. * projection to the destination projection.
  16554. *
  16555. * @param {ol.proj.Projection} source Source.
  16556. * @param {ol.proj.Projection} destination Destination.
  16557. * @param {ol.TransformFunction} transformFn Transform.
  16558. */
  16559. ol.proj.addTransform = function(source, destination, transformFn) {
  16560. var sourceCode = source.getCode();
  16561. var destinationCode = destination.getCode();
  16562. var transforms = ol.proj.transforms_;
  16563. if (!goog.object.containsKey(transforms, sourceCode)) {
  16564. transforms[sourceCode] = {};
  16565. }
  16566. transforms[sourceCode][destinationCode] = transformFn;
  16567. };
  16568. /**
  16569. * Registers coordinate transform functions to convert coordinates between the
  16570. * source projection and the destination projection.
  16571. * The forward and inverse functions convert coordinate pairs; this function
  16572. * converts these into the functions used internally which also handle
  16573. * extents and coordinate arrays.
  16574. *
  16575. * @param {ol.proj.ProjectionLike} source Source projection.
  16576. * @param {ol.proj.ProjectionLike} destination Destination projection.
  16577. * @param {function(ol.Coordinate): ol.Coordinate} forward The forward transform
  16578. * function (that is, from the source projection to the destination
  16579. * projection) that takes a {@link ol.Coordinate} as argument and returns
  16580. * the transformed {@link ol.Coordinate}.
  16581. * @param {function(ol.Coordinate): ol.Coordinate} inverse The inverse transform
  16582. * function (that is, from the destination projection to the source
  16583. * projection) that takes a {@link ol.Coordinate} as argument and returns
  16584. * the transformed {@link ol.Coordinate}.
  16585. * @api stable
  16586. */
  16587. ol.proj.addCoordinateTransforms =
  16588. function(source, destination, forward, inverse) {
  16589. var sourceProj = ol.proj.get(source);
  16590. var destProj = ol.proj.get(destination);
  16591. ol.proj.addTransform(sourceProj, destProj,
  16592. ol.proj.createTransformFromCoordinateTransform(forward));
  16593. ol.proj.addTransform(destProj, sourceProj,
  16594. ol.proj.createTransformFromCoordinateTransform(inverse));
  16595. };
  16596. /**
  16597. * Creates a {@link ol.TransformFunction} from a simple 2D coordinate transform
  16598. * function.
  16599. * @param {function(ol.Coordinate): ol.Coordinate} transform Coordinate
  16600. * transform.
  16601. * @return {ol.TransformFunction} Transform function.
  16602. */
  16603. ol.proj.createTransformFromCoordinateTransform = function(transform) {
  16604. return (
  16605. /**
  16606. * @param {Array.<number>} input Input.
  16607. * @param {Array.<number>=} opt_output Output.
  16608. * @param {number=} opt_dimension Dimension.
  16609. * @return {Array.<number>} Output.
  16610. */
  16611. function(input, opt_output, opt_dimension) {
  16612. var length = input.length;
  16613. var dimension = opt_dimension !== undefined ? opt_dimension : 2;
  16614. var output = opt_output !== undefined ? opt_output : new Array(length);
  16615. var point, i, j;
  16616. for (i = 0; i < length; i += dimension) {
  16617. point = transform([input[i], input[i + 1]]);
  16618. output[i] = point[0];
  16619. output[i + 1] = point[1];
  16620. for (j = dimension - 1; j >= 2; --j) {
  16621. output[i + j] = input[i + j];
  16622. }
  16623. }
  16624. return output;
  16625. });
  16626. };
  16627. /**
  16628. * Unregisters the conversion function to convert coordinates from the source
  16629. * projection to the destination projection. This method is used to clean up
  16630. * cached transforms during testing.
  16631. *
  16632. * @param {ol.proj.Projection} source Source projection.
  16633. * @param {ol.proj.Projection} destination Destination projection.
  16634. * @return {ol.TransformFunction} transformFn The unregistered transform.
  16635. */
  16636. ol.proj.removeTransform = function(source, destination) {
  16637. var sourceCode = source.getCode();
  16638. var destinationCode = destination.getCode();
  16639. var transforms = ol.proj.transforms_;
  16640. goog.asserts.assert(sourceCode in transforms,
  16641. 'sourceCode should be in transforms');
  16642. goog.asserts.assert(destinationCode in transforms[sourceCode],
  16643. 'destinationCode should be in transforms of sourceCode');
  16644. var transform = transforms[sourceCode][destinationCode];
  16645. delete transforms[sourceCode][destinationCode];
  16646. if (goog.object.isEmpty(transforms[sourceCode])) {
  16647. delete transforms[sourceCode];
  16648. }
  16649. return transform;
  16650. };
  16651. /**
  16652. * Transforms a coordinate from longitude/latitude to a different projection.
  16653. * @param {ol.Coordinate} coordinate Coordinate as longitude and latitude, i.e.
  16654. * an array with longitude as 1st and latitude as 2nd element.
  16655. * @param {ol.proj.ProjectionLike=} opt_projection Target projection. The
  16656. * default is Web Mercator, i.e. 'EPSG:3857'.
  16657. * @return {ol.Coordinate} Coordinate projected to the target projection.
  16658. * @api stable
  16659. */
  16660. ol.proj.fromLonLat = function(coordinate, opt_projection) {
  16661. return ol.proj.transform(coordinate, 'EPSG:4326',
  16662. opt_projection !== undefined ? opt_projection : 'EPSG:3857');
  16663. };
  16664. /**
  16665. * Transforms a coordinate to longitude/latitude.
  16666. * @param {ol.Coordinate} coordinate Projected coordinate.
  16667. * @param {ol.proj.ProjectionLike=} opt_projection Projection of the coordinate.
  16668. * The default is Web Mercator, i.e. 'EPSG:3857'.
  16669. * @return {ol.Coordinate} Coordinate as longitude and latitude, i.e. an array
  16670. * with longitude as 1st and latitude as 2nd element.
  16671. * @api stable
  16672. */
  16673. ol.proj.toLonLat = function(coordinate, opt_projection) {
  16674. return ol.proj.transform(coordinate,
  16675. opt_projection !== undefined ? opt_projection : 'EPSG:3857', 'EPSG:4326');
  16676. };
  16677. /**
  16678. * Fetches a Projection object for the code specified.
  16679. *
  16680. * @param {ol.proj.ProjectionLike} projectionLike Either a code string which is
  16681. * a combination of authority and identifier such as "EPSG:4326", or an
  16682. * existing projection object, or undefined.
  16683. * @return {ol.proj.Projection} Projection object, or null if not in list.
  16684. * @api stable
  16685. */
  16686. ol.proj.get = function(projectionLike) {
  16687. var projection;
  16688. if (projectionLike instanceof ol.proj.Projection) {
  16689. projection = projectionLike;
  16690. } else if (goog.isString(projectionLike)) {
  16691. var code = projectionLike;
  16692. projection = ol.proj.projections_[code];
  16693. if (ol.ENABLE_PROJ4JS && projection === undefined &&
  16694. typeof proj4 == 'function' && proj4.defs(code) !== undefined) {
  16695. projection = new ol.proj.Projection({code: code});
  16696. ol.proj.addProjection(projection);
  16697. }
  16698. } else {
  16699. projection = null;
  16700. }
  16701. return projection;
  16702. };
  16703. /**
  16704. * Checks if two projections are the same, that is every coordinate in one
  16705. * projection does represent the same geographic point as the same coordinate in
  16706. * the other projection.
  16707. *
  16708. * @param {ol.proj.Projection} projection1 Projection 1.
  16709. * @param {ol.proj.Projection} projection2 Projection 2.
  16710. * @return {boolean} Equivalent.
  16711. */
  16712. ol.proj.equivalent = function(projection1, projection2) {
  16713. if (projection1 === projection2) {
  16714. return true;
  16715. } else if (projection1.getCode() === projection2.getCode()) {
  16716. return true;
  16717. } else if (projection1.getUnits() != projection2.getUnits()) {
  16718. return false;
  16719. } else {
  16720. var transformFn = ol.proj.getTransformFromProjections(
  16721. projection1, projection2);
  16722. return transformFn === ol.proj.cloneTransform;
  16723. }
  16724. };
  16725. /**
  16726. * Given the projection-like objects, searches for a transformation
  16727. * function to convert a coordinates array from the source projection to the
  16728. * destination projection.
  16729. *
  16730. * @param {ol.proj.ProjectionLike} source Source.
  16731. * @param {ol.proj.ProjectionLike} destination Destination.
  16732. * @return {ol.TransformFunction} Transform function.
  16733. * @api stable
  16734. */
  16735. ol.proj.getTransform = function(source, destination) {
  16736. var sourceProjection = ol.proj.get(source);
  16737. var destinationProjection = ol.proj.get(destination);
  16738. return ol.proj.getTransformFromProjections(
  16739. sourceProjection, destinationProjection);
  16740. };
  16741. /**
  16742. * Searches in the list of transform functions for the function for converting
  16743. * coordinates from the source projection to the destination projection.
  16744. *
  16745. * @param {ol.proj.Projection} sourceProjection Source Projection object.
  16746. * @param {ol.proj.Projection} destinationProjection Destination Projection
  16747. * object.
  16748. * @return {ol.TransformFunction} Transform function.
  16749. */
  16750. ol.proj.getTransformFromProjections =
  16751. function(sourceProjection, destinationProjection) {
  16752. var transforms = ol.proj.transforms_;
  16753. var sourceCode = sourceProjection.getCode();
  16754. var destinationCode = destinationProjection.getCode();
  16755. var transform;
  16756. if (goog.object.containsKey(transforms, sourceCode) &&
  16757. goog.object.containsKey(transforms[sourceCode], destinationCode)) {
  16758. transform = transforms[sourceCode][destinationCode];
  16759. }
  16760. if (transform === undefined) {
  16761. goog.asserts.assert(transform !== undefined, 'transform should be defined');
  16762. transform = ol.proj.identityTransform;
  16763. }
  16764. return transform;
  16765. };
  16766. /**
  16767. * @param {Array.<number>} input Input coordinate array.
  16768. * @param {Array.<number>=} opt_output Output array of coordinate values.
  16769. * @param {number=} opt_dimension Dimension.
  16770. * @return {Array.<number>} Input coordinate array (same array as input).
  16771. */
  16772. ol.proj.identityTransform = function(input, opt_output, opt_dimension) {
  16773. if (opt_output !== undefined && input !== opt_output) {
  16774. // TODO: consider making this a warning instead
  16775. goog.asserts.fail('This should not be used internally.');
  16776. for (var i = 0, ii = input.length; i < ii; ++i) {
  16777. opt_output[i] = input[i];
  16778. }
  16779. input = opt_output;
  16780. }
  16781. return input;
  16782. };
  16783. /**
  16784. * @param {Array.<number>} input Input coordinate array.
  16785. * @param {Array.<number>=} opt_output Output array of coordinate values.
  16786. * @param {number=} opt_dimension Dimension.
  16787. * @return {Array.<number>} Output coordinate array (new array, same coordinate
  16788. * values).
  16789. */
  16790. ol.proj.cloneTransform = function(input, opt_output, opt_dimension) {
  16791. var output;
  16792. if (opt_output !== undefined) {
  16793. for (var i = 0, ii = input.length; i < ii; ++i) {
  16794. opt_output[i] = input[i];
  16795. }
  16796. output = opt_output;
  16797. } else {
  16798. output = input.slice();
  16799. }
  16800. return output;
  16801. };
  16802. /**
  16803. * Transforms a coordinate from source projection to destination projection.
  16804. * This returns a new coordinate (and does not modify the original).
  16805. *
  16806. * See {@link ol.proj.transformExtent} for extent transformation.
  16807. * See the transform method of {@link ol.geom.Geometry} and its subclasses for
  16808. * geometry transforms.
  16809. *
  16810. * @param {ol.Coordinate} coordinate Coordinate.
  16811. * @param {ol.proj.ProjectionLike} source Source projection-like.
  16812. * @param {ol.proj.ProjectionLike} destination Destination projection-like.
  16813. * @return {ol.Coordinate} Coordinate.
  16814. * @api stable
  16815. */
  16816. ol.proj.transform = function(coordinate, source, destination) {
  16817. var transformFn = ol.proj.getTransform(source, destination);
  16818. return transformFn(coordinate, undefined, coordinate.length);
  16819. };
  16820. /**
  16821. * Transforms an extent from source projection to destination projection. This
  16822. * returns a new extent (and does not modify the original).
  16823. *
  16824. * @param {ol.Extent} extent The extent to transform.
  16825. * @param {ol.proj.ProjectionLike} source Source projection-like.
  16826. * @param {ol.proj.ProjectionLike} destination Destination projection-like.
  16827. * @return {ol.Extent} The transformed extent.
  16828. * @api stable
  16829. */
  16830. ol.proj.transformExtent = function(extent, source, destination) {
  16831. var transformFn = ol.proj.getTransform(source, destination);
  16832. return ol.extent.applyTransform(extent, transformFn);
  16833. };
  16834. /**
  16835. * Transforms the given point to the destination projection.
  16836. *
  16837. * @param {ol.Coordinate} point Point.
  16838. * @param {ol.proj.Projection} sourceProjection Source projection.
  16839. * @param {ol.proj.Projection} destinationProjection Destination projection.
  16840. * @return {ol.Coordinate} Point.
  16841. */
  16842. ol.proj.transformWithProjections =
  16843. function(point, sourceProjection, destinationProjection) {
  16844. var transformFn = ol.proj.getTransformFromProjections(
  16845. sourceProjection, destinationProjection);
  16846. return transformFn(point);
  16847. };
  16848. goog.provide('ol.geom.Geometry');
  16849. goog.provide('ol.geom.GeometryLayout');
  16850. goog.provide('ol.geom.GeometryType');
  16851. goog.require('goog.functions');
  16852. goog.require('ol.Object');
  16853. goog.require('ol.extent');
  16854. goog.require('ol.proj');
  16855. /**
  16856. * The geometry type. One of `'Point'`, `'LineString'`, `'LinearRing'`,
  16857. * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`,
  16858. * `'GeometryCollection'`, `'Circle'`.
  16859. * @enum {string}
  16860. * @api stable
  16861. */
  16862. ol.geom.GeometryType = {
  16863. POINT: 'Point',
  16864. LINE_STRING: 'LineString',
  16865. LINEAR_RING: 'LinearRing',
  16866. POLYGON: 'Polygon',
  16867. MULTI_POINT: 'MultiPoint',
  16868. MULTI_LINE_STRING: 'MultiLineString',
  16869. MULTI_POLYGON: 'MultiPolygon',
  16870. GEOMETRY_COLLECTION: 'GeometryCollection',
  16871. CIRCLE: 'Circle'
  16872. };
  16873. /**
  16874. * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z')
  16875. * or measure ('M') coordinate is available. Supported values are `'XY'`,
  16876. * `'XYZ'`, `'XYM'`, `'XYZM'`.
  16877. * @enum {string}
  16878. * @api stable
  16879. */
  16880. ol.geom.GeometryLayout = {
  16881. XY: 'XY',
  16882. XYZ: 'XYZ',
  16883. XYM: 'XYM',
  16884. XYZM: 'XYZM'
  16885. };
  16886. /**
  16887. * @classdesc
  16888. * Abstract base class; normally only used for creating subclasses and not
  16889. * instantiated in apps.
  16890. * Base class for vector geometries.
  16891. *
  16892. * To get notified of changes to the geometry, register a listener for the
  16893. * generic `change` event on your geometry instance.
  16894. *
  16895. * @constructor
  16896. * @extends {ol.Object}
  16897. * @api stable
  16898. */
  16899. ol.geom.Geometry = function() {
  16900. goog.base(this);
  16901. /**
  16902. * @private
  16903. * @type {ol.Extent}
  16904. */
  16905. this.extent_ = ol.extent.createEmpty();
  16906. /**
  16907. * @private
  16908. * @type {number}
  16909. */
  16910. this.extentRevision_ = -1;
  16911. /**
  16912. * @protected
  16913. * @type {Object.<string, ol.geom.Geometry>}
  16914. */
  16915. this.simplifiedGeometryCache = {};
  16916. /**
  16917. * @protected
  16918. * @type {number}
  16919. */
  16920. this.simplifiedGeometryMaxMinSquaredTolerance = 0;
  16921. /**
  16922. * @protected
  16923. * @type {number}
  16924. */
  16925. this.simplifiedGeometryRevision = 0;
  16926. };
  16927. goog.inherits(ol.geom.Geometry, ol.Object);
  16928. /**
  16929. * Make a complete copy of the geometry.
  16930. * @function
  16931. * @return {!ol.geom.Geometry} Clone.
  16932. */
  16933. ol.geom.Geometry.prototype.clone = goog.abstractMethod;
  16934. /**
  16935. * @param {number} x X.
  16936. * @param {number} y Y.
  16937. * @param {ol.Coordinate} closestPoint Closest point.
  16938. * @param {number} minSquaredDistance Minimum squared distance.
  16939. * @return {number} Minimum squared distance.
  16940. */
  16941. ol.geom.Geometry.prototype.closestPointXY = goog.abstractMethod;
  16942. /**
  16943. * Return the closest point of the geometry to the passed point as
  16944. * {@link ol.Coordinate coordinate}.
  16945. * @param {ol.Coordinate} point Point.
  16946. * @param {ol.Coordinate=} opt_closestPoint Closest point.
  16947. * @return {ol.Coordinate} Closest point.
  16948. * @api stable
  16949. */
  16950. ol.geom.Geometry.prototype.getClosestPoint = function(point, opt_closestPoint) {
  16951. var closestPoint = opt_closestPoint ? opt_closestPoint : [NaN, NaN];
  16952. this.closestPointXY(point[0], point[1], closestPoint, Infinity);
  16953. return closestPoint;
  16954. };
  16955. /**
  16956. * @param {ol.Coordinate} coordinate Coordinate.
  16957. * @return {boolean} Contains coordinate.
  16958. */
  16959. ol.geom.Geometry.prototype.containsCoordinate = function(coordinate) {
  16960. return this.containsXY(coordinate[0], coordinate[1]);
  16961. };
  16962. /**
  16963. * @param {ol.Extent} extent Extent.
  16964. * @protected
  16965. * @return {ol.Extent} extent Extent.
  16966. */
  16967. ol.geom.Geometry.prototype.computeExtent = goog.abstractMethod;
  16968. /**
  16969. * @param {number} x X.
  16970. * @param {number} y Y.
  16971. * @return {boolean} Contains (x, y).
  16972. */
  16973. ol.geom.Geometry.prototype.containsXY = goog.functions.FALSE;
  16974. /**
  16975. * Get the extent of the geometry.
  16976. * @param {ol.Extent=} opt_extent Extent.
  16977. * @return {ol.Extent} extent Extent.
  16978. * @api stable
  16979. */
  16980. ol.geom.Geometry.prototype.getExtent = function(opt_extent) {
  16981. if (this.extentRevision_ != this.getRevision()) {
  16982. this.extent_ = this.computeExtent(this.extent_);
  16983. this.extentRevision_ = this.getRevision();
  16984. }
  16985. return ol.extent.returnOrUpdate(this.extent_, opt_extent);
  16986. };
  16987. /**
  16988. * Create a simplified version of this geometry. For linestrings, this uses
  16989. * the the {@link
  16990. * https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  16991. * Douglas Peucker} algorithm. For polygons, a quantization-based
  16992. * simplification is used to preserve topology.
  16993. * @function
  16994. * @param {number} tolerance The tolerance distance for simplification.
  16995. * @return {ol.geom.Geometry} A new, simplified version of the original
  16996. * geometry.
  16997. * @api
  16998. */
  16999. ol.geom.Geometry.prototype.simplify = function(tolerance) {
  17000. return this.getSimplifiedGeometry(tolerance * tolerance);
  17001. };
  17002. /**
  17003. * Create a simplified version of this geometry using the Douglas Peucker
  17004. * algorithm.
  17005. * @see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
  17006. * @function
  17007. * @param {number} squaredTolerance Squared tolerance.
  17008. * @return {ol.geom.Geometry} Simplified geometry.
  17009. */
  17010. ol.geom.Geometry.prototype.getSimplifiedGeometry = goog.abstractMethod;
  17011. /**
  17012. * Get the type of this geometry.
  17013. * @function
  17014. * @return {ol.geom.GeometryType} Geometry type.
  17015. */
  17016. ol.geom.Geometry.prototype.getType = goog.abstractMethod;
  17017. /**
  17018. * Apply a transform function to each coordinate of the geometry.
  17019. * The geometry is modified in place.
  17020. * If you do not want the geometry modified in place, first clone() it and
  17021. * then use this function on the clone.
  17022. * @function
  17023. * @param {ol.TransformFunction} transformFn Transform.
  17024. */
  17025. ol.geom.Geometry.prototype.applyTransform = goog.abstractMethod;
  17026. /**
  17027. * Test if the geometry and the passed extent intersect.
  17028. * @param {ol.Extent} extent Extent.
  17029. * @return {boolean} `true` if the geometry and the extent intersect.
  17030. * @function
  17031. */
  17032. ol.geom.Geometry.prototype.intersectsExtent = goog.abstractMethod;
  17033. /**
  17034. * Translate the geometry. This modifies the geometry coordinates in place. If
  17035. * instead you want a new geometry, first `clone()` this geometry.
  17036. * @param {number} deltaX Delta X.
  17037. * @param {number} deltaY Delta Y.
  17038. * @function
  17039. */
  17040. ol.geom.Geometry.prototype.translate = goog.abstractMethod;
  17041. /**
  17042. * Transform each coordinate of the geometry from one coordinate reference
  17043. * system to another. The geometry is modified in place.
  17044. * For example, a line will be transformed to a line and a circle to a circle.
  17045. * If you do not want the geometry modified in place, first clone() it and
  17046. * then use this function on the clone.
  17047. *
  17048. * @param {ol.proj.ProjectionLike} source The current projection. Can be a
  17049. * string identifier or a {@link ol.proj.Projection} object.
  17050. * @param {ol.proj.ProjectionLike} destination The desired projection. Can be a
  17051. * string identifier or a {@link ol.proj.Projection} object.
  17052. * @return {ol.geom.Geometry} This geometry. Note that original geometry is
  17053. * modified in place.
  17054. * @api stable
  17055. */
  17056. ol.geom.Geometry.prototype.transform = function(source, destination) {
  17057. this.applyTransform(ol.proj.getTransform(source, destination));
  17058. return this;
  17059. };
  17060. goog.provide('ol.geom.flat.transform');
  17061. goog.require('goog.vec.Mat4');
  17062. /**
  17063. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17064. * @param {number} offset Offset.
  17065. * @param {number} end End.
  17066. * @param {number} stride Stride.
  17067. * @param {goog.vec.Mat4.Number} transform Transform.
  17068. * @param {Array.<number>=} opt_dest Destination.
  17069. * @return {Array.<number>} Transformed coordinates.
  17070. */
  17071. ol.geom.flat.transform.transform2D =
  17072. function(flatCoordinates, offset, end, stride, transform, opt_dest) {
  17073. var m00 = goog.vec.Mat4.getElement(transform, 0, 0);
  17074. var m10 = goog.vec.Mat4.getElement(transform, 1, 0);
  17075. var m01 = goog.vec.Mat4.getElement(transform, 0, 1);
  17076. var m11 = goog.vec.Mat4.getElement(transform, 1, 1);
  17077. var m03 = goog.vec.Mat4.getElement(transform, 0, 3);
  17078. var m13 = goog.vec.Mat4.getElement(transform, 1, 3);
  17079. var dest = opt_dest ? opt_dest : [];
  17080. var i = 0;
  17081. var j;
  17082. for (j = offset; j < end; j += stride) {
  17083. var x = flatCoordinates[j];
  17084. var y = flatCoordinates[j + 1];
  17085. dest[i++] = m00 * x + m01 * y + m03;
  17086. dest[i++] = m10 * x + m11 * y + m13;
  17087. }
  17088. if (opt_dest && dest.length != i) {
  17089. dest.length = i;
  17090. }
  17091. return dest;
  17092. };
  17093. /**
  17094. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17095. * @param {number} offset Offset.
  17096. * @param {number} end End.
  17097. * @param {number} stride Stride.
  17098. * @param {number} deltaX Delta X.
  17099. * @param {number} deltaY Delta Y.
  17100. * @param {Array.<number>=} opt_dest Destination.
  17101. * @return {Array.<number>} Transformed coordinates.
  17102. */
  17103. ol.geom.flat.transform.translate =
  17104. function(flatCoordinates, offset, end, stride, deltaX, deltaY, opt_dest) {
  17105. var dest = opt_dest ? opt_dest : [];
  17106. var i = 0;
  17107. var j, k;
  17108. for (j = offset; j < end; j += stride) {
  17109. dest[i++] = flatCoordinates[j] + deltaX;
  17110. dest[i++] = flatCoordinates[j + 1] + deltaY;
  17111. for (k = j + 2; k < j + stride; ++k) {
  17112. dest[i++] = flatCoordinates[k];
  17113. }
  17114. }
  17115. if (opt_dest && dest.length != i) {
  17116. dest.length = i;
  17117. }
  17118. return dest;
  17119. };
  17120. goog.provide('ol.geom.SimpleGeometry');
  17121. goog.require('goog.asserts');
  17122. goog.require('goog.functions');
  17123. goog.require('goog.object');
  17124. goog.require('ol.extent');
  17125. goog.require('ol.geom.Geometry');
  17126. goog.require('ol.geom.GeometryLayout');
  17127. goog.require('ol.geom.flat.transform');
  17128. /**
  17129. * @classdesc
  17130. * Abstract base class; only used for creating subclasses; do not instantiate
  17131. * in apps, as cannot be rendered.
  17132. *
  17133. * @constructor
  17134. * @extends {ol.geom.Geometry}
  17135. * @api stable
  17136. */
  17137. ol.geom.SimpleGeometry = function() {
  17138. goog.base(this);
  17139. /**
  17140. * @protected
  17141. * @type {ol.geom.GeometryLayout}
  17142. */
  17143. this.layout = ol.geom.GeometryLayout.XY;
  17144. /**
  17145. * @protected
  17146. * @type {number}
  17147. */
  17148. this.stride = 2;
  17149. /**
  17150. * @protected
  17151. * @type {Array.<number>}
  17152. */
  17153. this.flatCoordinates = null;
  17154. };
  17155. goog.inherits(ol.geom.SimpleGeometry, ol.geom.Geometry);
  17156. /**
  17157. * @param {number} stride Stride.
  17158. * @private
  17159. * @return {ol.geom.GeometryLayout} layout Layout.
  17160. */
  17161. ol.geom.SimpleGeometry.getLayoutForStride_ = function(stride) {
  17162. if (stride == 2) {
  17163. return ol.geom.GeometryLayout.XY;
  17164. } else if (stride == 3) {
  17165. return ol.geom.GeometryLayout.XYZ;
  17166. } else if (stride == 4) {
  17167. return ol.geom.GeometryLayout.XYZM;
  17168. } else {
  17169. goog.asserts.fail('unsupported stride: ' + stride);
  17170. }
  17171. };
  17172. /**
  17173. * @param {ol.geom.GeometryLayout} layout Layout.
  17174. * @return {number} Stride.
  17175. */
  17176. ol.geom.SimpleGeometry.getStrideForLayout = function(layout) {
  17177. if (layout == ol.geom.GeometryLayout.XY) {
  17178. return 2;
  17179. } else if (layout == ol.geom.GeometryLayout.XYZ) {
  17180. return 3;
  17181. } else if (layout == ol.geom.GeometryLayout.XYM) {
  17182. return 3;
  17183. } else if (layout == ol.geom.GeometryLayout.XYZM) {
  17184. return 4;
  17185. } else {
  17186. goog.asserts.fail('unsupported layout: ' + layout);
  17187. }
  17188. };
  17189. /**
  17190. * @inheritDoc
  17191. */
  17192. ol.geom.SimpleGeometry.prototype.containsXY = goog.functions.FALSE;
  17193. /**
  17194. * @inheritDoc
  17195. */
  17196. ol.geom.SimpleGeometry.prototype.computeExtent = function(extent) {
  17197. return ol.extent.createOrUpdateFromFlatCoordinates(
  17198. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  17199. extent);
  17200. };
  17201. /**
  17202. * @return {Array} Coordinates.
  17203. */
  17204. ol.geom.SimpleGeometry.prototype.getCoordinates = goog.abstractMethod;
  17205. /**
  17206. * Return the first coordinate of the geometry.
  17207. * @return {ol.Coordinate} First coordinate.
  17208. * @api stable
  17209. */
  17210. ol.geom.SimpleGeometry.prototype.getFirstCoordinate = function() {
  17211. return this.flatCoordinates.slice(0, this.stride);
  17212. };
  17213. /**
  17214. * @return {Array.<number>} Flat coordinates.
  17215. */
  17216. ol.geom.SimpleGeometry.prototype.getFlatCoordinates = function() {
  17217. return this.flatCoordinates;
  17218. };
  17219. /**
  17220. * Return the last coordinate of the geometry.
  17221. * @return {ol.Coordinate} Last point.
  17222. * @api stable
  17223. */
  17224. ol.geom.SimpleGeometry.prototype.getLastCoordinate = function() {
  17225. return this.flatCoordinates.slice(this.flatCoordinates.length - this.stride);
  17226. };
  17227. /**
  17228. * Return the {@link ol.geom.GeometryLayout layout} of the geometry.
  17229. * @return {ol.geom.GeometryLayout} Layout.
  17230. * @api stable
  17231. */
  17232. ol.geom.SimpleGeometry.prototype.getLayout = function() {
  17233. return this.layout;
  17234. };
  17235. /**
  17236. * @inheritDoc
  17237. */
  17238. ol.geom.SimpleGeometry.prototype.getSimplifiedGeometry =
  17239. function(squaredTolerance) {
  17240. if (this.simplifiedGeometryRevision != this.getRevision()) {
  17241. goog.object.clear(this.simplifiedGeometryCache);
  17242. this.simplifiedGeometryMaxMinSquaredTolerance = 0;
  17243. this.simplifiedGeometryRevision = this.getRevision();
  17244. }
  17245. // If squaredTolerance is negative or if we know that simplification will not
  17246. // have any effect then just return this.
  17247. if (squaredTolerance < 0 ||
  17248. (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&
  17249. squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)) {
  17250. return this;
  17251. }
  17252. var key = squaredTolerance.toString();
  17253. if (this.simplifiedGeometryCache.hasOwnProperty(key)) {
  17254. return this.simplifiedGeometryCache[key];
  17255. } else {
  17256. var simplifiedGeometry =
  17257. this.getSimplifiedGeometryInternal(squaredTolerance);
  17258. var simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates();
  17259. if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) {
  17260. this.simplifiedGeometryCache[key] = simplifiedGeometry;
  17261. return simplifiedGeometry;
  17262. } else {
  17263. // Simplification did not actually remove any coordinates. We now know
  17264. // that any calls to getSimplifiedGeometry with a squaredTolerance less
  17265. // than or equal to the current squaredTolerance will also not have any
  17266. // effect. This allows us to short circuit simplification (saving CPU
  17267. // cycles) and prevents the cache of simplified geometries from filling
  17268. // up with useless identical copies of this geometry (saving memory).
  17269. this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;
  17270. return this;
  17271. }
  17272. }
  17273. };
  17274. /**
  17275. * @param {number} squaredTolerance Squared tolerance.
  17276. * @return {ol.geom.SimpleGeometry} Simplified geometry.
  17277. * @protected
  17278. */
  17279. ol.geom.SimpleGeometry.prototype.getSimplifiedGeometryInternal =
  17280. function(squaredTolerance) {
  17281. return this;
  17282. };
  17283. /**
  17284. * @return {number} Stride.
  17285. */
  17286. ol.geom.SimpleGeometry.prototype.getStride = function() {
  17287. return this.stride;
  17288. };
  17289. /**
  17290. * @param {ol.geom.GeometryLayout} layout Layout.
  17291. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17292. * @protected
  17293. */
  17294. ol.geom.SimpleGeometry.prototype.setFlatCoordinatesInternal =
  17295. function(layout, flatCoordinates) {
  17296. this.stride = ol.geom.SimpleGeometry.getStrideForLayout(layout);
  17297. this.layout = layout;
  17298. this.flatCoordinates = flatCoordinates;
  17299. };
  17300. /**
  17301. * @param {Array} coordinates Coordinates.
  17302. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  17303. */
  17304. ol.geom.SimpleGeometry.prototype.setCoordinates = goog.abstractMethod;
  17305. /**
  17306. * @param {ol.geom.GeometryLayout|undefined} layout Layout.
  17307. * @param {Array} coordinates Coordinates.
  17308. * @param {number} nesting Nesting.
  17309. * @protected
  17310. */
  17311. ol.geom.SimpleGeometry.prototype.setLayout =
  17312. function(layout, coordinates, nesting) {
  17313. /** @type {number} */
  17314. var stride;
  17315. if (layout) {
  17316. stride = ol.geom.SimpleGeometry.getStrideForLayout(layout);
  17317. } else {
  17318. var i;
  17319. for (i = 0; i < nesting; ++i) {
  17320. if (coordinates.length === 0) {
  17321. this.layout = ol.geom.GeometryLayout.XY;
  17322. this.stride = 2;
  17323. return;
  17324. } else {
  17325. coordinates = /** @type {Array} */ (coordinates[0]);
  17326. }
  17327. }
  17328. stride = (/** @type {Array} */ (coordinates)).length;
  17329. layout = ol.geom.SimpleGeometry.getLayoutForStride_(stride);
  17330. }
  17331. this.layout = layout;
  17332. this.stride = stride;
  17333. };
  17334. /**
  17335. * @inheritDoc
  17336. * @api stable
  17337. */
  17338. ol.geom.SimpleGeometry.prototype.applyTransform = function(transformFn) {
  17339. if (this.flatCoordinates) {
  17340. transformFn(this.flatCoordinates, this.flatCoordinates, this.stride);
  17341. this.changed();
  17342. }
  17343. };
  17344. /**
  17345. * @inheritDoc
  17346. * @api stable
  17347. */
  17348. ol.geom.SimpleGeometry.prototype.translate = function(deltaX, deltaY) {
  17349. var flatCoordinates = this.getFlatCoordinates();
  17350. if (flatCoordinates) {
  17351. var stride = this.getStride();
  17352. ol.geom.flat.transform.translate(
  17353. flatCoordinates, 0, flatCoordinates.length, stride,
  17354. deltaX, deltaY, flatCoordinates);
  17355. this.changed();
  17356. }
  17357. };
  17358. /**
  17359. * @param {ol.geom.SimpleGeometry} simpleGeometry Simple geometry.
  17360. * @param {goog.vec.Mat4.Number} transform Transform.
  17361. * @param {Array.<number>=} opt_dest Destination.
  17362. * @return {Array.<number>} Transformed flat coordinates.
  17363. */
  17364. ol.geom.transformSimpleGeometry2D =
  17365. function(simpleGeometry, transform, opt_dest) {
  17366. var flatCoordinates = simpleGeometry.getFlatCoordinates();
  17367. if (!flatCoordinates) {
  17368. return null;
  17369. } else {
  17370. var stride = simpleGeometry.getStride();
  17371. return ol.geom.flat.transform.transform2D(
  17372. flatCoordinates, 0, flatCoordinates.length, stride,
  17373. transform, opt_dest);
  17374. }
  17375. };
  17376. goog.provide('ol.geom.flat.area');
  17377. /**
  17378. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17379. * @param {number} offset Offset.
  17380. * @param {number} end End.
  17381. * @param {number} stride Stride.
  17382. * @return {number} Area.
  17383. */
  17384. ol.geom.flat.area.linearRing = function(flatCoordinates, offset, end, stride) {
  17385. var twiceArea = 0;
  17386. var x1 = flatCoordinates[end - stride];
  17387. var y1 = flatCoordinates[end - stride + 1];
  17388. for (; offset < end; offset += stride) {
  17389. var x2 = flatCoordinates[offset];
  17390. var y2 = flatCoordinates[offset + 1];
  17391. twiceArea += y1 * x2 - x1 * y2;
  17392. x1 = x2;
  17393. y1 = y2;
  17394. }
  17395. return twiceArea / 2;
  17396. };
  17397. /**
  17398. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17399. * @param {number} offset Offset.
  17400. * @param {Array.<number>} ends Ends.
  17401. * @param {number} stride Stride.
  17402. * @return {number} Area.
  17403. */
  17404. ol.geom.flat.area.linearRings =
  17405. function(flatCoordinates, offset, ends, stride) {
  17406. var area = 0;
  17407. var i, ii;
  17408. for (i = 0, ii = ends.length; i < ii; ++i) {
  17409. var end = ends[i];
  17410. area += ol.geom.flat.area.linearRing(flatCoordinates, offset, end, stride);
  17411. offset = end;
  17412. }
  17413. return area;
  17414. };
  17415. /**
  17416. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17417. * @param {number} offset Offset.
  17418. * @param {Array.<Array.<number>>} endss Endss.
  17419. * @param {number} stride Stride.
  17420. * @return {number} Area.
  17421. */
  17422. ol.geom.flat.area.linearRingss =
  17423. function(flatCoordinates, offset, endss, stride) {
  17424. var area = 0;
  17425. var i, ii;
  17426. for (i = 0, ii = endss.length; i < ii; ++i) {
  17427. var ends = endss[i];
  17428. area +=
  17429. ol.geom.flat.area.linearRings(flatCoordinates, offset, ends, stride);
  17430. offset = ends[ends.length - 1];
  17431. }
  17432. return area;
  17433. };
  17434. goog.provide('ol.geom.flat.closest');
  17435. goog.require('goog.asserts');
  17436. goog.require('goog.math');
  17437. goog.require('ol.math');
  17438. /**
  17439. * Returns the point on the 2D line segment flatCoordinates[offset1] to
  17440. * flatCoordinates[offset2] that is closest to the point (x, y). Extra
  17441. * dimensions are linearly interpolated.
  17442. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17443. * @param {number} offset1 Offset 1.
  17444. * @param {number} offset2 Offset 2.
  17445. * @param {number} stride Stride.
  17446. * @param {number} x X.
  17447. * @param {number} y Y.
  17448. * @param {Array.<number>} closestPoint Closest point.
  17449. */
  17450. ol.geom.flat.closest.point =
  17451. function(flatCoordinates, offset1, offset2, stride, x, y, closestPoint) {
  17452. var x1 = flatCoordinates[offset1];
  17453. var y1 = flatCoordinates[offset1 + 1];
  17454. var dx = flatCoordinates[offset2] - x1;
  17455. var dy = flatCoordinates[offset2 + 1] - y1;
  17456. var i, offset;
  17457. if (dx === 0 && dy === 0) {
  17458. offset = offset1;
  17459. } else {
  17460. var t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
  17461. if (t > 1) {
  17462. offset = offset2;
  17463. } else if (t > 0) {
  17464. for (i = 0; i < stride; ++i) {
  17465. closestPoint[i] = goog.math.lerp(flatCoordinates[offset1 + i],
  17466. flatCoordinates[offset2 + i], t);
  17467. }
  17468. closestPoint.length = stride;
  17469. return;
  17470. } else {
  17471. offset = offset1;
  17472. }
  17473. }
  17474. for (i = 0; i < stride; ++i) {
  17475. closestPoint[i] = flatCoordinates[offset + i];
  17476. }
  17477. closestPoint.length = stride;
  17478. };
  17479. /**
  17480. * Return the squared of the largest distance between any pair of consecutive
  17481. * coordinates.
  17482. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17483. * @param {number} offset Offset.
  17484. * @param {number} end End.
  17485. * @param {number} stride Stride.
  17486. * @param {number} maxSquaredDelta Max squared delta.
  17487. * @return {number} Max squared delta.
  17488. */
  17489. ol.geom.flat.closest.getMaxSquaredDelta =
  17490. function(flatCoordinates, offset, end, stride, maxSquaredDelta) {
  17491. var x1 = flatCoordinates[offset];
  17492. var y1 = flatCoordinates[offset + 1];
  17493. for (offset += stride; offset < end; offset += stride) {
  17494. var x2 = flatCoordinates[offset];
  17495. var y2 = flatCoordinates[offset + 1];
  17496. var squaredDelta = ol.math.squaredDistance(x1, y1, x2, y2);
  17497. if (squaredDelta > maxSquaredDelta) {
  17498. maxSquaredDelta = squaredDelta;
  17499. }
  17500. x1 = x2;
  17501. y1 = y2;
  17502. }
  17503. return maxSquaredDelta;
  17504. };
  17505. /**
  17506. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17507. * @param {number} offset Offset.
  17508. * @param {Array.<number>} ends Ends.
  17509. * @param {number} stride Stride.
  17510. * @param {number} maxSquaredDelta Max squared delta.
  17511. * @return {number} Max squared delta.
  17512. */
  17513. ol.geom.flat.closest.getsMaxSquaredDelta =
  17514. function(flatCoordinates, offset, ends, stride, maxSquaredDelta) {
  17515. var i, ii;
  17516. for (i = 0, ii = ends.length; i < ii; ++i) {
  17517. var end = ends[i];
  17518. maxSquaredDelta = ol.geom.flat.closest.getMaxSquaredDelta(
  17519. flatCoordinates, offset, end, stride, maxSquaredDelta);
  17520. offset = end;
  17521. }
  17522. return maxSquaredDelta;
  17523. };
  17524. /**
  17525. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17526. * @param {number} offset Offset.
  17527. * @param {Array.<Array.<number>>} endss Endss.
  17528. * @param {number} stride Stride.
  17529. * @param {number} maxSquaredDelta Max squared delta.
  17530. * @return {number} Max squared delta.
  17531. */
  17532. ol.geom.flat.closest.getssMaxSquaredDelta =
  17533. function(flatCoordinates, offset, endss, stride, maxSquaredDelta) {
  17534. var i, ii;
  17535. for (i = 0, ii = endss.length; i < ii; ++i) {
  17536. var ends = endss[i];
  17537. maxSquaredDelta = ol.geom.flat.closest.getsMaxSquaredDelta(
  17538. flatCoordinates, offset, ends, stride, maxSquaredDelta);
  17539. offset = ends[ends.length - 1];
  17540. }
  17541. return maxSquaredDelta;
  17542. };
  17543. /**
  17544. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17545. * @param {number} offset Offset.
  17546. * @param {number} end End.
  17547. * @param {number} stride Stride.
  17548. * @param {number} maxDelta Max delta.
  17549. * @param {boolean} isRing Is ring.
  17550. * @param {number} x X.
  17551. * @param {number} y Y.
  17552. * @param {Array.<number>} closestPoint Closest point.
  17553. * @param {number} minSquaredDistance Minimum squared distance.
  17554. * @param {Array.<number>=} opt_tmpPoint Temporary point object.
  17555. * @return {number} Minimum squared distance.
  17556. */
  17557. ol.geom.flat.closest.getClosestPoint = function(flatCoordinates, offset, end,
  17558. stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance,
  17559. opt_tmpPoint) {
  17560. if (offset == end) {
  17561. return minSquaredDistance;
  17562. }
  17563. var i, squaredDistance;
  17564. if (maxDelta === 0) {
  17565. // All points are identical, so just test the first point.
  17566. squaredDistance = ol.math.squaredDistance(
  17567. x, y, flatCoordinates[offset], flatCoordinates[offset + 1]);
  17568. if (squaredDistance < minSquaredDistance) {
  17569. for (i = 0; i < stride; ++i) {
  17570. closestPoint[i] = flatCoordinates[offset + i];
  17571. }
  17572. closestPoint.length = stride;
  17573. return squaredDistance;
  17574. } else {
  17575. return minSquaredDistance;
  17576. }
  17577. }
  17578. goog.asserts.assert(maxDelta > 0, 'maxDelta should be larger than 0');
  17579. var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN];
  17580. var index = offset + stride;
  17581. while (index < end) {
  17582. ol.geom.flat.closest.point(
  17583. flatCoordinates, index - stride, index, stride, x, y, tmpPoint);
  17584. squaredDistance = ol.math.squaredDistance(x, y, tmpPoint[0], tmpPoint[1]);
  17585. if (squaredDistance < minSquaredDistance) {
  17586. minSquaredDistance = squaredDistance;
  17587. for (i = 0; i < stride; ++i) {
  17588. closestPoint[i] = tmpPoint[i];
  17589. }
  17590. closestPoint.length = stride;
  17591. index += stride;
  17592. } else {
  17593. // Skip ahead multiple points, because we know that all the skipped
  17594. // points cannot be any closer than the closest point we have found so
  17595. // far. We know this because we know how close the current point is, how
  17596. // close the closest point we have found so far is, and the maximum
  17597. // distance between consecutive points. For example, if we're currently
  17598. // at distance 10, the best we've found so far is 3, and that the maximum
  17599. // distance between consecutive points is 2, then we'll need to skip at
  17600. // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of
  17601. // finding a closer point. We use Math.max(..., 1) to ensure that we
  17602. // always advance at least one point, to avoid an infinite loop.
  17603. index += stride * Math.max(
  17604. ((Math.sqrt(squaredDistance) -
  17605. Math.sqrt(minSquaredDistance)) / maxDelta) | 0, 1);
  17606. }
  17607. }
  17608. if (isRing) {
  17609. // Check the closing segment.
  17610. ol.geom.flat.closest.point(
  17611. flatCoordinates, end - stride, offset, stride, x, y, tmpPoint);
  17612. squaredDistance = ol.math.squaredDistance(x, y, tmpPoint[0], tmpPoint[1]);
  17613. if (squaredDistance < minSquaredDistance) {
  17614. minSquaredDistance = squaredDistance;
  17615. for (i = 0; i < stride; ++i) {
  17616. closestPoint[i] = tmpPoint[i];
  17617. }
  17618. closestPoint.length = stride;
  17619. }
  17620. }
  17621. return minSquaredDistance;
  17622. };
  17623. /**
  17624. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17625. * @param {number} offset Offset.
  17626. * @param {Array.<number>} ends Ends.
  17627. * @param {number} stride Stride.
  17628. * @param {number} maxDelta Max delta.
  17629. * @param {boolean} isRing Is ring.
  17630. * @param {number} x X.
  17631. * @param {number} y Y.
  17632. * @param {Array.<number>} closestPoint Closest point.
  17633. * @param {number} minSquaredDistance Minimum squared distance.
  17634. * @param {Array.<number>=} opt_tmpPoint Temporary point object.
  17635. * @return {number} Minimum squared distance.
  17636. */
  17637. ol.geom.flat.closest.getsClosestPoint = function(flatCoordinates, offset, ends,
  17638. stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance,
  17639. opt_tmpPoint) {
  17640. var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN];
  17641. var i, ii;
  17642. for (i = 0, ii = ends.length; i < ii; ++i) {
  17643. var end = ends[i];
  17644. minSquaredDistance = ol.geom.flat.closest.getClosestPoint(
  17645. flatCoordinates, offset, end, stride,
  17646. maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint);
  17647. offset = end;
  17648. }
  17649. return minSquaredDistance;
  17650. };
  17651. /**
  17652. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17653. * @param {number} offset Offset.
  17654. * @param {Array.<Array.<number>>} endss Endss.
  17655. * @param {number} stride Stride.
  17656. * @param {number} maxDelta Max delta.
  17657. * @param {boolean} isRing Is ring.
  17658. * @param {number} x X.
  17659. * @param {number} y Y.
  17660. * @param {Array.<number>} closestPoint Closest point.
  17661. * @param {number} minSquaredDistance Minimum squared distance.
  17662. * @param {Array.<number>=} opt_tmpPoint Temporary point object.
  17663. * @return {number} Minimum squared distance.
  17664. */
  17665. ol.geom.flat.closest.getssClosestPoint = function(flatCoordinates, offset,
  17666. endss, stride, maxDelta, isRing, x, y, closestPoint, minSquaredDistance,
  17667. opt_tmpPoint) {
  17668. var tmpPoint = opt_tmpPoint ? opt_tmpPoint : [NaN, NaN];
  17669. var i, ii;
  17670. for (i = 0, ii = endss.length; i < ii; ++i) {
  17671. var ends = endss[i];
  17672. minSquaredDistance = ol.geom.flat.closest.getsClosestPoint(
  17673. flatCoordinates, offset, ends, stride,
  17674. maxDelta, isRing, x, y, closestPoint, minSquaredDistance, tmpPoint);
  17675. offset = ends[ends.length - 1];
  17676. }
  17677. return minSquaredDistance;
  17678. };
  17679. goog.provide('ol.geom.flat.deflate');
  17680. goog.require('goog.asserts');
  17681. /**
  17682. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17683. * @param {number} offset Offset.
  17684. * @param {ol.Coordinate} coordinate Coordinate.
  17685. * @param {number} stride Stride.
  17686. * @return {number} offset Offset.
  17687. */
  17688. ol.geom.flat.deflate.coordinate =
  17689. function(flatCoordinates, offset, coordinate, stride) {
  17690. goog.asserts.assert(coordinate.length == stride,
  17691. 'length of the coordinate array should match stride');
  17692. var i, ii;
  17693. for (i = 0, ii = coordinate.length; i < ii; ++i) {
  17694. flatCoordinates[offset++] = coordinate[i];
  17695. }
  17696. return offset;
  17697. };
  17698. /**
  17699. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17700. * @param {number} offset Offset.
  17701. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  17702. * @param {number} stride Stride.
  17703. * @return {number} offset Offset.
  17704. */
  17705. ol.geom.flat.deflate.coordinates =
  17706. function(flatCoordinates, offset, coordinates, stride) {
  17707. var i, ii;
  17708. for (i = 0, ii = coordinates.length; i < ii; ++i) {
  17709. var coordinate = coordinates[i];
  17710. goog.asserts.assert(coordinate.length == stride,
  17711. 'length of coordinate array should match stride');
  17712. var j;
  17713. for (j = 0; j < stride; ++j) {
  17714. flatCoordinates[offset++] = coordinate[j];
  17715. }
  17716. }
  17717. return offset;
  17718. };
  17719. /**
  17720. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17721. * @param {number} offset Offset.
  17722. * @param {Array.<Array.<ol.Coordinate>>} coordinatess Coordinatess.
  17723. * @param {number} stride Stride.
  17724. * @param {Array.<number>=} opt_ends Ends.
  17725. * @return {Array.<number>} Ends.
  17726. */
  17727. ol.geom.flat.deflate.coordinatess =
  17728. function(flatCoordinates, offset, coordinatess, stride, opt_ends) {
  17729. var ends = opt_ends ? opt_ends : [];
  17730. var i = 0;
  17731. var j, jj;
  17732. for (j = 0, jj = coordinatess.length; j < jj; ++j) {
  17733. var end = ol.geom.flat.deflate.coordinates(
  17734. flatCoordinates, offset, coordinatess[j], stride);
  17735. ends[i++] = end;
  17736. offset = end;
  17737. }
  17738. ends.length = i;
  17739. return ends;
  17740. };
  17741. /**
  17742. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17743. * @param {number} offset Offset.
  17744. * @param {Array.<Array.<Array.<ol.Coordinate>>>} coordinatesss Coordinatesss.
  17745. * @param {number} stride Stride.
  17746. * @param {Array.<Array.<number>>=} opt_endss Endss.
  17747. * @return {Array.<Array.<number>>} Endss.
  17748. */
  17749. ol.geom.flat.deflate.coordinatesss =
  17750. function(flatCoordinates, offset, coordinatesss, stride, opt_endss) {
  17751. var endss = opt_endss ? opt_endss : [];
  17752. var i = 0;
  17753. var j, jj;
  17754. for (j = 0, jj = coordinatesss.length; j < jj; ++j) {
  17755. var ends = ol.geom.flat.deflate.coordinatess(
  17756. flatCoordinates, offset, coordinatesss[j], stride, endss[i]);
  17757. endss[i++] = ends;
  17758. offset = ends[ends.length - 1];
  17759. }
  17760. endss.length = i;
  17761. return endss;
  17762. };
  17763. goog.provide('ol.geom.flat.inflate');
  17764. /**
  17765. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17766. * @param {number} offset Offset.
  17767. * @param {number} end End.
  17768. * @param {number} stride Stride.
  17769. * @param {Array.<ol.Coordinate>=} opt_coordinates Coordinates.
  17770. * @return {Array.<ol.Coordinate>} Coordinates.
  17771. */
  17772. ol.geom.flat.inflate.coordinates =
  17773. function(flatCoordinates, offset, end, stride, opt_coordinates) {
  17774. var coordinates = opt_coordinates !== undefined ? opt_coordinates : [];
  17775. var i = 0;
  17776. var j;
  17777. for (j = offset; j < end; j += stride) {
  17778. coordinates[i++] = flatCoordinates.slice(j, j + stride);
  17779. }
  17780. coordinates.length = i;
  17781. return coordinates;
  17782. };
  17783. /**
  17784. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17785. * @param {number} offset Offset.
  17786. * @param {Array.<number>} ends Ends.
  17787. * @param {number} stride Stride.
  17788. * @param {Array.<Array.<ol.Coordinate>>=} opt_coordinatess Coordinatess.
  17789. * @return {Array.<Array.<ol.Coordinate>>} Coordinatess.
  17790. */
  17791. ol.geom.flat.inflate.coordinatess =
  17792. function(flatCoordinates, offset, ends, stride, opt_coordinatess) {
  17793. var coordinatess = opt_coordinatess !== undefined ? opt_coordinatess : [];
  17794. var i = 0;
  17795. var j, jj;
  17796. for (j = 0, jj = ends.length; j < jj; ++j) {
  17797. var end = ends[j];
  17798. coordinatess[i++] = ol.geom.flat.inflate.coordinates(
  17799. flatCoordinates, offset, end, stride, coordinatess[i]);
  17800. offset = end;
  17801. }
  17802. coordinatess.length = i;
  17803. return coordinatess;
  17804. };
  17805. /**
  17806. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17807. * @param {number} offset Offset.
  17808. * @param {Array.<Array.<number>>} endss Endss.
  17809. * @param {number} stride Stride.
  17810. * @param {Array.<Array.<Array.<ol.Coordinate>>>=} opt_coordinatesss
  17811. * Coordinatesss.
  17812. * @return {Array.<Array.<Array.<ol.Coordinate>>>} Coordinatesss.
  17813. */
  17814. ol.geom.flat.inflate.coordinatesss =
  17815. function(flatCoordinates, offset, endss, stride, opt_coordinatesss) {
  17816. var coordinatesss = opt_coordinatesss !== undefined ? opt_coordinatesss : [];
  17817. var i = 0;
  17818. var j, jj;
  17819. for (j = 0, jj = endss.length; j < jj; ++j) {
  17820. var ends = endss[j];
  17821. coordinatesss[i++] = ol.geom.flat.inflate.coordinatess(
  17822. flatCoordinates, offset, ends, stride, coordinatesss[i]);
  17823. offset = ends[ends.length - 1];
  17824. }
  17825. coordinatesss.length = i;
  17826. return coordinatesss;
  17827. };
  17828. // Based on simplify-js https://github.com/mourner/simplify-js
  17829. // Copyright (c) 2012, Vladimir Agafonkin
  17830. // All rights reserved.
  17831. //
  17832. // Redistribution and use in source and binary forms, with or without
  17833. // modification, are permitted provided that the following conditions are met:
  17834. //
  17835. // 1. Redistributions of source code must retain the above copyright notice,
  17836. // this list of conditions and the following disclaimer.
  17837. //
  17838. // 2. Redistributions in binary form must reproduce the above copyright
  17839. // notice, this list of conditions and the following disclaimer in the
  17840. // documentation and/or other materials provided with the distribution.
  17841. //
  17842. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17843. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17844. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17845. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  17846. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  17847. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  17848. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  17849. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  17850. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  17851. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  17852. // POSSIBILITY OF SUCH DAMAGE.
  17853. goog.provide('ol.geom.flat.simplify');
  17854. goog.require('ol.math');
  17855. /**
  17856. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17857. * @param {number} offset Offset.
  17858. * @param {number} end End.
  17859. * @param {number} stride Stride.
  17860. * @param {number} squaredTolerance Squared tolerance.
  17861. * @param {boolean} highQuality Highest quality.
  17862. * @param {Array.<number>=} opt_simplifiedFlatCoordinates Simplified flat
  17863. * coordinates.
  17864. * @return {Array.<number>} Simplified line string.
  17865. */
  17866. ol.geom.flat.simplify.lineString = function(flatCoordinates, offset, end,
  17867. stride, squaredTolerance, highQuality, opt_simplifiedFlatCoordinates) {
  17868. var simplifiedFlatCoordinates = opt_simplifiedFlatCoordinates !== undefined ?
  17869. opt_simplifiedFlatCoordinates : [];
  17870. if (!highQuality) {
  17871. end = ol.geom.flat.simplify.radialDistance(flatCoordinates, offset, end,
  17872. stride, squaredTolerance,
  17873. simplifiedFlatCoordinates, 0);
  17874. flatCoordinates = simplifiedFlatCoordinates;
  17875. offset = 0;
  17876. stride = 2;
  17877. }
  17878. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.douglasPeucker(
  17879. flatCoordinates, offset, end, stride, squaredTolerance,
  17880. simplifiedFlatCoordinates, 0);
  17881. return simplifiedFlatCoordinates;
  17882. };
  17883. /**
  17884. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17885. * @param {number} offset Offset.
  17886. * @param {number} end End.
  17887. * @param {number} stride Stride.
  17888. * @param {number} squaredTolerance Squared tolerance.
  17889. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  17890. * coordinates.
  17891. * @param {number} simplifiedOffset Simplified offset.
  17892. * @return {number} Simplified offset.
  17893. */
  17894. ol.geom.flat.simplify.douglasPeucker = function(flatCoordinates, offset, end,
  17895. stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) {
  17896. var n = (end - offset) / stride;
  17897. if (n < 3) {
  17898. for (; offset < end; offset += stride) {
  17899. simplifiedFlatCoordinates[simplifiedOffset++] =
  17900. flatCoordinates[offset];
  17901. simplifiedFlatCoordinates[simplifiedOffset++] =
  17902. flatCoordinates[offset + 1];
  17903. }
  17904. return simplifiedOffset;
  17905. }
  17906. /** @type {Array.<number>} */
  17907. var markers = new Array(n);
  17908. markers[0] = 1;
  17909. markers[n - 1] = 1;
  17910. /** @type {Array.<number>} */
  17911. var stack = [offset, end - stride];
  17912. var index = 0;
  17913. var i;
  17914. while (stack.length > 0) {
  17915. var last = stack.pop();
  17916. var first = stack.pop();
  17917. var maxSquaredDistance = 0;
  17918. var x1 = flatCoordinates[first];
  17919. var y1 = flatCoordinates[first + 1];
  17920. var x2 = flatCoordinates[last];
  17921. var y2 = flatCoordinates[last + 1];
  17922. for (i = first + stride; i < last; i += stride) {
  17923. var x = flatCoordinates[i];
  17924. var y = flatCoordinates[i + 1];
  17925. var squaredDistance = ol.math.squaredSegmentDistance(
  17926. x, y, x1, y1, x2, y2);
  17927. if (squaredDistance > maxSquaredDistance) {
  17928. index = i;
  17929. maxSquaredDistance = squaredDistance;
  17930. }
  17931. }
  17932. if (maxSquaredDistance > squaredTolerance) {
  17933. markers[(index - offset) / stride] = 1;
  17934. if (first + stride < index) {
  17935. stack.push(first, index);
  17936. }
  17937. if (index + stride < last) {
  17938. stack.push(index, last);
  17939. }
  17940. }
  17941. }
  17942. for (i = 0; i < n; ++i) {
  17943. if (markers[i]) {
  17944. simplifiedFlatCoordinates[simplifiedOffset++] =
  17945. flatCoordinates[offset + i * stride];
  17946. simplifiedFlatCoordinates[simplifiedOffset++] =
  17947. flatCoordinates[offset + i * stride + 1];
  17948. }
  17949. }
  17950. return simplifiedOffset;
  17951. };
  17952. /**
  17953. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17954. * @param {number} offset Offset.
  17955. * @param {Array.<number>} ends Ends.
  17956. * @param {number} stride Stride.
  17957. * @param {number} squaredTolerance Squared tolerance.
  17958. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  17959. * coordinates.
  17960. * @param {number} simplifiedOffset Simplified offset.
  17961. * @param {Array.<number>} simplifiedEnds Simplified ends.
  17962. * @return {number} Simplified offset.
  17963. */
  17964. ol.geom.flat.simplify.douglasPeuckers = function(flatCoordinates, offset,
  17965. ends, stride, squaredTolerance, simplifiedFlatCoordinates,
  17966. simplifiedOffset, simplifiedEnds) {
  17967. var i, ii;
  17968. for (i = 0, ii = ends.length; i < ii; ++i) {
  17969. var end = ends[i];
  17970. simplifiedOffset = ol.geom.flat.simplify.douglasPeucker(
  17971. flatCoordinates, offset, end, stride, squaredTolerance,
  17972. simplifiedFlatCoordinates, simplifiedOffset);
  17973. simplifiedEnds.push(simplifiedOffset);
  17974. offset = end;
  17975. }
  17976. return simplifiedOffset;
  17977. };
  17978. /**
  17979. * @param {Array.<number>} flatCoordinates Flat coordinates.
  17980. * @param {number} offset Offset.
  17981. * @param {Array.<Array.<number>>} endss Endss.
  17982. * @param {number} stride Stride.
  17983. * @param {number} squaredTolerance Squared tolerance.
  17984. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  17985. * coordinates.
  17986. * @param {number} simplifiedOffset Simplified offset.
  17987. * @param {Array.<Array.<number>>} simplifiedEndss Simplified endss.
  17988. * @return {number} Simplified offset.
  17989. */
  17990. ol.geom.flat.simplify.douglasPeuckerss = function(
  17991. flatCoordinates, offset, endss, stride, squaredTolerance,
  17992. simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) {
  17993. var i, ii;
  17994. for (i = 0, ii = endss.length; i < ii; ++i) {
  17995. var ends = endss[i];
  17996. var simplifiedEnds = [];
  17997. simplifiedOffset = ol.geom.flat.simplify.douglasPeuckers(
  17998. flatCoordinates, offset, ends, stride, squaredTolerance,
  17999. simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds);
  18000. simplifiedEndss.push(simplifiedEnds);
  18001. offset = ends[ends.length - 1];
  18002. }
  18003. return simplifiedOffset;
  18004. };
  18005. /**
  18006. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18007. * @param {number} offset Offset.
  18008. * @param {number} end End.
  18009. * @param {number} stride Stride.
  18010. * @param {number} squaredTolerance Squared tolerance.
  18011. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  18012. * coordinates.
  18013. * @param {number} simplifiedOffset Simplified offset.
  18014. * @return {number} Simplified offset.
  18015. */
  18016. ol.geom.flat.simplify.radialDistance = function(flatCoordinates, offset, end,
  18017. stride, squaredTolerance, simplifiedFlatCoordinates, simplifiedOffset) {
  18018. if (end <= offset + stride) {
  18019. // zero or one point, no simplification possible, so copy and return
  18020. for (; offset < end; offset += stride) {
  18021. simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];
  18022. simplifiedFlatCoordinates[simplifiedOffset++] =
  18023. flatCoordinates[offset + 1];
  18024. }
  18025. return simplifiedOffset;
  18026. }
  18027. var x1 = flatCoordinates[offset];
  18028. var y1 = flatCoordinates[offset + 1];
  18029. // copy first point
  18030. simplifiedFlatCoordinates[simplifiedOffset++] = x1;
  18031. simplifiedFlatCoordinates[simplifiedOffset++] = y1;
  18032. var x2 = x1;
  18033. var y2 = y1;
  18034. for (offset += stride; offset < end; offset += stride) {
  18035. x2 = flatCoordinates[offset];
  18036. y2 = flatCoordinates[offset + 1];
  18037. if (ol.math.squaredDistance(x1, y1, x2, y2) > squaredTolerance) {
  18038. // copy point at offset
  18039. simplifiedFlatCoordinates[simplifiedOffset++] = x2;
  18040. simplifiedFlatCoordinates[simplifiedOffset++] = y2;
  18041. x1 = x2;
  18042. y1 = y2;
  18043. }
  18044. }
  18045. if (x2 != x1 || y2 != y1) {
  18046. // copy last point
  18047. simplifiedFlatCoordinates[simplifiedOffset++] = x2;
  18048. simplifiedFlatCoordinates[simplifiedOffset++] = y2;
  18049. }
  18050. return simplifiedOffset;
  18051. };
  18052. /**
  18053. * @param {number} value Value.
  18054. * @param {number} tolerance Tolerance.
  18055. * @return {number} Rounded value.
  18056. */
  18057. ol.geom.flat.simplify.snap = function(value, tolerance) {
  18058. return tolerance * Math.round(value / tolerance);
  18059. };
  18060. /**
  18061. * Simplifies a line string using an algorithm designed by Tim Schaub.
  18062. * Coordinates are snapped to the nearest value in a virtual grid and
  18063. * consecutive duplicate coordinates are discarded. This effectively preserves
  18064. * topology as the simplification of any subsection of a line string is
  18065. * independent of the rest of the line string. This means that, for examples,
  18066. * the common edge between two polygons will be simplified to the same line
  18067. * string independently in both polygons. This implementation uses a single
  18068. * pass over the coordinates and eliminates intermediate collinear points.
  18069. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18070. * @param {number} offset Offset.
  18071. * @param {number} end End.
  18072. * @param {number} stride Stride.
  18073. * @param {number} tolerance Tolerance.
  18074. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  18075. * coordinates.
  18076. * @param {number} simplifiedOffset Simplified offset.
  18077. * @return {number} Simplified offset.
  18078. */
  18079. ol.geom.flat.simplify.quantize = function(flatCoordinates, offset, end, stride,
  18080. tolerance, simplifiedFlatCoordinates, simplifiedOffset) {
  18081. // do nothing if the line is empty
  18082. if (offset == end) {
  18083. return simplifiedOffset;
  18084. }
  18085. // snap the first coordinate (P1)
  18086. var x1 = ol.geom.flat.simplify.snap(flatCoordinates[offset], tolerance);
  18087. var y1 = ol.geom.flat.simplify.snap(flatCoordinates[offset + 1], tolerance);
  18088. offset += stride;
  18089. // add the first coordinate to the output
  18090. simplifiedFlatCoordinates[simplifiedOffset++] = x1;
  18091. simplifiedFlatCoordinates[simplifiedOffset++] = y1;
  18092. // find the next coordinate that does not snap to the same value as the first
  18093. // coordinate (P2)
  18094. var x2, y2;
  18095. do {
  18096. x2 = ol.geom.flat.simplify.snap(flatCoordinates[offset], tolerance);
  18097. y2 = ol.geom.flat.simplify.snap(flatCoordinates[offset + 1], tolerance);
  18098. offset += stride;
  18099. if (offset == end) {
  18100. // all coordinates snap to the same value, the line collapses to a point
  18101. // push the last snapped value anyway to ensure that the output contains
  18102. // at least two points
  18103. // FIXME should we really return at least two points anyway?
  18104. simplifiedFlatCoordinates[simplifiedOffset++] = x2;
  18105. simplifiedFlatCoordinates[simplifiedOffset++] = y2;
  18106. return simplifiedOffset;
  18107. }
  18108. } while (x2 == x1 && y2 == y1);
  18109. while (offset < end) {
  18110. var x3, y3;
  18111. // snap the next coordinate (P3)
  18112. x3 = ol.geom.flat.simplify.snap(flatCoordinates[offset], tolerance);
  18113. y3 = ol.geom.flat.simplify.snap(flatCoordinates[offset + 1], tolerance);
  18114. offset += stride;
  18115. // skip P3 if it is equal to P2
  18116. if (x3 == x2 && y3 == y2) {
  18117. continue;
  18118. }
  18119. // calculate the delta between P1 and P2
  18120. var dx1 = x2 - x1;
  18121. var dy1 = y2 - y1;
  18122. // calculate the delta between P3 and P1
  18123. var dx2 = x3 - x1;
  18124. var dy2 = y3 - y1;
  18125. // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from
  18126. // P1 in the same direction then P2 is on the straight line between P1 and
  18127. // P3
  18128. if ((dx1 * dy2 == dy1 * dx2) &&
  18129. ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) &&
  18130. ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1))) {
  18131. // discard P2 and set P2 = P3
  18132. x2 = x3;
  18133. y2 = y3;
  18134. continue;
  18135. }
  18136. // either P1, P2, and P3 are not colinear, or they are colinear but P3 is
  18137. // between P3 and P1 or on the opposite half of the line to P2. add P2,
  18138. // and continue with P1 = P2 and P2 = P3
  18139. simplifiedFlatCoordinates[simplifiedOffset++] = x2;
  18140. simplifiedFlatCoordinates[simplifiedOffset++] = y2;
  18141. x1 = x2;
  18142. y1 = y2;
  18143. x2 = x3;
  18144. y2 = y3;
  18145. }
  18146. // add the last point (P2)
  18147. simplifiedFlatCoordinates[simplifiedOffset++] = x2;
  18148. simplifiedFlatCoordinates[simplifiedOffset++] = y2;
  18149. return simplifiedOffset;
  18150. };
  18151. /**
  18152. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18153. * @param {number} offset Offset.
  18154. * @param {Array.<number>} ends Ends.
  18155. * @param {number} stride Stride.
  18156. * @param {number} tolerance Tolerance.
  18157. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  18158. * coordinates.
  18159. * @param {number} simplifiedOffset Simplified offset.
  18160. * @param {Array.<number>} simplifiedEnds Simplified ends.
  18161. * @return {number} Simplified offset.
  18162. */
  18163. ol.geom.flat.simplify.quantizes = function(
  18164. flatCoordinates, offset, ends, stride,
  18165. tolerance,
  18166. simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds) {
  18167. var i, ii;
  18168. for (i = 0, ii = ends.length; i < ii; ++i) {
  18169. var end = ends[i];
  18170. simplifiedOffset = ol.geom.flat.simplify.quantize(
  18171. flatCoordinates, offset, end, stride,
  18172. tolerance,
  18173. simplifiedFlatCoordinates, simplifiedOffset);
  18174. simplifiedEnds.push(simplifiedOffset);
  18175. offset = end;
  18176. }
  18177. return simplifiedOffset;
  18178. };
  18179. /**
  18180. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18181. * @param {number} offset Offset.
  18182. * @param {Array.<Array.<number>>} endss Endss.
  18183. * @param {number} stride Stride.
  18184. * @param {number} tolerance Tolerance.
  18185. * @param {Array.<number>} simplifiedFlatCoordinates Simplified flat
  18186. * coordinates.
  18187. * @param {number} simplifiedOffset Simplified offset.
  18188. * @param {Array.<Array.<number>>} simplifiedEndss Simplified endss.
  18189. * @return {number} Simplified offset.
  18190. */
  18191. ol.geom.flat.simplify.quantizess = function(
  18192. flatCoordinates, offset, endss, stride,
  18193. tolerance,
  18194. simplifiedFlatCoordinates, simplifiedOffset, simplifiedEndss) {
  18195. var i, ii;
  18196. for (i = 0, ii = endss.length; i < ii; ++i) {
  18197. var ends = endss[i];
  18198. var simplifiedEnds = [];
  18199. simplifiedOffset = ol.geom.flat.simplify.quantizes(
  18200. flatCoordinates, offset, ends, stride,
  18201. tolerance,
  18202. simplifiedFlatCoordinates, simplifiedOffset, simplifiedEnds);
  18203. simplifiedEndss.push(simplifiedEnds);
  18204. offset = ends[ends.length - 1];
  18205. }
  18206. return simplifiedOffset;
  18207. };
  18208. goog.provide('ol.geom.LinearRing');
  18209. goog.require('ol.extent');
  18210. goog.require('ol.geom.GeometryLayout');
  18211. goog.require('ol.geom.GeometryType');
  18212. goog.require('ol.geom.SimpleGeometry');
  18213. goog.require('ol.geom.flat.area');
  18214. goog.require('ol.geom.flat.closest');
  18215. goog.require('ol.geom.flat.deflate');
  18216. goog.require('ol.geom.flat.inflate');
  18217. goog.require('ol.geom.flat.simplify');
  18218. /**
  18219. * @classdesc
  18220. * Linear ring geometry. Only used as part of polygon; cannot be rendered
  18221. * on its own.
  18222. *
  18223. * @constructor
  18224. * @extends {ol.geom.SimpleGeometry}
  18225. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  18226. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  18227. * @api stable
  18228. */
  18229. ol.geom.LinearRing = function(coordinates, opt_layout) {
  18230. goog.base(this);
  18231. /**
  18232. * @private
  18233. * @type {number}
  18234. */
  18235. this.maxDelta_ = -1;
  18236. /**
  18237. * @private
  18238. * @type {number}
  18239. */
  18240. this.maxDeltaRevision_ = -1;
  18241. this.setCoordinates(coordinates, opt_layout);
  18242. };
  18243. goog.inherits(ol.geom.LinearRing, ol.geom.SimpleGeometry);
  18244. /**
  18245. * Make a complete copy of the geometry.
  18246. * @return {!ol.geom.LinearRing} Clone.
  18247. * @api stable
  18248. */
  18249. ol.geom.LinearRing.prototype.clone = function() {
  18250. var linearRing = new ol.geom.LinearRing(null);
  18251. linearRing.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  18252. return linearRing;
  18253. };
  18254. /**
  18255. * @inheritDoc
  18256. */
  18257. ol.geom.LinearRing.prototype.closestPointXY =
  18258. function(x, y, closestPoint, minSquaredDistance) {
  18259. if (minSquaredDistance <
  18260. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  18261. return minSquaredDistance;
  18262. }
  18263. if (this.maxDeltaRevision_ != this.getRevision()) {
  18264. this.maxDelta_ = Math.sqrt(ol.geom.flat.closest.getMaxSquaredDelta(
  18265. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0));
  18266. this.maxDeltaRevision_ = this.getRevision();
  18267. }
  18268. return ol.geom.flat.closest.getClosestPoint(
  18269. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  18270. this.maxDelta_, true, x, y, closestPoint, minSquaredDistance);
  18271. };
  18272. /**
  18273. * Return the area of the linear ring on projected plane.
  18274. * @return {number} Area (on projected plane).
  18275. * @api stable
  18276. */
  18277. ol.geom.LinearRing.prototype.getArea = function() {
  18278. return ol.geom.flat.area.linearRing(
  18279. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
  18280. };
  18281. /**
  18282. * Return the coordinates of the linear ring.
  18283. * @return {Array.<ol.Coordinate>} Coordinates.
  18284. * @api stable
  18285. */
  18286. ol.geom.LinearRing.prototype.getCoordinates = function() {
  18287. return ol.geom.flat.inflate.coordinates(
  18288. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
  18289. };
  18290. /**
  18291. * @inheritDoc
  18292. */
  18293. ol.geom.LinearRing.prototype.getSimplifiedGeometryInternal =
  18294. function(squaredTolerance) {
  18295. var simplifiedFlatCoordinates = [];
  18296. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.douglasPeucker(
  18297. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  18298. squaredTolerance, simplifiedFlatCoordinates, 0);
  18299. var simplifiedLinearRing = new ol.geom.LinearRing(null);
  18300. simplifiedLinearRing.setFlatCoordinates(
  18301. ol.geom.GeometryLayout.XY, simplifiedFlatCoordinates);
  18302. return simplifiedLinearRing;
  18303. };
  18304. /**
  18305. * @inheritDoc
  18306. * @api stable
  18307. */
  18308. ol.geom.LinearRing.prototype.getType = function() {
  18309. return ol.geom.GeometryType.LINEAR_RING;
  18310. };
  18311. /**
  18312. * Set the coordinates of the linear ring.
  18313. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  18314. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  18315. * @api stable
  18316. */
  18317. ol.geom.LinearRing.prototype.setCoordinates =
  18318. function(coordinates, opt_layout) {
  18319. if (!coordinates) {
  18320. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  18321. } else {
  18322. this.setLayout(opt_layout, coordinates, 1);
  18323. if (!this.flatCoordinates) {
  18324. this.flatCoordinates = [];
  18325. }
  18326. this.flatCoordinates.length = ol.geom.flat.deflate.coordinates(
  18327. this.flatCoordinates, 0, coordinates, this.stride);
  18328. this.changed();
  18329. }
  18330. };
  18331. /**
  18332. * @param {ol.geom.GeometryLayout} layout Layout.
  18333. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18334. */
  18335. ol.geom.LinearRing.prototype.setFlatCoordinates =
  18336. function(layout, flatCoordinates) {
  18337. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  18338. this.changed();
  18339. };
  18340. goog.provide('ol.geom.Point');
  18341. goog.require('ol.extent');
  18342. goog.require('ol.geom.GeometryLayout');
  18343. goog.require('ol.geom.GeometryType');
  18344. goog.require('ol.geom.SimpleGeometry');
  18345. goog.require('ol.geom.flat.deflate');
  18346. goog.require('ol.math');
  18347. /**
  18348. * @classdesc
  18349. * Point geometry.
  18350. *
  18351. * @constructor
  18352. * @extends {ol.geom.SimpleGeometry}
  18353. * @param {ol.Coordinate} coordinates Coordinates.
  18354. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  18355. * @api stable
  18356. */
  18357. ol.geom.Point = function(coordinates, opt_layout) {
  18358. goog.base(this);
  18359. this.setCoordinates(coordinates, opt_layout);
  18360. };
  18361. goog.inherits(ol.geom.Point, ol.geom.SimpleGeometry);
  18362. /**
  18363. * Make a complete copy of the geometry.
  18364. * @return {!ol.geom.Point} Clone.
  18365. * @api stable
  18366. */
  18367. ol.geom.Point.prototype.clone = function() {
  18368. var point = new ol.geom.Point(null);
  18369. point.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  18370. return point;
  18371. };
  18372. /**
  18373. * @inheritDoc
  18374. */
  18375. ol.geom.Point.prototype.closestPointXY =
  18376. function(x, y, closestPoint, minSquaredDistance) {
  18377. var flatCoordinates = this.flatCoordinates;
  18378. var squaredDistance = ol.math.squaredDistance(
  18379. x, y, flatCoordinates[0], flatCoordinates[1]);
  18380. if (squaredDistance < minSquaredDistance) {
  18381. var stride = this.stride;
  18382. var i;
  18383. for (i = 0; i < stride; ++i) {
  18384. closestPoint[i] = flatCoordinates[i];
  18385. }
  18386. closestPoint.length = stride;
  18387. return squaredDistance;
  18388. } else {
  18389. return minSquaredDistance;
  18390. }
  18391. };
  18392. /**
  18393. * Return the coordinate of the point.
  18394. * @return {ol.Coordinate} Coordinates.
  18395. * @api stable
  18396. */
  18397. ol.geom.Point.prototype.getCoordinates = function() {
  18398. return !this.flatCoordinates ? [] : this.flatCoordinates.slice();
  18399. };
  18400. /**
  18401. * @inheritDoc
  18402. */
  18403. ol.geom.Point.prototype.computeExtent = function(extent) {
  18404. return ol.extent.createOrUpdateFromCoordinate(this.flatCoordinates, extent);
  18405. };
  18406. /**
  18407. * @inheritDoc
  18408. * @api stable
  18409. */
  18410. ol.geom.Point.prototype.getType = function() {
  18411. return ol.geom.GeometryType.POINT;
  18412. };
  18413. /**
  18414. * @inheritDoc
  18415. * @api stable
  18416. */
  18417. ol.geom.Point.prototype.intersectsExtent = function(extent) {
  18418. return ol.extent.containsXY(extent,
  18419. this.flatCoordinates[0], this.flatCoordinates[1]);
  18420. };
  18421. /**
  18422. * Set the coordinate of the point.
  18423. * @param {ol.Coordinate} coordinates Coordinates.
  18424. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  18425. * @api stable
  18426. */
  18427. ol.geom.Point.prototype.setCoordinates = function(coordinates, opt_layout) {
  18428. if (!coordinates) {
  18429. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  18430. } else {
  18431. this.setLayout(opt_layout, coordinates, 0);
  18432. if (!this.flatCoordinates) {
  18433. this.flatCoordinates = [];
  18434. }
  18435. this.flatCoordinates.length = ol.geom.flat.deflate.coordinate(
  18436. this.flatCoordinates, 0, coordinates, this.stride);
  18437. this.changed();
  18438. }
  18439. };
  18440. /**
  18441. * @param {ol.geom.GeometryLayout} layout Layout.
  18442. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18443. */
  18444. ol.geom.Point.prototype.setFlatCoordinates = function(layout, flatCoordinates) {
  18445. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  18446. this.changed();
  18447. };
  18448. goog.provide('ol.geom.flat.contains');
  18449. goog.require('goog.asserts');
  18450. goog.require('ol.extent');
  18451. /**
  18452. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18453. * @param {number} offset Offset.
  18454. * @param {number} end End.
  18455. * @param {number} stride Stride.
  18456. * @param {ol.Extent} extent Extent.
  18457. * @return {boolean} Contains extent.
  18458. */
  18459. ol.geom.flat.contains.linearRingContainsExtent =
  18460. function(flatCoordinates, offset, end, stride, extent) {
  18461. var outside = ol.extent.forEachCorner(extent,
  18462. /**
  18463. * @param {ol.Coordinate} coordinate Coordinate.
  18464. */
  18465. function(coordinate) {
  18466. return !ol.geom.flat.contains.linearRingContainsXY(flatCoordinates,
  18467. offset, end, stride, coordinate[0], coordinate[1]);
  18468. });
  18469. return !outside;
  18470. };
  18471. /**
  18472. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18473. * @param {number} offset Offset.
  18474. * @param {number} end End.
  18475. * @param {number} stride Stride.
  18476. * @param {number} x X.
  18477. * @param {number} y Y.
  18478. * @return {boolean} Contains (x, y).
  18479. */
  18480. ol.geom.flat.contains.linearRingContainsXY =
  18481. function(flatCoordinates, offset, end, stride, x, y) {
  18482. // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  18483. var contains = false;
  18484. var x1 = flatCoordinates[end - stride];
  18485. var y1 = flatCoordinates[end - stride + 1];
  18486. for (; offset < end; offset += stride) {
  18487. var x2 = flatCoordinates[offset];
  18488. var y2 = flatCoordinates[offset + 1];
  18489. var intersect = ((y1 > y) != (y2 > y)) &&
  18490. (x < (x2 - x1) * (y - y1) / (y2 - y1) + x1);
  18491. if (intersect) {
  18492. contains = !contains;
  18493. }
  18494. x1 = x2;
  18495. y1 = y2;
  18496. }
  18497. return contains;
  18498. };
  18499. /**
  18500. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18501. * @param {number} offset Offset.
  18502. * @param {Array.<number>} ends Ends.
  18503. * @param {number} stride Stride.
  18504. * @param {number} x X.
  18505. * @param {number} y Y.
  18506. * @return {boolean} Contains (x, y).
  18507. */
  18508. ol.geom.flat.contains.linearRingsContainsXY =
  18509. function(flatCoordinates, offset, ends, stride, x, y) {
  18510. goog.asserts.assert(ends.length > 0, 'ends should not be an empty array');
  18511. if (ends.length === 0) {
  18512. return false;
  18513. }
  18514. if (!ol.geom.flat.contains.linearRingContainsXY(
  18515. flatCoordinates, offset, ends[0], stride, x, y)) {
  18516. return false;
  18517. }
  18518. var i, ii;
  18519. for (i = 1, ii = ends.length; i < ii; ++i) {
  18520. if (ol.geom.flat.contains.linearRingContainsXY(
  18521. flatCoordinates, ends[i - 1], ends[i], stride, x, y)) {
  18522. return false;
  18523. }
  18524. }
  18525. return true;
  18526. };
  18527. /**
  18528. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18529. * @param {number} offset Offset.
  18530. * @param {Array.<Array.<number>>} endss Endss.
  18531. * @param {number} stride Stride.
  18532. * @param {number} x X.
  18533. * @param {number} y Y.
  18534. * @return {boolean} Contains (x, y).
  18535. */
  18536. ol.geom.flat.contains.linearRingssContainsXY =
  18537. function(flatCoordinates, offset, endss, stride, x, y) {
  18538. goog.asserts.assert(endss.length > 0, 'endss should not be an empty array');
  18539. if (endss.length === 0) {
  18540. return false;
  18541. }
  18542. var i, ii;
  18543. for (i = 0, ii = endss.length; i < ii; ++i) {
  18544. var ends = endss[i];
  18545. if (ol.geom.flat.contains.linearRingsContainsXY(
  18546. flatCoordinates, offset, ends, stride, x, y)) {
  18547. return true;
  18548. }
  18549. offset = ends[ends.length - 1];
  18550. }
  18551. return false;
  18552. };
  18553. goog.provide('ol.geom.flat.interiorpoint');
  18554. goog.require('goog.asserts');
  18555. goog.require('ol.geom.flat.contains');
  18556. /**
  18557. * Calculates a point that is likely to lie in the interior of the linear rings.
  18558. * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint.
  18559. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18560. * @param {number} offset Offset.
  18561. * @param {Array.<number>} ends Ends.
  18562. * @param {number} stride Stride.
  18563. * @param {Array.<number>} flatCenters Flat centers.
  18564. * @param {number} flatCentersOffset Flat center offset.
  18565. * @param {Array.<number>=} opt_dest Destination.
  18566. * @return {Array.<number>} Destination.
  18567. */
  18568. ol.geom.flat.interiorpoint.linearRings = function(flatCoordinates, offset,
  18569. ends, stride, flatCenters, flatCentersOffset, opt_dest) {
  18570. var i, ii, x, x1, x2, y1, y2;
  18571. var y = flatCenters[flatCentersOffset + 1];
  18572. /** @type {Array.<number>} */
  18573. var intersections = [];
  18574. // Calculate intersections with the horizontal line
  18575. var end = ends[0];
  18576. x1 = flatCoordinates[end - stride];
  18577. y1 = flatCoordinates[end - stride + 1];
  18578. for (i = offset; i < end; i += stride) {
  18579. x2 = flatCoordinates[i];
  18580. y2 = flatCoordinates[i + 1];
  18581. if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) {
  18582. x = (y - y1) / (y2 - y1) * (x2 - x1) + x1;
  18583. intersections.push(x);
  18584. }
  18585. x1 = x2;
  18586. y1 = y2;
  18587. }
  18588. // Find the longest segment of the horizontal line that has its center point
  18589. // inside the linear ring.
  18590. var pointX = NaN;
  18591. var maxSegmentLength = -Infinity;
  18592. intersections.sort();
  18593. x1 = intersections[0];
  18594. for (i = 1, ii = intersections.length; i < ii; ++i) {
  18595. x2 = intersections[i];
  18596. var segmentLength = Math.abs(x2 - x1);
  18597. if (segmentLength > maxSegmentLength) {
  18598. x = (x1 + x2) / 2;
  18599. if (ol.geom.flat.contains.linearRingsContainsXY(
  18600. flatCoordinates, offset, ends, stride, x, y)) {
  18601. pointX = x;
  18602. maxSegmentLength = segmentLength;
  18603. }
  18604. }
  18605. x1 = x2;
  18606. }
  18607. if (isNaN(pointX)) {
  18608. // There is no horizontal line that has its center point inside the linear
  18609. // ring. Use the center of the the linear ring's extent.
  18610. pointX = flatCenters[flatCentersOffset];
  18611. }
  18612. if (opt_dest) {
  18613. opt_dest.push(pointX, y);
  18614. return opt_dest;
  18615. } else {
  18616. return [pointX, y];
  18617. }
  18618. };
  18619. /**
  18620. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18621. * @param {number} offset Offset.
  18622. * @param {Array.<Array.<number>>} endss Endss.
  18623. * @param {number} stride Stride.
  18624. * @param {Array.<number>} flatCenters Flat centers.
  18625. * @return {Array.<number>} Interior points.
  18626. */
  18627. ol.geom.flat.interiorpoint.linearRingss =
  18628. function(flatCoordinates, offset, endss, stride, flatCenters) {
  18629. goog.asserts.assert(2 * endss.length == flatCenters.length,
  18630. 'endss.length times 2 should be flatCenters.length');
  18631. var interiorPoints = [];
  18632. var i, ii;
  18633. for (i = 0, ii = endss.length; i < ii; ++i) {
  18634. var ends = endss[i];
  18635. interiorPoints = ol.geom.flat.interiorpoint.linearRings(flatCoordinates,
  18636. offset, ends, stride, flatCenters, 2 * i, interiorPoints);
  18637. offset = ends[ends.length - 1];
  18638. }
  18639. return interiorPoints;
  18640. };
  18641. goog.provide('ol.geom.flat.segments');
  18642. /**
  18643. * This function calls `callback` for each segment of the flat coordinates
  18644. * array. If the callback returns a truthy value the function returns that
  18645. * value immediately. Otherwise the function returns `false`.
  18646. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18647. * @param {number} offset Offset.
  18648. * @param {number} end End.
  18649. * @param {number} stride Stride.
  18650. * @param {function(this: S, ol.Coordinate, ol.Coordinate): T} callback Function
  18651. * called for each segment.
  18652. * @param {S=} opt_this The object to be used as the value of 'this'
  18653. * within callback.
  18654. * @return {T|boolean} Value.
  18655. * @template T,S
  18656. */
  18657. ol.geom.flat.segments.forEach =
  18658. function(flatCoordinates, offset, end, stride, callback, opt_this) {
  18659. var point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]];
  18660. var point2 = [];
  18661. var ret;
  18662. for (; (offset + stride) < end; offset += stride) {
  18663. point2[0] = flatCoordinates[offset + stride];
  18664. point2[1] = flatCoordinates[offset + stride + 1];
  18665. ret = callback.call(opt_this, point1, point2);
  18666. if (ret) {
  18667. return ret;
  18668. }
  18669. point1[0] = point2[0];
  18670. point1[1] = point2[1];
  18671. }
  18672. return false;
  18673. };
  18674. goog.provide('ol.geom.flat.intersectsextent');
  18675. goog.require('goog.asserts');
  18676. goog.require('ol.extent');
  18677. goog.require('ol.geom.flat.contains');
  18678. goog.require('ol.geom.flat.segments');
  18679. /**
  18680. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18681. * @param {number} offset Offset.
  18682. * @param {number} end End.
  18683. * @param {number} stride Stride.
  18684. * @param {ol.Extent} extent Extent.
  18685. * @return {boolean} True if the geometry and the extent intersect.
  18686. */
  18687. ol.geom.flat.intersectsextent.lineString =
  18688. function(flatCoordinates, offset, end, stride, extent) {
  18689. var coordinatesExtent = ol.extent.extendFlatCoordinates(
  18690. ol.extent.createEmpty(), flatCoordinates, offset, end, stride);
  18691. if (!ol.extent.intersects(extent, coordinatesExtent)) {
  18692. return false;
  18693. }
  18694. if (ol.extent.containsExtent(extent, coordinatesExtent)) {
  18695. return true;
  18696. }
  18697. if (coordinatesExtent[0] >= extent[0] &&
  18698. coordinatesExtent[2] <= extent[2]) {
  18699. return true;
  18700. }
  18701. if (coordinatesExtent[1] >= extent[1] &&
  18702. coordinatesExtent[3] <= extent[3]) {
  18703. return true;
  18704. }
  18705. return ol.geom.flat.segments.forEach(flatCoordinates, offset, end, stride,
  18706. /**
  18707. * @param {ol.Coordinate} point1 Start point.
  18708. * @param {ol.Coordinate} point2 End point.
  18709. * @return {boolean} `true` if the segment and the extent intersect,
  18710. * `false` otherwise.
  18711. */
  18712. function(point1, point2) {
  18713. return ol.extent.intersectsSegment(extent, point1, point2);
  18714. });
  18715. };
  18716. /**
  18717. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18718. * @param {number} offset Offset.
  18719. * @param {Array.<number>} ends Ends.
  18720. * @param {number} stride Stride.
  18721. * @param {ol.Extent} extent Extent.
  18722. * @return {boolean} True if the geometry and the extent intersect.
  18723. */
  18724. ol.geom.flat.intersectsextent.lineStrings =
  18725. function(flatCoordinates, offset, ends, stride, extent) {
  18726. var i, ii;
  18727. for (i = 0, ii = ends.length; i < ii; ++i) {
  18728. if (ol.geom.flat.intersectsextent.lineString(
  18729. flatCoordinates, offset, ends[i], stride, extent)) {
  18730. return true;
  18731. }
  18732. offset = ends[i];
  18733. }
  18734. return false;
  18735. };
  18736. /**
  18737. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18738. * @param {number} offset Offset.
  18739. * @param {number} end End.
  18740. * @param {number} stride Stride.
  18741. * @param {ol.Extent} extent Extent.
  18742. * @return {boolean} True if the geometry and the extent intersect.
  18743. */
  18744. ol.geom.flat.intersectsextent.linearRing =
  18745. function(flatCoordinates, offset, end, stride, extent) {
  18746. if (ol.geom.flat.intersectsextent.lineString(
  18747. flatCoordinates, offset, end, stride, extent)) {
  18748. return true;
  18749. }
  18750. if (ol.geom.flat.contains.linearRingContainsXY(
  18751. flatCoordinates, offset, end, stride, extent[0], extent[1])) {
  18752. return true;
  18753. }
  18754. if (ol.geom.flat.contains.linearRingContainsXY(
  18755. flatCoordinates, offset, end, stride, extent[0], extent[3])) {
  18756. return true;
  18757. }
  18758. if (ol.geom.flat.contains.linearRingContainsXY(
  18759. flatCoordinates, offset, end, stride, extent[2], extent[1])) {
  18760. return true;
  18761. }
  18762. if (ol.geom.flat.contains.linearRingContainsXY(
  18763. flatCoordinates, offset, end, stride, extent[2], extent[3])) {
  18764. return true;
  18765. }
  18766. return false;
  18767. };
  18768. /**
  18769. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18770. * @param {number} offset Offset.
  18771. * @param {Array.<number>} ends Ends.
  18772. * @param {number} stride Stride.
  18773. * @param {ol.Extent} extent Extent.
  18774. * @return {boolean} True if the geometry and the extent intersect.
  18775. */
  18776. ol.geom.flat.intersectsextent.linearRings =
  18777. function(flatCoordinates, offset, ends, stride, extent) {
  18778. goog.asserts.assert(ends.length > 0, 'ends should not be an empty array');
  18779. if (!ol.geom.flat.intersectsextent.linearRing(
  18780. flatCoordinates, offset, ends[0], stride, extent)) {
  18781. return false;
  18782. }
  18783. if (ends.length === 1) {
  18784. return true;
  18785. }
  18786. var i, ii;
  18787. for (i = 1, ii = ends.length; i < ii; ++i) {
  18788. if (ol.geom.flat.contains.linearRingContainsExtent(
  18789. flatCoordinates, ends[i - 1], ends[i], stride, extent)) {
  18790. return false;
  18791. }
  18792. }
  18793. return true;
  18794. };
  18795. /**
  18796. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18797. * @param {number} offset Offset.
  18798. * @param {Array.<Array.<number>>} endss Endss.
  18799. * @param {number} stride Stride.
  18800. * @param {ol.Extent} extent Extent.
  18801. * @return {boolean} True if the geometry and the extent intersect.
  18802. */
  18803. ol.geom.flat.intersectsextent.linearRingss =
  18804. function(flatCoordinates, offset, endss, stride, extent) {
  18805. goog.asserts.assert(endss.length > 0, 'endss should not be an empty array');
  18806. var i, ii;
  18807. for (i = 0, ii = endss.length; i < ii; ++i) {
  18808. var ends = endss[i];
  18809. if (ol.geom.flat.intersectsextent.linearRings(
  18810. flatCoordinates, offset, ends, stride, extent)) {
  18811. return true;
  18812. }
  18813. offset = ends[ends.length - 1];
  18814. }
  18815. return false;
  18816. };
  18817. goog.provide('ol.geom.flat.reverse');
  18818. /**
  18819. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18820. * @param {number} offset Offset.
  18821. * @param {number} end End.
  18822. * @param {number} stride Stride.
  18823. */
  18824. ol.geom.flat.reverse.coordinates =
  18825. function(flatCoordinates, offset, end, stride) {
  18826. while (offset < end - stride) {
  18827. var i;
  18828. for (i = 0; i < stride; ++i) {
  18829. var tmp = flatCoordinates[offset + i];
  18830. flatCoordinates[offset + i] = flatCoordinates[end - stride + i];
  18831. flatCoordinates[end - stride + i] = tmp;
  18832. }
  18833. offset += stride;
  18834. end -= stride;
  18835. }
  18836. };
  18837. goog.provide('ol.geom.flat.orient');
  18838. goog.require('ol');
  18839. goog.require('ol.geom.flat.reverse');
  18840. /**
  18841. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18842. * @param {number} offset Offset.
  18843. * @param {number} end End.
  18844. * @param {number} stride Stride.
  18845. * @return {boolean} Is clockwise.
  18846. */
  18847. ol.geom.flat.orient.linearRingIsClockwise =
  18848. function(flatCoordinates, offset, end, stride) {
  18849. // http://tinyurl.com/clockwise-method
  18850. // https://github.com/OSGeo/gdal/blob/trunk/gdal/ogr/ogrlinearring.cpp
  18851. var edge = 0;
  18852. var x1 = flatCoordinates[end - stride];
  18853. var y1 = flatCoordinates[end - stride + 1];
  18854. for (; offset < end; offset += stride) {
  18855. var x2 = flatCoordinates[offset];
  18856. var y2 = flatCoordinates[offset + 1];
  18857. edge += (x2 - x1) * (y2 + y1);
  18858. x1 = x2;
  18859. y1 = y2;
  18860. }
  18861. return edge > 0;
  18862. };
  18863. /**
  18864. * Determines if linear rings are oriented. By default, left-hand orientation
  18865. * is tested (first ring must be clockwise, remaining rings counter-clockwise).
  18866. * To test for right-hand orientation, use the `opt_right` argument.
  18867. *
  18868. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18869. * @param {number} offset Offset.
  18870. * @param {Array.<number>} ends Array of end indexes.
  18871. * @param {number} stride Stride.
  18872. * @param {boolean=} opt_right Test for right-hand orientation
  18873. * (counter-clockwise exterior ring and clockwise interior rings).
  18874. * @return {boolean} Rings are correctly oriented.
  18875. */
  18876. ol.geom.flat.orient.linearRingsAreOriented =
  18877. function(flatCoordinates, offset, ends, stride, opt_right) {
  18878. var right = opt_right !== undefined ? opt_right : false;
  18879. var i, ii;
  18880. for (i = 0, ii = ends.length; i < ii; ++i) {
  18881. var end = ends[i];
  18882. var isClockwise = ol.geom.flat.orient.linearRingIsClockwise(
  18883. flatCoordinates, offset, end, stride);
  18884. if (i === 0) {
  18885. if ((right && isClockwise) || (!right && !isClockwise)) {
  18886. return false;
  18887. }
  18888. } else {
  18889. if ((right && !isClockwise) || (!right && isClockwise)) {
  18890. return false;
  18891. }
  18892. }
  18893. offset = end;
  18894. }
  18895. return true;
  18896. };
  18897. /**
  18898. * Determines if linear rings are oriented. By default, left-hand orientation
  18899. * is tested (first ring must be clockwise, remaining rings counter-clockwise).
  18900. * To test for right-hand orientation, use the `opt_right` argument.
  18901. *
  18902. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18903. * @param {number} offset Offset.
  18904. * @param {Array.<Array.<number>>} endss Array of array of end indexes.
  18905. * @param {number} stride Stride.
  18906. * @param {boolean=} opt_right Test for right-hand orientation
  18907. * (counter-clockwise exterior ring and clockwise interior rings).
  18908. * @return {boolean} Rings are correctly oriented.
  18909. */
  18910. ol.geom.flat.orient.linearRingssAreOriented =
  18911. function(flatCoordinates, offset, endss, stride, opt_right) {
  18912. var i, ii;
  18913. for (i = 0, ii = endss.length; i < ii; ++i) {
  18914. if (!ol.geom.flat.orient.linearRingsAreOriented(
  18915. flatCoordinates, offset, endss[i], stride, opt_right)) {
  18916. return false;
  18917. }
  18918. }
  18919. return true;
  18920. };
  18921. /**
  18922. * Orient coordinates in a flat array of linear rings. By default, rings
  18923. * are oriented following the left-hand rule (clockwise for exterior and
  18924. * counter-clockwise for interior rings). To orient according to the
  18925. * right-hand rule, use the `opt_right` argument.
  18926. *
  18927. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18928. * @param {number} offset Offset.
  18929. * @param {Array.<number>} ends Ends.
  18930. * @param {number} stride Stride.
  18931. * @param {boolean=} opt_right Follow the right-hand rule for orientation.
  18932. * @return {number} End.
  18933. */
  18934. ol.geom.flat.orient.orientLinearRings =
  18935. function(flatCoordinates, offset, ends, stride, opt_right) {
  18936. var right = opt_right !== undefined ? opt_right : false;
  18937. var i, ii;
  18938. for (i = 0, ii = ends.length; i < ii; ++i) {
  18939. var end = ends[i];
  18940. var isClockwise = ol.geom.flat.orient.linearRingIsClockwise(
  18941. flatCoordinates, offset, end, stride);
  18942. var reverse = i === 0 ?
  18943. (right && isClockwise) || (!right && !isClockwise) :
  18944. (right && !isClockwise) || (!right && isClockwise);
  18945. if (reverse) {
  18946. ol.geom.flat.reverse.coordinates(flatCoordinates, offset, end, stride);
  18947. }
  18948. offset = end;
  18949. }
  18950. return offset;
  18951. };
  18952. /**
  18953. * Orient coordinates in a flat array of linear rings. By default, rings
  18954. * are oriented following the left-hand rule (clockwise for exterior and
  18955. * counter-clockwise for interior rings). To orient according to the
  18956. * right-hand rule, use the `opt_right` argument.
  18957. *
  18958. * @param {Array.<number>} flatCoordinates Flat coordinates.
  18959. * @param {number} offset Offset.
  18960. * @param {Array.<Array.<number>>} endss Array of array of end indexes.
  18961. * @param {number} stride Stride.
  18962. * @param {boolean=} opt_right Follow the right-hand rule for orientation.
  18963. * @return {number} End.
  18964. */
  18965. ol.geom.flat.orient.orientLinearRingss =
  18966. function(flatCoordinates, offset, endss, stride, opt_right) {
  18967. var i, ii;
  18968. for (i = 0, ii = endss.length; i < ii; ++i) {
  18969. offset = ol.geom.flat.orient.orientLinearRings(
  18970. flatCoordinates, offset, endss[i], stride, opt_right);
  18971. }
  18972. return offset;
  18973. };
  18974. goog.provide('ol.geom.Polygon');
  18975. goog.require('goog.array');
  18976. goog.require('goog.asserts');
  18977. goog.require('goog.math');
  18978. goog.require('ol');
  18979. goog.require('ol.extent');
  18980. goog.require('ol.geom.GeometryLayout');
  18981. goog.require('ol.geom.GeometryType');
  18982. goog.require('ol.geom.LinearRing');
  18983. goog.require('ol.geom.Point');
  18984. goog.require('ol.geom.SimpleGeometry');
  18985. goog.require('ol.geom.flat.area');
  18986. goog.require('ol.geom.flat.closest');
  18987. goog.require('ol.geom.flat.contains');
  18988. goog.require('ol.geom.flat.deflate');
  18989. goog.require('ol.geom.flat.inflate');
  18990. goog.require('ol.geom.flat.interiorpoint');
  18991. goog.require('ol.geom.flat.intersectsextent');
  18992. goog.require('ol.geom.flat.orient');
  18993. goog.require('ol.geom.flat.simplify');
  18994. /**
  18995. * @classdesc
  18996. * Polygon geometry.
  18997. *
  18998. * @constructor
  18999. * @extends {ol.geom.SimpleGeometry}
  19000. * @param {Array.<Array.<ol.Coordinate>>} coordinates Coordinates.
  19001. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  19002. * @api stable
  19003. */
  19004. ol.geom.Polygon = function(coordinates, opt_layout) {
  19005. goog.base(this);
  19006. /**
  19007. * @type {Array.<number>}
  19008. * @private
  19009. */
  19010. this.ends_ = [];
  19011. /**
  19012. * @private
  19013. * @type {number}
  19014. */
  19015. this.flatInteriorPointRevision_ = -1;
  19016. /**
  19017. * @private
  19018. * @type {ol.Coordinate}
  19019. */
  19020. this.flatInteriorPoint_ = null;
  19021. /**
  19022. * @private
  19023. * @type {number}
  19024. */
  19025. this.maxDelta_ = -1;
  19026. /**
  19027. * @private
  19028. * @type {number}
  19029. */
  19030. this.maxDeltaRevision_ = -1;
  19031. /**
  19032. * @private
  19033. * @type {number}
  19034. */
  19035. this.orientedRevision_ = -1;
  19036. /**
  19037. * @private
  19038. * @type {Array.<number>}
  19039. */
  19040. this.orientedFlatCoordinates_ = null;
  19041. this.setCoordinates(coordinates, opt_layout);
  19042. };
  19043. goog.inherits(ol.geom.Polygon, ol.geom.SimpleGeometry);
  19044. /**
  19045. * Append the passed linear ring to this polygon.
  19046. * @param {ol.geom.LinearRing} linearRing Linear ring.
  19047. * @api stable
  19048. */
  19049. ol.geom.Polygon.prototype.appendLinearRing = function(linearRing) {
  19050. goog.asserts.assert(linearRing.getLayout() == this.layout,
  19051. 'layout of linearRing should match layout');
  19052. if (!this.flatCoordinates) {
  19053. this.flatCoordinates = linearRing.getFlatCoordinates().slice();
  19054. } else {
  19055. goog.array.extend(this.flatCoordinates, linearRing.getFlatCoordinates());
  19056. }
  19057. this.ends_.push(this.flatCoordinates.length);
  19058. this.changed();
  19059. };
  19060. /**
  19061. * Make a complete copy of the geometry.
  19062. * @return {!ol.geom.Polygon} Clone.
  19063. * @api stable
  19064. */
  19065. ol.geom.Polygon.prototype.clone = function() {
  19066. var polygon = new ol.geom.Polygon(null);
  19067. polygon.setFlatCoordinates(
  19068. this.layout, this.flatCoordinates.slice(), this.ends_.slice());
  19069. return polygon;
  19070. };
  19071. /**
  19072. * @inheritDoc
  19073. */
  19074. ol.geom.Polygon.prototype.closestPointXY =
  19075. function(x, y, closestPoint, minSquaredDistance) {
  19076. if (minSquaredDistance <
  19077. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  19078. return minSquaredDistance;
  19079. }
  19080. if (this.maxDeltaRevision_ != this.getRevision()) {
  19081. this.maxDelta_ = Math.sqrt(ol.geom.flat.closest.getsMaxSquaredDelta(
  19082. this.flatCoordinates, 0, this.ends_, this.stride, 0));
  19083. this.maxDeltaRevision_ = this.getRevision();
  19084. }
  19085. return ol.geom.flat.closest.getsClosestPoint(
  19086. this.flatCoordinates, 0, this.ends_, this.stride,
  19087. this.maxDelta_, true, x, y, closestPoint, minSquaredDistance);
  19088. };
  19089. /**
  19090. * @inheritDoc
  19091. */
  19092. ol.geom.Polygon.prototype.containsXY = function(x, y) {
  19093. return ol.geom.flat.contains.linearRingsContainsXY(
  19094. this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, x, y);
  19095. };
  19096. /**
  19097. * Return the area of the polygon on projected plane.
  19098. * @return {number} Area (on projected plane).
  19099. * @api stable
  19100. */
  19101. ol.geom.Polygon.prototype.getArea = function() {
  19102. return ol.geom.flat.area.linearRings(
  19103. this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride);
  19104. };
  19105. /**
  19106. * Get the coordinate array for this geometry. This array has the structure
  19107. * of a GeoJSON coordinate array for polygons.
  19108. *
  19109. * @param {boolean=} opt_right Orient coordinates according to the right-hand
  19110. * rule (counter-clockwise for exterior and clockwise for interior rings).
  19111. * If `false`, coordinates will be oriented according to the left-hand rule
  19112. * (clockwise for exterior and counter-clockwise for interior rings).
  19113. * By default, coordinate orientation will depend on how the geometry was
  19114. * constructed.
  19115. * @return {Array.<Array.<ol.Coordinate>>} Coordinates.
  19116. * @api stable
  19117. */
  19118. ol.geom.Polygon.prototype.getCoordinates = function(opt_right) {
  19119. var flatCoordinates;
  19120. if (opt_right !== undefined) {
  19121. flatCoordinates = this.getOrientedFlatCoordinates().slice();
  19122. ol.geom.flat.orient.orientLinearRings(
  19123. flatCoordinates, 0, this.ends_, this.stride, opt_right);
  19124. } else {
  19125. flatCoordinates = this.flatCoordinates;
  19126. }
  19127. return ol.geom.flat.inflate.coordinatess(
  19128. flatCoordinates, 0, this.ends_, this.stride);
  19129. };
  19130. /**
  19131. * @return {Array.<number>} Ends.
  19132. */
  19133. ol.geom.Polygon.prototype.getEnds = function() {
  19134. return this.ends_;
  19135. };
  19136. /**
  19137. * @return {Array.<number>} Interior point.
  19138. */
  19139. ol.geom.Polygon.prototype.getFlatInteriorPoint = function() {
  19140. if (this.flatInteriorPointRevision_ != this.getRevision()) {
  19141. var flatCenter = ol.extent.getCenter(this.getExtent());
  19142. this.flatInteriorPoint_ = ol.geom.flat.interiorpoint.linearRings(
  19143. this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride,
  19144. flatCenter, 0);
  19145. this.flatInteriorPointRevision_ = this.getRevision();
  19146. }
  19147. return this.flatInteriorPoint_;
  19148. };
  19149. /**
  19150. * Return an interior point of the polygon.
  19151. * @return {ol.geom.Point} Interior point.
  19152. * @api stable
  19153. */
  19154. ol.geom.Polygon.prototype.getInteriorPoint = function() {
  19155. return new ol.geom.Point(this.getFlatInteriorPoint());
  19156. };
  19157. /**
  19158. * Return the number of rings of the polygon, this includes the exterior
  19159. * ring and any interior rings.
  19160. *
  19161. * @return {number} Number of rings.
  19162. * @api
  19163. */
  19164. ol.geom.Polygon.prototype.getLinearRingCount = function() {
  19165. return this.ends_.length;
  19166. };
  19167. /**
  19168. * Return the Nth linear ring of the polygon geometry. Return `null` if the
  19169. * given index is out of range.
  19170. * The exterior linear ring is available at index `0` and the interior rings
  19171. * at index `1` and beyond.
  19172. *
  19173. * @param {number} index Index.
  19174. * @return {ol.geom.LinearRing} Linear ring.
  19175. * @api stable
  19176. */
  19177. ol.geom.Polygon.prototype.getLinearRing = function(index) {
  19178. goog.asserts.assert(0 <= index && index < this.ends_.length,
  19179. 'index should be in between 0 and and length of this.ends_');
  19180. if (index < 0 || this.ends_.length <= index) {
  19181. return null;
  19182. }
  19183. var linearRing = new ol.geom.LinearRing(null);
  19184. linearRing.setFlatCoordinates(this.layout, this.flatCoordinates.slice(
  19185. index === 0 ? 0 : this.ends_[index - 1], this.ends_[index]));
  19186. return linearRing;
  19187. };
  19188. /**
  19189. * Return the linear rings of the polygon.
  19190. * @return {Array.<ol.geom.LinearRing>} Linear rings.
  19191. * @api stable
  19192. */
  19193. ol.geom.Polygon.prototype.getLinearRings = function() {
  19194. var layout = this.layout;
  19195. var flatCoordinates = this.flatCoordinates;
  19196. var ends = this.ends_;
  19197. var linearRings = [];
  19198. var offset = 0;
  19199. var i, ii;
  19200. for (i = 0, ii = ends.length; i < ii; ++i) {
  19201. var end = ends[i];
  19202. var linearRing = new ol.geom.LinearRing(null);
  19203. linearRing.setFlatCoordinates(layout, flatCoordinates.slice(offset, end));
  19204. linearRings.push(linearRing);
  19205. offset = end;
  19206. }
  19207. return linearRings;
  19208. };
  19209. /**
  19210. * @return {Array.<number>} Oriented flat coordinates.
  19211. */
  19212. ol.geom.Polygon.prototype.getOrientedFlatCoordinates = function() {
  19213. if (this.orientedRevision_ != this.getRevision()) {
  19214. var flatCoordinates = this.flatCoordinates;
  19215. if (ol.geom.flat.orient.linearRingsAreOriented(
  19216. flatCoordinates, 0, this.ends_, this.stride)) {
  19217. this.orientedFlatCoordinates_ = flatCoordinates;
  19218. } else {
  19219. this.orientedFlatCoordinates_ = flatCoordinates.slice();
  19220. this.orientedFlatCoordinates_.length =
  19221. ol.geom.flat.orient.orientLinearRings(
  19222. this.orientedFlatCoordinates_, 0, this.ends_, this.stride);
  19223. }
  19224. this.orientedRevision_ = this.getRevision();
  19225. }
  19226. return this.orientedFlatCoordinates_;
  19227. };
  19228. /**
  19229. * @inheritDoc
  19230. */
  19231. ol.geom.Polygon.prototype.getSimplifiedGeometryInternal =
  19232. function(squaredTolerance) {
  19233. var simplifiedFlatCoordinates = [];
  19234. var simplifiedEnds = [];
  19235. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.quantizes(
  19236. this.flatCoordinates, 0, this.ends_, this.stride,
  19237. Math.sqrt(squaredTolerance),
  19238. simplifiedFlatCoordinates, 0, simplifiedEnds);
  19239. var simplifiedPolygon = new ol.geom.Polygon(null);
  19240. simplifiedPolygon.setFlatCoordinates(
  19241. ol.geom.GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds);
  19242. return simplifiedPolygon;
  19243. };
  19244. /**
  19245. * @inheritDoc
  19246. * @api stable
  19247. */
  19248. ol.geom.Polygon.prototype.getType = function() {
  19249. return ol.geom.GeometryType.POLYGON;
  19250. };
  19251. /**
  19252. * @inheritDoc
  19253. * @api stable
  19254. */
  19255. ol.geom.Polygon.prototype.intersectsExtent = function(extent) {
  19256. return ol.geom.flat.intersectsextent.linearRings(
  19257. this.getOrientedFlatCoordinates(), 0, this.ends_, this.stride, extent);
  19258. };
  19259. /**
  19260. * Set the coordinates of the polygon.
  19261. * @param {Array.<Array.<ol.Coordinate>>} coordinates Coordinates.
  19262. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  19263. * @api stable
  19264. */
  19265. ol.geom.Polygon.prototype.setCoordinates = function(coordinates, opt_layout) {
  19266. if (!coordinates) {
  19267. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null, this.ends_);
  19268. } else {
  19269. this.setLayout(opt_layout, coordinates, 2);
  19270. if (!this.flatCoordinates) {
  19271. this.flatCoordinates = [];
  19272. }
  19273. var ends = ol.geom.flat.deflate.coordinatess(
  19274. this.flatCoordinates, 0, coordinates, this.stride, this.ends_);
  19275. this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];
  19276. this.changed();
  19277. }
  19278. };
  19279. /**
  19280. * @param {ol.geom.GeometryLayout} layout Layout.
  19281. * @param {Array.<number>} flatCoordinates Flat coordinates.
  19282. * @param {Array.<number>} ends Ends.
  19283. */
  19284. ol.geom.Polygon.prototype.setFlatCoordinates =
  19285. function(layout, flatCoordinates, ends) {
  19286. if (!flatCoordinates) {
  19287. goog.asserts.assert(ends && ends.length === 0,
  19288. 'ends must be an empty array');
  19289. } else if (ends.length === 0) {
  19290. goog.asserts.assert(flatCoordinates.length === 0,
  19291. 'flatCoordinates should be an empty array');
  19292. } else {
  19293. goog.asserts.assert(flatCoordinates.length == ends[ends.length - 1],
  19294. 'the length of flatCoordinates should be the last entry of ends');
  19295. }
  19296. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  19297. this.ends_ = ends;
  19298. this.changed();
  19299. };
  19300. /**
  19301. * Create an approximation of a circle on the surface of a sphere.
  19302. * @param {ol.Sphere} sphere The sphere.
  19303. * @param {ol.Coordinate} center Center (`[lon, lat]` in degrees).
  19304. * @param {number} radius The great-circle distance from the center to
  19305. * the polygon vertices.
  19306. * @param {number=} opt_n Optional number of vertices for the resulting
  19307. * polygon. Default is `32`.
  19308. * @return {ol.geom.Polygon} The "circular" polygon.
  19309. * @api stable
  19310. */
  19311. ol.geom.Polygon.circular = function(sphere, center, radius, opt_n) {
  19312. var n = opt_n ? opt_n : 32;
  19313. /** @type {Array.<number>} */
  19314. var flatCoordinates = [];
  19315. var i;
  19316. for (i = 0; i < n; ++i) {
  19317. goog.array.extend(
  19318. flatCoordinates, sphere.offset(center, radius, 2 * Math.PI * i / n));
  19319. }
  19320. flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);
  19321. var polygon = new ol.geom.Polygon(null);
  19322. polygon.setFlatCoordinates(
  19323. ol.geom.GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]);
  19324. return polygon;
  19325. };
  19326. /**
  19327. * Create a polygon from an extent. The layout used is `XY`.
  19328. * @param {ol.Extent} extent The extent.
  19329. * @return {ol.geom.Polygon} The polygon.
  19330. * @api
  19331. */
  19332. ol.geom.Polygon.fromExtent = function(extent) {
  19333. var minX = extent[0];
  19334. var minY = extent[1];
  19335. var maxX = extent[2];
  19336. var maxY = extent[3];
  19337. var flatCoordinates =
  19338. [minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY];
  19339. var polygon = new ol.geom.Polygon(null);
  19340. polygon.setFlatCoordinates(
  19341. ol.geom.GeometryLayout.XY, flatCoordinates, [flatCoordinates.length]);
  19342. return polygon;
  19343. };
  19344. /**
  19345. * Create a regular polygon from a circle.
  19346. * @param {ol.geom.Circle} circle Circle geometry.
  19347. * @param {number=} opt_sides Number of sides of the polygon. Default is 32.
  19348. * @param {number=} opt_angle Start angle for the first vertex of the polygon in
  19349. * radians. Default is 0.
  19350. * @return {ol.geom.Polygon} Polygon geometry.
  19351. * @api
  19352. */
  19353. ol.geom.Polygon.fromCircle = function(circle, opt_sides, opt_angle) {
  19354. var sides = opt_sides ? opt_sides : 32;
  19355. var stride = circle.getStride();
  19356. var layout = circle.getLayout();
  19357. var polygon = new ol.geom.Polygon(null, layout);
  19358. var flatCoordinates = goog.array.repeat(0, stride * (sides + 1));
  19359. var ends = [flatCoordinates.length];
  19360. polygon.setFlatCoordinates(layout, flatCoordinates, ends);
  19361. ol.geom.Polygon.makeRegular(
  19362. polygon, circle.getCenter(), circle.getRadius(), opt_angle);
  19363. return polygon;
  19364. };
  19365. /**
  19366. * Modify the coordinates of a polygon to make it a regular polygon.
  19367. * @param {ol.geom.Polygon} polygon Polygon geometry.
  19368. * @param {ol.Coordinate} center Center of the regular polygon.
  19369. * @param {number} radius Radius of the regular polygon.
  19370. * @param {number=} opt_angle Start angle for the first vertex of the polygon in
  19371. * radians. Default is 0.
  19372. */
  19373. ol.geom.Polygon.makeRegular = function(polygon, center, radius, opt_angle) {
  19374. var flatCoordinates = polygon.getFlatCoordinates();
  19375. var layout = polygon.getLayout();
  19376. var stride = polygon.getStride();
  19377. var ends = polygon.getEnds();
  19378. goog.asserts.assert(ends.length === 1, 'only 1 ring is supported');
  19379. var sides = flatCoordinates.length / stride - 1;
  19380. var startAngle = opt_angle ? opt_angle : 0;
  19381. var angle, offset;
  19382. for (var i = 0; i <= sides; ++i) {
  19383. offset = i * stride;
  19384. angle = startAngle + (goog.math.modulo(i, sides) * 2 * Math.PI / sides);
  19385. flatCoordinates[offset] = center[0] + (radius * Math.cos(angle));
  19386. flatCoordinates[offset + 1] = center[1] + (radius * Math.sin(angle));
  19387. }
  19388. polygon.setFlatCoordinates(layout, flatCoordinates, ends);
  19389. };
  19390. goog.provide('ol.View');
  19391. goog.provide('ol.ViewHint');
  19392. goog.provide('ol.ViewProperty');
  19393. goog.require('goog.asserts');
  19394. goog.require('ol');
  19395. goog.require('ol.CenterConstraint');
  19396. goog.require('ol.Constraints');
  19397. goog.require('ol.Object');
  19398. goog.require('ol.ResolutionConstraint');
  19399. goog.require('ol.RotationConstraint');
  19400. goog.require('ol.RotationConstraintType');
  19401. goog.require('ol.Size');
  19402. goog.require('ol.coordinate');
  19403. goog.require('ol.extent');
  19404. goog.require('ol.geom.Polygon');
  19405. goog.require('ol.geom.SimpleGeometry');
  19406. goog.require('ol.proj');
  19407. goog.require('ol.proj.METERS_PER_UNIT');
  19408. goog.require('ol.proj.Projection');
  19409. goog.require('ol.proj.Units');
  19410. /**
  19411. * @enum {string}
  19412. */
  19413. ol.ViewProperty = {
  19414. CENTER: 'center',
  19415. RESOLUTION: 'resolution',
  19416. ROTATION: 'rotation'
  19417. };
  19418. /**
  19419. * @enum {number}
  19420. */
  19421. ol.ViewHint = {
  19422. ANIMATING: 0,
  19423. INTERACTING: 1
  19424. };
  19425. /**
  19426. * @classdesc
  19427. * An ol.View object represents a simple 2D view of the map.
  19428. *
  19429. * This is the object to act upon to change the center, resolution,
  19430. * and rotation of the map.
  19431. *
  19432. * ### The view states
  19433. *
  19434. * An `ol.View` is determined by three states: `center`, `resolution`,
  19435. * and `rotation`. Each state has a corresponding getter and setter, e.g.
  19436. * `getCenter` and `setCenter` for the `center` state.
  19437. *
  19438. * An `ol.View` has a `projection`. The projection determines the
  19439. * coordinate system of the center, and its units determine the units of the
  19440. * resolution (projection units per pixel). The default projection is
  19441. * Spherical Mercator (EPSG:3857).
  19442. *
  19443. * ### The constraints
  19444. *
  19445. * `setCenter`, `setResolution` and `setRotation` can be used to change the
  19446. * states of the view. Any value can be passed to the setters. And the value
  19447. * that is passed to a setter will effectively be the value set in the view,
  19448. * and returned by the corresponding getter.
  19449. *
  19450. * But an `ol.View` object also has a *resolution constraint*, a
  19451. * *rotation constraint* and a *center constraint*.
  19452. *
  19453. * As said above, no constraints are applied when the setters are used to set
  19454. * new states for the view. Applying constraints is done explicitly through
  19455. * the use of the `constrain*` functions (`constrainResolution` and
  19456. * `constrainRotation` and `constrainCenter`).
  19457. *
  19458. * The main users of the constraints are the interactions and the
  19459. * controls. For example, double-clicking on the map changes the view to
  19460. * the "next" resolution. And releasing the fingers after pinch-zooming
  19461. * snaps to the closest resolution (with an animation).
  19462. *
  19463. * The *resolution constraint* snaps to specific resolutions. It is
  19464. * determined by the following options: `resolutions`, `maxResolution`,
  19465. * `maxZoom`, and `zoomFactor`. If `resolutions` is set, the other three
  19466. * options are ignored. See documentation for each option for more
  19467. * information.
  19468. *
  19469. * The *rotation constraint* snaps to specific angles. It is determined
  19470. * by the following options: `enableRotation` and `constrainRotation`.
  19471. * By default the rotation value is snapped to zero when approaching the
  19472. * horizontal.
  19473. *
  19474. * The *center constraint* is determined by the `extent` option. By
  19475. * default the center is not constrained at all.
  19476. *
  19477. * @constructor
  19478. * @extends {ol.Object}
  19479. * @param {olx.ViewOptions=} opt_options View options.
  19480. * @api stable
  19481. */
  19482. ol.View = function(opt_options) {
  19483. goog.base(this);
  19484. var options = opt_options || {};
  19485. /**
  19486. * @private
  19487. * @type {Array.<number>}
  19488. */
  19489. this.hints_ = [0, 0];
  19490. /**
  19491. * @type {Object.<string, *>}
  19492. */
  19493. var properties = {};
  19494. properties[ol.ViewProperty.CENTER] = options.center !== undefined ?
  19495. options.center : null;
  19496. /**
  19497. * @private
  19498. * @const
  19499. * @type {ol.proj.Projection}
  19500. */
  19501. this.projection_ = ol.proj.createProjection(options.projection, 'EPSG:3857');
  19502. var resolutionConstraintInfo = ol.View.createResolutionConstraint_(
  19503. options);
  19504. /**
  19505. * @private
  19506. * @type {number}
  19507. */
  19508. this.maxResolution_ = resolutionConstraintInfo.maxResolution;
  19509. /**
  19510. * @private
  19511. * @type {number}
  19512. */
  19513. this.minResolution_ = resolutionConstraintInfo.minResolution;
  19514. /**
  19515. * @private
  19516. * @type {number}
  19517. */
  19518. this.minZoom_ = resolutionConstraintInfo.minZoom;
  19519. var centerConstraint = ol.View.createCenterConstraint_(options);
  19520. var resolutionConstraint = resolutionConstraintInfo.constraint;
  19521. var rotationConstraint = ol.View.createRotationConstraint_(options);
  19522. /**
  19523. * @private
  19524. * @type {ol.Constraints}
  19525. */
  19526. this.constraints_ = new ol.Constraints(
  19527. centerConstraint, resolutionConstraint, rotationConstraint);
  19528. if (options.resolution !== undefined) {
  19529. properties[ol.ViewProperty.RESOLUTION] = options.resolution;
  19530. } else if (options.zoom !== undefined) {
  19531. properties[ol.ViewProperty.RESOLUTION] = this.constrainResolution(
  19532. this.maxResolution_, options.zoom - this.minZoom_);
  19533. }
  19534. properties[ol.ViewProperty.ROTATION] =
  19535. options.rotation !== undefined ? options.rotation : 0;
  19536. this.setProperties(properties);
  19537. };
  19538. goog.inherits(ol.View, ol.Object);
  19539. /**
  19540. * @param {number} rotation Target rotation.
  19541. * @param {ol.Coordinate} anchor Rotation anchor.
  19542. * @return {ol.Coordinate|undefined} Center for rotation and anchor.
  19543. */
  19544. ol.View.prototype.calculateCenterRotate = function(rotation, anchor) {
  19545. var center;
  19546. var currentCenter = this.getCenter();
  19547. if (currentCenter !== undefined) {
  19548. center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]];
  19549. ol.coordinate.rotate(center, rotation - this.getRotation());
  19550. ol.coordinate.add(center, anchor);
  19551. }
  19552. return center;
  19553. };
  19554. /**
  19555. * @param {number} resolution Target resolution.
  19556. * @param {ol.Coordinate} anchor Zoom anchor.
  19557. * @return {ol.Coordinate|undefined} Center for resolution and anchor.
  19558. */
  19559. ol.View.prototype.calculateCenterZoom = function(resolution, anchor) {
  19560. var center;
  19561. var currentCenter = this.getCenter();
  19562. var currentResolution = this.getResolution();
  19563. if (currentCenter !== undefined && currentResolution !== undefined) {
  19564. var x = anchor[0] -
  19565. resolution * (anchor[0] - currentCenter[0]) / currentResolution;
  19566. var y = anchor[1] -
  19567. resolution * (anchor[1] - currentCenter[1]) / currentResolution;
  19568. center = [x, y];
  19569. }
  19570. return center;
  19571. };
  19572. /**
  19573. * Get the constrained center of this view.
  19574. * @param {ol.Coordinate|undefined} center Center.
  19575. * @return {ol.Coordinate|undefined} Constrained center.
  19576. * @api
  19577. */
  19578. ol.View.prototype.constrainCenter = function(center) {
  19579. return this.constraints_.center(center);
  19580. };
  19581. /**
  19582. * Get the constrained resolution of this view.
  19583. * @param {number|undefined} resolution Resolution.
  19584. * @param {number=} opt_delta Delta. Default is `0`.
  19585. * @param {number=} opt_direction Direction. Default is `0`.
  19586. * @return {number|undefined} Constrained resolution.
  19587. * @api
  19588. */
  19589. ol.View.prototype.constrainResolution = function(
  19590. resolution, opt_delta, opt_direction) {
  19591. var delta = opt_delta || 0;
  19592. var direction = opt_direction || 0;
  19593. return this.constraints_.resolution(resolution, delta, direction);
  19594. };
  19595. /**
  19596. * Get the constrained rotation of this view.
  19597. * @param {number|undefined} rotation Rotation.
  19598. * @param {number=} opt_delta Delta. Default is `0`.
  19599. * @return {number|undefined} Constrained rotation.
  19600. * @api
  19601. */
  19602. ol.View.prototype.constrainRotation = function(rotation, opt_delta) {
  19603. var delta = opt_delta || 0;
  19604. return this.constraints_.rotation(rotation, delta);
  19605. };
  19606. /**
  19607. * Get the view center.
  19608. * @return {ol.Coordinate|undefined} The center of the view.
  19609. * @observable
  19610. * @api stable
  19611. */
  19612. ol.View.prototype.getCenter = function() {
  19613. return /** @type {ol.Coordinate|undefined} */ (
  19614. this.get(ol.ViewProperty.CENTER));
  19615. };
  19616. /**
  19617. * @return {Array.<number>} Hint.
  19618. */
  19619. ol.View.prototype.getHints = function() {
  19620. return this.hints_.slice();
  19621. };
  19622. /**
  19623. * Calculate the extent for the current view state and the passed size.
  19624. * The size is the pixel dimensions of the box into which the calculated extent
  19625. * should fit. In most cases you want to get the extent of the entire map,
  19626. * that is `map.getSize()`.
  19627. * @param {ol.Size} size Box pixel size.
  19628. * @return {ol.Extent} Extent.
  19629. * @api stable
  19630. */
  19631. ol.View.prototype.calculateExtent = function(size) {
  19632. var center = this.getCenter();
  19633. goog.asserts.assert(center, 'The view center is not defined');
  19634. var resolution = this.getResolution();
  19635. goog.asserts.assert(resolution !== undefined,
  19636. 'The view resolution is not defined');
  19637. var rotation = this.getRotation();
  19638. goog.asserts.assert(rotation !== undefined,
  19639. 'The view rotation is not defined');
  19640. return ol.extent.getForViewAndSize(center, resolution, rotation, size);
  19641. };
  19642. /**
  19643. * Get the view projection.
  19644. * @return {ol.proj.Projection} The projection of the view.
  19645. * @api stable
  19646. */
  19647. ol.View.prototype.getProjection = function() {
  19648. return this.projection_;
  19649. };
  19650. /**
  19651. * Get the view resolution.
  19652. * @return {number|undefined} The resolution of the view.
  19653. * @observable
  19654. * @api stable
  19655. */
  19656. ol.View.prototype.getResolution = function() {
  19657. return /** @type {number|undefined} */ (
  19658. this.get(ol.ViewProperty.RESOLUTION));
  19659. };
  19660. /**
  19661. * Get the resolution for a provided extent (in map units) and size (in pixels).
  19662. * @param {ol.Extent} extent Extent.
  19663. * @param {ol.Size} size Box pixel size.
  19664. * @return {number} The resolution at which the provided extent will render at
  19665. * the given size.
  19666. */
  19667. ol.View.prototype.getResolutionForExtent = function(extent, size) {
  19668. var xResolution = ol.extent.getWidth(extent) / size[0];
  19669. var yResolution = ol.extent.getHeight(extent) / size[1];
  19670. return Math.max(xResolution, yResolution);
  19671. };
  19672. /**
  19673. * Return a function that returns a value between 0 and 1 for a
  19674. * resolution. Exponential scaling is assumed.
  19675. * @param {number=} opt_power Power.
  19676. * @return {function(number): number} Resolution for value function.
  19677. */
  19678. ol.View.prototype.getResolutionForValueFunction = function(opt_power) {
  19679. var power = opt_power || 2;
  19680. var maxResolution = this.maxResolution_;
  19681. var minResolution = this.minResolution_;
  19682. var max = Math.log(maxResolution / minResolution) / Math.log(power);
  19683. return (
  19684. /**
  19685. * @param {number} value Value.
  19686. * @return {number} Resolution.
  19687. */
  19688. function(value) {
  19689. var resolution = maxResolution / Math.pow(power, value * max);
  19690. goog.asserts.assert(resolution >= minResolution &&
  19691. resolution <= maxResolution,
  19692. 'calculated resolution outside allowed bounds (%s <= %s <= %s)',
  19693. minResolution, resolution, maxResolution);
  19694. return resolution;
  19695. });
  19696. };
  19697. /**
  19698. * Get the view rotation.
  19699. * @return {number} The rotation of the view in radians.
  19700. * @observable
  19701. * @api stable
  19702. */
  19703. ol.View.prototype.getRotation = function() {
  19704. return /** @type {number} */ (this.get(ol.ViewProperty.ROTATION));
  19705. };
  19706. /**
  19707. * Return a function that returns a resolution for a value between
  19708. * 0 and 1. Exponential scaling is assumed.
  19709. * @param {number=} opt_power Power.
  19710. * @return {function(number): number} Value for resolution function.
  19711. */
  19712. ol.View.prototype.getValueForResolutionFunction = function(opt_power) {
  19713. var power = opt_power || 2;
  19714. var maxResolution = this.maxResolution_;
  19715. var minResolution = this.minResolution_;
  19716. var max = Math.log(maxResolution / minResolution) / Math.log(power);
  19717. return (
  19718. /**
  19719. * @param {number} resolution Resolution.
  19720. * @return {number} Value.
  19721. */
  19722. function(resolution) {
  19723. var value =
  19724. (Math.log(maxResolution / resolution) / Math.log(power)) / max;
  19725. goog.asserts.assert(value >= 0 && value <= 1,
  19726. 'calculated value (%s) ouside allowed range (0-1)', value);
  19727. return value;
  19728. });
  19729. };
  19730. /**
  19731. * @return {olx.ViewState} View state.
  19732. */
  19733. ol.View.prototype.getState = function() {
  19734. goog.asserts.assert(this.isDef(),
  19735. 'the view was not defined (had no center and/or resolution)');
  19736. var center = /** @type {ol.Coordinate} */ (this.getCenter());
  19737. var projection = this.getProjection();
  19738. var resolution = /** @type {number} */ (this.getResolution());
  19739. var rotation = this.getRotation();
  19740. return /** @type {olx.ViewState} */ ({
  19741. // Snap center to closest pixel
  19742. center: [
  19743. Math.round(center[0] / resolution) * resolution,
  19744. Math.round(center[1] / resolution) * resolution
  19745. ],
  19746. projection: projection !== undefined ? projection : null,
  19747. resolution: resolution,
  19748. rotation: rotation
  19749. });
  19750. };
  19751. /**
  19752. * Get the current zoom level. Return undefined if the current
  19753. * resolution is undefined or not a "constrained resolution".
  19754. * @return {number|undefined} Zoom.
  19755. * @api stable
  19756. */
  19757. ol.View.prototype.getZoom = function() {
  19758. var offset;
  19759. var resolution = this.getResolution();
  19760. if (resolution !== undefined) {
  19761. var res, z = 0;
  19762. do {
  19763. res = this.constrainResolution(this.maxResolution_, z);
  19764. if (res == resolution) {
  19765. offset = z;
  19766. break;
  19767. }
  19768. ++z;
  19769. } while (res > this.minResolution_);
  19770. }
  19771. return offset !== undefined ? this.minZoom_ + offset : offset;
  19772. };
  19773. /**
  19774. * Fit the given geometry or extent based on the given map size and border.
  19775. * The size is pixel dimensions of the box to fit the extent into.
  19776. * In most cases you will want to use the map size, that is `map.getSize()`.
  19777. * Takes care of the map angle.
  19778. * @param {ol.geom.SimpleGeometry|ol.Extent} geometry Geometry.
  19779. * @param {ol.Size} size Box pixel size.
  19780. * @param {olx.view.FitOptions=} opt_options Options.
  19781. * @api
  19782. */
  19783. ol.View.prototype.fit = function(geometry, size, opt_options) {
  19784. if (!(geometry instanceof ol.geom.SimpleGeometry)) {
  19785. goog.asserts.assert(goog.isArray(geometry),
  19786. 'invalid extent or geometry');
  19787. goog.asserts.assert(!ol.extent.isEmpty(geometry),
  19788. 'cannot fit empty extent');
  19789. geometry = ol.geom.Polygon.fromExtent(geometry);
  19790. }
  19791. var options = opt_options || {};
  19792. var padding = options.padding !== undefined ? options.padding : [0, 0, 0, 0];
  19793. var constrainResolution = options.constrainResolution !== undefined ?
  19794. options.constrainResolution : true;
  19795. var nearest = options.nearest !== undefined ? options.nearest : false;
  19796. var minResolution;
  19797. if (options.minResolution !== undefined) {
  19798. minResolution = options.minResolution;
  19799. } else if (options.maxZoom !== undefined) {
  19800. minResolution = this.constrainResolution(
  19801. this.maxResolution_, options.maxZoom - this.minZoom_, 0);
  19802. } else {
  19803. minResolution = 0;
  19804. }
  19805. var coords = geometry.getFlatCoordinates();
  19806. // calculate rotated extent
  19807. var rotation = this.getRotation();
  19808. goog.asserts.assert(rotation !== undefined, 'rotation was not defined');
  19809. var cosAngle = Math.cos(-rotation);
  19810. var sinAngle = Math.sin(-rotation);
  19811. var minRotX = +Infinity;
  19812. var minRotY = +Infinity;
  19813. var maxRotX = -Infinity;
  19814. var maxRotY = -Infinity;
  19815. var stride = geometry.getStride();
  19816. for (var i = 0, ii = coords.length; i < ii; i += stride) {
  19817. var rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle;
  19818. var rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle;
  19819. minRotX = Math.min(minRotX, rotX);
  19820. minRotY = Math.min(minRotY, rotY);
  19821. maxRotX = Math.max(maxRotX, rotX);
  19822. maxRotY = Math.max(maxRotY, rotY);
  19823. }
  19824. // calculate resolution
  19825. var resolution = this.getResolutionForExtent(
  19826. [minRotX, minRotY, maxRotX, maxRotY],
  19827. [size[0] - padding[1] - padding[3], size[1] - padding[0] - padding[2]]);
  19828. resolution = isNaN(resolution) ? minResolution :
  19829. Math.max(resolution, minResolution);
  19830. if (constrainResolution) {
  19831. var constrainedResolution = this.constrainResolution(resolution, 0, 0);
  19832. if (!nearest && constrainedResolution < resolution) {
  19833. constrainedResolution = this.constrainResolution(
  19834. constrainedResolution, -1, 0);
  19835. }
  19836. resolution = constrainedResolution;
  19837. }
  19838. this.setResolution(resolution);
  19839. // calculate center
  19840. sinAngle = -sinAngle; // go back to original rotation
  19841. var centerRotX = (minRotX + maxRotX) / 2;
  19842. var centerRotY = (minRotY + maxRotY) / 2;
  19843. centerRotX += (padding[1] - padding[3]) / 2 * resolution;
  19844. centerRotY += (padding[0] - padding[2]) / 2 * resolution;
  19845. var centerX = centerRotX * cosAngle - centerRotY * sinAngle;
  19846. var centerY = centerRotY * cosAngle + centerRotX * sinAngle;
  19847. this.setCenter([centerX, centerY]);
  19848. };
  19849. /**
  19850. * Center on coordinate and view position.
  19851. * @param {ol.Coordinate} coordinate Coordinate.
  19852. * @param {ol.Size} size Box pixel size.
  19853. * @param {ol.Pixel} position Position on the view to center on.
  19854. * @api
  19855. */
  19856. ol.View.prototype.centerOn = function(coordinate, size, position) {
  19857. // calculate rotated position
  19858. var rotation = this.getRotation();
  19859. var cosAngle = Math.cos(-rotation);
  19860. var sinAngle = Math.sin(-rotation);
  19861. var rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle;
  19862. var rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle;
  19863. var resolution = this.getResolution();
  19864. rotX += (size[0] / 2 - position[0]) * resolution;
  19865. rotY += (position[1] - size[1] / 2) * resolution;
  19866. // go back to original angle
  19867. sinAngle = -sinAngle; // go back to original rotation
  19868. var centerX = rotX * cosAngle - rotY * sinAngle;
  19869. var centerY = rotY * cosAngle + rotX * sinAngle;
  19870. this.setCenter([centerX, centerY]);
  19871. };
  19872. /**
  19873. * @return {boolean} Is defined.
  19874. */
  19875. ol.View.prototype.isDef = function() {
  19876. return !!this.getCenter() && this.getResolution() !== undefined;
  19877. };
  19878. /**
  19879. * Rotate the view around a given coordinate.
  19880. * @param {number} rotation New rotation value for the view.
  19881. * @param {ol.Coordinate=} opt_anchor The rotation center.
  19882. * @api stable
  19883. */
  19884. ol.View.prototype.rotate = function(rotation, opt_anchor) {
  19885. if (opt_anchor !== undefined) {
  19886. var center = this.calculateCenterRotate(rotation, opt_anchor);
  19887. this.setCenter(center);
  19888. }
  19889. this.setRotation(rotation);
  19890. };
  19891. /**
  19892. * Set the center of the current view.
  19893. * @param {ol.Coordinate|undefined} center The center of the view.
  19894. * @observable
  19895. * @api stable
  19896. */
  19897. ol.View.prototype.setCenter = function(center) {
  19898. this.set(ol.ViewProperty.CENTER, center);
  19899. };
  19900. /**
  19901. * @param {ol.ViewHint} hint Hint.
  19902. * @param {number} delta Delta.
  19903. * @return {number} New value.
  19904. */
  19905. ol.View.prototype.setHint = function(hint, delta) {
  19906. goog.asserts.assert(0 <= hint && hint < this.hints_.length,
  19907. 'illegal hint (%s), must be between 0 and %s', hint, this.hints_.length);
  19908. this.hints_[hint] += delta;
  19909. goog.asserts.assert(this.hints_[hint] >= 0,
  19910. 'Hint at %s must be positive, was %s', hint, this.hints_[hint]);
  19911. return this.hints_[hint];
  19912. };
  19913. /**
  19914. * Set the resolution for this view.
  19915. * @param {number|undefined} resolution The resolution of the view.
  19916. * @observable
  19917. * @api stable
  19918. */
  19919. ol.View.prototype.setResolution = function(resolution) {
  19920. this.set(ol.ViewProperty.RESOLUTION, resolution);
  19921. };
  19922. /**
  19923. * Set the rotation for this view.
  19924. * @param {number} rotation The rotation of the view in radians.
  19925. * @observable
  19926. * @api stable
  19927. */
  19928. ol.View.prototype.setRotation = function(rotation) {
  19929. this.set(ol.ViewProperty.ROTATION, rotation);
  19930. };
  19931. /**
  19932. * Zoom to a specific zoom level.
  19933. * @param {number} zoom Zoom level.
  19934. * @api stable
  19935. */
  19936. ol.View.prototype.setZoom = function(zoom) {
  19937. var resolution = this.constrainResolution(
  19938. this.maxResolution_, zoom - this.minZoom_, 0);
  19939. this.setResolution(resolution);
  19940. };
  19941. /**
  19942. * @param {olx.ViewOptions} options View options.
  19943. * @private
  19944. * @return {ol.CenterConstraintType}
  19945. */
  19946. ol.View.createCenterConstraint_ = function(options) {
  19947. if (options.extent !== undefined) {
  19948. return ol.CenterConstraint.createExtent(options.extent);
  19949. } else {
  19950. return ol.CenterConstraint.none;
  19951. }
  19952. };
  19953. /**
  19954. * @private
  19955. * @param {olx.ViewOptions} options View options.
  19956. * @return {{constraint: ol.ResolutionConstraintType, maxResolution: number,
  19957. * minResolution: number}}
  19958. */
  19959. ol.View.createResolutionConstraint_ = function(options) {
  19960. var resolutionConstraint;
  19961. var maxResolution;
  19962. var minResolution;
  19963. // TODO: move these to be ol constants
  19964. // see https://github.com/openlayers/ol3/issues/2076
  19965. var defaultMaxZoom = 28;
  19966. var defaultZoomFactor = 2;
  19967. var minZoom = options.minZoom !== undefined ?
  19968. options.minZoom : ol.DEFAULT_MIN_ZOOM;
  19969. var maxZoom = options.maxZoom !== undefined ?
  19970. options.maxZoom : defaultMaxZoom;
  19971. var zoomFactor = options.zoomFactor !== undefined ?
  19972. options.zoomFactor : defaultZoomFactor;
  19973. if (options.resolutions !== undefined) {
  19974. var resolutions = options.resolutions;
  19975. maxResolution = resolutions[0];
  19976. minResolution = resolutions[resolutions.length - 1];
  19977. resolutionConstraint = ol.ResolutionConstraint.createSnapToResolutions(
  19978. resolutions);
  19979. } else {
  19980. // calculate the default min and max resolution
  19981. var projection = ol.proj.createProjection(options.projection, 'EPSG:3857');
  19982. var extent = projection.getExtent();
  19983. var size = !extent ?
  19984. // use an extent that can fit the whole world if need be
  19985. 360 * ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES] /
  19986. ol.proj.METERS_PER_UNIT[projection.getUnits()] :
  19987. Math.max(ol.extent.getWidth(extent), ol.extent.getHeight(extent));
  19988. var defaultMaxResolution = size / ol.DEFAULT_TILE_SIZE / Math.pow(
  19989. defaultZoomFactor, ol.DEFAULT_MIN_ZOOM);
  19990. var defaultMinResolution = defaultMaxResolution / Math.pow(
  19991. defaultZoomFactor, defaultMaxZoom - ol.DEFAULT_MIN_ZOOM);
  19992. // user provided maxResolution takes precedence
  19993. maxResolution = options.maxResolution;
  19994. if (maxResolution !== undefined) {
  19995. minZoom = 0;
  19996. } else {
  19997. maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom);
  19998. }
  19999. // user provided minResolution takes precedence
  20000. minResolution = options.minResolution;
  20001. if (minResolution === undefined) {
  20002. if (options.maxZoom !== undefined) {
  20003. if (options.maxResolution !== undefined) {
  20004. minResolution = maxResolution / Math.pow(zoomFactor, maxZoom);
  20005. } else {
  20006. minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom);
  20007. }
  20008. } else {
  20009. minResolution = defaultMinResolution;
  20010. }
  20011. }
  20012. // given discrete zoom levels, minResolution may be different than provided
  20013. maxZoom = minZoom + Math.floor(
  20014. Math.log(maxResolution / minResolution) / Math.log(zoomFactor));
  20015. minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom);
  20016. resolutionConstraint = ol.ResolutionConstraint.createSnapToPower(
  20017. zoomFactor, maxResolution, maxZoom - minZoom);
  20018. }
  20019. return {constraint: resolutionConstraint, maxResolution: maxResolution,
  20020. minResolution: minResolution, minZoom: minZoom};
  20021. };
  20022. /**
  20023. * @private
  20024. * @param {olx.ViewOptions} options View options.
  20025. * @return {ol.RotationConstraintType} Rotation constraint.
  20026. */
  20027. ol.View.createRotationConstraint_ = function(options) {
  20028. var enableRotation = options.enableRotation !== undefined ?
  20029. options.enableRotation : true;
  20030. if (enableRotation) {
  20031. var constrainRotation = options.constrainRotation;
  20032. if (constrainRotation === undefined || constrainRotation === true) {
  20033. return ol.RotationConstraint.createSnapToZero();
  20034. } else if (constrainRotation === false) {
  20035. return ol.RotationConstraint.none;
  20036. } else if (goog.isNumber(constrainRotation)) {
  20037. return ol.RotationConstraint.createSnapToN(constrainRotation);
  20038. } else {
  20039. goog.asserts.fail(
  20040. 'illegal option for constrainRotation (%s)', constrainRotation);
  20041. return ol.RotationConstraint.none;
  20042. }
  20043. } else {
  20044. return ol.RotationConstraint.disable;
  20045. }
  20046. };
  20047. goog.provide('ol.easing');
  20048. /**
  20049. * Start slow and speed up.
  20050. * @param {number} t Input between 0 and 1.
  20051. * @return {number} Output between 0 and 1.
  20052. * @api
  20053. */
  20054. ol.easing.easeIn = function(t) {
  20055. return Math.pow(t, 3);
  20056. };
  20057. /**
  20058. * Start fast and slow down.
  20059. * @param {number} t Input between 0 and 1.
  20060. * @return {number} Output between 0 and 1.
  20061. * @api
  20062. */
  20063. ol.easing.easeOut = function(t) {
  20064. return 1 - ol.easing.easeIn(1 - t);
  20065. };
  20066. /**
  20067. * Start slow, speed up, and then slow down again.
  20068. * @param {number} t Input between 0 and 1.
  20069. * @return {number} Output between 0 and 1.
  20070. * @api
  20071. */
  20072. ol.easing.inAndOut = function(t) {
  20073. return 3 * t * t - 2 * t * t * t;
  20074. };
  20075. /**
  20076. * Maintain a constant speed over time.
  20077. * @param {number} t Input between 0 and 1.
  20078. * @return {number} Output between 0 and 1.
  20079. * @api
  20080. */
  20081. ol.easing.linear = function(t) {
  20082. return t;
  20083. };
  20084. /**
  20085. * Start slow, speed up, and at the very end slow down again. This has the
  20086. * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown
  20087. * is delayed.
  20088. * @param {number} t Input between 0 and 1.
  20089. * @return {number} Output between 0 and 1.
  20090. * @api
  20091. */
  20092. ol.easing.upAndDown = function(t) {
  20093. if (t < 0.5) {
  20094. return ol.easing.inAndOut(2 * t);
  20095. } else {
  20096. return 1 - ol.easing.inAndOut(2 * (t - 0.5));
  20097. }
  20098. };
  20099. goog.provide('ol.animation');
  20100. goog.require('ol');
  20101. goog.require('ol.PreRenderFunction');
  20102. goog.require('ol.ViewHint');
  20103. goog.require('ol.coordinate');
  20104. goog.require('ol.easing');
  20105. /**
  20106. * Generate an animated transition that will "bounce" the resolution as it
  20107. * approaches the final value.
  20108. * @param {olx.animation.BounceOptions} options Bounce options.
  20109. * @return {ol.PreRenderFunction} Pre-render function.
  20110. * @api
  20111. */
  20112. ol.animation.bounce = function(options) {
  20113. var resolution = options.resolution;
  20114. var start = options.start ? options.start : Date.now();
  20115. var duration = options.duration !== undefined ? options.duration : 1000;
  20116. var easing = options.easing ?
  20117. options.easing : ol.easing.upAndDown;
  20118. return (
  20119. /**
  20120. * @param {ol.Map} map Map.
  20121. * @param {?olx.FrameState} frameState Frame state.
  20122. */
  20123. function(map, frameState) {
  20124. if (frameState.time < start) {
  20125. frameState.animate = true;
  20126. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20127. return true;
  20128. } else if (frameState.time < start + duration) {
  20129. var delta = easing((frameState.time - start) / duration);
  20130. var deltaResolution = resolution - frameState.viewState.resolution;
  20131. frameState.animate = true;
  20132. frameState.viewState.resolution += delta * deltaResolution;
  20133. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20134. return true;
  20135. } else {
  20136. return false;
  20137. }
  20138. });
  20139. };
  20140. /**
  20141. * Generate an animated transition while updating the view center.
  20142. * @param {olx.animation.PanOptions} options Pan options.
  20143. * @return {ol.PreRenderFunction} Pre-render function.
  20144. * @api
  20145. */
  20146. ol.animation.pan = function(options) {
  20147. var source = options.source;
  20148. var start = options.start ? options.start : Date.now();
  20149. var sourceX = source[0];
  20150. var sourceY = source[1];
  20151. var duration = options.duration !== undefined ? options.duration : 1000;
  20152. var easing = options.easing ?
  20153. options.easing : ol.easing.inAndOut;
  20154. return (
  20155. /**
  20156. * @param {ol.Map} map Map.
  20157. * @param {?olx.FrameState} frameState Frame state.
  20158. */
  20159. function(map, frameState) {
  20160. if (frameState.time < start) {
  20161. frameState.animate = true;
  20162. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20163. return true;
  20164. } else if (frameState.time < start + duration) {
  20165. var delta = 1 - easing((frameState.time - start) / duration);
  20166. var deltaX = sourceX - frameState.viewState.center[0];
  20167. var deltaY = sourceY - frameState.viewState.center[1];
  20168. frameState.animate = true;
  20169. frameState.viewState.center[0] += delta * deltaX;
  20170. frameState.viewState.center[1] += delta * deltaY;
  20171. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20172. return true;
  20173. } else {
  20174. return false;
  20175. }
  20176. });
  20177. };
  20178. /**
  20179. * Generate an animated transition while updating the view rotation.
  20180. * @param {olx.animation.RotateOptions} options Rotate options.
  20181. * @return {ol.PreRenderFunction} Pre-render function.
  20182. * @api
  20183. */
  20184. ol.animation.rotate = function(options) {
  20185. var sourceRotation = options.rotation ? options.rotation : 0;
  20186. var start = options.start ? options.start : Date.now();
  20187. var duration = options.duration !== undefined ? options.duration : 1000;
  20188. var easing = options.easing ?
  20189. options.easing : ol.easing.inAndOut;
  20190. var anchor = options.anchor ?
  20191. options.anchor : null;
  20192. return (
  20193. /**
  20194. * @param {ol.Map} map Map.
  20195. * @param {?olx.FrameState} frameState Frame state.
  20196. */
  20197. function(map, frameState) {
  20198. if (frameState.time < start) {
  20199. frameState.animate = true;
  20200. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20201. return true;
  20202. } else if (frameState.time < start + duration) {
  20203. var delta = 1 - easing((frameState.time - start) / duration);
  20204. var deltaRotation =
  20205. (sourceRotation - frameState.viewState.rotation) * delta;
  20206. frameState.animate = true;
  20207. frameState.viewState.rotation += deltaRotation;
  20208. if (anchor) {
  20209. var center = frameState.viewState.center;
  20210. ol.coordinate.sub(center, anchor);
  20211. ol.coordinate.rotate(center, deltaRotation);
  20212. ol.coordinate.add(center, anchor);
  20213. }
  20214. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20215. return true;
  20216. } else {
  20217. return false;
  20218. }
  20219. });
  20220. };
  20221. /**
  20222. * Generate an animated transition while updating the view resolution.
  20223. * @param {olx.animation.ZoomOptions} options Zoom options.
  20224. * @return {ol.PreRenderFunction} Pre-render function.
  20225. * @api
  20226. */
  20227. ol.animation.zoom = function(options) {
  20228. var sourceResolution = options.resolution;
  20229. var start = options.start ? options.start : Date.now();
  20230. var duration = options.duration !== undefined ? options.duration : 1000;
  20231. var easing = options.easing ?
  20232. options.easing : ol.easing.inAndOut;
  20233. return (
  20234. /**
  20235. * @param {ol.Map} map Map.
  20236. * @param {?olx.FrameState} frameState Frame state.
  20237. */
  20238. function(map, frameState) {
  20239. if (frameState.time < start) {
  20240. frameState.animate = true;
  20241. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20242. return true;
  20243. } else if (frameState.time < start + duration) {
  20244. var delta = 1 - easing((frameState.time - start) / duration);
  20245. var deltaResolution =
  20246. sourceResolution - frameState.viewState.resolution;
  20247. frameState.animate = true;
  20248. frameState.viewState.resolution += delta * deltaResolution;
  20249. frameState.viewHints[ol.ViewHint.ANIMATING] += 1;
  20250. return true;
  20251. } else {
  20252. return false;
  20253. }
  20254. });
  20255. };
  20256. goog.provide('ol.TileCoord');
  20257. goog.provide('ol.tilecoord');
  20258. goog.require('goog.asserts');
  20259. goog.require('ol.extent');
  20260. /**
  20261. * An array of three numbers representing the location of a tile in a tile
  20262. * grid. The order is `z`, `x`, and `y`. `z` is the zoom level.
  20263. * @typedef {Array.<number>} ol.TileCoord
  20264. * @api
  20265. */
  20266. ol.TileCoord;
  20267. /**
  20268. * @enum {number}
  20269. */
  20270. ol.QuadKeyCharCode = {
  20271. ZERO: '0'.charCodeAt(0),
  20272. ONE: '1'.charCodeAt(0),
  20273. TWO: '2'.charCodeAt(0),
  20274. THREE: '3'.charCodeAt(0)
  20275. };
  20276. /**
  20277. * @param {string} str String that follows pattern “z/x/y” where x, y and z are
  20278. * numbers.
  20279. * @return {ol.TileCoord} Tile coord.
  20280. */
  20281. ol.tilecoord.createFromString = function(str) {
  20282. var v = str.split('/');
  20283. goog.asserts.assert(v.length === 3,
  20284. 'must provide a string in "z/x/y" format, got "%s"', str);
  20285. return v.map(function(e) {
  20286. return parseInt(e, 10);
  20287. });
  20288. };
  20289. /**
  20290. * @param {number} z Z.
  20291. * @param {number} x X.
  20292. * @param {number} y Y.
  20293. * @param {ol.TileCoord=} opt_tileCoord Tile coordinate.
  20294. * @return {ol.TileCoord} Tile coordinate.
  20295. */
  20296. ol.tilecoord.createOrUpdate = function(z, x, y, opt_tileCoord) {
  20297. if (opt_tileCoord !== undefined) {
  20298. opt_tileCoord[0] = z;
  20299. opt_tileCoord[1] = x;
  20300. opt_tileCoord[2] = y;
  20301. return opt_tileCoord;
  20302. } else {
  20303. return [z, x, y];
  20304. }
  20305. };
  20306. /**
  20307. * @param {number} z Z.
  20308. * @param {number} x X.
  20309. * @param {number} y Y.
  20310. * @return {string} Key.
  20311. */
  20312. ol.tilecoord.getKeyZXY = function(z, x, y) {
  20313. return z + '/' + x + '/' + y;
  20314. };
  20315. /**
  20316. * @param {ol.TileCoord} tileCoord Tile coord.
  20317. * @return {number} Hash.
  20318. */
  20319. ol.tilecoord.hash = function(tileCoord) {
  20320. return (tileCoord[1] << tileCoord[0]) + tileCoord[2];
  20321. };
  20322. /**
  20323. * @param {ol.TileCoord} tileCoord Tile coord.
  20324. * @return {string} Quad key.
  20325. */
  20326. ol.tilecoord.quadKey = function(tileCoord) {
  20327. var z = tileCoord[0];
  20328. var digits = new Array(z);
  20329. var mask = 1 << (z - 1);
  20330. var i, charCode;
  20331. for (i = 0; i < z; ++i) {
  20332. charCode = ol.QuadKeyCharCode.ZERO;
  20333. if (tileCoord[1] & mask) {
  20334. charCode += 1;
  20335. }
  20336. if (tileCoord[2] & mask) {
  20337. charCode += 2;
  20338. }
  20339. digits[i] = String.fromCharCode(charCode);
  20340. mask >>= 1;
  20341. }
  20342. return digits.join('');
  20343. };
  20344. /**
  20345. * @param {ol.TileCoord} tileCoord Tile coord.
  20346. * @return {string} String.
  20347. */
  20348. ol.tilecoord.toString = function(tileCoord) {
  20349. return ol.tilecoord.getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]);
  20350. };
  20351. /**
  20352. * @param {ol.TileCoord} tileCoord Tile coordinate.
  20353. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  20354. * @param {ol.proj.Projection} projection Projection.
  20355. * @return {ol.TileCoord} Tile coordinate.
  20356. */
  20357. ol.tilecoord.wrapX = function(tileCoord, tileGrid, projection) {
  20358. var z = tileCoord[0];
  20359. var center = tileGrid.getTileCoordCenter(tileCoord);
  20360. var projectionExtent = ol.tilegrid.extentFromProjection(projection);
  20361. if (!ol.extent.containsCoordinate(projectionExtent, center)) {
  20362. var worldWidth = ol.extent.getWidth(projectionExtent);
  20363. var worldsAway = Math.ceil((projectionExtent[0] - center[0]) / worldWidth);
  20364. center[0] += worldWidth * worldsAway;
  20365. return tileGrid.getTileCoordForCoordAndZ(center, z);
  20366. } else {
  20367. return tileCoord;
  20368. }
  20369. };
  20370. /**
  20371. * @param {ol.TileCoord} tileCoord Tile coordinate.
  20372. * @param {!ol.tilegrid.TileGrid} tileGrid Tile grid.
  20373. * @return {boolean} Tile coordinate is within extent and zoom level range.
  20374. */
  20375. ol.tilecoord.withinExtentAndZ = function(tileCoord, tileGrid) {
  20376. var z = tileCoord[0];
  20377. var x = tileCoord[1];
  20378. var y = tileCoord[2];
  20379. if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) {
  20380. return false;
  20381. }
  20382. var extent = tileGrid.getExtent();
  20383. var tileRange;
  20384. if (!extent) {
  20385. tileRange = tileGrid.getFullTileRange(z);
  20386. } else {
  20387. tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  20388. }
  20389. if (!tileRange) {
  20390. return true;
  20391. } else {
  20392. return tileRange.containsXY(x, y);
  20393. }
  20394. };
  20395. goog.provide('ol.TileRange');
  20396. goog.require('goog.asserts');
  20397. goog.require('ol.Size');
  20398. goog.require('ol.TileCoord');
  20399. /**
  20400. * A representation of a contiguous block of tiles. A tile range is specified
  20401. * by its min/max tile coordinates and is inclusive of coordinates.
  20402. *
  20403. * @constructor
  20404. * @param {number} minX Minimum X.
  20405. * @param {number} maxX Maximum X.
  20406. * @param {number} minY Minimum Y.
  20407. * @param {number} maxY Maximum Y.
  20408. * @struct
  20409. */
  20410. ol.TileRange = function(minX, maxX, minY, maxY) {
  20411. /**
  20412. * @type {number}
  20413. */
  20414. this.minX = minX;
  20415. /**
  20416. * @type {number}
  20417. */
  20418. this.maxX = maxX;
  20419. /**
  20420. * @type {number}
  20421. */
  20422. this.minY = minY;
  20423. /**
  20424. * @type {number}
  20425. */
  20426. this.maxY = maxY;
  20427. };
  20428. /**
  20429. * @param {...ol.TileCoord} var_args Tile coordinates.
  20430. * @return {!ol.TileRange} Bounding tile box.
  20431. */
  20432. ol.TileRange.boundingTileRange = function(var_args) {
  20433. var tileCoord0 = /** @type {ol.TileCoord} */ (arguments[0]);
  20434. var tileCoord0Z = tileCoord0[0];
  20435. var tileCoord0X = tileCoord0[1];
  20436. var tileCoord0Y = tileCoord0[2];
  20437. var tileRange = new ol.TileRange(tileCoord0X, tileCoord0X,
  20438. tileCoord0Y, tileCoord0Y);
  20439. var i, ii, tileCoord, tileCoordX, tileCoordY, tileCoordZ;
  20440. for (i = 1, ii = arguments.length; i < ii; ++i) {
  20441. tileCoord = /** @type {ol.TileCoord} */ (arguments[i]);
  20442. tileCoordZ = tileCoord[0];
  20443. tileCoordX = tileCoord[1];
  20444. tileCoordY = tileCoord[2];
  20445. goog.asserts.assert(tileCoordZ == tileCoord0Z,
  20446. 'passed tilecoords all have the same Z-value');
  20447. tileRange.minX = Math.min(tileRange.minX, tileCoordX);
  20448. tileRange.maxX = Math.max(tileRange.maxX, tileCoordX);
  20449. tileRange.minY = Math.min(tileRange.minY, tileCoordY);
  20450. tileRange.maxY = Math.max(tileRange.maxY, tileCoordY);
  20451. }
  20452. return tileRange;
  20453. };
  20454. /**
  20455. * @param {number} minX Minimum X.
  20456. * @param {number} maxX Maximum X.
  20457. * @param {number} minY Minimum Y.
  20458. * @param {number} maxY Maximum Y.
  20459. * @param {ol.TileRange|undefined} tileRange TileRange.
  20460. * @return {ol.TileRange} Tile range.
  20461. */
  20462. ol.TileRange.createOrUpdate = function(minX, maxX, minY, maxY, tileRange) {
  20463. if (tileRange !== undefined) {
  20464. tileRange.minX = minX;
  20465. tileRange.maxX = maxX;
  20466. tileRange.minY = minY;
  20467. tileRange.maxY = maxY;
  20468. return tileRange;
  20469. } else {
  20470. return new ol.TileRange(minX, maxX, minY, maxY);
  20471. }
  20472. };
  20473. /**
  20474. * @param {ol.TileCoord} tileCoord Tile coordinate.
  20475. * @return {boolean} Contains tile coordinate.
  20476. */
  20477. ol.TileRange.prototype.contains = function(tileCoord) {
  20478. return this.containsXY(tileCoord[1], tileCoord[2]);
  20479. };
  20480. /**
  20481. * @param {ol.TileRange} tileRange Tile range.
  20482. * @return {boolean} Contains.
  20483. */
  20484. ol.TileRange.prototype.containsTileRange = function(tileRange) {
  20485. return this.minX <= tileRange.minX && tileRange.maxX <= this.maxX &&
  20486. this.minY <= tileRange.minY && tileRange.maxY <= this.maxY;
  20487. };
  20488. /**
  20489. * @param {number} x Tile coordinate x.
  20490. * @param {number} y Tile coordinate y.
  20491. * @return {boolean} Contains coordinate.
  20492. */
  20493. ol.TileRange.prototype.containsXY = function(x, y) {
  20494. return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY;
  20495. };
  20496. /**
  20497. * @param {ol.TileRange} tileRange Tile range.
  20498. * @return {boolean} Equals.
  20499. */
  20500. ol.TileRange.prototype.equals = function(tileRange) {
  20501. return this.minX == tileRange.minX && this.minY == tileRange.minY &&
  20502. this.maxX == tileRange.maxX && this.maxY == tileRange.maxY;
  20503. };
  20504. /**
  20505. * @param {ol.TileRange} tileRange Tile range.
  20506. */
  20507. ol.TileRange.prototype.extend = function(tileRange) {
  20508. if (tileRange.minX < this.minX) {
  20509. this.minX = tileRange.minX;
  20510. }
  20511. if (tileRange.maxX > this.maxX) {
  20512. this.maxX = tileRange.maxX;
  20513. }
  20514. if (tileRange.minY < this.minY) {
  20515. this.minY = tileRange.minY;
  20516. }
  20517. if (tileRange.maxY > this.maxY) {
  20518. this.maxY = tileRange.maxY;
  20519. }
  20520. };
  20521. /**
  20522. * @return {number} Height.
  20523. */
  20524. ol.TileRange.prototype.getHeight = function() {
  20525. return this.maxY - this.minY + 1;
  20526. };
  20527. /**
  20528. * @return {ol.Size} Size.
  20529. */
  20530. ol.TileRange.prototype.getSize = function() {
  20531. return [this.getWidth(), this.getHeight()];
  20532. };
  20533. /**
  20534. * @return {number} Width.
  20535. */
  20536. ol.TileRange.prototype.getWidth = function() {
  20537. return this.maxX - this.minX + 1;
  20538. };
  20539. /**
  20540. * @param {ol.TileRange} tileRange Tile range.
  20541. * @return {boolean} Intersects.
  20542. */
  20543. ol.TileRange.prototype.intersects = function(tileRange) {
  20544. return this.minX <= tileRange.maxX &&
  20545. this.maxX >= tileRange.minX &&
  20546. this.minY <= tileRange.maxY &&
  20547. this.maxY >= tileRange.minY;
  20548. };
  20549. goog.provide('ol.Attribution');
  20550. goog.require('goog.math');
  20551. goog.require('ol.TileRange');
  20552. /**
  20553. * @classdesc
  20554. * An attribution for a layer source.
  20555. *
  20556. * Example:
  20557. *
  20558. * source: new ol.source.OSM({
  20559. * attributions: [
  20560. * new ol.Attribution({
  20561. * html: 'All maps &copy; ' +
  20562. * '<a href="http://www.opencyclemap.org/">OpenCycleMap</a>'
  20563. * }),
  20564. * ol.source.OSM.ATTRIBUTION
  20565. * ],
  20566. * ..
  20567. *
  20568. * @constructor
  20569. * @param {olx.AttributionOptions} options Attribution options.
  20570. * @struct
  20571. * @api stable
  20572. */
  20573. ol.Attribution = function(options) {
  20574. /**
  20575. * @private
  20576. * @type {string}
  20577. */
  20578. this.html_ = options.html;
  20579. /**
  20580. * @private
  20581. * @type {Object.<string, Array.<ol.TileRange>>}
  20582. */
  20583. this.tileRanges_ = options.tileRanges ? options.tileRanges : null;
  20584. };
  20585. /**
  20586. * Get the attribution markup.
  20587. * @return {string} The attribution HTML.
  20588. * @api stable
  20589. */
  20590. ol.Attribution.prototype.getHTML = function() {
  20591. return this.html_;
  20592. };
  20593. /**
  20594. * @param {Object.<string, ol.TileRange>} tileRanges Tile ranges.
  20595. * @param {!ol.tilegrid.TileGrid} tileGrid Tile grid.
  20596. * @param {!ol.proj.Projection} projection Projection.
  20597. * @return {boolean} Intersects any tile range.
  20598. */
  20599. ol.Attribution.prototype.intersectsAnyTileRange =
  20600. function(tileRanges, tileGrid, projection) {
  20601. if (!this.tileRanges_) {
  20602. return true;
  20603. }
  20604. var i, ii, tileRange, zKey;
  20605. for (zKey in tileRanges) {
  20606. if (!(zKey in this.tileRanges_)) {
  20607. continue;
  20608. }
  20609. tileRange = tileRanges[zKey];
  20610. var testTileRange;
  20611. for (i = 0, ii = this.tileRanges_[zKey].length; i < ii; ++i) {
  20612. testTileRange = this.tileRanges_[zKey][i];
  20613. if (testTileRange.intersects(tileRange)) {
  20614. return true;
  20615. }
  20616. var extentTileRange = tileGrid.getTileRangeForExtentAndZ(
  20617. projection.getExtent(), parseInt(zKey, 10));
  20618. var width = extentTileRange.getWidth();
  20619. if (tileRange.minX < extentTileRange.minX ||
  20620. tileRange.maxX > extentTileRange.maxX) {
  20621. if (testTileRange.intersects(new ol.TileRange(
  20622. goog.math.modulo(tileRange.minX, width),
  20623. goog.math.modulo(tileRange.maxX, width),
  20624. tileRange.minY, tileRange.maxY))) {
  20625. return true;
  20626. }
  20627. if (tileRange.getWidth() > width &&
  20628. testTileRange.intersects(extentTileRange)) {
  20629. return true;
  20630. }
  20631. }
  20632. }
  20633. }
  20634. return false;
  20635. };
  20636. goog.provide('ol.CanvasFunctionType');
  20637. /**
  20638. * A function returning the canvas element (`{HTMLCanvasElement}`)
  20639. * used by the source as an image. The arguments passed to the function are:
  20640. * {@link ol.Extent} the image extent, `{number}` the image resolution,
  20641. * `{number}` the device pixel ratio, {@link ol.Size} the image size, and
  20642. * {@link ol.proj.Projection} the image projection. The canvas returned by
  20643. * this function is cached by the source. The this keyword inside the function
  20644. * references the {@link ol.source.ImageCanvas}.
  20645. *
  20646. * @typedef {function(this:ol.source.ImageCanvas, ol.Extent, number,
  20647. * number, ol.Size, ol.proj.Projection): HTMLCanvasElement}
  20648. * @api
  20649. */
  20650. ol.CanvasFunctionType;
  20651. /**
  20652. * An implementation of Google Maps' MVCArray.
  20653. * @see https://developers.google.com/maps/documentation/javascript/reference
  20654. */
  20655. goog.provide('ol.Collection');
  20656. goog.provide('ol.CollectionEvent');
  20657. goog.provide('ol.CollectionEventType');
  20658. goog.require('goog.array');
  20659. goog.require('goog.events.Event');
  20660. goog.require('ol.Object');
  20661. /**
  20662. * @enum {string}
  20663. */
  20664. ol.CollectionEventType = {
  20665. /**
  20666. * Triggered when an item is added to the collection.
  20667. * @event ol.CollectionEvent#add
  20668. * @api stable
  20669. */
  20670. ADD: 'add',
  20671. /**
  20672. * Triggered when an item is removed from the collection.
  20673. * @event ol.CollectionEvent#remove
  20674. * @api stable
  20675. */
  20676. REMOVE: 'remove'
  20677. };
  20678. /**
  20679. * @classdesc
  20680. * Events emitted by {@link ol.Collection} instances are instances of this
  20681. * type.
  20682. *
  20683. * @constructor
  20684. * @extends {goog.events.Event}
  20685. * @implements {oli.CollectionEvent}
  20686. * @param {ol.CollectionEventType} type Type.
  20687. * @param {*=} opt_element Element.
  20688. * @param {Object=} opt_target Target.
  20689. */
  20690. ol.CollectionEvent = function(type, opt_element, opt_target) {
  20691. goog.base(this, type, opt_target);
  20692. /**
  20693. * The element that is added to or removed from the collection.
  20694. * @type {*}
  20695. * @api stable
  20696. */
  20697. this.element = opt_element;
  20698. };
  20699. goog.inherits(ol.CollectionEvent, goog.events.Event);
  20700. /**
  20701. * @enum {string}
  20702. */
  20703. ol.CollectionProperty = {
  20704. LENGTH: 'length'
  20705. };
  20706. /**
  20707. * @classdesc
  20708. * An expanded version of standard JS Array, adding convenience methods for
  20709. * manipulation. Add and remove changes to the Collection trigger a Collection
  20710. * event. Note that this does not cover changes to the objects _within_ the
  20711. * Collection; they trigger events on the appropriate object, not on the
  20712. * Collection as a whole.
  20713. *
  20714. * @constructor
  20715. * @extends {ol.Object}
  20716. * @fires ol.CollectionEvent
  20717. * @param {!Array.<T>=} opt_array Array.
  20718. * @template T
  20719. * @api stable
  20720. */
  20721. ol.Collection = function(opt_array) {
  20722. goog.base(this);
  20723. /**
  20724. * @private
  20725. * @type {!Array.<T>}
  20726. */
  20727. this.array_ = opt_array ? opt_array : [];
  20728. this.updateLength_();
  20729. };
  20730. goog.inherits(ol.Collection, ol.Object);
  20731. /**
  20732. * Remove all elements from the collection.
  20733. * @api stable
  20734. */
  20735. ol.Collection.prototype.clear = function() {
  20736. while (this.getLength() > 0) {
  20737. this.pop();
  20738. }
  20739. };
  20740. /**
  20741. * Add elements to the collection. This pushes each item in the provided array
  20742. * to the end of the collection.
  20743. * @param {!Array.<T>} arr Array.
  20744. * @return {ol.Collection.<T>} This collection.
  20745. * @api stable
  20746. */
  20747. ol.Collection.prototype.extend = function(arr) {
  20748. var i, ii;
  20749. for (i = 0, ii = arr.length; i < ii; ++i) {
  20750. this.push(arr[i]);
  20751. }
  20752. return this;
  20753. };
  20754. /**
  20755. * Iterate over each element, calling the provided callback.
  20756. * @param {function(this: S, T, number, Array.<T>): *} f The function to call
  20757. * for every element. This function takes 3 arguments (the element, the
  20758. * index and the array). The return value is ignored.
  20759. * @param {S=} opt_this The object to use as `this` in `f`.
  20760. * @template S
  20761. * @api stable
  20762. */
  20763. ol.Collection.prototype.forEach = function(f, opt_this) {
  20764. this.array_.forEach(f, opt_this);
  20765. };
  20766. /**
  20767. * Get a reference to the underlying Array object. Warning: if the array
  20768. * is mutated, no events will be dispatched by the collection, and the
  20769. * collection's "length" property won't be in sync with the actual length
  20770. * of the array.
  20771. * @return {!Array.<T>} Array.
  20772. * @api stable
  20773. */
  20774. ol.Collection.prototype.getArray = function() {
  20775. return this.array_;
  20776. };
  20777. /**
  20778. * Get the element at the provided index.
  20779. * @param {number} index Index.
  20780. * @return {T} Element.
  20781. * @api stable
  20782. */
  20783. ol.Collection.prototype.item = function(index) {
  20784. return this.array_[index];
  20785. };
  20786. /**
  20787. * Get the length of this collection.
  20788. * @return {number} The length of the array.
  20789. * @observable
  20790. * @api stable
  20791. */
  20792. ol.Collection.prototype.getLength = function() {
  20793. return /** @type {number} */ (this.get(ol.CollectionProperty.LENGTH));
  20794. };
  20795. /**
  20796. * Insert an element at the provided index.
  20797. * @param {number} index Index.
  20798. * @param {T} elem Element.
  20799. * @api stable
  20800. */
  20801. ol.Collection.prototype.insertAt = function(index, elem) {
  20802. goog.array.insertAt(this.array_, elem, index);
  20803. this.updateLength_();
  20804. this.dispatchEvent(
  20805. new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
  20806. };
  20807. /**
  20808. * Remove the last element of the collection and return it.
  20809. * Return `undefined` if the collection is empty.
  20810. * @return {T|undefined} Element.
  20811. * @api stable
  20812. */
  20813. ol.Collection.prototype.pop = function() {
  20814. return this.removeAt(this.getLength() - 1);
  20815. };
  20816. /**
  20817. * Insert the provided element at the end of the collection.
  20818. * @param {T} elem Element.
  20819. * @return {number} Length.
  20820. * @api stable
  20821. */
  20822. ol.Collection.prototype.push = function(elem) {
  20823. var n = this.array_.length;
  20824. this.insertAt(n, elem);
  20825. return n;
  20826. };
  20827. /**
  20828. * Remove the first occurrence of an element from the collection.
  20829. * @param {T} elem Element.
  20830. * @return {T|undefined} The removed element or undefined if none found.
  20831. * @api stable
  20832. */
  20833. ol.Collection.prototype.remove = function(elem) {
  20834. var arr = this.array_;
  20835. var i, ii;
  20836. for (i = 0, ii = arr.length; i < ii; ++i) {
  20837. if (arr[i] === elem) {
  20838. return this.removeAt(i);
  20839. }
  20840. }
  20841. return undefined;
  20842. };
  20843. /**
  20844. * Remove the element at the provided index and return it.
  20845. * Return `undefined` if the collection does not contain this index.
  20846. * @param {number} index Index.
  20847. * @return {T|undefined} Value.
  20848. * @api stable
  20849. */
  20850. ol.Collection.prototype.removeAt = function(index) {
  20851. var prev = this.array_[index];
  20852. goog.array.removeAt(this.array_, index);
  20853. this.updateLength_();
  20854. this.dispatchEvent(
  20855. new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
  20856. return prev;
  20857. };
  20858. /**
  20859. * Set the element at the provided index.
  20860. * @param {number} index Index.
  20861. * @param {T} elem Element.
  20862. * @api stable
  20863. */
  20864. ol.Collection.prototype.setAt = function(index, elem) {
  20865. var n = this.getLength();
  20866. if (index < n) {
  20867. var prev = this.array_[index];
  20868. this.array_[index] = elem;
  20869. this.dispatchEvent(
  20870. new ol.CollectionEvent(ol.CollectionEventType.REMOVE, prev, this));
  20871. this.dispatchEvent(
  20872. new ol.CollectionEvent(ol.CollectionEventType.ADD, elem, this));
  20873. } else {
  20874. var j;
  20875. for (j = n; j < index; ++j) {
  20876. this.insertAt(j, undefined);
  20877. }
  20878. this.insertAt(index, elem);
  20879. }
  20880. };
  20881. /**
  20882. * @private
  20883. */
  20884. ol.Collection.prototype.updateLength_ = function() {
  20885. this.set(ol.CollectionProperty.LENGTH, this.array_.length);
  20886. };
  20887. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  20888. //
  20889. // Licensed under the Apache License, Version 2.0 (the "License");
  20890. // you may not use this file except in compliance with the License.
  20891. // You may obtain a copy of the License at
  20892. //
  20893. // http://www.apache.org/licenses/LICENSE-2.0
  20894. //
  20895. // Unless required by applicable law or agreed to in writing, software
  20896. // distributed under the License is distributed on an "AS-IS" BASIS,
  20897. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20898. // See the License for the specific language governing permissions and
  20899. // limitations under the License.
  20900. /**
  20901. * @fileoverview Names of standard colors with their associated hex values.
  20902. */
  20903. goog.provide('goog.color.names');
  20904. /**
  20905. * A map that contains a lot of colors that are recognised by various browsers.
  20906. * This list is way larger than the minimal one dictated by W3C.
  20907. * The keys of this map are the lowercase "readable" names of the colors, while
  20908. * the values are the "hex" values.
  20909. *
  20910. * @type {!Object<string, string>}
  20911. */
  20912. goog.color.names = {
  20913. 'aliceblue': '#f0f8ff',
  20914. 'antiquewhite': '#faebd7',
  20915. 'aqua': '#00ffff',
  20916. 'aquamarine': '#7fffd4',
  20917. 'azure': '#f0ffff',
  20918. 'beige': '#f5f5dc',
  20919. 'bisque': '#ffe4c4',
  20920. 'black': '#000000',
  20921. 'blanchedalmond': '#ffebcd',
  20922. 'blue': '#0000ff',
  20923. 'blueviolet': '#8a2be2',
  20924. 'brown': '#a52a2a',
  20925. 'burlywood': '#deb887',
  20926. 'cadetblue': '#5f9ea0',
  20927. 'chartreuse': '#7fff00',
  20928. 'chocolate': '#d2691e',
  20929. 'coral': '#ff7f50',
  20930. 'cornflowerblue': '#6495ed',
  20931. 'cornsilk': '#fff8dc',
  20932. 'crimson': '#dc143c',
  20933. 'cyan': '#00ffff',
  20934. 'darkblue': '#00008b',
  20935. 'darkcyan': '#008b8b',
  20936. 'darkgoldenrod': '#b8860b',
  20937. 'darkgray': '#a9a9a9',
  20938. 'darkgreen': '#006400',
  20939. 'darkgrey': '#a9a9a9',
  20940. 'darkkhaki': '#bdb76b',
  20941. 'darkmagenta': '#8b008b',
  20942. 'darkolivegreen': '#556b2f',
  20943. 'darkorange': '#ff8c00',
  20944. 'darkorchid': '#9932cc',
  20945. 'darkred': '#8b0000',
  20946. 'darksalmon': '#e9967a',
  20947. 'darkseagreen': '#8fbc8f',
  20948. 'darkslateblue': '#483d8b',
  20949. 'darkslategray': '#2f4f4f',
  20950. 'darkslategrey': '#2f4f4f',
  20951. 'darkturquoise': '#00ced1',
  20952. 'darkviolet': '#9400d3',
  20953. 'deeppink': '#ff1493',
  20954. 'deepskyblue': '#00bfff',
  20955. 'dimgray': '#696969',
  20956. 'dimgrey': '#696969',
  20957. 'dodgerblue': '#1e90ff',
  20958. 'firebrick': '#b22222',
  20959. 'floralwhite': '#fffaf0',
  20960. 'forestgreen': '#228b22',
  20961. 'fuchsia': '#ff00ff',
  20962. 'gainsboro': '#dcdcdc',
  20963. 'ghostwhite': '#f8f8ff',
  20964. 'gold': '#ffd700',
  20965. 'goldenrod': '#daa520',
  20966. 'gray': '#808080',
  20967. 'green': '#008000',
  20968. 'greenyellow': '#adff2f',
  20969. 'grey': '#808080',
  20970. 'honeydew': '#f0fff0',
  20971. 'hotpink': '#ff69b4',
  20972. 'indianred': '#cd5c5c',
  20973. 'indigo': '#4b0082',
  20974. 'ivory': '#fffff0',
  20975. 'khaki': '#f0e68c',
  20976. 'lavender': '#e6e6fa',
  20977. 'lavenderblush': '#fff0f5',
  20978. 'lawngreen': '#7cfc00',
  20979. 'lemonchiffon': '#fffacd',
  20980. 'lightblue': '#add8e6',
  20981. 'lightcoral': '#f08080',
  20982. 'lightcyan': '#e0ffff',
  20983. 'lightgoldenrodyellow': '#fafad2',
  20984. 'lightgray': '#d3d3d3',
  20985. 'lightgreen': '#90ee90',
  20986. 'lightgrey': '#d3d3d3',
  20987. 'lightpink': '#ffb6c1',
  20988. 'lightsalmon': '#ffa07a',
  20989. 'lightseagreen': '#20b2aa',
  20990. 'lightskyblue': '#87cefa',
  20991. 'lightslategray': '#778899',
  20992. 'lightslategrey': '#778899',
  20993. 'lightsteelblue': '#b0c4de',
  20994. 'lightyellow': '#ffffe0',
  20995. 'lime': '#00ff00',
  20996. 'limegreen': '#32cd32',
  20997. 'linen': '#faf0e6',
  20998. 'magenta': '#ff00ff',
  20999. 'maroon': '#800000',
  21000. 'mediumaquamarine': '#66cdaa',
  21001. 'mediumblue': '#0000cd',
  21002. 'mediumorchid': '#ba55d3',
  21003. 'mediumpurple': '#9370db',
  21004. 'mediumseagreen': '#3cb371',
  21005. 'mediumslateblue': '#7b68ee',
  21006. 'mediumspringgreen': '#00fa9a',
  21007. 'mediumturquoise': '#48d1cc',
  21008. 'mediumvioletred': '#c71585',
  21009. 'midnightblue': '#191970',
  21010. 'mintcream': '#f5fffa',
  21011. 'mistyrose': '#ffe4e1',
  21012. 'moccasin': '#ffe4b5',
  21013. 'navajowhite': '#ffdead',
  21014. 'navy': '#000080',
  21015. 'oldlace': '#fdf5e6',
  21016. 'olive': '#808000',
  21017. 'olivedrab': '#6b8e23',
  21018. 'orange': '#ffa500',
  21019. 'orangered': '#ff4500',
  21020. 'orchid': '#da70d6',
  21021. 'palegoldenrod': '#eee8aa',
  21022. 'palegreen': '#98fb98',
  21023. 'paleturquoise': '#afeeee',
  21024. 'palevioletred': '#db7093',
  21025. 'papayawhip': '#ffefd5',
  21026. 'peachpuff': '#ffdab9',
  21027. 'peru': '#cd853f',
  21028. 'pink': '#ffc0cb',
  21029. 'plum': '#dda0dd',
  21030. 'powderblue': '#b0e0e6',
  21031. 'purple': '#800080',
  21032. 'red': '#ff0000',
  21033. 'rosybrown': '#bc8f8f',
  21034. 'royalblue': '#4169e1',
  21035. 'saddlebrown': '#8b4513',
  21036. 'salmon': '#fa8072',
  21037. 'sandybrown': '#f4a460',
  21038. 'seagreen': '#2e8b57',
  21039. 'seashell': '#fff5ee',
  21040. 'sienna': '#a0522d',
  21041. 'silver': '#c0c0c0',
  21042. 'skyblue': '#87ceeb',
  21043. 'slateblue': '#6a5acd',
  21044. 'slategray': '#708090',
  21045. 'slategrey': '#708090',
  21046. 'snow': '#fffafa',
  21047. 'springgreen': '#00ff7f',
  21048. 'steelblue': '#4682b4',
  21049. 'tan': '#d2b48c',
  21050. 'teal': '#008080',
  21051. 'thistle': '#d8bfd8',
  21052. 'tomato': '#ff6347',
  21053. 'turquoise': '#40e0d0',
  21054. 'violet': '#ee82ee',
  21055. 'wheat': '#f5deb3',
  21056. 'white': '#ffffff',
  21057. 'whitesmoke': '#f5f5f5',
  21058. 'yellow': '#ffff00',
  21059. 'yellowgreen': '#9acd32'
  21060. };
  21061. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  21062. //
  21063. // Licensed under the Apache License, Version 2.0 (the "License");
  21064. // you may not use this file except in compliance with the License.
  21065. // You may obtain a copy of the License at
  21066. //
  21067. // http://www.apache.org/licenses/LICENSE-2.0
  21068. //
  21069. // Unless required by applicable law or agreed to in writing, software
  21070. // distributed under the License is distributed on an "AS-IS" BASIS,
  21071. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21072. // See the License for the specific language governing permissions and
  21073. // limitations under the License.
  21074. /**
  21075. * @fileoverview Utilities related to color and color conversion.
  21076. */
  21077. goog.provide('goog.color');
  21078. goog.provide('goog.color.Hsl');
  21079. goog.provide('goog.color.Hsv');
  21080. goog.provide('goog.color.Rgb');
  21081. goog.require('goog.color.names');
  21082. goog.require('goog.math');
  21083. /**
  21084. * RGB color representation. An array containing three elements [r, g, b],
  21085. * each an integer in [0, 255], representing the red, green, and blue components
  21086. * of the color respectively.
  21087. * @typedef {Array<number>}
  21088. */
  21089. goog.color.Rgb;
  21090. /**
  21091. * HSV color representation. An array containing three elements [h, s, v]:
  21092. * h (hue) must be an integer in [0, 360], cyclic.
  21093. * s (saturation) must be a number in [0, 1].
  21094. * v (value/brightness) must be an integer in [0, 255].
  21095. * @typedef {Array<number>}
  21096. */
  21097. goog.color.Hsv;
  21098. /**
  21099. * HSL color representation. An array containing three elements [h, s, l]:
  21100. * h (hue) must be an integer in [0, 360], cyclic.
  21101. * s (saturation) must be a number in [0, 1].
  21102. * l (lightness) must be a number in [0, 1].
  21103. * @typedef {Array<number>}
  21104. */
  21105. goog.color.Hsl;
  21106. /**
  21107. * Parses a color out of a string.
  21108. * @param {string} str Color in some format.
  21109. * @return {{hex: string, type: string}} 'hex' is a string containing a hex
  21110. * representation of the color, 'type' is a string containing the type
  21111. * of color format passed in ('hex', 'rgb', 'named').
  21112. */
  21113. goog.color.parse = function(str) {
  21114. var result = {};
  21115. str = String(str);
  21116. var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
  21117. if (goog.color.isValidHexColor_(maybeHex)) {
  21118. result.hex = goog.color.normalizeHex(maybeHex);
  21119. result.type = 'hex';
  21120. return result;
  21121. } else {
  21122. var rgb = goog.color.isValidRgbColor_(str);
  21123. if (rgb.length) {
  21124. result.hex = goog.color.rgbArrayToHex(rgb);
  21125. result.type = 'rgb';
  21126. return result;
  21127. } else if (goog.color.names) {
  21128. var hex = goog.color.names[str.toLowerCase()];
  21129. if (hex) {
  21130. result.hex = hex;
  21131. result.type = 'named';
  21132. return result;
  21133. }
  21134. }
  21135. }
  21136. throw Error(str + ' is not a valid color string');
  21137. };
  21138. /**
  21139. * Determines if the given string can be parsed as a color.
  21140. * {@see goog.color.parse}.
  21141. * @param {string} str Potential color string.
  21142. * @return {boolean} True if str is in a format that can be parsed to a color.
  21143. */
  21144. goog.color.isValidColor = function(str) {
  21145. var maybeHex = goog.color.prependHashIfNecessaryHelper(str);
  21146. return !!(goog.color.isValidHexColor_(maybeHex) ||
  21147. goog.color.isValidRgbColor_(str).length ||
  21148. goog.color.names && goog.color.names[str.toLowerCase()]);
  21149. };
  21150. /**
  21151. * Parses red, green, blue components out of a valid rgb color string.
  21152. * Throws Error if the color string is invalid.
  21153. * @param {string} str RGB representation of a color.
  21154. * {@see goog.color.isValidRgbColor_}.
  21155. * @return {!goog.color.Rgb} rgb representation of the color.
  21156. */
  21157. goog.color.parseRgb = function(str) {
  21158. var rgb = goog.color.isValidRgbColor_(str);
  21159. if (!rgb.length) {
  21160. throw Error(str + ' is not a valid RGB color');
  21161. }
  21162. return rgb;
  21163. };
  21164. /**
  21165. * Converts a hex representation of a color to RGB.
  21166. * @param {string} hexColor Color to convert.
  21167. * @return {string} string of the form 'rgb(R,G,B)' which can be used in
  21168. * styles.
  21169. */
  21170. goog.color.hexToRgbStyle = function(hexColor) {
  21171. return goog.color.rgbStyle_(goog.color.hexToRgb(hexColor));
  21172. };
  21173. /**
  21174. * Regular expression for extracting the digits in a hex color triplet.
  21175. * @type {RegExp}
  21176. * @private
  21177. */
  21178. goog.color.hexTripletRe_ = /#(.)(.)(.)/;
  21179. /**
  21180. * Normalize an hex representation of a color
  21181. * @param {string} hexColor an hex color string.
  21182. * @return {string} hex color in the format '#rrggbb' with all lowercase
  21183. * literals.
  21184. */
  21185. goog.color.normalizeHex = function(hexColor) {
  21186. if (!goog.color.isValidHexColor_(hexColor)) {
  21187. throw Error("'" + hexColor + "' is not a valid hex color");
  21188. }
  21189. if (hexColor.length == 4) { // of the form #RGB
  21190. hexColor = hexColor.replace(goog.color.hexTripletRe_, '#$1$1$2$2$3$3');
  21191. }
  21192. return hexColor.toLowerCase();
  21193. };
  21194. /**
  21195. * Converts a hex representation of a color to RGB.
  21196. * @param {string} hexColor Color to convert.
  21197. * @return {!goog.color.Rgb} rgb representation of the color.
  21198. */
  21199. goog.color.hexToRgb = function(hexColor) {
  21200. hexColor = goog.color.normalizeHex(hexColor);
  21201. var r = parseInt(hexColor.substr(1, 2), 16);
  21202. var g = parseInt(hexColor.substr(3, 2), 16);
  21203. var b = parseInt(hexColor.substr(5, 2), 16);
  21204. return [r, g, b];
  21205. };
  21206. /**
  21207. * Converts a color from RGB to hex representation.
  21208. * @param {number} r Amount of red, int between 0 and 255.
  21209. * @param {number} g Amount of green, int between 0 and 255.
  21210. * @param {number} b Amount of blue, int between 0 and 255.
  21211. * @return {string} hex representation of the color.
  21212. */
  21213. goog.color.rgbToHex = function(r, g, b) {
  21214. r = Number(r);
  21215. g = Number(g);
  21216. b = Number(b);
  21217. if (isNaN(r) || r < 0 || r > 255 ||
  21218. isNaN(g) || g < 0 || g > 255 ||
  21219. isNaN(b) || b < 0 || b > 255) {
  21220. throw Error('"(' + r + ',' + g + ',' + b + '") is not a valid RGB color');
  21221. }
  21222. var hexR = goog.color.prependZeroIfNecessaryHelper(r.toString(16));
  21223. var hexG = goog.color.prependZeroIfNecessaryHelper(g.toString(16));
  21224. var hexB = goog.color.prependZeroIfNecessaryHelper(b.toString(16));
  21225. return '#' + hexR + hexG + hexB;
  21226. };
  21227. /**
  21228. * Converts a color from RGB to hex representation.
  21229. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21230. * @return {string} hex representation of the color.
  21231. */
  21232. goog.color.rgbArrayToHex = function(rgb) {
  21233. return goog.color.rgbToHex(rgb[0], rgb[1], rgb[2]);
  21234. };
  21235. /**
  21236. * Converts a color from RGB color space to HSL color space.
  21237. * Modified from {@link http://en.wikipedia.org/wiki/HLS_color_space}.
  21238. * @param {number} r Value of red, in [0, 255].
  21239. * @param {number} g Value of green, in [0, 255].
  21240. * @param {number} b Value of blue, in [0, 255].
  21241. * @return {!goog.color.Hsl} hsl representation of the color.
  21242. */
  21243. goog.color.rgbToHsl = function(r, g, b) {
  21244. // First must normalize r, g, b to be between 0 and 1.
  21245. var normR = r / 255;
  21246. var normG = g / 255;
  21247. var normB = b / 255;
  21248. var max = Math.max(normR, normG, normB);
  21249. var min = Math.min(normR, normG, normB);
  21250. var h = 0;
  21251. var s = 0;
  21252. // Luminosity is the average of the max and min rgb color intensities.
  21253. var l = 0.5 * (max + min);
  21254. // The hue and saturation are dependent on which color intensity is the max.
  21255. // If max and min are equal, the color is gray and h and s should be 0.
  21256. if (max != min) {
  21257. if (max == normR) {
  21258. h = 60 * (normG - normB) / (max - min);
  21259. } else if (max == normG) {
  21260. h = 60 * (normB - normR) / (max - min) + 120;
  21261. } else if (max == normB) {
  21262. h = 60 * (normR - normG) / (max - min) + 240;
  21263. }
  21264. if (0 < l && l <= 0.5) {
  21265. s = (max - min) / (2 * l);
  21266. } else {
  21267. s = (max - min) / (2 - 2 * l);
  21268. }
  21269. }
  21270. // Make sure the hue falls between 0 and 360.
  21271. return [Math.round(h + 360) % 360, s, l];
  21272. };
  21273. /**
  21274. * Converts a color from RGB color space to HSL color space.
  21275. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21276. * @return {!goog.color.Hsl} hsl representation of the color.
  21277. */
  21278. goog.color.rgbArrayToHsl = function(rgb) {
  21279. return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
  21280. };
  21281. /**
  21282. * Helper for hslToRgb.
  21283. * @param {number} v1 Helper variable 1.
  21284. * @param {number} v2 Helper variable 2.
  21285. * @param {number} vH Helper variable 3.
  21286. * @return {number} Appropriate RGB value, given the above.
  21287. * @private
  21288. */
  21289. goog.color.hueToRgb_ = function(v1, v2, vH) {
  21290. if (vH < 0) {
  21291. vH += 1;
  21292. } else if (vH > 1) {
  21293. vH -= 1;
  21294. }
  21295. if ((6 * vH) < 1) {
  21296. return (v1 + (v2 - v1) * 6 * vH);
  21297. } else if (2 * vH < 1) {
  21298. return v2;
  21299. } else if (3 * vH < 2) {
  21300. return (v1 + (v2 - v1) * ((2 / 3) - vH) * 6);
  21301. }
  21302. return v1;
  21303. };
  21304. /**
  21305. * Converts a color from HSL color space to RGB color space.
  21306. * Modified from {@link http://www.easyrgb.com/math.html}
  21307. * @param {number} h Hue, in [0, 360].
  21308. * @param {number} s Saturation, in [0, 1].
  21309. * @param {number} l Luminosity, in [0, 1].
  21310. * @return {!goog.color.Rgb} rgb representation of the color.
  21311. */
  21312. goog.color.hslToRgb = function(h, s, l) {
  21313. var r = 0;
  21314. var g = 0;
  21315. var b = 0;
  21316. var normH = h / 360; // normalize h to fall in [0, 1]
  21317. if (s == 0) {
  21318. r = g = b = l * 255;
  21319. } else {
  21320. var temp1 = 0;
  21321. var temp2 = 0;
  21322. if (l < 0.5) {
  21323. temp2 = l * (1 + s);
  21324. } else {
  21325. temp2 = l + s - (s * l);
  21326. }
  21327. temp1 = 2 * l - temp2;
  21328. r = 255 * goog.color.hueToRgb_(temp1, temp2, normH + (1 / 3));
  21329. g = 255 * goog.color.hueToRgb_(temp1, temp2, normH);
  21330. b = 255 * goog.color.hueToRgb_(temp1, temp2, normH - (1 / 3));
  21331. }
  21332. return [Math.round(r), Math.round(g), Math.round(b)];
  21333. };
  21334. /**
  21335. * Converts a color from HSL color space to RGB color space.
  21336. * @param {goog.color.Hsl} hsl hsl representation of the color.
  21337. * @return {!goog.color.Rgb} rgb representation of the color.
  21338. */
  21339. goog.color.hslArrayToRgb = function(hsl) {
  21340. return goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]);
  21341. };
  21342. /**
  21343. * Helper for isValidHexColor_.
  21344. * @type {RegExp}
  21345. * @private
  21346. */
  21347. goog.color.validHexColorRe_ = /^#(?:[0-9a-f]{3}){1,2}$/i;
  21348. /**
  21349. * Checks if a string is a valid hex color. We expect strings of the format
  21350. * #RRGGBB (ex: #1b3d5f) or #RGB (ex: #3CA == #33CCAA).
  21351. * @param {string} str String to check.
  21352. * @return {boolean} Whether the string is a valid hex color.
  21353. * @private
  21354. */
  21355. goog.color.isValidHexColor_ = function(str) {
  21356. return goog.color.validHexColorRe_.test(str);
  21357. };
  21358. /**
  21359. * Helper for isNormalizedHexColor_.
  21360. * @type {RegExp}
  21361. * @private
  21362. */
  21363. goog.color.normalizedHexColorRe_ = /^#[0-9a-f]{6}$/;
  21364. /**
  21365. * Checks if a string is a normalized hex color.
  21366. * We expect strings of the format #RRGGBB (ex: #1b3d5f)
  21367. * using only lowercase letters.
  21368. * @param {string} str String to check.
  21369. * @return {boolean} Whether the string is a normalized hex color.
  21370. * @private
  21371. */
  21372. goog.color.isNormalizedHexColor_ = function(str) {
  21373. return goog.color.normalizedHexColorRe_.test(str);
  21374. };
  21375. /**
  21376. * Regular expression for matching and capturing RGB style strings. Helper for
  21377. * isValidRgbColor_.
  21378. * @type {RegExp}
  21379. * @private
  21380. */
  21381. goog.color.rgbColorRe_ =
  21382. /^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;
  21383. /**
  21384. * Checks if a string is a valid rgb color. We expect strings of the format
  21385. * '(r, g, b)', or 'rgb(r, g, b)', where each color component is an int in
  21386. * [0, 255].
  21387. * @param {string} str String to check.
  21388. * @return {!goog.color.Rgb} the rgb representation of the color if it is
  21389. * a valid color, or the empty array otherwise.
  21390. * @private
  21391. */
  21392. goog.color.isValidRgbColor_ = function(str) {
  21393. // Each component is separate (rather than using a repeater) so we can
  21394. // capture the match. Also, we explicitly set each component to be either 0,
  21395. // or start with a non-zero, to prevent octal numbers from slipping through.
  21396. var regExpResultArray = str.match(goog.color.rgbColorRe_);
  21397. if (regExpResultArray) {
  21398. var r = Number(regExpResultArray[1]);
  21399. var g = Number(regExpResultArray[2]);
  21400. var b = Number(regExpResultArray[3]);
  21401. if (r >= 0 && r <= 255 &&
  21402. g >= 0 && g <= 255 &&
  21403. b >= 0 && b <= 255) {
  21404. return [r, g, b];
  21405. }
  21406. }
  21407. return [];
  21408. };
  21409. /**
  21410. * Takes a hex value and prepends a zero if it's a single digit.
  21411. * Small helper method for use by goog.color and friends.
  21412. * @param {string} hex Hex value to prepend if single digit.
  21413. * @return {string} hex value prepended with zero if it was single digit,
  21414. * otherwise the same value that was passed in.
  21415. */
  21416. goog.color.prependZeroIfNecessaryHelper = function(hex) {
  21417. return hex.length == 1 ? '0' + hex : hex;
  21418. };
  21419. /**
  21420. * Takes a string a prepends a '#' sign if one doesn't exist.
  21421. * Small helper method for use by goog.color and friends.
  21422. * @param {string} str String to check.
  21423. * @return {string} The value passed in, prepended with a '#' if it didn't
  21424. * already have one.
  21425. */
  21426. goog.color.prependHashIfNecessaryHelper = function(str) {
  21427. return str.charAt(0) == '#' ? str : '#' + str;
  21428. };
  21429. /**
  21430. * Takes an array of [r, g, b] and converts it into a string appropriate for
  21431. * CSS styles.
  21432. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21433. * @return {string} string of the form 'rgb(r,g,b)'.
  21434. * @private
  21435. */
  21436. goog.color.rgbStyle_ = function(rgb) {
  21437. return 'rgb(' + rgb.join(',') + ')';
  21438. };
  21439. /**
  21440. * Converts an HSV triplet to an RGB array. V is brightness because b is
  21441. * reserved for blue in RGB.
  21442. * @param {number} h Hue value in [0, 360].
  21443. * @param {number} s Saturation value in [0, 1].
  21444. * @param {number} brightness brightness in [0, 255].
  21445. * @return {!goog.color.Rgb} rgb representation of the color.
  21446. */
  21447. goog.color.hsvToRgb = function(h, s, brightness) {
  21448. var red = 0;
  21449. var green = 0;
  21450. var blue = 0;
  21451. if (s == 0) {
  21452. red = brightness;
  21453. green = brightness;
  21454. blue = brightness;
  21455. } else {
  21456. var sextant = Math.floor(h / 60);
  21457. var remainder = (h / 60) - sextant;
  21458. var val1 = brightness * (1 - s);
  21459. var val2 = brightness * (1 - (s * remainder));
  21460. var val3 = brightness * (1 - (s * (1 - remainder)));
  21461. switch (sextant) {
  21462. case 1:
  21463. red = val2;
  21464. green = brightness;
  21465. blue = val1;
  21466. break;
  21467. case 2:
  21468. red = val1;
  21469. green = brightness;
  21470. blue = val3;
  21471. break;
  21472. case 3:
  21473. red = val1;
  21474. green = val2;
  21475. blue = brightness;
  21476. break;
  21477. case 4:
  21478. red = val3;
  21479. green = val1;
  21480. blue = brightness;
  21481. break;
  21482. case 5:
  21483. red = brightness;
  21484. green = val1;
  21485. blue = val2;
  21486. break;
  21487. case 6:
  21488. case 0:
  21489. red = brightness;
  21490. green = val3;
  21491. blue = val1;
  21492. break;
  21493. }
  21494. }
  21495. return [Math.floor(red), Math.floor(green), Math.floor(blue)];
  21496. };
  21497. /**
  21498. * Converts from RGB values to an array of HSV values.
  21499. * @param {number} red Red value in [0, 255].
  21500. * @param {number} green Green value in [0, 255].
  21501. * @param {number} blue Blue value in [0, 255].
  21502. * @return {!goog.color.Hsv} hsv representation of the color.
  21503. */
  21504. goog.color.rgbToHsv = function(red, green, blue) {
  21505. var max = Math.max(Math.max(red, green), blue);
  21506. var min = Math.min(Math.min(red, green), blue);
  21507. var hue;
  21508. var saturation;
  21509. var value = max;
  21510. if (min == max) {
  21511. hue = 0;
  21512. saturation = 0;
  21513. } else {
  21514. var delta = (max - min);
  21515. saturation = delta / max;
  21516. if (red == max) {
  21517. hue = (green - blue) / delta;
  21518. } else if (green == max) {
  21519. hue = 2 + ((blue - red) / delta);
  21520. } else {
  21521. hue = 4 + ((red - green) / delta);
  21522. }
  21523. hue *= 60;
  21524. if (hue < 0) {
  21525. hue += 360;
  21526. }
  21527. if (hue > 360) {
  21528. hue -= 360;
  21529. }
  21530. }
  21531. return [hue, saturation, value];
  21532. };
  21533. /**
  21534. * Converts from an array of RGB values to an array of HSV values.
  21535. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21536. * @return {!goog.color.Hsv} hsv representation of the color.
  21537. */
  21538. goog.color.rgbArrayToHsv = function(rgb) {
  21539. return goog.color.rgbToHsv(rgb[0], rgb[1], rgb[2]);
  21540. };
  21541. /**
  21542. * Converts an HSV triplet to an RGB array.
  21543. * @param {goog.color.Hsv} hsv hsv representation of the color.
  21544. * @return {!goog.color.Rgb} rgb representation of the color.
  21545. */
  21546. goog.color.hsvArrayToRgb = function(hsv) {
  21547. return goog.color.hsvToRgb(hsv[0], hsv[1], hsv[2]);
  21548. };
  21549. /**
  21550. * Converts a hex representation of a color to HSL.
  21551. * @param {string} hex Color to convert.
  21552. * @return {!goog.color.Hsv} hsv representation of the color.
  21553. */
  21554. goog.color.hexToHsl = function(hex) {
  21555. var rgb = goog.color.hexToRgb(hex);
  21556. return goog.color.rgbToHsl(rgb[0], rgb[1], rgb[2]);
  21557. };
  21558. /**
  21559. * Converts from h,s,l values to a hex string
  21560. * @param {number} h Hue, in [0, 360].
  21561. * @param {number} s Saturation, in [0, 1].
  21562. * @param {number} l Luminosity, in [0, 1].
  21563. * @return {string} hex representation of the color.
  21564. */
  21565. goog.color.hslToHex = function(h, s, l) {
  21566. return goog.color.rgbArrayToHex(goog.color.hslToRgb(h, s, l));
  21567. };
  21568. /**
  21569. * Converts from an hsl array to a hex string
  21570. * @param {goog.color.Hsl} hsl hsl representation of the color.
  21571. * @return {string} hex representation of the color.
  21572. */
  21573. goog.color.hslArrayToHex = function(hsl) {
  21574. return goog.color.rgbArrayToHex(goog.color.hslToRgb(hsl[0], hsl[1], hsl[2]));
  21575. };
  21576. /**
  21577. * Converts a hex representation of a color to HSV
  21578. * @param {string} hex Color to convert.
  21579. * @return {!goog.color.Hsv} hsv representation of the color.
  21580. */
  21581. goog.color.hexToHsv = function(hex) {
  21582. return goog.color.rgbArrayToHsv(goog.color.hexToRgb(hex));
  21583. };
  21584. /**
  21585. * Converts from h,s,v values to a hex string
  21586. * @param {number} h Hue, in [0, 360].
  21587. * @param {number} s Saturation, in [0, 1].
  21588. * @param {number} v Value, in [0, 255].
  21589. * @return {string} hex representation of the color.
  21590. */
  21591. goog.color.hsvToHex = function(h, s, v) {
  21592. return goog.color.rgbArrayToHex(goog.color.hsvToRgb(h, s, v));
  21593. };
  21594. /**
  21595. * Converts from an HSV array to a hex string
  21596. * @param {goog.color.Hsv} hsv hsv representation of the color.
  21597. * @return {string} hex representation of the color.
  21598. */
  21599. goog.color.hsvArrayToHex = function(hsv) {
  21600. return goog.color.hsvToHex(hsv[0], hsv[1], hsv[2]);
  21601. };
  21602. /**
  21603. * Calculates the Euclidean distance between two color vectors on an HSL sphere.
  21604. * A demo of the sphere can be found at:
  21605. * http://en.wikipedia.org/wiki/HSL_color_space
  21606. * In short, a vector for color (H, S, L) in this system can be expressed as
  21607. * (S*L'*cos(2*PI*H), S*L'*sin(2*PI*H), L), where L' = abs(L - 0.5), and we
  21608. * simply calculate the 1-2 distance using these coordinates
  21609. * @param {goog.color.Hsl} hsl1 First color in hsl representation.
  21610. * @param {goog.color.Hsl} hsl2 Second color in hsl representation.
  21611. * @return {number} Distance between the two colors, in the range [0, 1].
  21612. */
  21613. goog.color.hslDistance = function(hsl1, hsl2) {
  21614. var sl1, sl2;
  21615. if (hsl1[2] <= 0.5) {
  21616. sl1 = hsl1[1] * hsl1[2];
  21617. } else {
  21618. sl1 = hsl1[1] * (1.0 - hsl1[2]);
  21619. }
  21620. if (hsl2[2] <= 0.5) {
  21621. sl2 = hsl2[1] * hsl2[2];
  21622. } else {
  21623. sl2 = hsl2[1] * (1.0 - hsl2[2]);
  21624. }
  21625. var h1 = hsl1[0] / 360.0;
  21626. var h2 = hsl2[0] / 360.0;
  21627. var dh = (h1 - h2) * 2.0 * Math.PI;
  21628. return (hsl1[2] - hsl2[2]) * (hsl1[2] - hsl2[2]) +
  21629. sl1 * sl1 + sl2 * sl2 - 2 * sl1 * sl2 * Math.cos(dh);
  21630. };
  21631. /**
  21632. * Blend two colors together, using the specified factor to indicate the weight
  21633. * given to the first color
  21634. * @param {goog.color.Rgb} rgb1 First color represented in rgb.
  21635. * @param {goog.color.Rgb} rgb2 Second color represented in rgb.
  21636. * @param {number} factor The weight to be given to rgb1 over rgb2. Values
  21637. * should be in the range [0, 1]. If less than 0, factor will be set to 0.
  21638. * If greater than 1, factor will be set to 1.
  21639. * @return {!goog.color.Rgb} Combined color represented in rgb.
  21640. */
  21641. goog.color.blend = function(rgb1, rgb2, factor) {
  21642. factor = goog.math.clamp(factor, 0, 1);
  21643. return [
  21644. Math.round(factor * rgb1[0] + (1.0 - factor) * rgb2[0]),
  21645. Math.round(factor * rgb1[1] + (1.0 - factor) * rgb2[1]),
  21646. Math.round(factor * rgb1[2] + (1.0 - factor) * rgb2[2])
  21647. ];
  21648. };
  21649. /**
  21650. * Adds black to the specified color, darkening it
  21651. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21652. * @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
  21653. * 1 will return black. If less than 0, factor will be set to 0. If greater
  21654. * than 1, factor will be set to 1.
  21655. * @return {!goog.color.Rgb} Combined rgb color.
  21656. */
  21657. goog.color.darken = function(rgb, factor) {
  21658. var black = [0, 0, 0];
  21659. return goog.color.blend(black, rgb, factor);
  21660. };
  21661. /**
  21662. * Adds white to the specified color, lightening it
  21663. * @param {goog.color.Rgb} rgb rgb representation of the color.
  21664. * @param {number} factor Number in the range [0, 1]. 0 will do nothing, while
  21665. * 1 will return white. If less than 0, factor will be set to 0. If greater
  21666. * than 1, factor will be set to 1.
  21667. * @return {!goog.color.Rgb} Combined rgb color.
  21668. */
  21669. goog.color.lighten = function(rgb, factor) {
  21670. var white = [255, 255, 255];
  21671. return goog.color.blend(white, rgb, factor);
  21672. };
  21673. /**
  21674. * Find the "best" (highest-contrast) of the suggested colors for the prime
  21675. * color. Uses W3C formula for judging readability and visual accessibility:
  21676. * http://www.w3.org/TR/AERT#color-contrast
  21677. * @param {goog.color.Rgb} prime Color represented as a rgb array.
  21678. * @param {Array<goog.color.Rgb>} suggestions Array of colors,
  21679. * each representing a rgb array.
  21680. * @return {!goog.color.Rgb} Highest-contrast color represented by an array..
  21681. */
  21682. goog.color.highContrast = function(prime, suggestions) {
  21683. var suggestionsWithDiff = [];
  21684. for (var i = 0; i < suggestions.length; i++) {
  21685. suggestionsWithDiff.push({
  21686. color: suggestions[i],
  21687. diff: goog.color.yiqBrightnessDiff_(suggestions[i], prime) +
  21688. goog.color.colorDiff_(suggestions[i], prime)
  21689. });
  21690. }
  21691. suggestionsWithDiff.sort(function(a, b) {
  21692. return b.diff - a.diff;
  21693. });
  21694. return suggestionsWithDiff[0].color;
  21695. };
  21696. /**
  21697. * Calculate brightness of a color according to YIQ formula (brightness is Y).
  21698. * More info on YIQ here: http://en.wikipedia.org/wiki/YIQ. Helper method for
  21699. * goog.color.highContrast()
  21700. * @param {goog.color.Rgb} rgb Color represented by a rgb array.
  21701. * @return {number} brightness (Y).
  21702. * @private
  21703. */
  21704. goog.color.yiqBrightness_ = function(rgb) {
  21705. return Math.round((rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000);
  21706. };
  21707. /**
  21708. * Calculate difference in brightness of two colors. Helper method for
  21709. * goog.color.highContrast()
  21710. * @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
  21711. * @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
  21712. * @return {number} Brightness difference.
  21713. * @private
  21714. */
  21715. goog.color.yiqBrightnessDiff_ = function(rgb1, rgb2) {
  21716. return Math.abs(goog.color.yiqBrightness_(rgb1) -
  21717. goog.color.yiqBrightness_(rgb2));
  21718. };
  21719. /**
  21720. * Calculate color difference between two colors. Helper method for
  21721. * goog.color.highContrast()
  21722. * @param {goog.color.Rgb} rgb1 Color represented by a rgb array.
  21723. * @param {goog.color.Rgb} rgb2 Color represented by a rgb array.
  21724. * @return {number} Color difference.
  21725. * @private
  21726. */
  21727. goog.color.colorDiff_ = function(rgb1, rgb2) {
  21728. return Math.abs(rgb1[0] - rgb2[0]) + Math.abs(rgb1[1] - rgb2[1]) +
  21729. Math.abs(rgb1[2] - rgb2[2]);
  21730. };
  21731. // We can't use goog.color or goog.color.alpha because they interally use a hex
  21732. // string representation that encodes each channel in a single byte. This
  21733. // causes occasional loss of precision and rounding errors, especially in the
  21734. // alpha channel.
  21735. goog.provide('ol.Color');
  21736. goog.provide('ol.color');
  21737. goog.require('goog.asserts');
  21738. goog.require('goog.color');
  21739. goog.require('goog.color.names');
  21740. goog.require('goog.vec.Mat4');
  21741. goog.require('ol');
  21742. goog.require('ol.math');
  21743. /**
  21744. * A color represented as a short array [red, green, blue, alpha].
  21745. * red, green, and blue should be integers in the range 0..255 inclusive.
  21746. * alpha should be a float in the range 0..1 inclusive.
  21747. * @typedef {Array.<number>}
  21748. * @api
  21749. */
  21750. ol.Color;
  21751. /**
  21752. * This RegExp matches # followed by 3 or 6 hex digits.
  21753. * @const
  21754. * @type {RegExp}
  21755. * @private
  21756. */
  21757. ol.color.hexColorRe_ = /^#(?:[0-9a-f]{3}){1,2}$/i;
  21758. /**
  21759. * @see goog.color.rgbColorRe_
  21760. * @const
  21761. * @type {RegExp}
  21762. * @private
  21763. */
  21764. ol.color.rgbColorRe_ =
  21765. /^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;
  21766. /**
  21767. * @see goog.color.alpha.rgbaColorRe_
  21768. * @const
  21769. * @type {RegExp}
  21770. * @private
  21771. */
  21772. ol.color.rgbaColorRe_ =
  21773. /^(?:rgba)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|1|0\.\d{0,10})\)$/i;
  21774. /**
  21775. * @param {ol.Color} dst Destination.
  21776. * @param {ol.Color} src Source.
  21777. * @param {ol.Color=} opt_color Color.
  21778. * @return {ol.Color} Color.
  21779. */
  21780. ol.color.blend = function(dst, src, opt_color) {
  21781. // http://en.wikipedia.org/wiki/Alpha_compositing
  21782. // FIXME do we need to scale by 255?
  21783. var out = opt_color ? opt_color : [];
  21784. var dstA = dst[3];
  21785. var srcA = src[3];
  21786. if (dstA == 1) {
  21787. out[0] = (src[0] * srcA + dst[0] * (1 - srcA) + 0.5) | 0;
  21788. out[1] = (src[1] * srcA + dst[1] * (1 - srcA) + 0.5) | 0;
  21789. out[2] = (src[2] * srcA + dst[2] * (1 - srcA) + 0.5) | 0;
  21790. out[3] = 1;
  21791. } else if (srcA === 0) {
  21792. out[0] = dst[0];
  21793. out[1] = dst[1];
  21794. out[2] = dst[2];
  21795. out[3] = dstA;
  21796. } else {
  21797. var outA = srcA + dstA * (1 - srcA);
  21798. if (outA === 0) {
  21799. out[0] = 0;
  21800. out[1] = 0;
  21801. out[2] = 0;
  21802. out[3] = 0;
  21803. } else {
  21804. out[0] = ((src[0] * srcA + dst[0] * dstA * (1 - srcA)) / outA + 0.5) | 0;
  21805. out[1] = ((src[1] * srcA + dst[1] * dstA * (1 - srcA)) / outA + 0.5) | 0;
  21806. out[2] = ((src[2] * srcA + dst[2] * dstA * (1 - srcA)) / outA + 0.5) | 0;
  21807. out[3] = outA;
  21808. }
  21809. }
  21810. goog.asserts.assert(ol.color.isValid(out),
  21811. 'Output color of blend should be a valid color');
  21812. return out;
  21813. };
  21814. /**
  21815. * Return the color as an array. This function maintains a cache of calculated
  21816. * arrays which means the result should not be modified.
  21817. * @param {ol.Color|string} color Color.
  21818. * @return {ol.Color} Color.
  21819. * @api
  21820. */
  21821. ol.color.asArray = function(color) {
  21822. if (goog.isArray(color)) {
  21823. return color;
  21824. } else {
  21825. goog.asserts.assert(goog.isString(color), 'Color should be a string');
  21826. return ol.color.fromString(color);
  21827. }
  21828. };
  21829. /**
  21830. * Return the color as an rgba string.
  21831. * @param {ol.Color|string} color Color.
  21832. * @return {string} Rgba string.
  21833. * @api
  21834. */
  21835. ol.color.asString = function(color) {
  21836. if (goog.isString(color)) {
  21837. return color;
  21838. } else {
  21839. goog.asserts.assert(goog.isArray(color), 'Color should be an array');
  21840. return ol.color.toString(color);
  21841. }
  21842. };
  21843. /**
  21844. * @param {ol.Color} color1 Color1.
  21845. * @param {ol.Color} color2 Color2.
  21846. * @return {boolean} Equals.
  21847. */
  21848. ol.color.equals = function(color1, color2) {
  21849. return color1 === color2 || (
  21850. color1[0] == color2[0] && color1[1] == color2[1] &&
  21851. color1[2] == color2[2] && color1[3] == color2[3]);
  21852. };
  21853. /**
  21854. * @param {string} s String.
  21855. * @return {ol.Color} Color.
  21856. */
  21857. ol.color.fromString = (
  21858. /**
  21859. * @return {function(string): ol.Color}
  21860. */
  21861. function() {
  21862. // We maintain a small cache of parsed strings. To provide cheap LRU-like
  21863. // semantics, whenever the cache grows too large we simply delete an
  21864. // arbitrary 25% of the entries.
  21865. /**
  21866. * @const
  21867. * @type {number}
  21868. */
  21869. var MAX_CACHE_SIZE = 1024;
  21870. /**
  21871. * @type {Object.<string, ol.Color>}
  21872. */
  21873. var cache = {};
  21874. /**
  21875. * @type {number}
  21876. */
  21877. var cacheSize = 0;
  21878. return (
  21879. /**
  21880. * @param {string} s String.
  21881. * @return {ol.Color} Color.
  21882. */
  21883. function(s) {
  21884. var color;
  21885. if (cache.hasOwnProperty(s)) {
  21886. color = cache[s];
  21887. } else {
  21888. if (cacheSize >= MAX_CACHE_SIZE) {
  21889. var i = 0;
  21890. var key;
  21891. for (key in cache) {
  21892. if ((i++ & 3) === 0) {
  21893. delete cache[key];
  21894. --cacheSize;
  21895. }
  21896. }
  21897. }
  21898. color = ol.color.fromStringInternal_(s);
  21899. cache[s] = color;
  21900. ++cacheSize;
  21901. }
  21902. return color;
  21903. });
  21904. })();
  21905. /**
  21906. * @param {string} s String.
  21907. * @private
  21908. * @return {ol.Color} Color.
  21909. */
  21910. ol.color.fromStringInternal_ = function(s) {
  21911. var isHex = false;
  21912. if (ol.ENABLE_NAMED_COLORS && goog.color.names.hasOwnProperty(s)) {
  21913. // goog.color.names does not have a type declaration, so add a typecast
  21914. s = /** @type {string} */ (goog.color.names[s]);
  21915. isHex = true;
  21916. }
  21917. var r, g, b, a, color, match;
  21918. if (isHex || (match = ol.color.hexColorRe_.exec(s))) { // hex
  21919. var n = s.length - 1; // number of hex digits
  21920. goog.asserts.assert(n == 3 || n == 6,
  21921. 'Color string length should be 3 or 6');
  21922. var d = n == 3 ? 1 : 2; // number of digits per channel
  21923. r = parseInt(s.substr(1 + 0 * d, d), 16);
  21924. g = parseInt(s.substr(1 + 1 * d, d), 16);
  21925. b = parseInt(s.substr(1 + 2 * d, d), 16);
  21926. if (d == 1) {
  21927. r = (r << 4) + r;
  21928. g = (g << 4) + g;
  21929. b = (b << 4) + b;
  21930. }
  21931. a = 1;
  21932. color = [r, g, b, a];
  21933. goog.asserts.assert(ol.color.isValid(color),
  21934. 'Color should be a valid color');
  21935. return color;
  21936. } else if ((match = ol.color.rgbaColorRe_.exec(s))) { // rgba()
  21937. r = Number(match[1]);
  21938. g = Number(match[2]);
  21939. b = Number(match[3]);
  21940. a = Number(match[4]);
  21941. color = [r, g, b, a];
  21942. return ol.color.normalize(color, color);
  21943. } else if ((match = ol.color.rgbColorRe_.exec(s))) { // rgb()
  21944. r = Number(match[1]);
  21945. g = Number(match[2]);
  21946. b = Number(match[3]);
  21947. color = [r, g, b, 1];
  21948. return ol.color.normalize(color, color);
  21949. } else {
  21950. goog.asserts.fail(s + ' is not a valid color');
  21951. }
  21952. };
  21953. /**
  21954. * @param {ol.Color} color Color.
  21955. * @return {boolean} Is valid.
  21956. */
  21957. ol.color.isValid = function(color) {
  21958. return 0 <= color[0] && color[0] < 256 &&
  21959. 0 <= color[1] && color[1] < 256 &&
  21960. 0 <= color[2] && color[2] < 256 &&
  21961. 0 <= color[3] && color[3] <= 1;
  21962. };
  21963. /**
  21964. * @param {ol.Color} color Color.
  21965. * @param {ol.Color=} opt_color Color.
  21966. * @return {ol.Color} Clamped color.
  21967. */
  21968. ol.color.normalize = function(color, opt_color) {
  21969. var result = opt_color || [];
  21970. result[0] = ol.math.clamp((color[0] + 0.5) | 0, 0, 255);
  21971. result[1] = ol.math.clamp((color[1] + 0.5) | 0, 0, 255);
  21972. result[2] = ol.math.clamp((color[2] + 0.5) | 0, 0, 255);
  21973. result[3] = ol.math.clamp(color[3], 0, 1);
  21974. return result;
  21975. };
  21976. /**
  21977. * @param {ol.Color} color Color.
  21978. * @return {string} String.
  21979. */
  21980. ol.color.toString = function(color) {
  21981. var r = color[0];
  21982. if (r != (r | 0)) {
  21983. r = (r + 0.5) | 0;
  21984. }
  21985. var g = color[1];
  21986. if (g != (g | 0)) {
  21987. g = (g + 0.5) | 0;
  21988. }
  21989. var b = color[2];
  21990. if (b != (b | 0)) {
  21991. b = (b + 0.5) | 0;
  21992. }
  21993. var a = color[3];
  21994. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  21995. };
  21996. /**
  21997. * @param {!ol.Color} color Color.
  21998. * @param {goog.vec.Mat4.Number} transform Transform.
  21999. * @param {!ol.Color=} opt_color Color.
  22000. * @return {ol.Color} Transformed color.
  22001. */
  22002. ol.color.transform = function(color, transform, opt_color) {
  22003. var result = opt_color ? opt_color : [];
  22004. result = goog.vec.Mat4.multVec3(transform, color, result);
  22005. goog.asserts.assert(goog.isArray(result), 'result should be an array');
  22006. result[3] = color[3];
  22007. return ol.color.normalize(result, result);
  22008. };
  22009. /**
  22010. * @param {ol.Color|string} color1 Color2.
  22011. * @param {ol.Color|string} color2 Color2.
  22012. * @return {boolean} Equals.
  22013. */
  22014. ol.color.stringOrColorEquals = function(color1, color2) {
  22015. if (color1 === color2 || color1 == color2) {
  22016. return true;
  22017. }
  22018. if (goog.isString(color1)) {
  22019. color1 = ol.color.fromString(color1);
  22020. }
  22021. if (goog.isString(color2)) {
  22022. color2 = ol.color.fromString(color2);
  22023. }
  22024. return ol.color.equals(color1, color2);
  22025. };
  22026. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  22027. //
  22028. // Licensed under the Apache License, Version 2.0 (the "License");
  22029. // you may not use this file except in compliance with the License.
  22030. // You may obtain a copy of the License at
  22031. //
  22032. // http://www.apache.org/licenses/LICENSE-2.0
  22033. //
  22034. // Unless required by applicable law or agreed to in writing, software
  22035. // distributed under the License is distributed on an "AS-IS" BASIS,
  22036. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22037. // See the License for the specific language governing permissions and
  22038. // limitations under the License.
  22039. /**
  22040. * @fileoverview Browser capability checks for the dom package.
  22041. *
  22042. */
  22043. goog.provide('goog.dom.BrowserFeature');
  22044. goog.require('goog.userAgent');
  22045. /**
  22046. * Enum of browser capabilities.
  22047. * @enum {boolean}
  22048. */
  22049. goog.dom.BrowserFeature = {
  22050. /**
  22051. * Whether attributes 'name' and 'type' can be added to an element after it's
  22052. * created. False in Internet Explorer prior to version 9.
  22053. */
  22054. CAN_ADD_NAME_OR_TYPE_ATTRIBUTES: !goog.userAgent.IE ||
  22055. goog.userAgent.isDocumentModeOrHigher(9),
  22056. /**
  22057. * Whether we can use element.children to access an element's Element
  22058. * children. Available since Gecko 1.9.1, IE 9. (IE<9 also includes comment
  22059. * nodes in the collection.)
  22060. */
  22061. CAN_USE_CHILDREN_ATTRIBUTE: !goog.userAgent.GECKO && !goog.userAgent.IE ||
  22062. goog.userAgent.IE && goog.userAgent.isDocumentModeOrHigher(9) ||
  22063. goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9.1'),
  22064. /**
  22065. * Opera, Safari 3, and Internet Explorer 9 all support innerText but they
  22066. * include text nodes in script and style tags. Not document-mode-dependent.
  22067. */
  22068. CAN_USE_INNER_TEXT: (
  22069. goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9')),
  22070. /**
  22071. * MSIE, Opera, and Safari>=4 support element.parentElement to access an
  22072. * element's parent if it is an Element.
  22073. */
  22074. CAN_USE_PARENT_ELEMENT_PROPERTY: goog.userAgent.IE || goog.userAgent.OPERA ||
  22075. goog.userAgent.WEBKIT,
  22076. /**
  22077. * Whether NoScope elements need a scoped element written before them in
  22078. * innerHTML.
  22079. * MSDN: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx#1
  22080. */
  22081. INNER_HTML_NEEDS_SCOPED_ELEMENT: goog.userAgent.IE,
  22082. /**
  22083. * Whether we use legacy IE range API.
  22084. */
  22085. LEGACY_IE_RANGES: goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)
  22086. };
  22087. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  22088. //
  22089. // Licensed under the Apache License, Version 2.0 (the "License");
  22090. // you may not use this file except in compliance with the License.
  22091. // You may obtain a copy of the License at
  22092. //
  22093. // http://www.apache.org/licenses/LICENSE-2.0
  22094. //
  22095. // Unless required by applicable law or agreed to in writing, software
  22096. // distributed under the License is distributed on an "AS-IS" BASIS,
  22097. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22098. // See the License for the specific language governing permissions and
  22099. // limitations under the License.
  22100. /**
  22101. * @fileoverview Defines the goog.dom.TagName enum. This enumerates
  22102. * all HTML tag names specified in either the the W3C HTML 4.01 index of
  22103. * elements or the HTML5 draft specification.
  22104. *
  22105. * References:
  22106. * http://www.w3.org/TR/html401/index/elements.html
  22107. * http://dev.w3.org/html5/spec/section-index.html
  22108. *
  22109. */
  22110. goog.provide('goog.dom.TagName');
  22111. /**
  22112. * Enum of all html tag names specified by the W3C HTML4.01 and HTML5
  22113. * specifications.
  22114. * @enum {string}
  22115. */
  22116. goog.dom.TagName = {
  22117. A: 'A',
  22118. ABBR: 'ABBR',
  22119. ACRONYM: 'ACRONYM',
  22120. ADDRESS: 'ADDRESS',
  22121. APPLET: 'APPLET',
  22122. AREA: 'AREA',
  22123. ARTICLE: 'ARTICLE',
  22124. ASIDE: 'ASIDE',
  22125. AUDIO: 'AUDIO',
  22126. B: 'B',
  22127. BASE: 'BASE',
  22128. BASEFONT: 'BASEFONT',
  22129. BDI: 'BDI',
  22130. BDO: 'BDO',
  22131. BIG: 'BIG',
  22132. BLOCKQUOTE: 'BLOCKQUOTE',
  22133. BODY: 'BODY',
  22134. BR: 'BR',
  22135. BUTTON: 'BUTTON',
  22136. CANVAS: 'CANVAS',
  22137. CAPTION: 'CAPTION',
  22138. CENTER: 'CENTER',
  22139. CITE: 'CITE',
  22140. CODE: 'CODE',
  22141. COL: 'COL',
  22142. COLGROUP: 'COLGROUP',
  22143. COMMAND: 'COMMAND',
  22144. DATA: 'DATA',
  22145. DATALIST: 'DATALIST',
  22146. DD: 'DD',
  22147. DEL: 'DEL',
  22148. DETAILS: 'DETAILS',
  22149. DFN: 'DFN',
  22150. DIALOG: 'DIALOG',
  22151. DIR: 'DIR',
  22152. DIV: 'DIV',
  22153. DL: 'DL',
  22154. DT: 'DT',
  22155. EM: 'EM',
  22156. EMBED: 'EMBED',
  22157. FIELDSET: 'FIELDSET',
  22158. FIGCAPTION: 'FIGCAPTION',
  22159. FIGURE: 'FIGURE',
  22160. FONT: 'FONT',
  22161. FOOTER: 'FOOTER',
  22162. FORM: 'FORM',
  22163. FRAME: 'FRAME',
  22164. FRAMESET: 'FRAMESET',
  22165. H1: 'H1',
  22166. H2: 'H2',
  22167. H3: 'H3',
  22168. H4: 'H4',
  22169. H5: 'H5',
  22170. H6: 'H6',
  22171. HEAD: 'HEAD',
  22172. HEADER: 'HEADER',
  22173. HGROUP: 'HGROUP',
  22174. HR: 'HR',
  22175. HTML: 'HTML',
  22176. I: 'I',
  22177. IFRAME: 'IFRAME',
  22178. IMG: 'IMG',
  22179. INPUT: 'INPUT',
  22180. INS: 'INS',
  22181. ISINDEX: 'ISINDEX',
  22182. KBD: 'KBD',
  22183. KEYGEN: 'KEYGEN',
  22184. LABEL: 'LABEL',
  22185. LEGEND: 'LEGEND',
  22186. LI: 'LI',
  22187. LINK: 'LINK',
  22188. MAP: 'MAP',
  22189. MARK: 'MARK',
  22190. MATH: 'MATH',
  22191. MENU: 'MENU',
  22192. META: 'META',
  22193. METER: 'METER',
  22194. NAV: 'NAV',
  22195. NOFRAMES: 'NOFRAMES',
  22196. NOSCRIPT: 'NOSCRIPT',
  22197. OBJECT: 'OBJECT',
  22198. OL: 'OL',
  22199. OPTGROUP: 'OPTGROUP',
  22200. OPTION: 'OPTION',
  22201. OUTPUT: 'OUTPUT',
  22202. P: 'P',
  22203. PARAM: 'PARAM',
  22204. PRE: 'PRE',
  22205. PROGRESS: 'PROGRESS',
  22206. Q: 'Q',
  22207. RP: 'RP',
  22208. RT: 'RT',
  22209. RUBY: 'RUBY',
  22210. S: 'S',
  22211. SAMP: 'SAMP',
  22212. SCRIPT: 'SCRIPT',
  22213. SECTION: 'SECTION',
  22214. SELECT: 'SELECT',
  22215. SMALL: 'SMALL',
  22216. SOURCE: 'SOURCE',
  22217. SPAN: 'SPAN',
  22218. STRIKE: 'STRIKE',
  22219. STRONG: 'STRONG',
  22220. STYLE: 'STYLE',
  22221. SUB: 'SUB',
  22222. SUMMARY: 'SUMMARY',
  22223. SUP: 'SUP',
  22224. SVG: 'SVG',
  22225. TABLE: 'TABLE',
  22226. TBODY: 'TBODY',
  22227. TD: 'TD',
  22228. TEMPLATE: 'TEMPLATE',
  22229. TEXTAREA: 'TEXTAREA',
  22230. TFOOT: 'TFOOT',
  22231. TH: 'TH',
  22232. THEAD: 'THEAD',
  22233. TIME: 'TIME',
  22234. TITLE: 'TITLE',
  22235. TR: 'TR',
  22236. TRACK: 'TRACK',
  22237. TT: 'TT',
  22238. U: 'U',
  22239. UL: 'UL',
  22240. VAR: 'VAR',
  22241. VIDEO: 'VIDEO',
  22242. WBR: 'WBR'
  22243. };
  22244. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  22245. //
  22246. // Licensed under the Apache License, Version 2.0 (the "License");
  22247. // you may not use this file except in compliance with the License.
  22248. // You may obtain a copy of the License at
  22249. //
  22250. // http://www.apache.org/licenses/LICENSE-2.0
  22251. //
  22252. // Unless required by applicable law or agreed to in writing, software
  22253. // distributed under the License is distributed on an "AS-IS" BASIS,
  22254. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22255. // See the License for the specific language governing permissions and
  22256. // limitations under the License.
  22257. /**
  22258. * @fileoverview Utilities for HTML element tag names.
  22259. */
  22260. goog.provide('goog.dom.tags');
  22261. goog.require('goog.object');
  22262. /**
  22263. * The void elements specified by
  22264. * http://www.w3.org/TR/html-markup/syntax.html#void-elements.
  22265. * @const @private {!Object<string, boolean>}
  22266. */
  22267. goog.dom.tags.VOID_TAGS_ = goog.object.createSet(
  22268. 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
  22269. 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr');
  22270. /**
  22271. * Checks whether the tag is void (with no contents allowed and no legal end
  22272. * tag), for example 'br'.
  22273. * @param {string} tagName The tag name in lower case.
  22274. * @return {boolean}
  22275. */
  22276. goog.dom.tags.isVoidTag = function(tagName) {
  22277. return goog.dom.tags.VOID_TAGS_[tagName] === true;
  22278. };
  22279. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  22280. //
  22281. // Licensed under the Apache License, Version 2.0 (the "License");
  22282. // you may not use this file except in compliance with the License.
  22283. // You may obtain a copy of the License at
  22284. //
  22285. // http://www.apache.org/licenses/LICENSE-2.0
  22286. //
  22287. // Unless required by applicable law or agreed to in writing, software
  22288. // distributed under the License is distributed on an "AS-IS" BASIS,
  22289. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22290. // See the License for the specific language governing permissions and
  22291. // limitations under the License.
  22292. goog.provide('goog.string.TypedString');
  22293. /**
  22294. * Wrapper for strings that conform to a data type or language.
  22295. *
  22296. * Implementations of this interface are wrappers for strings, and typically
  22297. * associate a type contract with the wrapped string. Concrete implementations
  22298. * of this interface may choose to implement additional run-time type checking,
  22299. * see for example {@code goog.html.SafeHtml}. If available, client code that
  22300. * needs to ensure type membership of an object should use the type's function
  22301. * to assert type membership, such as {@code goog.html.SafeHtml.unwrap}.
  22302. * @interface
  22303. */
  22304. goog.string.TypedString = function() {};
  22305. /**
  22306. * Interface marker of the TypedString interface.
  22307. *
  22308. * This property can be used to determine at runtime whether or not an object
  22309. * implements this interface. All implementations of this interface set this
  22310. * property to {@code true}.
  22311. * @type {boolean}
  22312. */
  22313. goog.string.TypedString.prototype.implementsGoogStringTypedString;
  22314. /**
  22315. * Retrieves this wrapped string's value.
  22316. * @return {!string} The wrapped string's value.
  22317. */
  22318. goog.string.TypedString.prototype.getTypedStringValue;
  22319. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  22320. //
  22321. // Licensed under the Apache License, Version 2.0 (the "License");
  22322. // you may not use this file except in compliance with the License.
  22323. // You may obtain a copy of the License at
  22324. //
  22325. // http://www.apache.org/licenses/LICENSE-2.0
  22326. //
  22327. // Unless required by applicable law or agreed to in writing, software
  22328. // distributed under the License is distributed on an "AS-IS" BASIS,
  22329. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22330. // See the License for the specific language governing permissions and
  22331. // limitations under the License.
  22332. goog.provide('goog.string.Const');
  22333. goog.require('goog.asserts');
  22334. goog.require('goog.string.TypedString');
  22335. /**
  22336. * Wrapper for compile-time-constant strings.
  22337. *
  22338. * Const is a wrapper for strings that can only be created from program
  22339. * constants (i.e., string literals). This property relies on a custom Closure
  22340. * compiler check that {@code goog.string.Const.from} is only invoked on
  22341. * compile-time-constant expressions.
  22342. *
  22343. * Const is useful in APIs whose correct and secure use requires that certain
  22344. * arguments are not attacker controlled: Compile-time constants are inherently
  22345. * under the control of the application and not under control of external
  22346. * attackers, and hence are safe to use in such contexts.
  22347. *
  22348. * Instances of this type must be created via its factory method
  22349. * {@code goog.string.Const.from} and not by invoking its constructor. The
  22350. * constructor intentionally takes no parameters and the type is immutable;
  22351. * hence only a default instance corresponding to the empty string can be
  22352. * obtained via constructor invocation.
  22353. *
  22354. * @see goog.string.Const#from
  22355. * @constructor
  22356. * @final
  22357. * @struct
  22358. * @implements {goog.string.TypedString}
  22359. */
  22360. goog.string.Const = function() {
  22361. /**
  22362. * The wrapped value of this Const object. The field has a purposely ugly
  22363. * name to make (non-compiled) code that attempts to directly access this
  22364. * field stand out.
  22365. * @private {string}
  22366. */
  22367. this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = '';
  22368. /**
  22369. * A type marker used to implement additional run-time type checking.
  22370. * @see goog.string.Const#unwrap
  22371. * @const
  22372. * @private
  22373. */
  22374. this.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ =
  22375. goog.string.Const.TYPE_MARKER_;
  22376. };
  22377. /**
  22378. * @override
  22379. * @const
  22380. */
  22381. goog.string.Const.prototype.implementsGoogStringTypedString = true;
  22382. /**
  22383. * Returns this Const's value a string.
  22384. *
  22385. * IMPORTANT: In code where it is security-relevant that an object's type is
  22386. * indeed {@code goog.string.Const}, use {@code goog.string.Const.unwrap}
  22387. * instead of this method.
  22388. *
  22389. * @see goog.string.Const#unwrap
  22390. * @override
  22391. */
  22392. goog.string.Const.prototype.getTypedStringValue = function() {
  22393. return this.stringConstValueWithSecurityContract__googStringSecurityPrivate_;
  22394. };
  22395. /**
  22396. * Returns a debug-string representation of this value.
  22397. *
  22398. * To obtain the actual string value wrapped inside an object of this type,
  22399. * use {@code goog.string.Const.unwrap}.
  22400. *
  22401. * @see goog.string.Const#unwrap
  22402. * @override
  22403. */
  22404. goog.string.Const.prototype.toString = function() {
  22405. return 'Const{' +
  22406. this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ +
  22407. '}';
  22408. };
  22409. /**
  22410. * Performs a runtime check that the provided object is indeed an instance
  22411. * of {@code goog.string.Const}, and returns its value.
  22412. * @param {!goog.string.Const} stringConst The object to extract from.
  22413. * @return {string} The Const object's contained string, unless the run-time
  22414. * type check fails. In that case, {@code unwrap} returns an innocuous
  22415. * string, or, if assertions are enabled, throws
  22416. * {@code goog.asserts.AssertionError}.
  22417. */
  22418. goog.string.Const.unwrap = function(stringConst) {
  22419. // Perform additional run-time type-checking to ensure that stringConst is
  22420. // indeed an instance of the expected type. This provides some additional
  22421. // protection against security bugs due to application code that disables type
  22422. // checks.
  22423. if (stringConst instanceof goog.string.Const &&
  22424. stringConst.constructor === goog.string.Const &&
  22425. stringConst.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ ===
  22426. goog.string.Const.TYPE_MARKER_) {
  22427. return stringConst.
  22428. stringConstValueWithSecurityContract__googStringSecurityPrivate_;
  22429. } else {
  22430. goog.asserts.fail('expected object of type Const, got \'' +
  22431. stringConst + '\'');
  22432. return 'type_error:Const';
  22433. }
  22434. };
  22435. /**
  22436. * Creates a Const object from a compile-time constant string.
  22437. *
  22438. * It is illegal to invoke this function on an expression whose
  22439. * compile-time-contant value cannot be determined by the Closure compiler.
  22440. *
  22441. * Correct invocations include,
  22442. * <pre>
  22443. * var s = goog.string.Const.from('hello');
  22444. * var t = goog.string.Const.from('hello' + 'world');
  22445. * </pre>
  22446. *
  22447. * In contrast, the following are illegal:
  22448. * <pre>
  22449. * var s = goog.string.Const.from(getHello());
  22450. * var t = goog.string.Const.from('hello' + world);
  22451. * </pre>
  22452. *
  22453. * TODO(xtof): Compile-time checks that this function is only called
  22454. * with compile-time constant expressions.
  22455. *
  22456. * @param {string} s A constant string from which to create a Const.
  22457. * @return {!goog.string.Const} A Const object initialized to stringConst.
  22458. */
  22459. goog.string.Const.from = function(s) {
  22460. return goog.string.Const.create__googStringSecurityPrivate_(s);
  22461. };
  22462. /**
  22463. * Type marker for the Const type, used to implement additional run-time
  22464. * type checking.
  22465. * @const {!Object}
  22466. * @private
  22467. */
  22468. goog.string.Const.TYPE_MARKER_ = {};
  22469. /**
  22470. * Utility method to create Const instances.
  22471. * @param {string} s The string to initialize the Const object with.
  22472. * @return {!goog.string.Const} The initialized Const object.
  22473. * @private
  22474. */
  22475. goog.string.Const.create__googStringSecurityPrivate_ = function(s) {
  22476. var stringConst = new goog.string.Const();
  22477. stringConst.stringConstValueWithSecurityContract__googStringSecurityPrivate_ =
  22478. s;
  22479. return stringConst;
  22480. };
  22481. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  22482. //
  22483. // Licensed under the Apache License, Version 2.0 (the "License");
  22484. // you may not use this file except in compliance with the License.
  22485. // You may obtain a copy of the License at
  22486. //
  22487. // http://www.apache.org/licenses/LICENSE-2.0
  22488. //
  22489. // Unless required by applicable law or agreed to in writing, software
  22490. // distributed under the License is distributed on an "AS-IS" BASIS,
  22491. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22492. // See the License for the specific language governing permissions and
  22493. // limitations under the License.
  22494. /**
  22495. * @fileoverview The SafeStyle type and its builders.
  22496. *
  22497. * TODO(xtof): Link to document stating type contract.
  22498. */
  22499. goog.provide('goog.html.SafeStyle');
  22500. goog.require('goog.array');
  22501. goog.require('goog.asserts');
  22502. goog.require('goog.string');
  22503. goog.require('goog.string.Const');
  22504. goog.require('goog.string.TypedString');
  22505. /**
  22506. * A string-like object which represents a sequence of CSS declarations
  22507. * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})
  22508. * and that carries the security type contract that its value, as a string,
  22509. * will not cause untrusted script execution (XSS) when evaluated as CSS in a
  22510. * browser.
  22511. *
  22512. * Instances of this type must be created via the factory methods
  22513. * ({@code goog.html.SafeStyle.create} or
  22514. * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its
  22515. * constructor. The constructor intentionally takes no parameters and the type
  22516. * is immutable; hence only a default instance corresponding to the empty string
  22517. * can be obtained via constructor invocation.
  22518. *
  22519. * A SafeStyle's string representation ({@link #getTypedStringValue()}) can
  22520. * safely:
  22521. * <ul>
  22522. * <li>Be interpolated as the entire content of a *quoted* HTML style
  22523. * attribute, or before already existing properties. The SafeStyle string
  22524. * *must be HTML-attribute-escaped* (where " and ' are escaped) before
  22525. * interpolation.
  22526. * <li>Be interpolated as the entire content of a {}-wrapped block within a
  22527. * stylesheet, or before already existing properties. The SafeStyle string
  22528. * should not be escaped before interpolation. SafeStyle's contract also
  22529. * guarantees that the string will not be able to introduce new properties
  22530. * or elide existing ones.
  22531. * <li>Be assigned to the style property of a DOM node. The SafeStyle string
  22532. * should not be escaped before being assigned to the property.
  22533. * </ul>
  22534. *
  22535. * A SafeStyle may never contain literal angle brackets. Otherwise, it could
  22536. * be unsafe to place a SafeStyle into a &lt;style&gt; tag (where it can't
  22537. * be HTML escaped). For example, if the SafeStyle containing
  22538. * "{@code font: 'foo &lt;style/&gt;&lt;script&gt;evil&lt;/script&gt;'}" were
  22539. * interpolated within a &lt;style&gt; tag, this would then break out of the
  22540. * style context into HTML.
  22541. *
  22542. * A SafeStyle may contain literal single or double quotes, and as such the
  22543. * entire style string must be escaped when used in a style attribute (if
  22544. * this were not the case, the string could contain a matching quote that
  22545. * would escape from the style attribute).
  22546. *
  22547. * Values of this type must be composable, i.e. for any two values
  22548. * {@code style1} and {@code style2} of this type,
  22549. * {@code goog.html.SafeStyle.unwrap(style1) +
  22550. * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies
  22551. * the SafeStyle type constraint. This requirement implies that for any value
  22552. * {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must
  22553. * not end in a "property value" or "property name" context. For example,
  22554. * a value of {@code background:url("} or {@code font-} would not satisfy the
  22555. * SafeStyle contract. This is because concatenating such strings with a
  22556. * second value that itself does not contain unsafe CSS can result in an
  22557. * overall string that does. For example, if {@code javascript:evil())"} is
  22558. * appended to {@code background:url("}, the resulting string may result in
  22559. * the execution of a malicious script.
  22560. *
  22561. * TODO(user): Consider whether we should implement UTF-8 interchange
  22562. * validity checks and blacklisting of newlines (including Unicode ones) and
  22563. * other whitespace characters (\t, \f). Document here if so and also update
  22564. * SafeStyle.fromConstant().
  22565. *
  22566. * The following example values comply with this type's contract:
  22567. * <ul>
  22568. * <li><pre>width: 1em;</pre>
  22569. * <li><pre>height:1em;</pre>
  22570. * <li><pre>width: 1em;height: 1em;</pre>
  22571. * <li><pre>background:url('http://url');</pre>
  22572. * </ul>
  22573. * In addition, the empty string is safe for use in a CSS attribute.
  22574. *
  22575. * The following example values do NOT comply with this type's contract:
  22576. * <ul>
  22577. * <li><pre>background: red</pre> (missing a trailing semi-colon)
  22578. * <li><pre>background:</pre> (missing a value and a trailing semi-colon)
  22579. * <li><pre>1em</pre> (missing an attribute name, which provides context for
  22580. * the value)
  22581. * </ul>
  22582. *
  22583. * @see goog.html.SafeStyle#create
  22584. * @see goog.html.SafeStyle#fromConstant
  22585. * @see http://www.w3.org/TR/css3-syntax/
  22586. * @constructor
  22587. * @final
  22588. * @struct
  22589. * @implements {goog.string.TypedString}
  22590. */
  22591. goog.html.SafeStyle = function() {
  22592. /**
  22593. * The contained value of this SafeStyle. The field has a purposely
  22594. * ugly name to make (non-compiled) code that attempts to directly access this
  22595. * field stand out.
  22596. * @private {string}
  22597. */
  22598. this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';
  22599. /**
  22600. * A type marker used to implement additional run-time type checking.
  22601. * @see goog.html.SafeStyle#unwrap
  22602. * @const
  22603. * @private
  22604. */
  22605. this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  22606. goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  22607. };
  22608. /**
  22609. * @override
  22610. * @const
  22611. */
  22612. goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;
  22613. /**
  22614. * Type marker for the SafeStyle type, used to implement additional
  22615. * run-time type checking.
  22616. * @const {!Object}
  22617. * @private
  22618. */
  22619. goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  22620. /**
  22621. * Creates a SafeStyle object from a compile-time constant string.
  22622. *
  22623. * {@code style} should be in the format
  22624. * {@code name: value; [name: value; ...]} and must not have any < or >
  22625. * characters in it. This is so that SafeStyle's contract is preserved,
  22626. * allowing the SafeStyle to correctly be interpreted as a sequence of CSS
  22627. * declarations and without affecting the syntactic structure of any
  22628. * surrounding CSS and HTML.
  22629. *
  22630. * This method performs basic sanity checks on the format of {@code style}
  22631. * but does not constrain the format of {@code name} and {@code value}, except
  22632. * for disallowing tag characters.
  22633. *
  22634. * @param {!goog.string.Const} style A compile-time-constant string from which
  22635. * to create a SafeStyle.
  22636. * @return {!goog.html.SafeStyle} A SafeStyle object initialized to
  22637. * {@code style}.
  22638. */
  22639. goog.html.SafeStyle.fromConstant = function(style) {
  22640. var styleString = goog.string.Const.unwrap(style);
  22641. if (styleString.length === 0) {
  22642. return goog.html.SafeStyle.EMPTY;
  22643. }
  22644. goog.html.SafeStyle.checkStyle_(styleString);
  22645. goog.asserts.assert(goog.string.endsWith(styleString, ';'),
  22646. 'Last character of style string is not \';\': ' + styleString);
  22647. goog.asserts.assert(goog.string.contains(styleString, ':'),
  22648. 'Style string must contain at least one \':\', to ' +
  22649. 'specify a "name: value" pair: ' + styleString);
  22650. return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
  22651. styleString);
  22652. };
  22653. /**
  22654. * Checks if the style definition is valid.
  22655. * @param {string} style
  22656. * @private
  22657. */
  22658. goog.html.SafeStyle.checkStyle_ = function(style) {
  22659. goog.asserts.assert(!/[<>]/.test(style),
  22660. 'Forbidden characters in style string: ' + style);
  22661. };
  22662. /**
  22663. * Returns this SafeStyle's value as a string.
  22664. *
  22665. * IMPORTANT: In code where it is security relevant that an object's type is
  22666. * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of
  22667. * this method. If in doubt, assume that it's security relevant. In particular,
  22668. * note that goog.html functions which return a goog.html type do not guarantee
  22669. * the returned instance is of the right type. For example:
  22670. *
  22671. * <pre>
  22672. * var fakeSafeHtml = new String('fake');
  22673. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  22674. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  22675. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  22676. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
  22677. * // instanceof goog.html.SafeHtml.
  22678. * </pre>
  22679. *
  22680. * @see goog.html.SafeStyle#unwrap
  22681. * @override
  22682. */
  22683. goog.html.SafeStyle.prototype.getTypedStringValue = function() {
  22684. return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  22685. };
  22686. if (goog.DEBUG) {
  22687. /**
  22688. * Returns a debug string-representation of this value.
  22689. *
  22690. * To obtain the actual string value wrapped in a SafeStyle, use
  22691. * {@code goog.html.SafeStyle.unwrap}.
  22692. *
  22693. * @see goog.html.SafeStyle#unwrap
  22694. * @override
  22695. */
  22696. goog.html.SafeStyle.prototype.toString = function() {
  22697. return 'SafeStyle{' +
  22698. this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}';
  22699. };
  22700. }
  22701. /**
  22702. * Performs a runtime check that the provided object is indeed a
  22703. * SafeStyle object, and returns its value.
  22704. *
  22705. * @param {!goog.html.SafeStyle} safeStyle The object to extract from.
  22706. * @return {string} The safeStyle object's contained string, unless
  22707. * the run-time type check fails. In that case, {@code unwrap} returns an
  22708. * innocuous string, or, if assertions are enabled, throws
  22709. * {@code goog.asserts.AssertionError}.
  22710. */
  22711. goog.html.SafeStyle.unwrap = function(safeStyle) {
  22712. // Perform additional Run-time type-checking to ensure that
  22713. // safeStyle is indeed an instance of the expected type. This
  22714. // provides some additional protection against security bugs due to
  22715. // application code that disables type checks.
  22716. // Specifically, the following checks are performed:
  22717. // 1. The object is an instance of the expected type.
  22718. // 2. The object is not an instance of a subclass.
  22719. // 3. The object carries a type marker for the expected type. "Faking" an
  22720. // object requires a reference to the type marker, which has names intended
  22721. // to stand out in code reviews.
  22722. if (safeStyle instanceof goog.html.SafeStyle &&
  22723. safeStyle.constructor === goog.html.SafeStyle &&
  22724. safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  22725. goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  22726. return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  22727. } else {
  22728. goog.asserts.fail(
  22729. 'expected object of type SafeStyle, got \'' + safeStyle + '\'');
  22730. return 'type_error:SafeStyle';
  22731. }
  22732. };
  22733. /**
  22734. * Package-internal utility method to create SafeStyle instances.
  22735. *
  22736. * @param {string} style The string to initialize the SafeStyle object with.
  22737. * @return {!goog.html.SafeStyle} The initialized SafeStyle object.
  22738. * @package
  22739. */
  22740. goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse =
  22741. function(style) {
  22742. return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style);
  22743. };
  22744. /**
  22745. * Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This
  22746. * method exists only so that the compiler can dead code eliminate static
  22747. * fields (like EMPTY) when they're not accessed.
  22748. * @param {string} style
  22749. * @return {!goog.html.SafeStyle}
  22750. * @private
  22751. */
  22752. goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
  22753. style) {
  22754. this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
  22755. return this;
  22756. };
  22757. /**
  22758. * A SafeStyle instance corresponding to the empty string.
  22759. * @const {!goog.html.SafeStyle}
  22760. */
  22761. goog.html.SafeStyle.EMPTY =
  22762. goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');
  22763. /**
  22764. * The innocuous string generated by goog.html.SafeUrl.create when passed
  22765. * an unsafe value.
  22766. * @const {string}
  22767. */
  22768. goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';
  22769. /**
  22770. * Mapping of property names to their values.
  22771. * @typedef {!Object<string, goog.string.Const|string>}
  22772. */
  22773. goog.html.SafeStyle.PropertyMap;
  22774. /**
  22775. * Creates a new SafeStyle object from the properties specified in the map.
  22776. * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to
  22777. * their values, for example {'margin': '1px'}. Names must consist of
  22778. * [-_a-zA-Z0-9]. Values might be strings consisting of
  22779. * [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced.
  22780. * Other values must be wrapped in goog.string.Const. Null value causes
  22781. * skipping the property.
  22782. * @return {!goog.html.SafeStyle}
  22783. * @throws {Error} If invalid name is provided.
  22784. * @throws {goog.asserts.AssertionError} If invalid value is provided. With
  22785. * disabled assertions, invalid value is replaced by
  22786. * goog.html.SafeStyle.INNOCUOUS_STRING.
  22787. */
  22788. goog.html.SafeStyle.create = function(map) {
  22789. var style = '';
  22790. for (var name in map) {
  22791. if (!/^[-_a-zA-Z0-9]+$/.test(name)) {
  22792. throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name);
  22793. }
  22794. var value = map[name];
  22795. if (value == null) {
  22796. continue;
  22797. }
  22798. if (value instanceof goog.string.Const) {
  22799. value = goog.string.Const.unwrap(value);
  22800. // These characters can be used to change context and we don't want that
  22801. // even with const values.
  22802. goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].');
  22803. } else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) {
  22804. goog.asserts.fail(
  22805. 'String value allows only [-,."\'%_!# a-zA-Z0-9], got: ' + value);
  22806. value = goog.html.SafeStyle.INNOCUOUS_STRING;
  22807. } else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) {
  22808. goog.asserts.fail('String value requires balanced quotes, got: ' + value);
  22809. value = goog.html.SafeStyle.INNOCUOUS_STRING;
  22810. }
  22811. style += name + ':' + value + ';';
  22812. }
  22813. if (!style) {
  22814. return goog.html.SafeStyle.EMPTY;
  22815. }
  22816. goog.html.SafeStyle.checkStyle_(style);
  22817. return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
  22818. style);
  22819. };
  22820. /**
  22821. * Checks that quotes (" and ') are properly balanced inside a string. Assumes
  22822. * that neither escape (\) nor any other character that could result in
  22823. * breaking out of a string parsing context are allowed;
  22824. * see http://www.w3.org/TR/css3-syntax/#string-token-diagram.
  22825. * @param {string} value Untrusted CSS property value.
  22826. * @return {boolean} True if property value is safe with respect to quote
  22827. * balancedness.
  22828. * @private
  22829. */
  22830. goog.html.SafeStyle.hasBalancedQuotes_ = function(value) {
  22831. var outsideSingle = true;
  22832. var outsideDouble = true;
  22833. for (var i = 0; i < value.length; i++) {
  22834. var c = value.charAt(i);
  22835. if (c == "'" && outsideDouble) {
  22836. outsideSingle = !outsideSingle;
  22837. } else if (c == '"' && outsideSingle) {
  22838. outsideDouble = !outsideDouble;
  22839. }
  22840. }
  22841. return outsideSingle && outsideDouble;
  22842. };
  22843. // Keep in sync with the error string in create().
  22844. /**
  22845. * Regular expression for safe values.
  22846. *
  22847. * Quotes (" and ') are allowed, but a check must be done elsewhere to ensure
  22848. * they're balanced.
  22849. *
  22850. * ',' allows multiple values to be assigned to the same property
  22851. * (e.g. background-attachment or font-family) and hence could allow
  22852. * multiple values to get injected, but that should pose no risk of XSS.
  22853. * @const {!RegExp}
  22854. * @private
  22855. */
  22856. goog.html.SafeStyle.VALUE_RE_ = /^[-,."'%_!# a-zA-Z0-9]+$/;
  22857. /**
  22858. * Creates a new SafeStyle object by concatenating the values.
  22859. * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args
  22860. * SafeStyles to concatenate.
  22861. * @return {!goog.html.SafeStyle}
  22862. */
  22863. goog.html.SafeStyle.concat = function(var_args) {
  22864. var style = '';
  22865. /**
  22866. * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument
  22867. */
  22868. var addArgument = function(argument) {
  22869. if (goog.isArray(argument)) {
  22870. goog.array.forEach(argument, addArgument);
  22871. } else {
  22872. style += goog.html.SafeStyle.unwrap(argument);
  22873. }
  22874. };
  22875. goog.array.forEach(arguments, addArgument);
  22876. if (!style) {
  22877. return goog.html.SafeStyle.EMPTY;
  22878. }
  22879. return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
  22880. style);
  22881. };
  22882. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  22883. //
  22884. // Licensed under the Apache License, Version 2.0 (the "License");
  22885. // you may not use this file except in compliance with the License.
  22886. // You may obtain a copy of the License at
  22887. //
  22888. // http://www.apache.org/licenses/LICENSE-2.0
  22889. //
  22890. // Unless required by applicable law or agreed to in writing, software
  22891. // distributed under the License is distributed on an "AS-IS" BASIS,
  22892. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22893. // See the License for the specific language governing permissions and
  22894. // limitations under the License.
  22895. /**
  22896. * @fileoverview The SafeStyleSheet type and its builders.
  22897. *
  22898. * TODO(xtof): Link to document stating type contract.
  22899. */
  22900. goog.provide('goog.html.SafeStyleSheet');
  22901. goog.require('goog.array');
  22902. goog.require('goog.asserts');
  22903. goog.require('goog.string');
  22904. goog.require('goog.string.Const');
  22905. goog.require('goog.string.TypedString');
  22906. /**
  22907. * A string-like object which represents a CSS style sheet and that carries the
  22908. * security type contract that its value, as a string, will not cause untrusted
  22909. * script execution (XSS) when evaluated as CSS in a browser.
  22910. *
  22911. * Instances of this type must be created via the factory method
  22912. * {@code goog.html.SafeStyleSheet.fromConstant} and not by invoking its
  22913. * constructor. The constructor intentionally takes no parameters and the type
  22914. * is immutable; hence only a default instance corresponding to the empty string
  22915. * can be obtained via constructor invocation.
  22916. *
  22917. * A SafeStyleSheet's string representation can safely be interpolated as the
  22918. * content of a style element within HTML. The SafeStyleSheet string should
  22919. * not be escaped before interpolation.
  22920. *
  22921. * Values of this type must be composable, i.e. for any two values
  22922. * {@code styleSheet1} and {@code styleSheet2} of this type,
  22923. * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1) +
  22924. * goog.html.SafeStyleSheet.unwrap(styleSheet2)} must itself be a value that
  22925. * satisfies the SafeStyleSheet type constraint. This requirement implies that
  22926. * for any value {@code styleSheet} of this type,
  22927. * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1)} must end in
  22928. * "beginning of rule" context.
  22929. * A SafeStyleSheet can be constructed via security-reviewed unchecked
  22930. * conversions. In this case producers of SafeStyleSheet must ensure themselves
  22931. * that the SafeStyleSheet does not contain unsafe script. Note in particular
  22932. * that {@code &lt;} is dangerous, even when inside CSS strings, and so should
  22933. * always be forbidden or CSS-escaped in user controlled input. For example, if
  22934. * {@code &lt;/style&gt;&lt;script&gt;evil&lt;/script&gt;"} were interpolated
  22935. * inside a CSS string, it would break out of the context of the original
  22936. * style element and {@code evil} would execute. Also note that within an HTML
  22937. * style (raw text) element, HTML character references, such as
  22938. * {@code &amp;lt;}, are not allowed. See
  22939. * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements
  22940. * (similar considerations apply to the style element).
  22941. *
  22942. * @see goog.html.SafeStyleSheet#fromConstant
  22943. * @constructor
  22944. * @final
  22945. * @struct
  22946. * @implements {goog.string.TypedString}
  22947. */
  22948. goog.html.SafeStyleSheet = function() {
  22949. /**
  22950. * The contained value of this SafeStyleSheet. The field has a purposely
  22951. * ugly name to make (non-compiled) code that attempts to directly access this
  22952. * field stand out.
  22953. * @private {string}
  22954. */
  22955. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = '';
  22956. /**
  22957. * A type marker used to implement additional run-time type checking.
  22958. * @see goog.html.SafeStyleSheet#unwrap
  22959. * @const
  22960. * @private
  22961. */
  22962. this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  22963. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  22964. };
  22965. /**
  22966. * @override
  22967. * @const
  22968. */
  22969. goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = true;
  22970. /**
  22971. * Type marker for the SafeStyleSheet type, used to implement additional
  22972. * run-time type checking.
  22973. * @const {!Object}
  22974. * @private
  22975. */
  22976. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  22977. /**
  22978. * Creates a new SafeStyleSheet object by concatenating values.
  22979. * @param {...(!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>)}
  22980. * var_args Values to concatenate.
  22981. * @return {!goog.html.SafeStyleSheet}
  22982. */
  22983. goog.html.SafeStyleSheet.concat = function(var_args) {
  22984. var result = '';
  22985. /**
  22986. * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}
  22987. * argument
  22988. */
  22989. var addArgument = function(argument) {
  22990. if (goog.isArray(argument)) {
  22991. goog.array.forEach(argument, addArgument);
  22992. } else {
  22993. result += goog.html.SafeStyleSheet.unwrap(argument);
  22994. }
  22995. };
  22996. goog.array.forEach(arguments, addArgument);
  22997. return goog.html.SafeStyleSheet
  22998. .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(result);
  22999. };
  23000. /**
  23001. * Creates a SafeStyleSheet object from a compile-time constant string.
  23002. *
  23003. * {@code styleSheet} must not have any &lt; characters in it, so that
  23004. * the syntactic structure of the surrounding HTML is not affected.
  23005. *
  23006. * @param {!goog.string.Const} styleSheet A compile-time-constant string from
  23007. * which to create a SafeStyleSheet.
  23008. * @return {!goog.html.SafeStyleSheet} A SafeStyleSheet object initialized to
  23009. * {@code styleSheet}.
  23010. */
  23011. goog.html.SafeStyleSheet.fromConstant = function(styleSheet) {
  23012. var styleSheetString = goog.string.Const.unwrap(styleSheet);
  23013. if (styleSheetString.length === 0) {
  23014. return goog.html.SafeStyleSheet.EMPTY;
  23015. }
  23016. // > is a valid character in CSS selectors and there's no strict need to
  23017. // block it if we already block <.
  23018. goog.asserts.assert(!goog.string.contains(styleSheetString, '<'),
  23019. "Forbidden '<' character in style sheet string: " + styleSheetString);
  23020. return goog.html.SafeStyleSheet.
  23021. createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheetString);
  23022. };
  23023. /**
  23024. * Returns this SafeStyleSheet's value as a string.
  23025. *
  23026. * IMPORTANT: In code where it is security relevant that an object's type is
  23027. * indeed {@code SafeStyleSheet}, use {@code goog.html.SafeStyleSheet.unwrap}
  23028. * instead of this method. If in doubt, assume that it's security relevant. In
  23029. * particular, note that goog.html functions which return a goog.html type do
  23030. * not guarantee the returned instance is of the right type. For example:
  23031. *
  23032. * <pre>
  23033. * var fakeSafeHtml = new String('fake');
  23034. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  23035. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  23036. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  23037. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
  23038. * // instanceof goog.html.SafeHtml.
  23039. * </pre>
  23040. *
  23041. * @see goog.html.SafeStyleSheet#unwrap
  23042. * @override
  23043. */
  23044. goog.html.SafeStyleSheet.prototype.getTypedStringValue = function() {
  23045. return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
  23046. };
  23047. if (goog.DEBUG) {
  23048. /**
  23049. * Returns a debug string-representation of this value.
  23050. *
  23051. * To obtain the actual string value wrapped in a SafeStyleSheet, use
  23052. * {@code goog.html.SafeStyleSheet.unwrap}.
  23053. *
  23054. * @see goog.html.SafeStyleSheet#unwrap
  23055. * @override
  23056. */
  23057. goog.html.SafeStyleSheet.prototype.toString = function() {
  23058. return 'SafeStyleSheet{' +
  23059. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + '}';
  23060. };
  23061. }
  23062. /**
  23063. * Performs a runtime check that the provided object is indeed a
  23064. * SafeStyleSheet object, and returns its value.
  23065. *
  23066. * @param {!goog.html.SafeStyleSheet} safeStyleSheet The object to extract from.
  23067. * @return {string} The safeStyleSheet object's contained string, unless
  23068. * the run-time type check fails. In that case, {@code unwrap} returns an
  23069. * innocuous string, or, if assertions are enabled, throws
  23070. * {@code goog.asserts.AssertionError}.
  23071. */
  23072. goog.html.SafeStyleSheet.unwrap = function(safeStyleSheet) {
  23073. // Perform additional Run-time type-checking to ensure that
  23074. // safeStyleSheet is indeed an instance of the expected type. This
  23075. // provides some additional protection against security bugs due to
  23076. // application code that disables type checks.
  23077. // Specifically, the following checks are performed:
  23078. // 1. The object is an instance of the expected type.
  23079. // 2. The object is not an instance of a subclass.
  23080. // 3. The object carries a type marker for the expected type. "Faking" an
  23081. // object requires a reference to the type marker, which has names intended
  23082. // to stand out in code reviews.
  23083. if (safeStyleSheet instanceof goog.html.SafeStyleSheet &&
  23084. safeStyleSheet.constructor === goog.html.SafeStyleSheet &&
  23085. safeStyleSheet.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  23086. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  23087. return safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
  23088. } else {
  23089. goog.asserts.fail(
  23090. "expected object of type SafeStyleSheet, got '" + safeStyleSheet +
  23091. "'");
  23092. return 'type_error:SafeStyleSheet';
  23093. }
  23094. };
  23095. /**
  23096. * Package-internal utility method to create SafeStyleSheet instances.
  23097. *
  23098. * @param {string} styleSheet The string to initialize the SafeStyleSheet
  23099. * object with.
  23100. * @return {!goog.html.SafeStyleSheet} The initialized SafeStyleSheet object.
  23101. * @package
  23102. */
  23103. goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse =
  23104. function(styleSheet) {
  23105. return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_(
  23106. styleSheet);
  23107. };
  23108. /**
  23109. * Called from createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(). This
  23110. * method exists only so that the compiler can dead code eliminate static
  23111. * fields (like EMPTY) when they're not accessed.
  23112. * @param {string} styleSheet
  23113. * @return {!goog.html.SafeStyleSheet}
  23114. * @private
  23115. */
  23116. goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ =
  23117. function(styleSheet) {
  23118. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = styleSheet;
  23119. return this;
  23120. };
  23121. /**
  23122. * A SafeStyleSheet instance corresponding to the empty string.
  23123. * @const {!goog.html.SafeStyleSheet}
  23124. */
  23125. goog.html.SafeStyleSheet.EMPTY =
  23126. goog.html.SafeStyleSheet.
  23127. createSafeStyleSheetSecurityPrivateDoNotAccessOrElse('');
  23128. // Copyright 2015 The Closure Library Authors. All Rights Reserved.
  23129. //
  23130. // Licensed under the Apache License, Version 2.0 (the "License");
  23131. // you may not use this file except in compliance with the License.
  23132. // You may obtain a copy of the License at
  23133. //
  23134. // http://www.apache.org/licenses/LICENSE-2.0
  23135. //
  23136. // Unless required by applicable law or agreed to in writing, software
  23137. // distributed under the License is distributed on an "AS-IS" BASIS,
  23138. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23139. // See the License for the specific language governing permissions and
  23140. // limitations under the License.
  23141. /**
  23142. * @fileoverview Wrapper for URL and its createObjectUrl and revokeObjectUrl
  23143. * methods that are part of the HTML5 File API.
  23144. */
  23145. goog.provide('goog.fs.url');
  23146. /**
  23147. * Creates a blob URL for a blob object.
  23148. * Throws an error if the browser does not support Object Urls.
  23149. *
  23150. * @param {!Blob} blob The object for which to create the URL.
  23151. * @return {string} The URL for the object.
  23152. */
  23153. goog.fs.url.createObjectUrl = function(blob) {
  23154. return goog.fs.url.getUrlObject_().createObjectURL(blob);
  23155. };
  23156. /**
  23157. * Revokes a URL created by {@link goog.fs.url.createObjectUrl}.
  23158. * Throws an error if the browser does not support Object Urls.
  23159. *
  23160. * @param {string} url The URL to revoke.
  23161. */
  23162. goog.fs.url.revokeObjectUrl = function(url) {
  23163. goog.fs.url.getUrlObject_().revokeObjectURL(url);
  23164. };
  23165. /**
  23166. * @typedef {{createObjectURL: (function(!Blob): string),
  23167. * revokeObjectURL: function(string): void}}
  23168. */
  23169. goog.fs.url.UrlObject_;
  23170. /**
  23171. * Get the object that has the createObjectURL and revokeObjectURL functions for
  23172. * this browser.
  23173. *
  23174. * @return {goog.fs.url.UrlObject_} The object for this browser.
  23175. * @private
  23176. */
  23177. goog.fs.url.getUrlObject_ = function() {
  23178. var urlObject = goog.fs.url.findUrlObject_();
  23179. if (urlObject != null) {
  23180. return urlObject;
  23181. } else {
  23182. throw Error('This browser doesn\'t seem to support blob URLs');
  23183. }
  23184. };
  23185. /**
  23186. * Finds the object that has the createObjectURL and revokeObjectURL functions
  23187. * for this browser.
  23188. *
  23189. * @return {?goog.fs.url.UrlObject_} The object for this browser or null if the
  23190. * browser does not support Object Urls.
  23191. * @suppress {unnecessaryCasts} Depending on how the code is compiled, casting
  23192. * goog.global to UrlObject_ may result in unnecessary cast warning.
  23193. * However, the cast cannot be removed because with different set of
  23194. * compiler flags, the cast is indeed necessary. As such, silencing it.
  23195. * @private
  23196. */
  23197. goog.fs.url.findUrlObject_ = function() {
  23198. // This is what the spec says to do
  23199. // http://dev.w3.org/2006/webapi/FileAPI/#dfn-createObjectURL
  23200. if (goog.isDef(goog.global.URL) &&
  23201. goog.isDef(goog.global.URL.createObjectURL)) {
  23202. return /** @type {goog.fs.url.UrlObject_} */ (goog.global.URL);
  23203. // This is what Chrome does (as of 10.0.648.6 dev)
  23204. } else if (goog.isDef(goog.global.webkitURL) &&
  23205. goog.isDef(goog.global.webkitURL.createObjectURL)) {
  23206. return /** @type {goog.fs.url.UrlObject_} */ (goog.global.webkitURL);
  23207. // This is what the spec used to say to do
  23208. } else if (goog.isDef(goog.global.createObjectURL)) {
  23209. return /** @type {goog.fs.url.UrlObject_} */ (goog.global);
  23210. } else {
  23211. return null;
  23212. }
  23213. };
  23214. /**
  23215. * Checks whether this browser supports Object Urls. If not, calls to
  23216. * createObjectUrl and revokeObjectUrl will result in an error.
  23217. *
  23218. * @return {boolean} True if this browser supports Object Urls.
  23219. */
  23220. goog.fs.url.browserSupportsObjectUrls = function() {
  23221. return goog.fs.url.findUrlObject_() != null;
  23222. };
  23223. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  23224. //
  23225. // Licensed under the Apache License, Version 2.0 (the "License");
  23226. // you may not use this file except in compliance with the License.
  23227. // You may obtain a copy of the License at
  23228. //
  23229. // http://www.apache.org/licenses/LICENSE-2.0
  23230. //
  23231. // Unless required by applicable law or agreed to in writing, software
  23232. // distributed under the License is distributed on an "AS-IS" BASIS,
  23233. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23234. // See the License for the specific language governing permissions and
  23235. // limitations under the License.
  23236. /**
  23237. * @fileoverview Utility functions for supporting Bidi issues.
  23238. */
  23239. /**
  23240. * Namespace for bidi supporting functions.
  23241. */
  23242. goog.provide('goog.i18n.bidi');
  23243. goog.provide('goog.i18n.bidi.Dir');
  23244. goog.provide('goog.i18n.bidi.DirectionalString');
  23245. goog.provide('goog.i18n.bidi.Format');
  23246. /**
  23247. * @define {boolean} FORCE_RTL forces the {@link goog.i18n.bidi.IS_RTL} constant
  23248. * to say that the current locale is a RTL locale. This should only be used
  23249. * if you want to override the default behavior for deciding whether the
  23250. * current locale is RTL or not.
  23251. *
  23252. * {@see goog.i18n.bidi.IS_RTL}
  23253. */
  23254. goog.define('goog.i18n.bidi.FORCE_RTL', false);
  23255. /**
  23256. * Constant that defines whether or not the current locale is a RTL locale.
  23257. * If {@link goog.i18n.bidi.FORCE_RTL} is not true, this constant will default
  23258. * to check that {@link goog.LOCALE} is one of a few major RTL locales.
  23259. *
  23260. * <p>This is designed to be a maximally efficient compile-time constant. For
  23261. * example, for the default goog.LOCALE, compiling
  23262. * "if (goog.i18n.bidi.IS_RTL) alert('rtl') else {}" should produce no code. It
  23263. * is this design consideration that limits the implementation to only
  23264. * supporting a few major RTL locales, as opposed to the broader repertoire of
  23265. * something like goog.i18n.bidi.isRtlLanguage.
  23266. *
  23267. * <p>Since this constant refers to the directionality of the locale, it is up
  23268. * to the caller to determine if this constant should also be used for the
  23269. * direction of the UI.
  23270. *
  23271. * {@see goog.LOCALE}
  23272. *
  23273. * @type {boolean}
  23274. *
  23275. * TODO(user): write a test that checks that this is a compile-time constant.
  23276. */
  23277. goog.i18n.bidi.IS_RTL = goog.i18n.bidi.FORCE_RTL ||
  23278. (
  23279. (goog.LOCALE.substring(0, 2).toLowerCase() == 'ar' ||
  23280. goog.LOCALE.substring(0, 2).toLowerCase() == 'fa' ||
  23281. goog.LOCALE.substring(0, 2).toLowerCase() == 'he' ||
  23282. goog.LOCALE.substring(0, 2).toLowerCase() == 'iw' ||
  23283. goog.LOCALE.substring(0, 2).toLowerCase() == 'ps' ||
  23284. goog.LOCALE.substring(0, 2).toLowerCase() == 'sd' ||
  23285. goog.LOCALE.substring(0, 2).toLowerCase() == 'ug' ||
  23286. goog.LOCALE.substring(0, 2).toLowerCase() == 'ur' ||
  23287. goog.LOCALE.substring(0, 2).toLowerCase() == 'yi') &&
  23288. (goog.LOCALE.length == 2 ||
  23289. goog.LOCALE.substring(2, 3) == '-' ||
  23290. goog.LOCALE.substring(2, 3) == '_')
  23291. ) || (
  23292. goog.LOCALE.length >= 3 &&
  23293. goog.LOCALE.substring(0, 3).toLowerCase() == 'ckb' &&
  23294. (goog.LOCALE.length == 3 ||
  23295. goog.LOCALE.substring(3, 4) == '-' ||
  23296. goog.LOCALE.substring(3, 4) == '_')
  23297. );
  23298. /**
  23299. * Unicode formatting characters and directionality string constants.
  23300. * @enum {string}
  23301. */
  23302. goog.i18n.bidi.Format = {
  23303. /** Unicode "Left-To-Right Embedding" (LRE) character. */
  23304. LRE: '\u202A',
  23305. /** Unicode "Right-To-Left Embedding" (RLE) character. */
  23306. RLE: '\u202B',
  23307. /** Unicode "Pop Directional Formatting" (PDF) character. */
  23308. PDF: '\u202C',
  23309. /** Unicode "Left-To-Right Mark" (LRM) character. */
  23310. LRM: '\u200E',
  23311. /** Unicode "Right-To-Left Mark" (RLM) character. */
  23312. RLM: '\u200F'
  23313. };
  23314. /**
  23315. * Directionality enum.
  23316. * @enum {number}
  23317. */
  23318. goog.i18n.bidi.Dir = {
  23319. /**
  23320. * Left-to-right.
  23321. */
  23322. LTR: 1,
  23323. /**
  23324. * Right-to-left.
  23325. */
  23326. RTL: -1,
  23327. /**
  23328. * Neither left-to-right nor right-to-left.
  23329. */
  23330. NEUTRAL: 0
  23331. };
  23332. /**
  23333. * 'right' string constant.
  23334. * @type {string}
  23335. */
  23336. goog.i18n.bidi.RIGHT = 'right';
  23337. /**
  23338. * 'left' string constant.
  23339. * @type {string}
  23340. */
  23341. goog.i18n.bidi.LEFT = 'left';
  23342. /**
  23343. * 'left' if locale is RTL, 'right' if not.
  23344. * @type {string}
  23345. */
  23346. goog.i18n.bidi.I18N_RIGHT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.LEFT :
  23347. goog.i18n.bidi.RIGHT;
  23348. /**
  23349. * 'right' if locale is RTL, 'left' if not.
  23350. * @type {string}
  23351. */
  23352. goog.i18n.bidi.I18N_LEFT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.RIGHT :
  23353. goog.i18n.bidi.LEFT;
  23354. /**
  23355. * Convert a directionality given in various formats to a goog.i18n.bidi.Dir
  23356. * constant. Useful for interaction with different standards of directionality
  23357. * representation.
  23358. *
  23359. * @param {goog.i18n.bidi.Dir|number|boolean|null} givenDir Directionality given
  23360. * in one of the following formats:
  23361. * 1. A goog.i18n.bidi.Dir constant.
  23362. * 2. A number (positive = LTR, negative = RTL, 0 = neutral).
  23363. * 3. A boolean (true = RTL, false = LTR).
  23364. * 4. A null for unknown directionality.
  23365. * @param {boolean=} opt_noNeutral Whether a givenDir of zero or
  23366. * goog.i18n.bidi.Dir.NEUTRAL should be treated as null, i.e. unknown, in
  23367. * order to preserve legacy behavior.
  23368. * @return {?goog.i18n.bidi.Dir} A goog.i18n.bidi.Dir constant matching the
  23369. * given directionality. If given null, returns null (i.e. unknown).
  23370. */
  23371. goog.i18n.bidi.toDir = function(givenDir, opt_noNeutral) {
  23372. if (typeof givenDir == 'number') {
  23373. // This includes the non-null goog.i18n.bidi.Dir case.
  23374. return givenDir > 0 ? goog.i18n.bidi.Dir.LTR :
  23375. givenDir < 0 ? goog.i18n.bidi.Dir.RTL :
  23376. opt_noNeutral ? null : goog.i18n.bidi.Dir.NEUTRAL;
  23377. } else if (givenDir == null) {
  23378. return null;
  23379. } else {
  23380. // Must be typeof givenDir == 'boolean'.
  23381. return givenDir ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR;
  23382. }
  23383. };
  23384. /**
  23385. * A practical pattern to identify strong LTR characters. This pattern is not
  23386. * theoretically correct according to the Unicode standard. It is simplified for
  23387. * performance and small code size.
  23388. * @type {string}
  23389. * @private
  23390. */
  23391. goog.i18n.bidi.ltrChars_ =
  23392. 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' +
  23393. '\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF';
  23394. /**
  23395. * A practical pattern to identify strong RTL character. This pattern is not
  23396. * theoretically correct according to the Unicode standard. It is simplified
  23397. * for performance and small code size.
  23398. * @type {string}
  23399. * @private
  23400. */
  23401. goog.i18n.bidi.rtlChars_ =
  23402. '\u0591-\u06EF\u06FA-\u07FF\u200F\uFB1D-\uFDFF\uFE70-\uFEFC';
  23403. /**
  23404. * Simplified regular expression for an HTML tag (opening or closing) or an HTML
  23405. * escape. We might want to skip over such expressions when estimating the text
  23406. * directionality.
  23407. * @type {RegExp}
  23408. * @private
  23409. */
  23410. goog.i18n.bidi.htmlSkipReg_ = /<[^>]*>|&[^;]+;/g;
  23411. /**
  23412. * Returns the input text with spaces instead of HTML tags or HTML escapes, if
  23413. * opt_isStripNeeded is true. Else returns the input as is.
  23414. * Useful for text directionality estimation.
  23415. * Note: the function should not be used in other contexts; it is not 100%
  23416. * correct, but rather a good-enough implementation for directionality
  23417. * estimation purposes.
  23418. * @param {string} str The given string.
  23419. * @param {boolean=} opt_isStripNeeded Whether to perform the stripping.
  23420. * Default: false (to retain consistency with calling functions).
  23421. * @return {string} The given string cleaned of HTML tags / escapes.
  23422. * @private
  23423. */
  23424. goog.i18n.bidi.stripHtmlIfNeeded_ = function(str, opt_isStripNeeded) {
  23425. return opt_isStripNeeded ? str.replace(goog.i18n.bidi.htmlSkipReg_, '') :
  23426. str;
  23427. };
  23428. /**
  23429. * Regular expression to check for RTL characters.
  23430. * @type {RegExp}
  23431. * @private
  23432. */
  23433. goog.i18n.bidi.rtlCharReg_ = new RegExp('[' + goog.i18n.bidi.rtlChars_ + ']');
  23434. /**
  23435. * Regular expression to check for LTR characters.
  23436. * @type {RegExp}
  23437. * @private
  23438. */
  23439. goog.i18n.bidi.ltrCharReg_ = new RegExp('[' + goog.i18n.bidi.ltrChars_ + ']');
  23440. /**
  23441. * Test whether the given string has any RTL characters in it.
  23442. * @param {string} str The given string that need to be tested.
  23443. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23444. * Default: false.
  23445. * @return {boolean} Whether the string contains RTL characters.
  23446. */
  23447. goog.i18n.bidi.hasAnyRtl = function(str, opt_isHtml) {
  23448. return goog.i18n.bidi.rtlCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_(
  23449. str, opt_isHtml));
  23450. };
  23451. /**
  23452. * Test whether the given string has any RTL characters in it.
  23453. * @param {string} str The given string that need to be tested.
  23454. * @return {boolean} Whether the string contains RTL characters.
  23455. * @deprecated Use hasAnyRtl.
  23456. */
  23457. goog.i18n.bidi.hasRtlChar = goog.i18n.bidi.hasAnyRtl;
  23458. /**
  23459. * Test whether the given string has any LTR characters in it.
  23460. * @param {string} str The given string that need to be tested.
  23461. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23462. * Default: false.
  23463. * @return {boolean} Whether the string contains LTR characters.
  23464. */
  23465. goog.i18n.bidi.hasAnyLtr = function(str, opt_isHtml) {
  23466. return goog.i18n.bidi.ltrCharReg_.test(goog.i18n.bidi.stripHtmlIfNeeded_(
  23467. str, opt_isHtml));
  23468. };
  23469. /**
  23470. * Regular expression pattern to check if the first character in the string
  23471. * is LTR.
  23472. * @type {RegExp}
  23473. * @private
  23474. */
  23475. goog.i18n.bidi.ltrRe_ = new RegExp('^[' + goog.i18n.bidi.ltrChars_ + ']');
  23476. /**
  23477. * Regular expression pattern to check if the first character in the string
  23478. * is RTL.
  23479. * @type {RegExp}
  23480. * @private
  23481. */
  23482. goog.i18n.bidi.rtlRe_ = new RegExp('^[' + goog.i18n.bidi.rtlChars_ + ']');
  23483. /**
  23484. * Check if the first character in the string is RTL or not.
  23485. * @param {string} str The given string that need to be tested.
  23486. * @return {boolean} Whether the first character in str is an RTL char.
  23487. */
  23488. goog.i18n.bidi.isRtlChar = function(str) {
  23489. return goog.i18n.bidi.rtlRe_.test(str);
  23490. };
  23491. /**
  23492. * Check if the first character in the string is LTR or not.
  23493. * @param {string} str The given string that need to be tested.
  23494. * @return {boolean} Whether the first character in str is an LTR char.
  23495. */
  23496. goog.i18n.bidi.isLtrChar = function(str) {
  23497. return goog.i18n.bidi.ltrRe_.test(str);
  23498. };
  23499. /**
  23500. * Check if the first character in the string is neutral or not.
  23501. * @param {string} str The given string that need to be tested.
  23502. * @return {boolean} Whether the first character in str is a neutral char.
  23503. */
  23504. goog.i18n.bidi.isNeutralChar = function(str) {
  23505. return !goog.i18n.bidi.isLtrChar(str) && !goog.i18n.bidi.isRtlChar(str);
  23506. };
  23507. /**
  23508. * Regular expressions to check if a piece of text is of LTR directionality
  23509. * on first character with strong directionality.
  23510. * @type {RegExp}
  23511. * @private
  23512. */
  23513. goog.i18n.bidi.ltrDirCheckRe_ = new RegExp(
  23514. '^[^' + goog.i18n.bidi.rtlChars_ + ']*[' + goog.i18n.bidi.ltrChars_ + ']');
  23515. /**
  23516. * Regular expressions to check if a piece of text is of RTL directionality
  23517. * on first character with strong directionality.
  23518. * @type {RegExp}
  23519. * @private
  23520. */
  23521. goog.i18n.bidi.rtlDirCheckRe_ = new RegExp(
  23522. '^[^' + goog.i18n.bidi.ltrChars_ + ']*[' + goog.i18n.bidi.rtlChars_ + ']');
  23523. /**
  23524. * Check whether the first strongly directional character (if any) is RTL.
  23525. * @param {string} str String being checked.
  23526. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23527. * Default: false.
  23528. * @return {boolean} Whether RTL directionality is detected using the first
  23529. * strongly-directional character method.
  23530. */
  23531. goog.i18n.bidi.startsWithRtl = function(str, opt_isHtml) {
  23532. return goog.i18n.bidi.rtlDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(
  23533. str, opt_isHtml));
  23534. };
  23535. /**
  23536. * Check whether the first strongly directional character (if any) is RTL.
  23537. * @param {string} str String being checked.
  23538. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23539. * Default: false.
  23540. * @return {boolean} Whether RTL directionality is detected using the first
  23541. * strongly-directional character method.
  23542. * @deprecated Use startsWithRtl.
  23543. */
  23544. goog.i18n.bidi.isRtlText = goog.i18n.bidi.startsWithRtl;
  23545. /**
  23546. * Check whether the first strongly directional character (if any) is LTR.
  23547. * @param {string} str String being checked.
  23548. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23549. * Default: false.
  23550. * @return {boolean} Whether LTR directionality is detected using the first
  23551. * strongly-directional character method.
  23552. */
  23553. goog.i18n.bidi.startsWithLtr = function(str, opt_isHtml) {
  23554. return goog.i18n.bidi.ltrDirCheckRe_.test(goog.i18n.bidi.stripHtmlIfNeeded_(
  23555. str, opt_isHtml));
  23556. };
  23557. /**
  23558. * Check whether the first strongly directional character (if any) is LTR.
  23559. * @param {string} str String being checked.
  23560. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23561. * Default: false.
  23562. * @return {boolean} Whether LTR directionality is detected using the first
  23563. * strongly-directional character method.
  23564. * @deprecated Use startsWithLtr.
  23565. */
  23566. goog.i18n.bidi.isLtrText = goog.i18n.bidi.startsWithLtr;
  23567. /**
  23568. * Regular expression to check if a string looks like something that must
  23569. * always be LTR even in RTL text, e.g. a URL. When estimating the
  23570. * directionality of text containing these, we treat these as weakly LTR,
  23571. * like numbers.
  23572. * @type {RegExp}
  23573. * @private
  23574. */
  23575. goog.i18n.bidi.isRequiredLtrRe_ = /^http:\/\/.*/;
  23576. /**
  23577. * Check whether the input string either contains no strongly directional
  23578. * characters or looks like a url.
  23579. * @param {string} str String being checked.
  23580. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23581. * Default: false.
  23582. * @return {boolean} Whether neutral directionality is detected.
  23583. */
  23584. goog.i18n.bidi.isNeutralText = function(str, opt_isHtml) {
  23585. str = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml);
  23586. return goog.i18n.bidi.isRequiredLtrRe_.test(str) ||
  23587. !goog.i18n.bidi.hasAnyLtr(str) && !goog.i18n.bidi.hasAnyRtl(str);
  23588. };
  23589. /**
  23590. * Regular expressions to check if the last strongly-directional character in a
  23591. * piece of text is LTR.
  23592. * @type {RegExp}
  23593. * @private
  23594. */
  23595. goog.i18n.bidi.ltrExitDirCheckRe_ = new RegExp(
  23596. '[' + goog.i18n.bidi.ltrChars_ + '][^' + goog.i18n.bidi.rtlChars_ + ']*$');
  23597. /**
  23598. * Regular expressions to check if the last strongly-directional character in a
  23599. * piece of text is RTL.
  23600. * @type {RegExp}
  23601. * @private
  23602. */
  23603. goog.i18n.bidi.rtlExitDirCheckRe_ = new RegExp(
  23604. '[' + goog.i18n.bidi.rtlChars_ + '][^' + goog.i18n.bidi.ltrChars_ + ']*$');
  23605. /**
  23606. * Check if the exit directionality a piece of text is LTR, i.e. if the last
  23607. * strongly-directional character in the string is LTR.
  23608. * @param {string} str String being checked.
  23609. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23610. * Default: false.
  23611. * @return {boolean} Whether LTR exit directionality was detected.
  23612. */
  23613. goog.i18n.bidi.endsWithLtr = function(str, opt_isHtml) {
  23614. return goog.i18n.bidi.ltrExitDirCheckRe_.test(
  23615. goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml));
  23616. };
  23617. /**
  23618. * Check if the exit directionality a piece of text is LTR, i.e. if the last
  23619. * strongly-directional character in the string is LTR.
  23620. * @param {string} str String being checked.
  23621. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23622. * Default: false.
  23623. * @return {boolean} Whether LTR exit directionality was detected.
  23624. * @deprecated Use endsWithLtr.
  23625. */
  23626. goog.i18n.bidi.isLtrExitText = goog.i18n.bidi.endsWithLtr;
  23627. /**
  23628. * Check if the exit directionality a piece of text is RTL, i.e. if the last
  23629. * strongly-directional character in the string is RTL.
  23630. * @param {string} str String being checked.
  23631. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23632. * Default: false.
  23633. * @return {boolean} Whether RTL exit directionality was detected.
  23634. */
  23635. goog.i18n.bidi.endsWithRtl = function(str, opt_isHtml) {
  23636. return goog.i18n.bidi.rtlExitDirCheckRe_.test(
  23637. goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml));
  23638. };
  23639. /**
  23640. * Check if the exit directionality a piece of text is RTL, i.e. if the last
  23641. * strongly-directional character in the string is RTL.
  23642. * @param {string} str String being checked.
  23643. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23644. * Default: false.
  23645. * @return {boolean} Whether RTL exit directionality was detected.
  23646. * @deprecated Use endsWithRtl.
  23647. */
  23648. goog.i18n.bidi.isRtlExitText = goog.i18n.bidi.endsWithRtl;
  23649. /**
  23650. * A regular expression for matching right-to-left language codes.
  23651. * See {@link #isRtlLanguage} for the design.
  23652. * @type {RegExp}
  23653. * @private
  23654. */
  23655. goog.i18n.bidi.rtlLocalesRe_ = new RegExp(
  23656. '^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|' +
  23657. '.*[-_](Arab|Hebr|Thaa|Nkoo|Tfng))' +
  23658. '(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)',
  23659. 'i');
  23660. /**
  23661. * Check if a BCP 47 / III language code indicates an RTL language, i.e. either:
  23662. * - a language code explicitly specifying one of the right-to-left scripts,
  23663. * e.g. "az-Arab", or<p>
  23664. * - a language code specifying one of the languages normally written in a
  23665. * right-to-left script, e.g. "fa" (Farsi), except ones explicitly specifying
  23666. * Latin or Cyrillic script (which are the usual LTR alternatives).<p>
  23667. * The list of right-to-left scripts appears in the 100-199 range in
  23668. * http://www.unicode.org/iso15924/iso15924-num.html, of which Arabic and
  23669. * Hebrew are by far the most widely used. We also recognize Thaana, N'Ko, and
  23670. * Tifinagh, which also have significant modern usage. The rest (Syriac,
  23671. * Samaritan, Mandaic, etc.) seem to have extremely limited or no modern usage
  23672. * and are not recognized to save on code size.
  23673. * The languages usually written in a right-to-left script are taken as those
  23674. * with Suppress-Script: Hebr|Arab|Thaa|Nkoo|Tfng in
  23675. * http://www.iana.org/assignments/language-subtag-registry,
  23676. * as well as Central (or Sorani) Kurdish (ckb), Sindhi (sd) and Uyghur (ug).
  23677. * Other subtags of the language code, e.g. regions like EG (Egypt), are
  23678. * ignored.
  23679. * @param {string} lang BCP 47 (a.k.a III) language code.
  23680. * @return {boolean} Whether the language code is an RTL language.
  23681. */
  23682. goog.i18n.bidi.isRtlLanguage = function(lang) {
  23683. return goog.i18n.bidi.rtlLocalesRe_.test(lang);
  23684. };
  23685. /**
  23686. * Regular expression for bracket guard replacement in html.
  23687. * @type {RegExp}
  23688. * @private
  23689. */
  23690. goog.i18n.bidi.bracketGuardHtmlRe_ =
  23691. /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(&lt;.*?(&gt;)+)/g;
  23692. /**
  23693. * Regular expression for bracket guard replacement in text.
  23694. * @type {RegExp}
  23695. * @private
  23696. */
  23697. goog.i18n.bidi.bracketGuardTextRe_ =
  23698. /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(<.*?>+)/g;
  23699. /**
  23700. * Apply bracket guard using html span tag. This is to address the problem of
  23701. * messy bracket display frequently happens in RTL layout.
  23702. * @param {string} s The string that need to be processed.
  23703. * @param {boolean=} opt_isRtlContext specifies default direction (usually
  23704. * direction of the UI).
  23705. * @return {string} The processed string, with all bracket guarded.
  23706. */
  23707. goog.i18n.bidi.guardBracketInHtml = function(s, opt_isRtlContext) {
  23708. var useRtl = opt_isRtlContext === undefined ?
  23709. goog.i18n.bidi.hasAnyRtl(s) : opt_isRtlContext;
  23710. if (useRtl) {
  23711. return s.replace(goog.i18n.bidi.bracketGuardHtmlRe_,
  23712. '<span dir=rtl>$&</span>');
  23713. }
  23714. return s.replace(goog.i18n.bidi.bracketGuardHtmlRe_,
  23715. '<span dir=ltr>$&</span>');
  23716. };
  23717. /**
  23718. * Apply bracket guard using LRM and RLM. This is to address the problem of
  23719. * messy bracket display frequently happens in RTL layout.
  23720. * This version works for both plain text and html. But it does not work as
  23721. * good as guardBracketInHtml in some cases.
  23722. * @param {string} s The string that need to be processed.
  23723. * @param {boolean=} opt_isRtlContext specifies default direction (usually
  23724. * direction of the UI).
  23725. * @return {string} The processed string, with all bracket guarded.
  23726. */
  23727. goog.i18n.bidi.guardBracketInText = function(s, opt_isRtlContext) {
  23728. var useRtl = opt_isRtlContext === undefined ?
  23729. goog.i18n.bidi.hasAnyRtl(s) : opt_isRtlContext;
  23730. var mark = useRtl ? goog.i18n.bidi.Format.RLM : goog.i18n.bidi.Format.LRM;
  23731. return s.replace(goog.i18n.bidi.bracketGuardTextRe_, mark + '$&' + mark);
  23732. };
  23733. /**
  23734. * Enforce the html snippet in RTL directionality regardless overall context.
  23735. * If the html piece was enclosed by tag, dir will be applied to existing
  23736. * tag, otherwise a span tag will be added as wrapper. For this reason, if
  23737. * html snippet start with with tag, this tag must enclose the whole piece. If
  23738. * the tag already has a dir specified, this new one will override existing
  23739. * one in behavior (tested on FF and IE).
  23740. * @param {string} html The string that need to be processed.
  23741. * @return {string} The processed string, with directionality enforced to RTL.
  23742. */
  23743. goog.i18n.bidi.enforceRtlInHtml = function(html) {
  23744. if (html.charAt(0) == '<') {
  23745. return html.replace(/<\w+/, '$& dir=rtl');
  23746. }
  23747. // '\n' is important for FF so that it won't incorrectly merge span groups
  23748. return '\n<span dir=rtl>' + html + '</span>';
  23749. };
  23750. /**
  23751. * Enforce RTL on both end of the given text piece using unicode BiDi formatting
  23752. * characters RLE and PDF.
  23753. * @param {string} text The piece of text that need to be wrapped.
  23754. * @return {string} The wrapped string after process.
  23755. */
  23756. goog.i18n.bidi.enforceRtlInText = function(text) {
  23757. return goog.i18n.bidi.Format.RLE + text + goog.i18n.bidi.Format.PDF;
  23758. };
  23759. /**
  23760. * Enforce the html snippet in RTL directionality regardless overall context.
  23761. * If the html piece was enclosed by tag, dir will be applied to existing
  23762. * tag, otherwise a span tag will be added as wrapper. For this reason, if
  23763. * html snippet start with with tag, this tag must enclose the whole piece. If
  23764. * the tag already has a dir specified, this new one will override existing
  23765. * one in behavior (tested on FF and IE).
  23766. * @param {string} html The string that need to be processed.
  23767. * @return {string} The processed string, with directionality enforced to RTL.
  23768. */
  23769. goog.i18n.bidi.enforceLtrInHtml = function(html) {
  23770. if (html.charAt(0) == '<') {
  23771. return html.replace(/<\w+/, '$& dir=ltr');
  23772. }
  23773. // '\n' is important for FF so that it won't incorrectly merge span groups
  23774. return '\n<span dir=ltr>' + html + '</span>';
  23775. };
  23776. /**
  23777. * Enforce LTR on both end of the given text piece using unicode BiDi formatting
  23778. * characters LRE and PDF.
  23779. * @param {string} text The piece of text that need to be wrapped.
  23780. * @return {string} The wrapped string after process.
  23781. */
  23782. goog.i18n.bidi.enforceLtrInText = function(text) {
  23783. return goog.i18n.bidi.Format.LRE + text + goog.i18n.bidi.Format.PDF;
  23784. };
  23785. /**
  23786. * Regular expression to find dimensions such as "padding: .3 0.4ex 5px 6;"
  23787. * @type {RegExp}
  23788. * @private
  23789. */
  23790. goog.i18n.bidi.dimensionsRe_ =
  23791. /:\s*([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)/g;
  23792. /**
  23793. * Regular expression for left.
  23794. * @type {RegExp}
  23795. * @private
  23796. */
  23797. goog.i18n.bidi.leftRe_ = /left/gi;
  23798. /**
  23799. * Regular expression for right.
  23800. * @type {RegExp}
  23801. * @private
  23802. */
  23803. goog.i18n.bidi.rightRe_ = /right/gi;
  23804. /**
  23805. * Placeholder regular expression for swapping.
  23806. * @type {RegExp}
  23807. * @private
  23808. */
  23809. goog.i18n.bidi.tempRe_ = /%%%%/g;
  23810. /**
  23811. * Swap location parameters and 'left'/'right' in CSS specification. The
  23812. * processed string will be suited for RTL layout. Though this function can
  23813. * cover most cases, there are always exceptions. It is suggested to put
  23814. * those exceptions in separate group of CSS string.
  23815. * @param {string} cssStr CSS spefication string.
  23816. * @return {string} Processed CSS specification string.
  23817. */
  23818. goog.i18n.bidi.mirrorCSS = function(cssStr) {
  23819. return cssStr.
  23820. // reverse dimensions
  23821. replace(goog.i18n.bidi.dimensionsRe_, ':$1 $4 $3 $2').
  23822. replace(goog.i18n.bidi.leftRe_, '%%%%'). // swap left and right
  23823. replace(goog.i18n.bidi.rightRe_, goog.i18n.bidi.LEFT).
  23824. replace(goog.i18n.bidi.tempRe_, goog.i18n.bidi.RIGHT);
  23825. };
  23826. /**
  23827. * Regular expression for hebrew double quote substitution, finding quote
  23828. * directly after hebrew characters.
  23829. * @type {RegExp}
  23830. * @private
  23831. */
  23832. goog.i18n.bidi.doubleQuoteSubstituteRe_ = /([\u0591-\u05f2])"/g;
  23833. /**
  23834. * Regular expression for hebrew single quote substitution, finding quote
  23835. * directly after hebrew characters.
  23836. * @type {RegExp}
  23837. * @private
  23838. */
  23839. goog.i18n.bidi.singleQuoteSubstituteRe_ = /([\u0591-\u05f2])'/g;
  23840. /**
  23841. * Replace the double and single quote directly after a Hebrew character with
  23842. * GERESH and GERSHAYIM. In such case, most likely that's user intention.
  23843. * @param {string} str String that need to be processed.
  23844. * @return {string} Processed string with double/single quote replaced.
  23845. */
  23846. goog.i18n.bidi.normalizeHebrewQuote = function(str) {
  23847. return str.
  23848. replace(goog.i18n.bidi.doubleQuoteSubstituteRe_, '$1\u05f4').
  23849. replace(goog.i18n.bidi.singleQuoteSubstituteRe_, '$1\u05f3');
  23850. };
  23851. /**
  23852. * Regular expression to split a string into "words" for directionality
  23853. * estimation based on relative word counts.
  23854. * @type {RegExp}
  23855. * @private
  23856. */
  23857. goog.i18n.bidi.wordSeparatorRe_ = /\s+/;
  23858. /**
  23859. * Regular expression to check if a string contains any numerals. Used to
  23860. * differentiate between completely neutral strings and those containing
  23861. * numbers, which are weakly LTR.
  23862. *
  23863. * Native Arabic digits (\u0660 - \u0669) are not included because although they
  23864. * do flow left-to-right inside a number, this is the case even if the overall
  23865. * directionality is RTL, and a mathematical expression using these digits is
  23866. * supposed to flow right-to-left overall, including unary plus and minus
  23867. * appearing to the right of a number, and this does depend on the overall
  23868. * directionality being RTL. The digits used in Farsi (\u06F0 - \u06F9), on the
  23869. * other hand, are included, since Farsi math (including unary plus and minus)
  23870. * does flow left-to-right.
  23871. *
  23872. * @type {RegExp}
  23873. * @private
  23874. */
  23875. goog.i18n.bidi.hasNumeralsRe_ = /[\d\u06f0-\u06f9]/;
  23876. /**
  23877. * This constant controls threshold of RTL directionality.
  23878. * @type {number}
  23879. * @private
  23880. */
  23881. goog.i18n.bidi.rtlDetectionThreshold_ = 0.40;
  23882. /**
  23883. * Estimates the directionality of a string based on relative word counts.
  23884. * If the number of RTL words is above a certain percentage of the total number
  23885. * of strongly directional words, returns RTL.
  23886. * Otherwise, if any words are strongly or weakly LTR, returns LTR.
  23887. * Otherwise, returns UNKNOWN, which is used to mean "neutral".
  23888. * Numbers are counted as weakly LTR.
  23889. * @param {string} str The string to be checked.
  23890. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23891. * Default: false.
  23892. * @return {goog.i18n.bidi.Dir} Estimated overall directionality of {@code str}.
  23893. */
  23894. goog.i18n.bidi.estimateDirection = function(str, opt_isHtml) {
  23895. var rtlCount = 0;
  23896. var totalCount = 0;
  23897. var hasWeaklyLtr = false;
  23898. var tokens = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml).
  23899. split(goog.i18n.bidi.wordSeparatorRe_);
  23900. for (var i = 0; i < tokens.length; i++) {
  23901. var token = tokens[i];
  23902. if (goog.i18n.bidi.startsWithRtl(token)) {
  23903. rtlCount++;
  23904. totalCount++;
  23905. } else if (goog.i18n.bidi.isRequiredLtrRe_.test(token)) {
  23906. hasWeaklyLtr = true;
  23907. } else if (goog.i18n.bidi.hasAnyLtr(token)) {
  23908. totalCount++;
  23909. } else if (goog.i18n.bidi.hasNumeralsRe_.test(token)) {
  23910. hasWeaklyLtr = true;
  23911. }
  23912. }
  23913. return totalCount == 0 ?
  23914. (hasWeaklyLtr ? goog.i18n.bidi.Dir.LTR : goog.i18n.bidi.Dir.NEUTRAL) :
  23915. (rtlCount / totalCount > goog.i18n.bidi.rtlDetectionThreshold_ ?
  23916. goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR);
  23917. };
  23918. /**
  23919. * Check the directionality of a piece of text, return true if the piece of
  23920. * text should be laid out in RTL direction.
  23921. * @param {string} str The piece of text that need to be detected.
  23922. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped.
  23923. * Default: false.
  23924. * @return {boolean} Whether this piece of text should be laid out in RTL.
  23925. */
  23926. goog.i18n.bidi.detectRtlDirectionality = function(str, opt_isHtml) {
  23927. return goog.i18n.bidi.estimateDirection(str, opt_isHtml) ==
  23928. goog.i18n.bidi.Dir.RTL;
  23929. };
  23930. /**
  23931. * Sets text input element's directionality and text alignment based on a
  23932. * given directionality. Does nothing if the given directionality is unknown or
  23933. * neutral.
  23934. * @param {Element} element Input field element to set directionality to.
  23935. * @param {goog.i18n.bidi.Dir|number|boolean|null} dir Desired directionality,
  23936. * given in one of the following formats:
  23937. * 1. A goog.i18n.bidi.Dir constant.
  23938. * 2. A number (positive = LRT, negative = RTL, 0 = neutral).
  23939. * 3. A boolean (true = RTL, false = LTR).
  23940. * 4. A null for unknown directionality.
  23941. */
  23942. goog.i18n.bidi.setElementDirAndAlign = function(element, dir) {
  23943. if (element) {
  23944. dir = goog.i18n.bidi.toDir(dir);
  23945. if (dir) {
  23946. element.style.textAlign =
  23947. dir == goog.i18n.bidi.Dir.RTL ?
  23948. goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT;
  23949. element.dir = dir == goog.i18n.bidi.Dir.RTL ? 'rtl' : 'ltr';
  23950. }
  23951. }
  23952. };
  23953. /**
  23954. * Sets element dir based on estimated directionality of the given text.
  23955. * @param {!Element} element
  23956. * @param {string} text
  23957. */
  23958. goog.i18n.bidi.setElementDirByTextDirectionality = function(element, text) {
  23959. switch (goog.i18n.bidi.estimateDirection(text)) {
  23960. case (goog.i18n.bidi.Dir.LTR):
  23961. element.dir = 'ltr';
  23962. break;
  23963. case (goog.i18n.bidi.Dir.RTL):
  23964. element.dir = 'rtl';
  23965. break;
  23966. default:
  23967. // Default for no direction, inherit from document.
  23968. element.removeAttribute('dir');
  23969. }
  23970. };
  23971. /**
  23972. * Strings that have an (optional) known direction.
  23973. *
  23974. * Implementations of this interface are string-like objects that carry an
  23975. * attached direction, if known.
  23976. * @interface
  23977. */
  23978. goog.i18n.bidi.DirectionalString = function() {};
  23979. /**
  23980. * Interface marker of the DirectionalString interface.
  23981. *
  23982. * This property can be used to determine at runtime whether or not an object
  23983. * implements this interface. All implementations of this interface set this
  23984. * property to {@code true}.
  23985. * @type {boolean}
  23986. */
  23987. goog.i18n.bidi.DirectionalString.prototype.
  23988. implementsGoogI18nBidiDirectionalString;
  23989. /**
  23990. * Retrieves this object's known direction (if any).
  23991. * @return {?goog.i18n.bidi.Dir} The known direction. Null if unknown.
  23992. */
  23993. goog.i18n.bidi.DirectionalString.prototype.getDirection;
  23994. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  23995. //
  23996. // Licensed under the Apache License, Version 2.0 (the "License");
  23997. // you may not use this file except in compliance with the License.
  23998. // You may obtain a copy of the License at
  23999. //
  24000. // http://www.apache.org/licenses/LICENSE-2.0
  24001. //
  24002. // Unless required by applicable law or agreed to in writing, software
  24003. // distributed under the License is distributed on an "AS-IS" BASIS,
  24004. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24005. // See the License for the specific language governing permissions and
  24006. // limitations under the License.
  24007. /**
  24008. * @fileoverview The SafeUrl type and its builders.
  24009. *
  24010. * TODO(xtof): Link to document stating type contract.
  24011. */
  24012. goog.provide('goog.html.SafeUrl');
  24013. goog.require('goog.asserts');
  24014. goog.require('goog.fs.url');
  24015. goog.require('goog.i18n.bidi.Dir');
  24016. goog.require('goog.i18n.bidi.DirectionalString');
  24017. goog.require('goog.string.Const');
  24018. goog.require('goog.string.TypedString');
  24019. /**
  24020. * A string that is safe to use in URL context in DOM APIs and HTML documents.
  24021. *
  24022. * A SafeUrl is a string-like object that carries the security type contract
  24023. * that its value as a string will not cause untrusted script execution
  24024. * when evaluated as a hyperlink URL in a browser.
  24025. *
  24026. * Values of this type are guaranteed to be safe to use in URL/hyperlink
  24027. * contexts, such as, assignment to URL-valued DOM properties, or
  24028. * interpolation into a HTML template in URL context (e.g., inside a href
  24029. * attribute), in the sense that the use will not result in a
  24030. * Cross-Site-Scripting vulnerability.
  24031. *
  24032. * Note that, as documented in {@code goog.html.SafeUrl.unwrap}, this type's
  24033. * contract does not guarantee that instances are safe to interpolate into HTML
  24034. * without appropriate escaping.
  24035. *
  24036. * Note also that this type's contract does not imply any guarantees regarding
  24037. * the resource the URL refers to. In particular, SafeUrls are <b>not</b>
  24038. * safe to use in a context where the referred-to resource is interpreted as
  24039. * trusted code, e.g., as the src of a script tag.
  24040. *
  24041. * Instances of this type must be created via the factory methods
  24042. * ({@code goog.html.SafeUrl.fromConstant}, {@code goog.html.SafeUrl.sanitize}),
  24043. * etc and not by invoking its constructor. The constructor intentionally
  24044. * takes no parameters and the type is immutable; hence only a default instance
  24045. * corresponding to the empty string can be obtained via constructor invocation.
  24046. *
  24047. * @see goog.html.SafeUrl#fromConstant
  24048. * @see goog.html.SafeUrl#from
  24049. * @see goog.html.SafeUrl#sanitize
  24050. * @constructor
  24051. * @final
  24052. * @struct
  24053. * @implements {goog.i18n.bidi.DirectionalString}
  24054. * @implements {goog.string.TypedString}
  24055. */
  24056. goog.html.SafeUrl = function() {
  24057. /**
  24058. * The contained value of this SafeUrl. The field has a purposely ugly
  24059. * name to make (non-compiled) code that attempts to directly access this
  24060. * field stand out.
  24061. * @private {string}
  24062. */
  24063. this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';
  24064. /**
  24065. * A type marker used to implement additional run-time type checking.
  24066. * @see goog.html.SafeUrl#unwrap
  24067. * @const
  24068. * @private
  24069. */
  24070. this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  24071. goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  24072. };
  24073. /**
  24074. * The innocuous string generated by goog.html.SafeUrl.sanitize when passed
  24075. * an unsafe URL.
  24076. *
  24077. * about:invalid is registered in
  24078. * http://www.w3.org/TR/css3-values/#about-invalid.
  24079. * http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to
  24080. * contain a fragment, which is not to be considered when determining if an
  24081. * about URL is well-known.
  24082. *
  24083. * Using about:invalid seems preferable to using a fixed data URL, since
  24084. * browsers might choose to not report CSP violations on it, as legitimate
  24085. * CSS function calls to attr() can result in this URL being produced. It is
  24086. * also a standard URL which matches exactly the semantics we need:
  24087. * "The about:invalid URI references a non-existent document with a generic
  24088. * error condition. It can be used when a URI is necessary, but the default
  24089. * value shouldn't be resolveable as any type of document".
  24090. *
  24091. * @const {string}
  24092. */
  24093. goog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez';
  24094. /**
  24095. * @override
  24096. * @const
  24097. */
  24098. goog.html.SafeUrl.prototype.implementsGoogStringTypedString = true;
  24099. /**
  24100. * Returns this SafeUrl's value a string.
  24101. *
  24102. * IMPORTANT: In code where it is security relevant that an object's type is
  24103. * indeed {@code SafeUrl}, use {@code goog.html.SafeUrl.unwrap} instead of this
  24104. * method. If in doubt, assume that it's security relevant. In particular, note
  24105. * that goog.html functions which return a goog.html type do not guarantee that
  24106. * the returned instance is of the right type. For example:
  24107. *
  24108. * <pre>
  24109. * var fakeSafeHtml = new String('fake');
  24110. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  24111. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  24112. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  24113. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
  24114. * // goog.html.SafeHtml.
  24115. * </pre>
  24116. *
  24117. * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
  24118. * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
  24119. * be appropriately escaped before embedding in a HTML document. Note that the
  24120. * required escaping is context-sensitive (e.g. a different escaping is
  24121. * required for embedding a URL in a style property within a style
  24122. * attribute, as opposed to embedding in a href attribute).
  24123. *
  24124. * @see goog.html.SafeUrl#unwrap
  24125. * @override
  24126. */
  24127. goog.html.SafeUrl.prototype.getTypedStringValue = function() {
  24128. return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
  24129. };
  24130. /**
  24131. * @override
  24132. * @const
  24133. */
  24134. goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true;
  24135. /**
  24136. * Returns this URLs directionality, which is always {@code LTR}.
  24137. * @override
  24138. */
  24139. goog.html.SafeUrl.prototype.getDirection = function() {
  24140. return goog.i18n.bidi.Dir.LTR;
  24141. };
  24142. if (goog.DEBUG) {
  24143. /**
  24144. * Returns a debug string-representation of this value.
  24145. *
  24146. * To obtain the actual string value wrapped in a SafeUrl, use
  24147. * {@code goog.html.SafeUrl.unwrap}.
  24148. *
  24149. * @see goog.html.SafeUrl#unwrap
  24150. * @override
  24151. */
  24152. goog.html.SafeUrl.prototype.toString = function() {
  24153. return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +
  24154. '}';
  24155. };
  24156. }
  24157. /**
  24158. * Performs a runtime check that the provided object is indeed a SafeUrl
  24159. * object, and returns its value.
  24160. *
  24161. * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the
  24162. * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST
  24163. * be appropriately escaped before embedding in a HTML document. Note that the
  24164. * required escaping is context-sensitive (e.g. a different escaping is
  24165. * required for embedding a URL in a style property within a style
  24166. * attribute, as opposed to embedding in a href attribute).
  24167. *
  24168. * @param {!goog.html.SafeUrl} safeUrl The object to extract from.
  24169. * @return {string} The SafeUrl object's contained string, unless the run-time
  24170. * type check fails. In that case, {@code unwrap} returns an innocuous
  24171. * string, or, if assertions are enabled, throws
  24172. * {@code goog.asserts.AssertionError}.
  24173. */
  24174. goog.html.SafeUrl.unwrap = function(safeUrl) {
  24175. // Perform additional Run-time type-checking to ensure that safeUrl is indeed
  24176. // an instance of the expected type. This provides some additional protection
  24177. // against security bugs due to application code that disables type checks.
  24178. // Specifically, the following checks are performed:
  24179. // 1. The object is an instance of the expected type.
  24180. // 2. The object is not an instance of a subclass.
  24181. // 3. The object carries a type marker for the expected type. "Faking" an
  24182. // object requires a reference to the type marker, which has names intended
  24183. // to stand out in code reviews.
  24184. if (safeUrl instanceof goog.html.SafeUrl &&
  24185. safeUrl.constructor === goog.html.SafeUrl &&
  24186. safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  24187. goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  24188. return safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
  24189. } else {
  24190. goog.asserts.fail('expected object of type SafeUrl, got \'' +
  24191. safeUrl + '\'');
  24192. return 'type_error:SafeUrl';
  24193. }
  24194. };
  24195. /**
  24196. * Creates a SafeUrl object from a compile-time constant string.
  24197. *
  24198. * Compile-time constant strings are inherently program-controlled and hence
  24199. * trusted.
  24200. *
  24201. * @param {!goog.string.Const} url A compile-time-constant string from which to
  24202. * create a SafeUrl.
  24203. * @return {!goog.html.SafeUrl} A SafeUrl object initialized to {@code url}.
  24204. */
  24205. goog.html.SafeUrl.fromConstant = function(url) {
  24206. return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
  24207. goog.string.Const.unwrap(url));
  24208. };
  24209. /**
  24210. * A pattern that matches Blob or data types that can have SafeUrls created
  24211. * from URL.createObjectURL(blob) or via a data: URI. Only matches image and
  24212. * video types, currently.
  24213. * @const
  24214. * @private
  24215. */
  24216. goog.html.SAFE_MIME_TYPE_PATTERN_ =
  24217. /^(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm))$/i;
  24218. /**
  24219. * Creates a SafeUrl wrapping a blob URL for the given {@code blob}.
  24220. *
  24221. * The blob URL is created with {@code URL.createObjectURL}. If the MIME type
  24222. * for {@code blob} is not of a known safe image or video MIME type, then the
  24223. * SafeUrl will wrap {@link #INNOCUOUS_STRING}.
  24224. *
  24225. * @see http://www.w3.org/TR/FileAPI/#url
  24226. * @param {!Blob} blob
  24227. * @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped
  24228. * as a SafeUrl.
  24229. */
  24230. goog.html.SafeUrl.fromBlob = function(blob) {
  24231. var url = goog.html.SAFE_MIME_TYPE_PATTERN_.test(blob.type) ?
  24232. goog.fs.url.createObjectUrl(blob) : goog.html.SafeUrl.INNOCUOUS_STRING;
  24233. return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
  24234. };
  24235. /**
  24236. * Matches a base-64 data URL, with the first match group being the MIME type.
  24237. * @const
  24238. * @private
  24239. */
  24240. goog.html.DATA_URL_PATTERN_ = /^data:([^;,]*);base64,[a-z0-9+\/]+=*$/i;
  24241. /**
  24242. * Creates a SafeUrl wrapping a data: URL, after validating it matches a
  24243. * known-safe image or video MIME type.
  24244. *
  24245. * @param {string} dataUrl A valid base64 data URL with one of the whitelisted
  24246. * image or video MIME types.
  24247. * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}
  24248. * wrapped as a SafeUrl if it does not pass.
  24249. */
  24250. goog.html.SafeUrl.fromDataUrl = function(dataUrl) {
  24251. // There's a slight risk here that a browser sniffs the content type if it
  24252. // doesn't know the MIME type and executes HTML within the data: URL. For this
  24253. // to cause XSS it would also have to execute the HTML in the same origin
  24254. // of the page with the link. It seems unlikely that both of these will
  24255. // happen, particularly in not really old IEs.
  24256. var match = dataUrl.match(goog.html.DATA_URL_PATTERN_);
  24257. var valid = match && goog.html.SAFE_MIME_TYPE_PATTERN_.test(match[1]);
  24258. return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(
  24259. valid ? dataUrl : goog.html.SafeUrl.INNOCUOUS_STRING);
  24260. };
  24261. /**
  24262. * A pattern that recognizes a commonly useful subset of URLs that satisfy
  24263. * the SafeUrl contract.
  24264. *
  24265. * This regular expression matches a subset of URLs that will not cause script
  24266. * execution if used in URL context within a HTML document. Specifically, this
  24267. * regular expression matches if (comment from here on and regex copied from
  24268. * Soy's EscapingConventions):
  24269. * (1) Either a protocol in a whitelist (http, https, mailto or ftp).
  24270. * (2) or no protocol. A protocol must be followed by a colon. The below
  24271. * allows that by allowing colons only after one of the characters [/?#].
  24272. * A colon after a hash (#) must be in the fragment.
  24273. * Otherwise, a colon after a (?) must be in a query.
  24274. * Otherwise, a colon after a single solidus (/) must be in a path.
  24275. * Otherwise, a colon after a double solidus (//) must be in the authority
  24276. * (before port).
  24277. *
  24278. * The pattern disallows &, used in HTML entity declarations before
  24279. * one of the characters in [/?#]. This disallows HTML entities used in the
  24280. * protocol name, which should never happen, e.g. "h&#116;tp" for "http".
  24281. * It also disallows HTML entities in the first path part of a relative path,
  24282. * e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce
  24283. * that. More importantly, it disallows masking of a colon,
  24284. * e.g. "javascript&#58;...".
  24285. *
  24286. * @private
  24287. * @const {!RegExp}
  24288. */
  24289. goog.html.SAFE_URL_PATTERN_ =
  24290. /^(?:(?:https?|mailto|ftp):|[^&:/?#]*(?:[/?#]|$))/i;
  24291. /**
  24292. * Creates a SafeUrl object from {@code url}. If {@code url} is a
  24293. * goog.html.SafeUrl then it is simply returned. Otherwise the input string is
  24294. * validated to match a pattern of commonly used safe URLs. The string is
  24295. * converted to UTF-8 and non-whitelisted characters are percent-encoded. The
  24296. * string wrapped by the created SafeUrl will thus contain only ASCII printable
  24297. * characters.
  24298. *
  24299. * {@code url} may be a URL with the http, https, mailto or ftp scheme,
  24300. * or a relative URL (i.e., a URL without a scheme; specifically, a
  24301. * scheme-relative, absolute-path-relative, or path-relative URL).
  24302. *
  24303. * {@code url} is converted to UTF-8 and non-whitelisted characters are
  24304. * percent-encoded. Whitelisted characters are '%' and, from RFC 3986,
  24305. * unreserved characters and reserved characters, with the exception of '\'',
  24306. * '(' and ')'. This ensures the the SafeUrl contains only ASCII-printable
  24307. * characters and reduces the chance of security bugs were it to be
  24308. * interpolated into a specific context without the necessary escaping.
  24309. *
  24310. * If {@code url} fails validation or does not UTF-16 decode correctly
  24311. * (JavaScript strings are UTF-16 encoded), this function returns a SafeUrl
  24312. * object containing an innocuous string, goog.html.SafeUrl.INNOCUOUS_STRING.
  24313. *
  24314. * @see http://url.spec.whatwg.org/#concept-relative-url
  24315. * @param {string|!goog.string.TypedString} url The URL to validate.
  24316. * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.
  24317. */
  24318. goog.html.SafeUrl.sanitize = function(url) {
  24319. if (url instanceof goog.html.SafeUrl) {
  24320. return url;
  24321. }
  24322. else if (url.implementsGoogStringTypedString) {
  24323. url = url.getTypedStringValue();
  24324. } else {
  24325. url = String(url);
  24326. }
  24327. if (!goog.html.SAFE_URL_PATTERN_.test(url)) {
  24328. url = goog.html.SafeUrl.INNOCUOUS_STRING;
  24329. }
  24330. return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
  24331. };
  24332. /**
  24333. * Type marker for the SafeUrl type, used to implement additional run-time
  24334. * type checking.
  24335. * @const {!Object}
  24336. * @private
  24337. */
  24338. goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  24339. /**
  24340. * Package-internal utility method to create SafeUrl instances.
  24341. *
  24342. * @param {string} url The string to initialize the SafeUrl object with.
  24343. * @return {!goog.html.SafeUrl} The initialized SafeUrl object.
  24344. * @package
  24345. */
  24346. goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function(
  24347. url) {
  24348. var safeUrl = new goog.html.SafeUrl();
  24349. safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = url;
  24350. return safeUrl;
  24351. };
  24352. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  24353. //
  24354. // Licensed under the Apache License, Version 2.0 (the "License");
  24355. // you may not use this file except in compliance with the License.
  24356. // You may obtain a copy of the License at
  24357. //
  24358. // http://www.apache.org/licenses/LICENSE-2.0
  24359. //
  24360. // Unless required by applicable law or agreed to in writing, software
  24361. // distributed under the License is distributed on an "AS-IS" BASIS,
  24362. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24363. // See the License for the specific language governing permissions and
  24364. // limitations under the License.
  24365. /**
  24366. * @fileoverview The TrustedResourceUrl type and its builders.
  24367. *
  24368. * TODO(xtof): Link to document stating type contract.
  24369. */
  24370. goog.provide('goog.html.TrustedResourceUrl');
  24371. goog.require('goog.asserts');
  24372. goog.require('goog.i18n.bidi.Dir');
  24373. goog.require('goog.i18n.bidi.DirectionalString');
  24374. goog.require('goog.string.Const');
  24375. goog.require('goog.string.TypedString');
  24376. /**
  24377. * A URL which is under application control and from which script, CSS, and
  24378. * other resources that represent executable code, can be fetched.
  24379. *
  24380. * Given that the URL can only be constructed from strings under application
  24381. * control and is used to load resources, bugs resulting in a malformed URL
  24382. * should not have a security impact and are likely to be easily detectable
  24383. * during testing. Given the wide number of non-RFC compliant URLs in use,
  24384. * stricter validation could prevent some applications from being able to use
  24385. * this type.
  24386. *
  24387. * Instances of this type must be created via the factory method,
  24388. * ({@code goog.html.TrustedResourceUrl.fromConstant}), and not by invoking its
  24389. * constructor. The constructor intentionally takes no parameters and the type
  24390. * is immutable; hence only a default instance corresponding to the empty
  24391. * string can be obtained via constructor invocation.
  24392. *
  24393. * @see goog.html.TrustedResourceUrl#fromConstant
  24394. * @constructor
  24395. * @final
  24396. * @struct
  24397. * @implements {goog.i18n.bidi.DirectionalString}
  24398. * @implements {goog.string.TypedString}
  24399. */
  24400. goog.html.TrustedResourceUrl = function() {
  24401. /**
  24402. * The contained value of this TrustedResourceUrl. The field has a purposely
  24403. * ugly name to make (non-compiled) code that attempts to directly access this
  24404. * field stand out.
  24405. * @private {string}
  24406. */
  24407. this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = '';
  24408. /**
  24409. * A type marker used to implement additional run-time type checking.
  24410. * @see goog.html.TrustedResourceUrl#unwrap
  24411. * @const
  24412. * @private
  24413. */
  24414. this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  24415. goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  24416. };
  24417. /**
  24418. * @override
  24419. * @const
  24420. */
  24421. goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true;
  24422. /**
  24423. * Returns this TrustedResourceUrl's value as a string.
  24424. *
  24425. * IMPORTANT: In code where it is security relevant that an object's type is
  24426. * indeed {@code TrustedResourceUrl}, use
  24427. * {@code goog.html.TrustedResourceUrl.unwrap} instead of this method. If in
  24428. * doubt, assume that it's security relevant. In particular, note that
  24429. * goog.html functions which return a goog.html type do not guarantee that
  24430. * the returned instance is of the right type. For example:
  24431. *
  24432. * <pre>
  24433. * var fakeSafeHtml = new String('fake');
  24434. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  24435. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  24436. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  24437. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof
  24438. * // goog.html.SafeHtml.
  24439. * </pre>
  24440. *
  24441. * @see goog.html.TrustedResourceUrl#unwrap
  24442. * @override
  24443. */
  24444. goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() {
  24445. return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
  24446. };
  24447. /**
  24448. * @override
  24449. * @const
  24450. */
  24451. goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString =
  24452. true;
  24453. /**
  24454. * Returns this URLs directionality, which is always {@code LTR}.
  24455. * @override
  24456. */
  24457. goog.html.TrustedResourceUrl.prototype.getDirection = function() {
  24458. return goog.i18n.bidi.Dir.LTR;
  24459. };
  24460. if (goog.DEBUG) {
  24461. /**
  24462. * Returns a debug string-representation of this value.
  24463. *
  24464. * To obtain the actual string value wrapped in a TrustedResourceUrl, use
  24465. * {@code goog.html.TrustedResourceUrl.unwrap}.
  24466. *
  24467. * @see goog.html.TrustedResourceUrl#unwrap
  24468. * @override
  24469. */
  24470. goog.html.TrustedResourceUrl.prototype.toString = function() {
  24471. return 'TrustedResourceUrl{' +
  24472. this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}';
  24473. };
  24474. }
  24475. /**
  24476. * Performs a runtime check that the provided object is indeed a
  24477. * TrustedResourceUrl object, and returns its value.
  24478. *
  24479. * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to
  24480. * extract from.
  24481. * @return {string} The trustedResourceUrl object's contained string, unless
  24482. * the run-time type check fails. In that case, {@code unwrap} returns an
  24483. * innocuous string, or, if assertions are enabled, throws
  24484. * {@code goog.asserts.AssertionError}.
  24485. */
  24486. goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) {
  24487. // Perform additional Run-time type-checking to ensure that
  24488. // trustedResourceUrl is indeed an instance of the expected type. This
  24489. // provides some additional protection against security bugs due to
  24490. // application code that disables type checks.
  24491. // Specifically, the following checks are performed:
  24492. // 1. The object is an instance of the expected type.
  24493. // 2. The object is not an instance of a subclass.
  24494. // 3. The object carries a type marker for the expected type. "Faking" an
  24495. // object requires a reference to the type marker, which has names intended
  24496. // to stand out in code reviews.
  24497. if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl &&
  24498. trustedResourceUrl.constructor === goog.html.TrustedResourceUrl &&
  24499. trustedResourceUrl
  24500. .TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  24501. goog.html.TrustedResourceUrl
  24502. .TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  24503. return trustedResourceUrl
  24504. .privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;
  24505. } else {
  24506. goog.asserts.fail('expected object of type TrustedResourceUrl, got \'' +
  24507. trustedResourceUrl + '\'');
  24508. return 'type_error:TrustedResourceUrl';
  24509. }
  24510. };
  24511. /**
  24512. * Creates a TrustedResourceUrl object from a compile-time constant string.
  24513. *
  24514. * Compile-time constant strings are inherently program-controlled and hence
  24515. * trusted.
  24516. *
  24517. * @param {!goog.string.Const} url A compile-time-constant string from which to
  24518. * create a TrustedResourceUrl.
  24519. * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object
  24520. * initialized to {@code url}.
  24521. */
  24522. goog.html.TrustedResourceUrl.fromConstant = function(url) {
  24523. return goog.html.TrustedResourceUrl
  24524. .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(
  24525. goog.string.Const.unwrap(url));
  24526. };
  24527. /**
  24528. * Type marker for the TrustedResourceUrl type, used to implement additional
  24529. * run-time type checking.
  24530. * @const {!Object}
  24531. * @private
  24532. */
  24533. goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  24534. /**
  24535. * Package-internal utility method to create TrustedResourceUrl instances.
  24536. *
  24537. * @param {string} url The string to initialize the TrustedResourceUrl object
  24538. * with.
  24539. * @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl
  24540. * object.
  24541. * @package
  24542. */
  24543. goog.html.TrustedResourceUrl.
  24544. createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) {
  24545. var trustedResourceUrl = new goog.html.TrustedResourceUrl();
  24546. trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ =
  24547. url;
  24548. return trustedResourceUrl;
  24549. };
  24550. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  24551. //
  24552. // Licensed under the Apache License, Version 2.0 (the "License");
  24553. // you may not use this file except in compliance with the License.
  24554. // You may obtain a copy of the License at
  24555. //
  24556. // http://www.apache.org/licenses/LICENSE-2.0
  24557. //
  24558. // Unless required by applicable law or agreed to in writing, software
  24559. // distributed under the License is distributed on an "AS-IS" BASIS,
  24560. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24561. // See the License for the specific language governing permissions and
  24562. // limitations under the License.
  24563. /**
  24564. * @fileoverview The SafeHtml type and its builders.
  24565. *
  24566. * TODO(xtof): Link to document stating type contract.
  24567. */
  24568. goog.provide('goog.html.SafeHtml');
  24569. goog.require('goog.array');
  24570. goog.require('goog.asserts');
  24571. goog.require('goog.dom.TagName');
  24572. goog.require('goog.dom.tags');
  24573. goog.require('goog.html.SafeStyle');
  24574. goog.require('goog.html.SafeStyleSheet');
  24575. goog.require('goog.html.SafeUrl');
  24576. goog.require('goog.html.TrustedResourceUrl');
  24577. goog.require('goog.i18n.bidi.Dir');
  24578. goog.require('goog.i18n.bidi.DirectionalString');
  24579. goog.require('goog.object');
  24580. goog.require('goog.string');
  24581. goog.require('goog.string.Const');
  24582. goog.require('goog.string.TypedString');
  24583. /**
  24584. * A string that is safe to use in HTML context in DOM APIs and HTML documents.
  24585. *
  24586. * A SafeHtml is a string-like object that carries the security type contract
  24587. * that its value as a string will not cause untrusted script execution when
  24588. * evaluated as HTML in a browser.
  24589. *
  24590. * Values of this type are guaranteed to be safe to use in HTML contexts,
  24591. * such as, assignment to the innerHTML DOM property, or interpolation into
  24592. * a HTML template in HTML PC_DATA context, in the sense that the use will not
  24593. * result in a Cross-Site-Scripting vulnerability.
  24594. *
  24595. * Instances of this type must be created via the factory methods
  24596. * ({@code goog.html.SafeHtml.create}, {@code goog.html.SafeHtml.htmlEscape}),
  24597. * etc and not by invoking its constructor. The constructor intentionally
  24598. * takes no parameters and the type is immutable; hence only a default instance
  24599. * corresponding to the empty string can be obtained via constructor invocation.
  24600. *
  24601. * @see goog.html.SafeHtml#create
  24602. * @see goog.html.SafeHtml#htmlEscape
  24603. * @constructor
  24604. * @final
  24605. * @struct
  24606. * @implements {goog.i18n.bidi.DirectionalString}
  24607. * @implements {goog.string.TypedString}
  24608. */
  24609. goog.html.SafeHtml = function() {
  24610. /**
  24611. * The contained value of this SafeHtml. The field has a purposely ugly
  24612. * name to make (non-compiled) code that attempts to directly access this
  24613. * field stand out.
  24614. * @private {string}
  24615. */
  24616. this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';
  24617. /**
  24618. * A type marker used to implement additional run-time type checking.
  24619. * @see goog.html.SafeHtml#unwrap
  24620. * @const
  24621. * @private
  24622. */
  24623. this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  24624. goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  24625. /**
  24626. * This SafeHtml's directionality, or null if unknown.
  24627. * @private {?goog.i18n.bidi.Dir}
  24628. */
  24629. this.dir_ = null;
  24630. };
  24631. /**
  24632. * @override
  24633. * @const
  24634. */
  24635. goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true;
  24636. /** @override */
  24637. goog.html.SafeHtml.prototype.getDirection = function() {
  24638. return this.dir_;
  24639. };
  24640. /**
  24641. * @override
  24642. * @const
  24643. */
  24644. goog.html.SafeHtml.prototype.implementsGoogStringTypedString = true;
  24645. /**
  24646. * Returns this SafeHtml's value a string.
  24647. *
  24648. * IMPORTANT: In code where it is security relevant that an object's type is
  24649. * indeed {@code SafeHtml}, use {@code goog.html.SafeHtml.unwrap} instead of
  24650. * this method. If in doubt, assume that it's security relevant. In particular,
  24651. * note that goog.html functions which return a goog.html type do not guarantee
  24652. * that the returned instance is of the right type. For example:
  24653. *
  24654. * <pre>
  24655. * var fakeSafeHtml = new String('fake');
  24656. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  24657. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  24658. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  24659. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
  24660. * // instanceof goog.html.SafeHtml.
  24661. * </pre>
  24662. *
  24663. * @see goog.html.SafeHtml#unwrap
  24664. * @override
  24665. */
  24666. goog.html.SafeHtml.prototype.getTypedStringValue = function() {
  24667. return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
  24668. };
  24669. if (goog.DEBUG) {
  24670. /**
  24671. * Returns a debug string-representation of this value.
  24672. *
  24673. * To obtain the actual string value wrapped in a SafeHtml, use
  24674. * {@code goog.html.SafeHtml.unwrap}.
  24675. *
  24676. * @see goog.html.SafeHtml#unwrap
  24677. * @override
  24678. */
  24679. goog.html.SafeHtml.prototype.toString = function() {
  24680. return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +
  24681. '}';
  24682. };
  24683. }
  24684. /**
  24685. * Performs a runtime check that the provided object is indeed a SafeHtml
  24686. * object, and returns its value.
  24687. * @param {!goog.html.SafeHtml} safeHtml The object to extract from.
  24688. * @return {string} The SafeHtml object's contained string, unless the run-time
  24689. * type check fails. In that case, {@code unwrap} returns an innocuous
  24690. * string, or, if assertions are enabled, throws
  24691. * {@code goog.asserts.AssertionError}.
  24692. */
  24693. goog.html.SafeHtml.unwrap = function(safeHtml) {
  24694. // Perform additional run-time type-checking to ensure that safeHtml is indeed
  24695. // an instance of the expected type. This provides some additional protection
  24696. // against security bugs due to application code that disables type checks.
  24697. // Specifically, the following checks are performed:
  24698. // 1. The object is an instance of the expected type.
  24699. // 2. The object is not an instance of a subclass.
  24700. // 3. The object carries a type marker for the expected type. "Faking" an
  24701. // object requires a reference to the type marker, which has names intended
  24702. // to stand out in code reviews.
  24703. if (safeHtml instanceof goog.html.SafeHtml &&
  24704. safeHtml.constructor === goog.html.SafeHtml &&
  24705. safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  24706. goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  24707. return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_;
  24708. } else {
  24709. goog.asserts.fail('expected object of type SafeHtml, got \'' +
  24710. safeHtml + '\'');
  24711. return 'type_error:SafeHtml';
  24712. }
  24713. };
  24714. /**
  24715. * Shorthand for union of types that can sensibly be converted to strings
  24716. * or might already be SafeHtml (as SafeHtml is a goog.string.TypedString).
  24717. * @private
  24718. * @typedef {string|number|boolean|!goog.string.TypedString|
  24719. * !goog.i18n.bidi.DirectionalString}
  24720. */
  24721. goog.html.SafeHtml.TextOrHtml_;
  24722. /**
  24723. * Returns HTML-escaped text as a SafeHtml object.
  24724. *
  24725. * If text is of a type that implements
  24726. * {@code goog.i18n.bidi.DirectionalString}, the directionality of the new
  24727. * {@code SafeHtml} object is set to {@code text}'s directionality, if known.
  24728. * Otherwise, the directionality of the resulting SafeHtml is unknown (i.e.,
  24729. * {@code null}).
  24730. *
  24731. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
  24732. * the parameter is of type SafeHtml it is returned directly (no escaping
  24733. * is done).
  24734. * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
  24735. */
  24736. goog.html.SafeHtml.htmlEscape = function(textOrHtml) {
  24737. if (textOrHtml instanceof goog.html.SafeHtml) {
  24738. return textOrHtml;
  24739. }
  24740. var dir = null;
  24741. if (textOrHtml.implementsGoogI18nBidiDirectionalString) {
  24742. dir = textOrHtml.getDirection();
  24743. }
  24744. var textAsString;
  24745. if (textOrHtml.implementsGoogStringTypedString) {
  24746. textAsString = textOrHtml.getTypedStringValue();
  24747. } else {
  24748. textAsString = String(textOrHtml);
  24749. }
  24750. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  24751. goog.string.htmlEscape(textAsString), dir);
  24752. };
  24753. /**
  24754. * Returns HTML-escaped text as a SafeHtml object, with newlines changed to
  24755. * &lt;br&gt;.
  24756. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
  24757. * the parameter is of type SafeHtml it is returned directly (no escaping
  24758. * is done).
  24759. * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
  24760. */
  24761. goog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) {
  24762. if (textOrHtml instanceof goog.html.SafeHtml) {
  24763. return textOrHtml;
  24764. }
  24765. var html = goog.html.SafeHtml.htmlEscape(textOrHtml);
  24766. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  24767. goog.string.newLineToBr(goog.html.SafeHtml.unwrap(html)),
  24768. html.getDirection());
  24769. };
  24770. /**
  24771. * Returns HTML-escaped text as a SafeHtml object, with newlines changed to
  24772. * &lt;br&gt; and escaping whitespace to preserve spatial formatting. Character
  24773. * entity #160 is used to make it safer for XML.
  24774. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If
  24775. * the parameter is of type SafeHtml it is returned directly (no escaping
  24776. * is done).
  24777. * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.
  24778. */
  24779. goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function(
  24780. textOrHtml) {
  24781. if (textOrHtml instanceof goog.html.SafeHtml) {
  24782. return textOrHtml;
  24783. }
  24784. var html = goog.html.SafeHtml.htmlEscape(textOrHtml);
  24785. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  24786. goog.string.whitespaceEscape(goog.html.SafeHtml.unwrap(html)),
  24787. html.getDirection());
  24788. };
  24789. /**
  24790. * Coerces an arbitrary object into a SafeHtml object.
  24791. *
  24792. * If {@code textOrHtml} is already of type {@code goog.html.SafeHtml}, the same
  24793. * object is returned. Otherwise, {@code textOrHtml} is coerced to string, and
  24794. * HTML-escaped. If {@code textOrHtml} is of a type that implements
  24795. * {@code goog.i18n.bidi.DirectionalString}, its directionality, if known, is
  24796. * preserved.
  24797. *
  24798. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to
  24799. * coerce.
  24800. * @return {!goog.html.SafeHtml} The resulting SafeHtml object.
  24801. * @deprecated Use goog.html.SafeHtml.htmlEscape.
  24802. */
  24803. goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape;
  24804. /**
  24805. * @const
  24806. * @private
  24807. */
  24808. goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/;
  24809. /**
  24810. * Set of attributes containing URL as defined at
  24811. * http://www.w3.org/TR/html5/index.html#attributes-1.
  24812. * @private @const {!Object<string,boolean>}
  24813. */
  24814. goog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet('action', 'cite',
  24815. 'data', 'formaction', 'href', 'manifest', 'poster', 'src');
  24816. /**
  24817. * Tags which are unsupported via create(). They might be supported via a
  24818. * tag-specific create method. These are tags which might require a
  24819. * TrustedResourceUrl in one of their attributes or a restricted type for
  24820. * their content.
  24821. * @private @const {!Object<string,boolean>}
  24822. */
  24823. goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet(
  24824. goog.dom.TagName.EMBED, goog.dom.TagName.IFRAME, goog.dom.TagName.LINK,
  24825. goog.dom.TagName.OBJECT, goog.dom.TagName.SCRIPT, goog.dom.TagName.STYLE,
  24826. goog.dom.TagName.TEMPLATE);
  24827. /**
  24828. * @typedef {string|number|goog.string.TypedString|
  24829. * goog.html.SafeStyle.PropertyMap}
  24830. * @private
  24831. */
  24832. goog.html.SafeHtml.AttributeValue_;
  24833. /**
  24834. * Creates a SafeHtml content consisting of a tag with optional attributes and
  24835. * optional content.
  24836. *
  24837. * For convenience tag names and attribute names are accepted as regular
  24838. * strings, instead of goog.string.Const. Nevertheless, you should not pass
  24839. * user-controlled values to these parameters. Note that these parameters are
  24840. * syntactically validated at runtime, and invalid values will result in
  24841. * an exception.
  24842. *
  24843. * Example usage:
  24844. *
  24845. * goog.html.SafeHtml.create('br');
  24846. * goog.html.SafeHtml.create('div', {'class': 'a'});
  24847. * goog.html.SafeHtml.create('p', {}, 'a');
  24848. * goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br'));
  24849. *
  24850. * goog.html.SafeHtml.create('span', {
  24851. * 'style': {'margin': '0'}
  24852. * });
  24853. *
  24854. * To guarantee SafeHtml's type contract is upheld there are restrictions on
  24855. * attribute values and tag names.
  24856. *
  24857. * - For attributes which contain script code (on*), a goog.string.Const is
  24858. * required.
  24859. * - For attributes which contain style (style), a goog.html.SafeStyle or a
  24860. * goog.html.SafeStyle.PropertyMap is required.
  24861. * - For attributes which are interpreted as URLs (e.g. src, href) a
  24862. * goog.html.SafeUrl, goog.string.Const or string is required. If a string
  24863. * is passed, it will be sanitized with SafeUrl.sanitize().
  24864. * - For tags which can load code, more specific goog.html.SafeHtml.create*()
  24865. * functions must be used. Tags which can load code and are not supported by
  24866. * this function are embed, iframe, link, object, script, style, and template.
  24867. *
  24868. * @param {string} tagName The name of the tag. Only tag names consisting of
  24869. * [a-zA-Z0-9-] are allowed. Tag names documented above are disallowed.
  24870. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
  24871. * opt_attributes Mapping from attribute names to their values. Only
  24872. * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
  24873. * undefined causes the attribute to be omitted.
  24874. * @param {!goog.html.SafeHtml.TextOrHtml_|
  24875. * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to
  24876. * HTML-escape and put inside the tag. This must be empty for void tags
  24877. * like <br>. Array elements are concatenated.
  24878. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
  24879. * @throws {Error} If invalid tag name, attribute name, or attribute value is
  24880. * provided.
  24881. * @throws {goog.asserts.AssertionError} If content for void tag is provided.
  24882. */
  24883. goog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) {
  24884. if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) {
  24885. throw Error('Invalid tag name <' + tagName + '>.');
  24886. }
  24887. if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) {
  24888. throw Error('Tag name <' + tagName + '> is not allowed for SafeHtml.');
  24889. }
  24890. return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
  24891. tagName, opt_attributes, opt_content);
  24892. };
  24893. /**
  24894. * Creates a SafeHtml representing an iframe tag.
  24895. *
  24896. * By default the sandbox attribute is set to an empty value, which is the most
  24897. * secure option, as it confers the iframe the least privileges. If this
  24898. * is too restrictive then granting individual privileges is the preferable
  24899. * option. Unsetting the attribute entirely is the least secure option and
  24900. * should never be done unless it's stricly necessary.
  24901. *
  24902. * @param {goog.html.TrustedResourceUrl=} opt_src The value of the src
  24903. * attribute. If null or undefined src will not be set.
  24904. * @param {goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute.
  24905. * If null or undefined srcdoc will not be set.
  24906. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
  24907. * opt_attributes Mapping from attribute names to their values. Only
  24908. * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
  24909. * undefined causes the attribute to be omitted.
  24910. * @param {!goog.html.SafeHtml.TextOrHtml_|
  24911. * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to
  24912. * HTML-escape and put inside the tag. Array elements are concatenated.
  24913. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
  24914. * @throws {Error} If invalid tag name, attribute name, or attribute value is
  24915. * provided. If opt_attributes contains the src or srcdoc attributes.
  24916. */
  24917. goog.html.SafeHtml.createIframe = function(
  24918. opt_src, opt_srcdoc, opt_attributes, opt_content) {
  24919. var fixedAttributes = {};
  24920. fixedAttributes['src'] = opt_src || null;
  24921. fixedAttributes['srcdoc'] = opt_srcdoc || null;
  24922. var defaultAttributes = {'sandbox': ''};
  24923. var attributes = goog.html.SafeHtml.combineAttributes(
  24924. fixedAttributes, defaultAttributes, opt_attributes);
  24925. return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
  24926. 'iframe', attributes, opt_content);
  24927. };
  24928. /**
  24929. * Creates a SafeHtml representing a style tag. The type attribute is set
  24930. * to "text/css".
  24931. * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}
  24932. * styleSheet Content to put inside the tag. Array elements are
  24933. * concatenated.
  24934. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
  24935. * opt_attributes Mapping from attribute names to their values. Only
  24936. * attribute names consisting of [a-zA-Z0-9-] are allowed. Value of null or
  24937. * undefined causes the attribute to be omitted.
  24938. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
  24939. * @throws {Error} If invalid attribute name or attribute value is provided. If
  24940. * opt_attributes contains the type attribute.
  24941. */
  24942. goog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) {
  24943. var fixedAttributes = {'type': 'text/css'};
  24944. var defaultAttributes = {};
  24945. var attributes = goog.html.SafeHtml.combineAttributes(
  24946. fixedAttributes, defaultAttributes, opt_attributes);
  24947. var content = '';
  24948. styleSheet = goog.array.concat(styleSheet);
  24949. for (var i = 0; i < styleSheet.length; i++) {
  24950. content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]);
  24951. }
  24952. // Convert to SafeHtml so that it's not HTML-escaped.
  24953. var htmlContent = goog.html.SafeHtml
  24954. .createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  24955. content, goog.i18n.bidi.Dir.NEUTRAL);
  24956. return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(
  24957. 'style', attributes, htmlContent);
  24958. };
  24959. /**
  24960. * @param {string} tagName The tag name.
  24961. * @param {string} name The attribute name.
  24962. * @param {!goog.html.SafeHtml.AttributeValue_} value The attribute value.
  24963. * @return {string} A "name=value" string.
  24964. * @throws {Error} If attribute value is unsafe for the given tag and attribute.
  24965. * @private
  24966. */
  24967. goog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) {
  24968. // If it's goog.string.Const, allow any valid attribute name.
  24969. if (value instanceof goog.string.Const) {
  24970. value = goog.string.Const.unwrap(value);
  24971. } else if (name.toLowerCase() == 'style') {
  24972. value = goog.html.SafeHtml.getStyleValue_(value);
  24973. } else if (/^on/i.test(name)) {
  24974. // TODO(jakubvrana): Disallow more attributes with a special meaning.
  24975. throw Error('Attribute "' + name +
  24976. '" requires goog.string.Const value, "' + value + '" given.');
  24977. // URL attributes handled differently accroding to tag.
  24978. } else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) {
  24979. if (value instanceof goog.html.TrustedResourceUrl) {
  24980. value = goog.html.TrustedResourceUrl.unwrap(value);
  24981. } else if (value instanceof goog.html.SafeUrl) {
  24982. value = goog.html.SafeUrl.unwrap(value);
  24983. } else if (goog.isString(value)) {
  24984. value = goog.html.SafeUrl.sanitize(value).getTypedStringValue();
  24985. } else {
  24986. throw Error('Attribute "' + name + '" on tag "' + tagName +
  24987. '" requires goog.html.SafeUrl, goog.string.Const, or string,' +
  24988. ' value "' + value + '" given.');
  24989. }
  24990. }
  24991. // Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require
  24992. // HTML-escaping.
  24993. if (value.implementsGoogStringTypedString) {
  24994. // Ok to call getTypedStringValue() since there's no reliance on the type
  24995. // contract for security here.
  24996. value = value.getTypedStringValue();
  24997. }
  24998. goog.asserts.assert(goog.isString(value) || goog.isNumber(value),
  24999. 'String or number value expected, got ' +
  25000. (typeof value) + ' with value: ' + value);
  25001. return name + '="' + goog.string.htmlEscape(String(value)) + '"';
  25002. };
  25003. /**
  25004. * Gets value allowed in "style" attribute.
  25005. * @param {goog.html.SafeHtml.AttributeValue_} value It could be SafeStyle or a
  25006. * map which will be passed to goog.html.SafeStyle.create.
  25007. * @return {string} Unwrapped value.
  25008. * @throws {Error} If string value is given.
  25009. * @private
  25010. */
  25011. goog.html.SafeHtml.getStyleValue_ = function(value) {
  25012. if (!goog.isObject(value)) {
  25013. throw Error('The "style" attribute requires goog.html.SafeStyle or map ' +
  25014. 'of style properties, ' + (typeof value) + ' given: ' + value);
  25015. }
  25016. if (!(value instanceof goog.html.SafeStyle)) {
  25017. // Process the property bag into a style object.
  25018. value = goog.html.SafeStyle.create(value);
  25019. }
  25020. return goog.html.SafeStyle.unwrap(value);
  25021. };
  25022. /**
  25023. * Creates a SafeHtml content with known directionality consisting of a tag with
  25024. * optional attributes and optional content.
  25025. * @param {!goog.i18n.bidi.Dir} dir Directionality.
  25026. * @param {string} tagName
  25027. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes
  25028. * @param {!goog.html.SafeHtml.TextOrHtml_|
  25029. * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content
  25030. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.
  25031. */
  25032. goog.html.SafeHtml.createWithDir = function(dir, tagName, opt_attributes,
  25033. opt_content) {
  25034. var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content);
  25035. html.dir_ = dir;
  25036. return html;
  25037. };
  25038. /**
  25039. * Creates a new SafeHtml object by concatenating values.
  25040. * @param {...(!goog.html.SafeHtml.TextOrHtml_|
  25041. * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Values to concatenate.
  25042. * @return {!goog.html.SafeHtml}
  25043. */
  25044. goog.html.SafeHtml.concat = function(var_args) {
  25045. var dir = goog.i18n.bidi.Dir.NEUTRAL;
  25046. var content = '';
  25047. /**
  25048. * @param {!goog.html.SafeHtml.TextOrHtml_|
  25049. * !Array<!goog.html.SafeHtml.TextOrHtml_>} argument
  25050. */
  25051. var addArgument = function(argument) {
  25052. if (goog.isArray(argument)) {
  25053. goog.array.forEach(argument, addArgument);
  25054. } else {
  25055. var html = goog.html.SafeHtml.htmlEscape(argument);
  25056. content += goog.html.SafeHtml.unwrap(html);
  25057. var htmlDir = html.getDirection();
  25058. if (dir == goog.i18n.bidi.Dir.NEUTRAL) {
  25059. dir = htmlDir;
  25060. } else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) {
  25061. dir = null;
  25062. }
  25063. }
  25064. };
  25065. goog.array.forEach(arguments, addArgument);
  25066. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  25067. content, dir);
  25068. };
  25069. /**
  25070. * Creates a new SafeHtml object with known directionality by concatenating the
  25071. * values.
  25072. * @param {!goog.i18n.bidi.Dir} dir Directionality.
  25073. * @param {...(!goog.html.SafeHtml.TextOrHtml_|
  25074. * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Elements of array
  25075. * arguments would be processed recursively.
  25076. * @return {!goog.html.SafeHtml}
  25077. */
  25078. goog.html.SafeHtml.concatWithDir = function(dir, var_args) {
  25079. var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1));
  25080. html.dir_ = dir;
  25081. return html;
  25082. };
  25083. /**
  25084. * Type marker for the SafeHtml type, used to implement additional run-time
  25085. * type checking.
  25086. * @const {!Object}
  25087. * @private
  25088. */
  25089. goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  25090. /**
  25091. * Package-internal utility method to create SafeHtml instances.
  25092. *
  25093. * @param {string} html The string to initialize the SafeHtml object with.
  25094. * @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be
  25095. * constructed, or null if unknown.
  25096. * @return {!goog.html.SafeHtml} The initialized SafeHtml object.
  25097. * @package
  25098. */
  25099. goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function(
  25100. html, dir) {
  25101. return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_(
  25102. html, dir);
  25103. };
  25104. /**
  25105. * Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This
  25106. * method exists only so that the compiler can dead code eliminate static
  25107. * fields (like EMPTY) when they're not accessed.
  25108. * @param {string} html
  25109. * @param {?goog.i18n.bidi.Dir} dir
  25110. * @return {!goog.html.SafeHtml}
  25111. * @private
  25112. */
  25113. goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
  25114. html, dir) {
  25115. this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html;
  25116. this.dir_ = dir;
  25117. return this;
  25118. };
  25119. /**
  25120. * Like create() but does not restrict which tags can be constructed.
  25121. *
  25122. * @param {string} tagName Tag name. Set or validated by caller.
  25123. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=} opt_attributes
  25124. * @param {(!goog.html.SafeHtml.TextOrHtml_|
  25125. * !Array<!goog.html.SafeHtml.TextOrHtml_>)=} opt_content
  25126. * @return {!goog.html.SafeHtml}
  25127. * @throws {Error} If invalid or unsafe attribute name or value is provided.
  25128. * @throws {goog.asserts.AssertionError} If content for void tag is provided.
  25129. * @package
  25130. */
  25131. goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse =
  25132. function(tagName, opt_attributes, opt_content) {
  25133. var dir = null;
  25134. var result = '<' + tagName;
  25135. if (opt_attributes) {
  25136. for (var name in opt_attributes) {
  25137. if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) {
  25138. throw Error('Invalid attribute name "' + name + '".');
  25139. }
  25140. var value = opt_attributes[name];
  25141. if (!goog.isDefAndNotNull(value)) {
  25142. continue;
  25143. }
  25144. result += ' ' +
  25145. goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value);
  25146. }
  25147. }
  25148. var content = opt_content;
  25149. if (!goog.isDefAndNotNull(content)) {
  25150. content = [];
  25151. } else if (!goog.isArray(content)) {
  25152. content = [content];
  25153. }
  25154. if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) {
  25155. goog.asserts.assert(!content.length,
  25156. 'Void tag <' + tagName + '> does not allow content.');
  25157. result += '>';
  25158. } else {
  25159. var html = goog.html.SafeHtml.concat(content);
  25160. result += '>' + goog.html.SafeHtml.unwrap(html) + '</' + tagName + '>';
  25161. dir = html.getDirection();
  25162. }
  25163. var dirAttribute = opt_attributes && opt_attributes['dir'];
  25164. if (dirAttribute) {
  25165. if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) {
  25166. // If the tag has the "dir" attribute specified then its direction is
  25167. // neutral because it can be safely used in any context.
  25168. dir = goog.i18n.bidi.Dir.NEUTRAL;
  25169. } else {
  25170. dir = null;
  25171. }
  25172. }
  25173. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  25174. result, dir);
  25175. };
  25176. /**
  25177. * @param {!Object<string, string>} fixedAttributes
  25178. * @param {!Object<string, string>} defaultAttributes
  25179. * @param {!Object<string, goog.html.SafeHtml.AttributeValue_>=}
  25180. * opt_attributes Optional attributes passed to create*().
  25181. * @return {!Object<string, goog.html.SafeHtml.AttributeValue_>}
  25182. * @throws {Error} If opt_attributes contains an attribute with the same name
  25183. * as an attribute in fixedAttributes.
  25184. * @package
  25185. */
  25186. goog.html.SafeHtml.combineAttributes = function(
  25187. fixedAttributes, defaultAttributes, opt_attributes) {
  25188. var combinedAttributes = {};
  25189. var name;
  25190. for (name in fixedAttributes) {
  25191. goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');
  25192. combinedAttributes[name] = fixedAttributes[name];
  25193. }
  25194. for (name in defaultAttributes) {
  25195. goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');
  25196. combinedAttributes[name] = defaultAttributes[name];
  25197. }
  25198. for (name in opt_attributes) {
  25199. var nameLower = name.toLowerCase();
  25200. if (nameLower in fixedAttributes) {
  25201. throw Error('Cannot override "' + nameLower + '" attribute, got "' +
  25202. name + '" with value "' + opt_attributes[name] + '"');
  25203. }
  25204. if (nameLower in defaultAttributes) {
  25205. delete combinedAttributes[nameLower];
  25206. }
  25207. combinedAttributes[name] = opt_attributes[name];
  25208. }
  25209. return combinedAttributes;
  25210. };
  25211. /**
  25212. * A SafeHtml instance corresponding to the HTML doctype: "<!DOCTYPE html>".
  25213. * @const {!goog.html.SafeHtml}
  25214. */
  25215. goog.html.SafeHtml.DOCTYPE_HTML =
  25216. goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  25217. '<!DOCTYPE html>', goog.i18n.bidi.Dir.NEUTRAL);
  25218. /**
  25219. * A SafeHtml instance corresponding to the empty string.
  25220. * @const {!goog.html.SafeHtml}
  25221. */
  25222. goog.html.SafeHtml.EMPTY =
  25223. goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  25224. '', goog.i18n.bidi.Dir.NEUTRAL);
  25225. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  25226. //
  25227. // Licensed under the Apache License, Version 2.0 (the "License");
  25228. // you may not use this file except in compliance with the License.
  25229. // You may obtain a copy of the License at
  25230. //
  25231. // http://www.apache.org/licenses/LICENSE-2.0
  25232. //
  25233. // Unless required by applicable law or agreed to in writing, software
  25234. // distributed under the License is distributed on an "AS-IS" BASIS,
  25235. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25236. // See the License for the specific language governing permissions and
  25237. // limitations under the License.
  25238. /**
  25239. * @fileoverview Type-safe wrappers for unsafe DOM APIs.
  25240. *
  25241. * This file provides type-safe wrappers for DOM APIs that can result in
  25242. * cross-site scripting (XSS) vulnerabilities, if the API is supplied with
  25243. * untrusted (attacker-controlled) input. Instead of plain strings, the type
  25244. * safe wrappers consume values of types from the goog.html package whose
  25245. * contract promises that values are safe to use in the corresponding context.
  25246. *
  25247. * Hence, a program that exclusively uses the wrappers in this file (i.e., whose
  25248. * only reference to security-sensitive raw DOM APIs are in this file) is
  25249. * guaranteed to be free of XSS due to incorrect use of such DOM APIs (modulo
  25250. * correctness of code that produces values of the respective goog.html types,
  25251. * and absent code that violates type safety).
  25252. *
  25253. * For example, assigning to an element's .innerHTML property a string that is
  25254. * derived (even partially) from untrusted input typically results in an XSS
  25255. * vulnerability. The type-safe wrapper goog.html.setInnerHtml consumes a value
  25256. * of type goog.html.SafeHtml, whose contract states that using its values in a
  25257. * HTML context will not result in XSS. Hence a program that is free of direct
  25258. * assignments to any element's innerHTML property (with the exception of the
  25259. * assignment to .innerHTML in this file) is guaranteed to be free of XSS due to
  25260. * assignment of untrusted strings to the innerHTML property.
  25261. */
  25262. goog.provide('goog.dom.safe');
  25263. goog.provide('goog.dom.safe.InsertAdjacentHtmlPosition');
  25264. goog.require('goog.asserts');
  25265. goog.require('goog.html.SafeHtml');
  25266. goog.require('goog.html.SafeUrl');
  25267. goog.require('goog.html.TrustedResourceUrl');
  25268. goog.require('goog.string');
  25269. goog.require('goog.string.Const');
  25270. /** @enum {string} */
  25271. goog.dom.safe.InsertAdjacentHtmlPosition = {
  25272. AFTERBEGIN: 'afterbegin',
  25273. AFTEREND: 'afterend',
  25274. BEFOREBEGIN: 'beforebegin',
  25275. BEFOREEND: 'beforeend'
  25276. };
  25277. /**
  25278. * Inserts known-safe HTML into a Node, at the specified position.
  25279. * @param {!Node} node The node on which to call insertAdjacentHTML.
  25280. * @param {!goog.dom.safe.InsertAdjacentHtmlPosition} position Position where
  25281. * to insert the HTML.
  25282. * @param {!goog.html.SafeHtml} html The known-safe HTML to insert.
  25283. */
  25284. goog.dom.safe.insertAdjacentHtml = function(node, position, html) {
  25285. node.insertAdjacentHTML(position, goog.html.SafeHtml.unwrap(html));
  25286. };
  25287. /**
  25288. * Assigns known-safe HTML to an element's innerHTML property.
  25289. * @param {!Element} elem The element whose innerHTML is to be assigned to.
  25290. * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.
  25291. */
  25292. goog.dom.safe.setInnerHtml = function(elem, html) {
  25293. elem.innerHTML = goog.html.SafeHtml.unwrap(html);
  25294. };
  25295. /**
  25296. * Assigns known-safe HTML to an element's outerHTML property.
  25297. * @param {!Element} elem The element whose outerHTML is to be assigned to.
  25298. * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.
  25299. */
  25300. goog.dom.safe.setOuterHtml = function(elem, html) {
  25301. elem.outerHTML = goog.html.SafeHtml.unwrap(html);
  25302. };
  25303. /**
  25304. * Writes known-safe HTML to a document.
  25305. * @param {!Document} doc The document to be written to.
  25306. * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.
  25307. */
  25308. goog.dom.safe.documentWrite = function(doc, html) {
  25309. doc.write(goog.html.SafeHtml.unwrap(html));
  25310. };
  25311. /**
  25312. * Safely assigns a URL to an anchor element's href property.
  25313. *
  25314. * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to
  25315. * anchor's href property. If url is of type string however, it is first
  25316. * sanitized using goog.html.SafeUrl.sanitize.
  25317. *
  25318. * Example usage:
  25319. * goog.dom.safe.setAnchorHref(anchorEl, url);
  25320. * which is a safe alternative to
  25321. * anchorEl.href = url;
  25322. * The latter can result in XSS vulnerabilities if url is a
  25323. * user-/attacker-controlled value.
  25324. *
  25325. * @param {!HTMLAnchorElement} anchor The anchor element whose href property
  25326. * is to be assigned to.
  25327. * @param {string|!goog.html.SafeUrl} url The URL to assign.
  25328. * @see goog.html.SafeUrl#sanitize
  25329. */
  25330. goog.dom.safe.setAnchorHref = function(anchor, url) {
  25331. /** @type {!goog.html.SafeUrl} */
  25332. var safeUrl;
  25333. if (url instanceof goog.html.SafeUrl) {
  25334. safeUrl = url;
  25335. } else {
  25336. safeUrl = goog.html.SafeUrl.sanitize(url);
  25337. }
  25338. anchor.href = goog.html.SafeUrl.unwrap(safeUrl);
  25339. };
  25340. /**
  25341. * Safely assigns a URL to an embed element's src property.
  25342. *
  25343. * Example usage:
  25344. * goog.dom.safe.setEmbedSrc(embedEl, url);
  25345. * which is a safe alternative to
  25346. * embedEl.src = url;
  25347. * The latter can result in loading untrusted code unless it is ensured that
  25348. * the URL refers to a trustworthy resource.
  25349. *
  25350. * @param {!HTMLEmbedElement} embed The embed element whose src property
  25351. * is to be assigned to.
  25352. * @param {!goog.html.TrustedResourceUrl} url The URL to assign.
  25353. */
  25354. goog.dom.safe.setEmbedSrc = function(embed, url) {
  25355. embed.src = goog.html.TrustedResourceUrl.unwrap(url);
  25356. };
  25357. /**
  25358. * Safely assigns a URL to a frame element's src property.
  25359. *
  25360. * Example usage:
  25361. * goog.dom.safe.setFrameSrc(frameEl, url);
  25362. * which is a safe alternative to
  25363. * frameEl.src = url;
  25364. * The latter can result in loading untrusted code unless it is ensured that
  25365. * the URL refers to a trustworthy resource.
  25366. *
  25367. * @param {!HTMLFrameElement} frame The frame element whose src property
  25368. * is to be assigned to.
  25369. * @param {!goog.html.TrustedResourceUrl} url The URL to assign.
  25370. */
  25371. goog.dom.safe.setFrameSrc = function(frame, url) {
  25372. frame.src = goog.html.TrustedResourceUrl.unwrap(url);
  25373. };
  25374. /**
  25375. * Safely assigns a URL to an iframe element's src property.
  25376. *
  25377. * Example usage:
  25378. * goog.dom.safe.setIframeSrc(iframeEl, url);
  25379. * which is a safe alternative to
  25380. * iframeEl.src = url;
  25381. * The latter can result in loading untrusted code unless it is ensured that
  25382. * the URL refers to a trustworthy resource.
  25383. *
  25384. * @param {!HTMLIFrameElement} iframe The iframe element whose src property
  25385. * is to be assigned to.
  25386. * @param {!goog.html.TrustedResourceUrl} url The URL to assign.
  25387. */
  25388. goog.dom.safe.setIframeSrc = function(iframe, url) {
  25389. iframe.src = goog.html.TrustedResourceUrl.unwrap(url);
  25390. };
  25391. /**
  25392. * Safely sets a link element's href and rel properties. Whether or not
  25393. * the URL assigned to href has to be a goog.html.TrustedResourceUrl
  25394. * depends on the value of the rel property. If rel contains "stylesheet"
  25395. * then a TrustedResourceUrl is required.
  25396. *
  25397. * Example usage:
  25398. * goog.dom.safe.setLinkHrefAndRel(linkEl, url, 'stylesheet');
  25399. * which is a safe alternative to
  25400. * linkEl.rel = 'stylesheet';
  25401. * linkEl.href = url;
  25402. * The latter can result in loading untrusted code unless it is ensured that
  25403. * the URL refers to a trustworthy resource.
  25404. *
  25405. * @param {!HTMLLinkElement} link The link element whose href property
  25406. * is to be assigned to.
  25407. * @param {string|!goog.html.SafeUrl|!goog.html.TrustedResourceUrl} url The URL
  25408. * to assign to the href property. Must be a TrustedResourceUrl if the
  25409. * value assigned to rel contains "stylesheet". A string value is
  25410. * sanitized with goog.html.SafeUrl.sanitize.
  25411. * @param {string} rel The value to assign to the rel property.
  25412. * @throws {Error} if rel contains "stylesheet" and url is not a
  25413. * TrustedResourceUrl
  25414. * @see goog.html.SafeUrl#sanitize
  25415. */
  25416. goog.dom.safe.setLinkHrefAndRel = function(link, url, rel) {
  25417. link.rel = rel;
  25418. if (goog.string.caseInsensitiveContains(rel, 'stylesheet')) {
  25419. goog.asserts.assert(
  25420. url instanceof goog.html.TrustedResourceUrl,
  25421. 'URL must be TrustedResourceUrl because "rel" contains "stylesheet"');
  25422. link.href = goog.html.TrustedResourceUrl.unwrap(url);
  25423. } else if (url instanceof goog.html.TrustedResourceUrl) {
  25424. link.href = goog.html.TrustedResourceUrl.unwrap(url);
  25425. } else if (url instanceof goog.html.SafeUrl) {
  25426. link.href = goog.html.SafeUrl.unwrap(url);
  25427. } else { // string
  25428. // SafeUrl.sanitize must return legitimate SafeUrl when passed a string.
  25429. link.href = goog.html.SafeUrl.sanitize(url).getTypedStringValue();
  25430. }
  25431. };
  25432. /**
  25433. * Safely assigns a URL to an object element's data property.
  25434. *
  25435. * Example usage:
  25436. * goog.dom.safe.setObjectData(objectEl, url);
  25437. * which is a safe alternative to
  25438. * objectEl.data = url;
  25439. * The latter can result in loading untrusted code unless setit is ensured that
  25440. * the URL refers to a trustworthy resource.
  25441. *
  25442. * @param {!HTMLObjectElement} object The object element whose data property
  25443. * is to be assigned to.
  25444. * @param {!goog.html.TrustedResourceUrl} url The URL to assign.
  25445. */
  25446. goog.dom.safe.setObjectData = function(object, url) {
  25447. object.data = goog.html.TrustedResourceUrl.unwrap(url);
  25448. };
  25449. /**
  25450. * Safely assigns a URL to an iframe element's src property.
  25451. *
  25452. * Example usage:
  25453. * goog.dom.safe.setScriptSrc(scriptEl, url);
  25454. * which is a safe alternative to
  25455. * scriptEl.src = url;
  25456. * The latter can result in loading untrusted code unless it is ensured that
  25457. * the URL refers to a trustworthy resource.
  25458. *
  25459. * @param {!HTMLScriptElement} script The script element whose src property
  25460. * is to be assigned to.
  25461. * @param {!goog.html.TrustedResourceUrl} url The URL to assign.
  25462. */
  25463. goog.dom.safe.setScriptSrc = function(script, url) {
  25464. script.src = goog.html.TrustedResourceUrl.unwrap(url);
  25465. };
  25466. /**
  25467. * Safely assigns a URL to a Location object's href property.
  25468. *
  25469. * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to
  25470. * loc's href property. If url is of type string however, it is first sanitized
  25471. * using goog.html.SafeUrl.sanitize.
  25472. *
  25473. * Example usage:
  25474. * goog.dom.safe.setLocationHref(document.location, redirectUrl);
  25475. * which is a safe alternative to
  25476. * document.location.href = redirectUrl;
  25477. * The latter can result in XSS vulnerabilities if redirectUrl is a
  25478. * user-/attacker-controlled value.
  25479. *
  25480. * @param {!Location} loc The Location object whose href property is to be
  25481. * assigned to.
  25482. * @param {string|!goog.html.SafeUrl} url The URL to assign.
  25483. * @see goog.html.SafeUrl#sanitize
  25484. */
  25485. goog.dom.safe.setLocationHref = function(loc, url) {
  25486. /** @type {!goog.html.SafeUrl} */
  25487. var safeUrl;
  25488. if (url instanceof goog.html.SafeUrl) {
  25489. safeUrl = url;
  25490. } else {
  25491. safeUrl = goog.html.SafeUrl.sanitize(url);
  25492. }
  25493. loc.href = goog.html.SafeUrl.unwrap(safeUrl);
  25494. };
  25495. /**
  25496. * Safely opens a URL in a new window (via window.open).
  25497. *
  25498. * If url is of type goog.html.SafeUrl, its value is unwrapped and passed in to
  25499. * window.open. If url is of type string however, it is first sanitized
  25500. * using goog.html.SafeUrl.sanitize.
  25501. *
  25502. * Note that this function does not prevent leakages via the referer that is
  25503. * sent by window.open. It is advised to only use this to open 1st party URLs.
  25504. *
  25505. * Example usage:
  25506. * goog.dom.safe.openInWindow(url);
  25507. * which is a safe alternative to
  25508. * window.open(url);
  25509. * The latter can result in XSS vulnerabilities if redirectUrl is a
  25510. * user-/attacker-controlled value.
  25511. *
  25512. * @param {string|!goog.html.SafeUrl} url The URL to open.
  25513. * @param {Window=} opt_openerWin Window of which to call the .open() method.
  25514. * Defaults to the global window.
  25515. * @param {!goog.string.Const=} opt_name Name of the window to open in. Can be
  25516. * _top, etc as allowed by window.open().
  25517. * @param {string=} opt_specs Comma-separated list of specifications, same as
  25518. * in window.open().
  25519. * @param {boolean=} opt_replace Whether to replace the current entry in browser
  25520. * history, same as in window.open().
  25521. * @return {Window} Window the url was opened in.
  25522. */
  25523. goog.dom.safe.openInWindow = function(
  25524. url, opt_openerWin, opt_name, opt_specs, opt_replace) {
  25525. /** @type {!goog.html.SafeUrl} */
  25526. var safeUrl;
  25527. if (url instanceof goog.html.SafeUrl) {
  25528. safeUrl = url;
  25529. } else {
  25530. safeUrl = goog.html.SafeUrl.sanitize(url);
  25531. }
  25532. var win = opt_openerWin || window;
  25533. return win.open(goog.html.SafeUrl.unwrap(safeUrl),
  25534. // If opt_name is undefined, simply passing that in to open() causes IE to
  25535. // reuse the current window instead of opening a new one. Thus we pass ''
  25536. // in instead, which according to spec opens a new window. See
  25537. // https://html.spec.whatwg.org/multipage/browsers.html#dom-open .
  25538. opt_name ? goog.string.Const.unwrap(opt_name) : '',
  25539. opt_specs, opt_replace);
  25540. };
  25541. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  25542. //
  25543. // Licensed under the Apache License, Version 2.0 (the "License");
  25544. // you may not use this file except in compliance with the License.
  25545. // You may obtain a copy of the License at
  25546. //
  25547. // http://www.apache.org/licenses/LICENSE-2.0
  25548. //
  25549. // Unless required by applicable law or agreed to in writing, software
  25550. // distributed under the License is distributed on an "AS-IS" BASIS,
  25551. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25552. // See the License for the specific language governing permissions and
  25553. // limitations under the License.
  25554. /**
  25555. * @fileoverview A utility class for representing two-dimensional positions.
  25556. */
  25557. goog.provide('goog.math.Coordinate');
  25558. goog.require('goog.math');
  25559. /**
  25560. * Class for representing coordinates and positions.
  25561. * @param {number=} opt_x Left, defaults to 0.
  25562. * @param {number=} opt_y Top, defaults to 0.
  25563. * @struct
  25564. * @constructor
  25565. */
  25566. goog.math.Coordinate = function(opt_x, opt_y) {
  25567. /**
  25568. * X-value
  25569. * @type {number}
  25570. */
  25571. this.x = goog.isDef(opt_x) ? opt_x : 0;
  25572. /**
  25573. * Y-value
  25574. * @type {number}
  25575. */
  25576. this.y = goog.isDef(opt_y) ? opt_y : 0;
  25577. };
  25578. /**
  25579. * Returns a new copy of the coordinate.
  25580. * @return {!goog.math.Coordinate} A clone of this coordinate.
  25581. */
  25582. goog.math.Coordinate.prototype.clone = function() {
  25583. return new goog.math.Coordinate(this.x, this.y);
  25584. };
  25585. if (goog.DEBUG) {
  25586. /**
  25587. * Returns a nice string representing the coordinate.
  25588. * @return {string} In the form (50, 73).
  25589. * @override
  25590. */
  25591. goog.math.Coordinate.prototype.toString = function() {
  25592. return '(' + this.x + ', ' + this.y + ')';
  25593. };
  25594. }
  25595. /**
  25596. * Compares coordinates for equality.
  25597. * @param {goog.math.Coordinate} a A Coordinate.
  25598. * @param {goog.math.Coordinate} b A Coordinate.
  25599. * @return {boolean} True iff the coordinates are equal, or if both are null.
  25600. */
  25601. goog.math.Coordinate.equals = function(a, b) {
  25602. if (a == b) {
  25603. return true;
  25604. }
  25605. if (!a || !b) {
  25606. return false;
  25607. }
  25608. return a.x == b.x && a.y == b.y;
  25609. };
  25610. /**
  25611. * Returns the distance between two coordinates.
  25612. * @param {!goog.math.Coordinate} a A Coordinate.
  25613. * @param {!goog.math.Coordinate} b A Coordinate.
  25614. * @return {number} The distance between {@code a} and {@code b}.
  25615. */
  25616. goog.math.Coordinate.distance = function(a, b) {
  25617. var dx = a.x - b.x;
  25618. var dy = a.y - b.y;
  25619. return Math.sqrt(dx * dx + dy * dy);
  25620. };
  25621. /**
  25622. * Returns the magnitude of a coordinate.
  25623. * @param {!goog.math.Coordinate} a A Coordinate.
  25624. * @return {number} The distance between the origin and {@code a}.
  25625. */
  25626. goog.math.Coordinate.magnitude = function(a) {
  25627. return Math.sqrt(a.x * a.x + a.y * a.y);
  25628. };
  25629. /**
  25630. * Returns the angle from the origin to a coordinate.
  25631. * @param {!goog.math.Coordinate} a A Coordinate.
  25632. * @return {number} The angle, in degrees, clockwise from the positive X
  25633. * axis to {@code a}.
  25634. */
  25635. goog.math.Coordinate.azimuth = function(a) {
  25636. return goog.math.angle(0, 0, a.x, a.y);
  25637. };
  25638. /**
  25639. * Returns the squared distance between two coordinates. Squared distances can
  25640. * be used for comparisons when the actual value is not required.
  25641. *
  25642. * Performance note: eliminating the square root is an optimization often used
  25643. * in lower-level languages, but the speed difference is not nearly as
  25644. * pronounced in JavaScript (only a few percent.)
  25645. *
  25646. * @param {!goog.math.Coordinate} a A Coordinate.
  25647. * @param {!goog.math.Coordinate} b A Coordinate.
  25648. * @return {number} The squared distance between {@code a} and {@code b}.
  25649. */
  25650. goog.math.Coordinate.squaredDistance = function(a, b) {
  25651. var dx = a.x - b.x;
  25652. var dy = a.y - b.y;
  25653. return dx * dx + dy * dy;
  25654. };
  25655. /**
  25656. * Returns the difference between two coordinates as a new
  25657. * goog.math.Coordinate.
  25658. * @param {!goog.math.Coordinate} a A Coordinate.
  25659. * @param {!goog.math.Coordinate} b A Coordinate.
  25660. * @return {!goog.math.Coordinate} A Coordinate representing the difference
  25661. * between {@code a} and {@code b}.
  25662. */
  25663. goog.math.Coordinate.difference = function(a, b) {
  25664. return new goog.math.Coordinate(a.x - b.x, a.y - b.y);
  25665. };
  25666. /**
  25667. * Returns the sum of two coordinates as a new goog.math.Coordinate.
  25668. * @param {!goog.math.Coordinate} a A Coordinate.
  25669. * @param {!goog.math.Coordinate} b A Coordinate.
  25670. * @return {!goog.math.Coordinate} A Coordinate representing the sum of the two
  25671. * coordinates.
  25672. */
  25673. goog.math.Coordinate.sum = function(a, b) {
  25674. return new goog.math.Coordinate(a.x + b.x, a.y + b.y);
  25675. };
  25676. /**
  25677. * Rounds the x and y fields to the next larger integer values.
  25678. * @return {!goog.math.Coordinate} This coordinate with ceil'd fields.
  25679. */
  25680. goog.math.Coordinate.prototype.ceil = function() {
  25681. this.x = Math.ceil(this.x);
  25682. this.y = Math.ceil(this.y);
  25683. return this;
  25684. };
  25685. /**
  25686. * Rounds the x and y fields to the next smaller integer values.
  25687. * @return {!goog.math.Coordinate} This coordinate with floored fields.
  25688. */
  25689. goog.math.Coordinate.prototype.floor = function() {
  25690. this.x = Math.floor(this.x);
  25691. this.y = Math.floor(this.y);
  25692. return this;
  25693. };
  25694. /**
  25695. * Rounds the x and y fields to the nearest integer values.
  25696. * @return {!goog.math.Coordinate} This coordinate with rounded fields.
  25697. */
  25698. goog.math.Coordinate.prototype.round = function() {
  25699. this.x = Math.round(this.x);
  25700. this.y = Math.round(this.y);
  25701. return this;
  25702. };
  25703. /**
  25704. * Translates this box by the given offsets. If a {@code goog.math.Coordinate}
  25705. * is given, then the x and y values are translated by the coordinate's x and y.
  25706. * Otherwise, x and y are translated by {@code tx} and {@code opt_ty}
  25707. * respectively.
  25708. * @param {number|goog.math.Coordinate} tx The value to translate x by or the
  25709. * the coordinate to translate this coordinate by.
  25710. * @param {number=} opt_ty The value to translate y by.
  25711. * @return {!goog.math.Coordinate} This coordinate after translating.
  25712. */
  25713. goog.math.Coordinate.prototype.translate = function(tx, opt_ty) {
  25714. if (tx instanceof goog.math.Coordinate) {
  25715. this.x += tx.x;
  25716. this.y += tx.y;
  25717. } else {
  25718. this.x += tx;
  25719. if (goog.isNumber(opt_ty)) {
  25720. this.y += opt_ty;
  25721. }
  25722. }
  25723. return this;
  25724. };
  25725. /**
  25726. * Scales this coordinate by the given scale factors. The x and y values are
  25727. * scaled by {@code sx} and {@code opt_sy} respectively. If {@code opt_sy}
  25728. * is not given, then {@code sx} is used for both x and y.
  25729. * @param {number} sx The scale factor to use for the x dimension.
  25730. * @param {number=} opt_sy The scale factor to use for the y dimension.
  25731. * @return {!goog.math.Coordinate} This coordinate after scaling.
  25732. */
  25733. goog.math.Coordinate.prototype.scale = function(sx, opt_sy) {
  25734. var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
  25735. this.x *= sx;
  25736. this.y *= sy;
  25737. return this;
  25738. };
  25739. /**
  25740. * Rotates this coordinate clockwise about the origin (or, optionally, the given
  25741. * center) by the given angle, in radians.
  25742. * @param {number} radians The angle by which to rotate this coordinate
  25743. * clockwise about the given center, in radians.
  25744. * @param {!goog.math.Coordinate=} opt_center The center of rotation. Defaults
  25745. * to (0, 0) if not given.
  25746. */
  25747. goog.math.Coordinate.prototype.rotateRadians = function(radians, opt_center) {
  25748. var center = opt_center || new goog.math.Coordinate(0, 0);
  25749. var x = this.x;
  25750. var y = this.y;
  25751. var cos = Math.cos(radians);
  25752. var sin = Math.sin(radians);
  25753. this.x = (x - center.x) * cos - (y - center.y) * sin + center.x;
  25754. this.y = (x - center.x) * sin + (y - center.y) * cos + center.y;
  25755. };
  25756. /**
  25757. * Rotates this coordinate clockwise about the origin (or, optionally, the given
  25758. * center) by the given angle, in degrees.
  25759. * @param {number} degrees The angle by which to rotate this coordinate
  25760. * clockwise about the given center, in degrees.
  25761. * @param {!goog.math.Coordinate=} opt_center The center of rotation. Defaults
  25762. * to (0, 0) if not given.
  25763. */
  25764. goog.math.Coordinate.prototype.rotateDegrees = function(degrees, opt_center) {
  25765. this.rotateRadians(goog.math.toRadians(degrees), opt_center);
  25766. };
  25767. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  25768. //
  25769. // Licensed under the Apache License, Version 2.0 (the "License");
  25770. // you may not use this file except in compliance with the License.
  25771. // You may obtain a copy of the License at
  25772. //
  25773. // http://www.apache.org/licenses/LICENSE-2.0
  25774. //
  25775. // Unless required by applicable law or agreed to in writing, software
  25776. // distributed under the License is distributed on an "AS-IS" BASIS,
  25777. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25778. // See the License for the specific language governing permissions and
  25779. // limitations under the License.
  25780. /**
  25781. * @fileoverview A utility class for representing two-dimensional sizes.
  25782. * @author brenneman@google.com (Shawn Brenneman)
  25783. */
  25784. goog.provide('goog.math.Size');
  25785. /**
  25786. * Class for representing sizes consisting of a width and height. Undefined
  25787. * width and height support is deprecated and results in compiler warning.
  25788. * @param {number} width Width.
  25789. * @param {number} height Height.
  25790. * @struct
  25791. * @constructor
  25792. */
  25793. goog.math.Size = function(width, height) {
  25794. /**
  25795. * Width
  25796. * @type {number}
  25797. */
  25798. this.width = width;
  25799. /**
  25800. * Height
  25801. * @type {number}
  25802. */
  25803. this.height = height;
  25804. };
  25805. /**
  25806. * Compares sizes for equality.
  25807. * @param {goog.math.Size} a A Size.
  25808. * @param {goog.math.Size} b A Size.
  25809. * @return {boolean} True iff the sizes have equal widths and equal
  25810. * heights, or if both are null.
  25811. */
  25812. goog.math.Size.equals = function(a, b) {
  25813. if (a == b) {
  25814. return true;
  25815. }
  25816. if (!a || !b) {
  25817. return false;
  25818. }
  25819. return a.width == b.width && a.height == b.height;
  25820. };
  25821. /**
  25822. * @return {!goog.math.Size} A new copy of the Size.
  25823. */
  25824. goog.math.Size.prototype.clone = function() {
  25825. return new goog.math.Size(this.width, this.height);
  25826. };
  25827. if (goog.DEBUG) {
  25828. /**
  25829. * Returns a nice string representing size.
  25830. * @return {string} In the form (50 x 73).
  25831. * @override
  25832. */
  25833. goog.math.Size.prototype.toString = function() {
  25834. return '(' + this.width + ' x ' + this.height + ')';
  25835. };
  25836. }
  25837. /**
  25838. * @return {number} The longer of the two dimensions in the size.
  25839. */
  25840. goog.math.Size.prototype.getLongest = function() {
  25841. return Math.max(this.width, this.height);
  25842. };
  25843. /**
  25844. * @return {number} The shorter of the two dimensions in the size.
  25845. */
  25846. goog.math.Size.prototype.getShortest = function() {
  25847. return Math.min(this.width, this.height);
  25848. };
  25849. /**
  25850. * @return {number} The area of the size (width * height).
  25851. */
  25852. goog.math.Size.prototype.area = function() {
  25853. return this.width * this.height;
  25854. };
  25855. /**
  25856. * @return {number} The perimeter of the size (width + height) * 2.
  25857. */
  25858. goog.math.Size.prototype.perimeter = function() {
  25859. return (this.width + this.height) * 2;
  25860. };
  25861. /**
  25862. * @return {number} The ratio of the size's width to its height.
  25863. */
  25864. goog.math.Size.prototype.aspectRatio = function() {
  25865. return this.width / this.height;
  25866. };
  25867. /**
  25868. * @return {boolean} True if the size has zero area, false if both dimensions
  25869. * are non-zero numbers.
  25870. */
  25871. goog.math.Size.prototype.isEmpty = function() {
  25872. return !this.area();
  25873. };
  25874. /**
  25875. * Clamps the width and height parameters upward to integer values.
  25876. * @return {!goog.math.Size} This size with ceil'd components.
  25877. */
  25878. goog.math.Size.prototype.ceil = function() {
  25879. this.width = Math.ceil(this.width);
  25880. this.height = Math.ceil(this.height);
  25881. return this;
  25882. };
  25883. /**
  25884. * @param {!goog.math.Size} target The target size.
  25885. * @return {boolean} True if this Size is the same size or smaller than the
  25886. * target size in both dimensions.
  25887. */
  25888. goog.math.Size.prototype.fitsInside = function(target) {
  25889. return this.width <= target.width && this.height <= target.height;
  25890. };
  25891. /**
  25892. * Clamps the width and height parameters downward to integer values.
  25893. * @return {!goog.math.Size} This size with floored components.
  25894. */
  25895. goog.math.Size.prototype.floor = function() {
  25896. this.width = Math.floor(this.width);
  25897. this.height = Math.floor(this.height);
  25898. return this;
  25899. };
  25900. /**
  25901. * Rounds the width and height parameters to integer values.
  25902. * @return {!goog.math.Size} This size with rounded components.
  25903. */
  25904. goog.math.Size.prototype.round = function() {
  25905. this.width = Math.round(this.width);
  25906. this.height = Math.round(this.height);
  25907. return this;
  25908. };
  25909. /**
  25910. * Scales this size by the given scale factors. The width and height are scaled
  25911. * by {@code sx} and {@code opt_sy} respectively. If {@code opt_sy} is not
  25912. * given, then {@code sx} is used for both the width and height.
  25913. * @param {number} sx The scale factor to use for the width.
  25914. * @param {number=} opt_sy The scale factor to use for the height.
  25915. * @return {!goog.math.Size} This Size object after scaling.
  25916. */
  25917. goog.math.Size.prototype.scale = function(sx, opt_sy) {
  25918. var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
  25919. this.width *= sx;
  25920. this.height *= sy;
  25921. return this;
  25922. };
  25923. /**
  25924. * Uniformly scales the size to perfectly cover the dimensions of a given size.
  25925. * If the size is already larger than the target, it will be scaled down to the
  25926. * minimum size at which it still covers the entire target. The original aspect
  25927. * ratio will be preserved.
  25928. *
  25929. * This function assumes that both Sizes contain strictly positive dimensions.
  25930. * @param {!goog.math.Size} target The target size.
  25931. * @return {!goog.math.Size} This Size object, after optional scaling.
  25932. */
  25933. goog.math.Size.prototype.scaleToCover = function(target) {
  25934. var s = this.aspectRatio() <= target.aspectRatio() ?
  25935. target.width / this.width :
  25936. target.height / this.height;
  25937. return this.scale(s);
  25938. };
  25939. /**
  25940. * Uniformly scales the size to fit inside the dimensions of a given size. The
  25941. * original aspect ratio will be preserved.
  25942. *
  25943. * This function assumes that both Sizes contain strictly positive dimensions.
  25944. * @param {!goog.math.Size} target The target size.
  25945. * @return {!goog.math.Size} This Size object, after optional scaling.
  25946. */
  25947. goog.math.Size.prototype.scaleToFit = function(target) {
  25948. var s = this.aspectRatio() > target.aspectRatio() ?
  25949. target.width / this.width :
  25950. target.height / this.height;
  25951. return this.scale(s);
  25952. };
  25953. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  25954. //
  25955. // Licensed under the Apache License, Version 2.0 (the "License");
  25956. // you may not use this file except in compliance with the License.
  25957. // You may obtain a copy of the License at
  25958. //
  25959. // http://www.apache.org/licenses/LICENSE-2.0
  25960. //
  25961. // Unless required by applicable law or agreed to in writing, software
  25962. // distributed under the License is distributed on an "AS-IS" BASIS,
  25963. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25964. // See the License for the specific language governing permissions and
  25965. // limitations under the License.
  25966. /**
  25967. * @fileoverview Utilities for manipulating the browser's Document Object Model
  25968. * Inspiration taken *heavily* from mochikit (http://mochikit.com/).
  25969. *
  25970. * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer
  25971. * to a different document object. This is useful if you are working with
  25972. * frames or multiple windows.
  25973. *
  25974. * @author arv@google.com (Erik Arvidsson)
  25975. */
  25976. // TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem
  25977. // is that getTextContent should mimic the DOM3 textContent. We should add a
  25978. // getInnerText (or getText) which tries to return the visible text, innerText.
  25979. goog.provide('goog.dom');
  25980. goog.provide('goog.dom.Appendable');
  25981. goog.provide('goog.dom.DomHelper');
  25982. goog.require('goog.array');
  25983. goog.require('goog.asserts');
  25984. goog.require('goog.dom.BrowserFeature');
  25985. goog.require('goog.dom.NodeType');
  25986. goog.require('goog.dom.TagName');
  25987. goog.require('goog.dom.safe');
  25988. goog.require('goog.html.SafeHtml');
  25989. goog.require('goog.math.Coordinate');
  25990. goog.require('goog.math.Size');
  25991. goog.require('goog.object');
  25992. goog.require('goog.string');
  25993. goog.require('goog.string.Unicode');
  25994. goog.require('goog.userAgent');
  25995. /**
  25996. * @define {boolean} Whether we know at compile time that the browser is in
  25997. * quirks mode.
  25998. */
  25999. goog.define('goog.dom.ASSUME_QUIRKS_MODE', false);
  26000. /**
  26001. * @define {boolean} Whether we know at compile time that the browser is in
  26002. * standards compliance mode.
  26003. */
  26004. goog.define('goog.dom.ASSUME_STANDARDS_MODE', false);
  26005. /**
  26006. * Whether we know the compatibility mode at compile time.
  26007. * @type {boolean}
  26008. * @private
  26009. */
  26010. goog.dom.COMPAT_MODE_KNOWN_ =
  26011. goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;
  26012. /**
  26013. * Gets the DomHelper object for the document where the element resides.
  26014. * @param {(Node|Window)=} opt_element If present, gets the DomHelper for this
  26015. * element.
  26016. * @return {!goog.dom.DomHelper} The DomHelper.
  26017. */
  26018. goog.dom.getDomHelper = function(opt_element) {
  26019. return opt_element ?
  26020. new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :
  26021. (goog.dom.defaultDomHelper_ ||
  26022. (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));
  26023. };
  26024. /**
  26025. * Cached default DOM helper.
  26026. * @type {goog.dom.DomHelper}
  26027. * @private
  26028. */
  26029. goog.dom.defaultDomHelper_;
  26030. /**
  26031. * Gets the document object being used by the dom library.
  26032. * @return {!Document} Document object.
  26033. */
  26034. goog.dom.getDocument = function() {
  26035. return document;
  26036. };
  26037. /**
  26038. * Gets an element from the current document by element id.
  26039. *
  26040. * If an Element is passed in, it is returned.
  26041. *
  26042. * @param {string|Element} element Element ID or a DOM node.
  26043. * @return {Element} The element with the given ID, or the node passed in.
  26044. */
  26045. goog.dom.getElement = function(element) {
  26046. return goog.dom.getElementHelper_(document, element);
  26047. };
  26048. /**
  26049. * Gets an element by id from the given document (if present).
  26050. * If an element is given, it is returned.
  26051. * @param {!Document} doc
  26052. * @param {string|Element} element Element ID or a DOM node.
  26053. * @return {Element} The resulting element.
  26054. * @private
  26055. */
  26056. goog.dom.getElementHelper_ = function(doc, element) {
  26057. return goog.isString(element) ?
  26058. doc.getElementById(element) :
  26059. element;
  26060. };
  26061. /**
  26062. * Gets an element by id, asserting that the element is found.
  26063. *
  26064. * This is used when an element is expected to exist, and should fail with
  26065. * an assertion error if it does not (if assertions are enabled).
  26066. *
  26067. * @param {string} id Element ID.
  26068. * @return {!Element} The element with the given ID, if it exists.
  26069. */
  26070. goog.dom.getRequiredElement = function(id) {
  26071. return goog.dom.getRequiredElementHelper_(document, id);
  26072. };
  26073. /**
  26074. * Helper function for getRequiredElementHelper functions, both static and
  26075. * on DomHelper. Asserts the element with the given id exists.
  26076. * @param {!Document} doc
  26077. * @param {string} id
  26078. * @return {!Element} The element with the given ID, if it exists.
  26079. * @private
  26080. */
  26081. goog.dom.getRequiredElementHelper_ = function(doc, id) {
  26082. // To prevent users passing in Elements as is permitted in getElement().
  26083. goog.asserts.assertString(id);
  26084. var element = goog.dom.getElementHelper_(doc, id);
  26085. element = goog.asserts.assertElement(element,
  26086. 'No element found with id: ' + id);
  26087. return element;
  26088. };
  26089. /**
  26090. * Alias for getElement.
  26091. * @param {string|Element} element Element ID or a DOM node.
  26092. * @return {Element} The element with the given ID, or the node passed in.
  26093. * @deprecated Use {@link goog.dom.getElement} instead.
  26094. */
  26095. goog.dom.$ = goog.dom.getElement;
  26096. /**
  26097. * Looks up elements by both tag and class name, using browser native functions
  26098. * ({@code querySelectorAll}, {@code getElementsByTagName} or
  26099. * {@code getElementsByClassName}) where possible. This function
  26100. * is a useful, if limited, way of collecting a list of DOM elements
  26101. * with certain characteristics. {@code goog.dom.query} offers a
  26102. * more powerful and general solution which allows matching on CSS3
  26103. * selector expressions, but at increased cost in code size. If all you
  26104. * need is particular tags belonging to a single class, this function
  26105. * is fast and sleek.
  26106. *
  26107. * Note that tag names are case sensitive in the SVG namespace, and this
  26108. * function converts opt_tag to uppercase for comparisons. For queries in the
  26109. * SVG namespace you should use querySelector or querySelectorAll instead.
  26110. * https://bugzilla.mozilla.org/show_bug.cgi?id=963870
  26111. * https://bugs.webkit.org/show_bug.cgi?id=83438
  26112. *
  26113. * @see {goog.dom.query}
  26114. *
  26115. * @param {?string=} opt_tag Element tag name.
  26116. * @param {?string=} opt_class Optional class name.
  26117. * @param {(Document|Element)=} opt_el Optional element to look in.
  26118. * @return { {length: number} } Array-like list of elements (only a length
  26119. * property and numerical indices are guaranteed to exist).
  26120. */
  26121. goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {
  26122. return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class,
  26123. opt_el);
  26124. };
  26125. /**
  26126. * Returns a static, array-like list of the elements with the provided
  26127. * className.
  26128. * @see {goog.dom.query}
  26129. * @param {string} className the name of the class to look for.
  26130. * @param {(Document|Element)=} opt_el Optional element to look in.
  26131. * @return { {length: number} } The items found with the class name provided.
  26132. */
  26133. goog.dom.getElementsByClass = function(className, opt_el) {
  26134. var parent = opt_el || document;
  26135. if (goog.dom.canUseQuerySelector_(parent)) {
  26136. return parent.querySelectorAll('.' + className);
  26137. }
  26138. return goog.dom.getElementsByTagNameAndClass_(
  26139. document, '*', className, opt_el);
  26140. };
  26141. /**
  26142. * Returns the first element with the provided className.
  26143. * @see {goog.dom.query}
  26144. * @param {string} className the name of the class to look for.
  26145. * @param {Element|Document=} opt_el Optional element to look in.
  26146. * @return {Element} The first item with the class name provided.
  26147. */
  26148. goog.dom.getElementByClass = function(className, opt_el) {
  26149. var parent = opt_el || document;
  26150. var retVal = null;
  26151. if (parent.getElementsByClassName) {
  26152. retVal = parent.getElementsByClassName(className)[0];
  26153. } else if (goog.dom.canUseQuerySelector_(parent)) {
  26154. retVal = parent.querySelector('.' + className);
  26155. } else {
  26156. retVal = goog.dom.getElementsByTagNameAndClass_(
  26157. document, '*', className, opt_el)[0];
  26158. }
  26159. return retVal || null;
  26160. };
  26161. /**
  26162. * Ensures an element with the given className exists, and then returns the
  26163. * first element with the provided className.
  26164. * @see {goog.dom.query}
  26165. * @param {string} className the name of the class to look for.
  26166. * @param {!Element|!Document=} opt_root Optional element or document to look
  26167. * in.
  26168. * @return {!Element} The first item with the class name provided.
  26169. * @throws {goog.asserts.AssertionError} Thrown if no element is found.
  26170. */
  26171. goog.dom.getRequiredElementByClass = function(className, opt_root) {
  26172. var retValue = goog.dom.getElementByClass(className, opt_root);
  26173. return goog.asserts.assert(retValue,
  26174. 'No element found with className: ' + className);
  26175. };
  26176. /**
  26177. * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and
  26178. * fast W3C Selectors API.
  26179. * @param {!(Element|Document)} parent The parent document object.
  26180. * @return {boolean} whether or not we can use parent.querySelector* APIs.
  26181. * @private
  26182. */
  26183. goog.dom.canUseQuerySelector_ = function(parent) {
  26184. return !!(parent.querySelectorAll && parent.querySelector);
  26185. };
  26186. /**
  26187. * Helper for {@code getElementsByTagNameAndClass}.
  26188. * @param {!Document} doc The document to get the elements in.
  26189. * @param {?string=} opt_tag Element tag name.
  26190. * @param {?string=} opt_class Optional class name.
  26191. * @param {(Document|Element)=} opt_el Optional element to look in.
  26192. * @return { {length: number} } Array-like list of elements (only a length
  26193. * property and numerical indices are guaranteed to exist).
  26194. * @private
  26195. */
  26196. goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class,
  26197. opt_el) {
  26198. var parent = opt_el || doc;
  26199. var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : '';
  26200. if (goog.dom.canUseQuerySelector_(parent) &&
  26201. (tagName || opt_class)) {
  26202. var query = tagName + (opt_class ? '.' + opt_class : '');
  26203. return parent.querySelectorAll(query);
  26204. }
  26205. // Use the native getElementsByClassName if available, under the assumption
  26206. // that even when the tag name is specified, there will be fewer elements to
  26207. // filter through when going by class than by tag name
  26208. if (opt_class && parent.getElementsByClassName) {
  26209. var els = parent.getElementsByClassName(opt_class);
  26210. if (tagName) {
  26211. var arrayLike = {};
  26212. var len = 0;
  26213. // Filter for specific tags if requested.
  26214. for (var i = 0, el; el = els[i]; i++) {
  26215. if (tagName == el.nodeName) {
  26216. arrayLike[len++] = el;
  26217. }
  26218. }
  26219. arrayLike.length = len;
  26220. return arrayLike;
  26221. } else {
  26222. return els;
  26223. }
  26224. }
  26225. var els = parent.getElementsByTagName(tagName || '*');
  26226. if (opt_class) {
  26227. var arrayLike = {};
  26228. var len = 0;
  26229. for (var i = 0, el; el = els[i]; i++) {
  26230. var className = el.className;
  26231. // Check if className has a split function since SVG className does not.
  26232. if (typeof className.split == 'function' &&
  26233. goog.array.contains(className.split(/\s+/), opt_class)) {
  26234. arrayLike[len++] = el;
  26235. }
  26236. }
  26237. arrayLike.length = len;
  26238. return arrayLike;
  26239. } else {
  26240. return els;
  26241. }
  26242. };
  26243. /**
  26244. * Alias for {@code getElementsByTagNameAndClass}.
  26245. * @param {?string=} opt_tag Element tag name.
  26246. * @param {?string=} opt_class Optional class name.
  26247. * @param {Element=} opt_el Optional element to look in.
  26248. * @return { {length: number} } Array-like list of elements (only a length
  26249. * property and numerical indices are guaranteed to exist).
  26250. * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.
  26251. */
  26252. goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;
  26253. /**
  26254. * Sets multiple properties on a node.
  26255. * @param {Element} element DOM node to set properties on.
  26256. * @param {Object} properties Hash of property:value pairs.
  26257. */
  26258. goog.dom.setProperties = function(element, properties) {
  26259. goog.object.forEach(properties, function(val, key) {
  26260. if (key == 'style') {
  26261. element.style.cssText = val;
  26262. } else if (key == 'class') {
  26263. element.className = val;
  26264. } else if (key == 'for') {
  26265. element.htmlFor = val;
  26266. } else if (goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty(key)) {
  26267. element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);
  26268. } else if (goog.string.startsWith(key, 'aria-') ||
  26269. goog.string.startsWith(key, 'data-')) {
  26270. element.setAttribute(key, val);
  26271. } else {
  26272. element[key] = val;
  26273. }
  26274. });
  26275. };
  26276. /**
  26277. * Map of attributes that should be set using
  26278. * element.setAttribute(key, val) instead of element[key] = val. Used
  26279. * by goog.dom.setProperties.
  26280. *
  26281. * @private {!Object<string, string>}
  26282. * @const
  26283. */
  26284. goog.dom.DIRECT_ATTRIBUTE_MAP_ = {
  26285. 'cellpadding': 'cellPadding',
  26286. 'cellspacing': 'cellSpacing',
  26287. 'colspan': 'colSpan',
  26288. 'frameborder': 'frameBorder',
  26289. 'height': 'height',
  26290. 'maxlength': 'maxLength',
  26291. 'role': 'role',
  26292. 'rowspan': 'rowSpan',
  26293. 'type': 'type',
  26294. 'usemap': 'useMap',
  26295. 'valign': 'vAlign',
  26296. 'width': 'width'
  26297. };
  26298. /**
  26299. * Gets the dimensions of the viewport.
  26300. *
  26301. * Gecko Standards mode:
  26302. * docEl.clientWidth Width of viewport excluding scrollbar.
  26303. * win.innerWidth Width of viewport including scrollbar.
  26304. * body.clientWidth Width of body element.
  26305. *
  26306. * docEl.clientHeight Height of viewport excluding scrollbar.
  26307. * win.innerHeight Height of viewport including scrollbar.
  26308. * body.clientHeight Height of document.
  26309. *
  26310. * Gecko Backwards compatible mode:
  26311. * docEl.clientWidth Width of viewport excluding scrollbar.
  26312. * win.innerWidth Width of viewport including scrollbar.
  26313. * body.clientWidth Width of viewport excluding scrollbar.
  26314. *
  26315. * docEl.clientHeight Height of document.
  26316. * win.innerHeight Height of viewport including scrollbar.
  26317. * body.clientHeight Height of viewport excluding scrollbar.
  26318. *
  26319. * IE6/7 Standards mode:
  26320. * docEl.clientWidth Width of viewport excluding scrollbar.
  26321. * win.innerWidth Undefined.
  26322. * body.clientWidth Width of body element.
  26323. *
  26324. * docEl.clientHeight Height of viewport excluding scrollbar.
  26325. * win.innerHeight Undefined.
  26326. * body.clientHeight Height of document element.
  26327. *
  26328. * IE5 + IE6/7 Backwards compatible mode:
  26329. * docEl.clientWidth 0.
  26330. * win.innerWidth Undefined.
  26331. * body.clientWidth Width of viewport excluding scrollbar.
  26332. *
  26333. * docEl.clientHeight 0.
  26334. * win.innerHeight Undefined.
  26335. * body.clientHeight Height of viewport excluding scrollbar.
  26336. *
  26337. * Opera 9 Standards and backwards compatible mode:
  26338. * docEl.clientWidth Width of viewport excluding scrollbar.
  26339. * win.innerWidth Width of viewport including scrollbar.
  26340. * body.clientWidth Width of viewport excluding scrollbar.
  26341. *
  26342. * docEl.clientHeight Height of document.
  26343. * win.innerHeight Height of viewport including scrollbar.
  26344. * body.clientHeight Height of viewport excluding scrollbar.
  26345. *
  26346. * WebKit:
  26347. * Safari 2
  26348. * docEl.clientHeight Same as scrollHeight.
  26349. * docEl.clientWidth Same as innerWidth.
  26350. * win.innerWidth Width of viewport excluding scrollbar.
  26351. * win.innerHeight Height of the viewport including scrollbar.
  26352. * frame.innerHeight Height of the viewport exluding scrollbar.
  26353. *
  26354. * Safari 3 (tested in 522)
  26355. *
  26356. * docEl.clientWidth Width of viewport excluding scrollbar.
  26357. * docEl.clientHeight Height of viewport excluding scrollbar in strict mode.
  26358. * body.clientHeight Height of viewport excluding scrollbar in quirks mode.
  26359. *
  26360. * @param {Window=} opt_window Optional window element to test.
  26361. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  26362. */
  26363. goog.dom.getViewportSize = function(opt_window) {
  26364. // TODO(arv): This should not take an argument
  26365. return goog.dom.getViewportSize_(opt_window || window);
  26366. };
  26367. /**
  26368. * Helper for {@code getViewportSize}.
  26369. * @param {Window} win The window to get the view port size for.
  26370. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  26371. * @private
  26372. */
  26373. goog.dom.getViewportSize_ = function(win) {
  26374. var doc = win.document;
  26375. var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;
  26376. return new goog.math.Size(el.clientWidth, el.clientHeight);
  26377. };
  26378. /**
  26379. * Calculates the height of the document.
  26380. *
  26381. * @return {number} The height of the current document.
  26382. */
  26383. goog.dom.getDocumentHeight = function() {
  26384. return goog.dom.getDocumentHeight_(window);
  26385. };
  26386. /**
  26387. * Calculates the height of the document of the given window.
  26388. *
  26389. * Function code copied from the opensocial gadget api:
  26390. * gadgets.window.adjustHeight(opt_height)
  26391. *
  26392. * @private
  26393. * @param {!Window} win The window whose document height to retrieve.
  26394. * @return {number} The height of the document of the given window.
  26395. */
  26396. goog.dom.getDocumentHeight_ = function(win) {
  26397. // NOTE(eae): This method will return the window size rather than the document
  26398. // size in webkit quirks mode.
  26399. var doc = win.document;
  26400. var height = 0;
  26401. if (doc) {
  26402. // Calculating inner content height is hard and different between
  26403. // browsers rendering in Strict vs. Quirks mode. We use a combination of
  26404. // three properties within document.body and document.documentElement:
  26405. // - scrollHeight
  26406. // - offsetHeight
  26407. // - clientHeight
  26408. // These values differ significantly between browsers and rendering modes.
  26409. // But there are patterns. It just takes a lot of time and persistence
  26410. // to figure out.
  26411. var body = doc.body;
  26412. var docEl = /** @type {!HTMLElement} */ (doc.documentElement);
  26413. if (!(docEl && body)) {
  26414. return 0;
  26415. }
  26416. // Get the height of the viewport
  26417. var vh = goog.dom.getViewportSize_(win).height;
  26418. if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {
  26419. // In Strict mode:
  26420. // The inner content height is contained in either:
  26421. // document.documentElement.scrollHeight
  26422. // document.documentElement.offsetHeight
  26423. // Based on studying the values output by different browsers,
  26424. // use the value that's NOT equal to the viewport height found above.
  26425. height = docEl.scrollHeight != vh ?
  26426. docEl.scrollHeight : docEl.offsetHeight;
  26427. } else {
  26428. // In Quirks mode:
  26429. // documentElement.clientHeight is equal to documentElement.offsetHeight
  26430. // except in IE. In most browsers, document.documentElement can be used
  26431. // to calculate the inner content height.
  26432. // However, in other browsers (e.g. IE), document.body must be used
  26433. // instead. How do we know which one to use?
  26434. // If document.documentElement.clientHeight does NOT equal
  26435. // document.documentElement.offsetHeight, then use document.body.
  26436. var sh = docEl.scrollHeight;
  26437. var oh = docEl.offsetHeight;
  26438. if (docEl.clientHeight != oh) {
  26439. sh = body.scrollHeight;
  26440. oh = body.offsetHeight;
  26441. }
  26442. // Detect whether the inner content height is bigger or smaller
  26443. // than the bounding box (viewport). If bigger, take the larger
  26444. // value. If smaller, take the smaller value.
  26445. if (sh > vh) {
  26446. // Content is larger
  26447. height = sh > oh ? sh : oh;
  26448. } else {
  26449. // Content is smaller
  26450. height = sh < oh ? sh : oh;
  26451. }
  26452. }
  26453. }
  26454. return height;
  26455. };
  26456. /**
  26457. * Gets the page scroll distance as a coordinate object.
  26458. *
  26459. * @param {Window=} opt_window Optional window element to test.
  26460. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
  26461. * @deprecated Use {@link goog.dom.getDocumentScroll} instead.
  26462. */
  26463. goog.dom.getPageScroll = function(opt_window) {
  26464. var win = opt_window || goog.global || window;
  26465. return goog.dom.getDomHelper(win.document).getDocumentScroll();
  26466. };
  26467. /**
  26468. * Gets the document scroll distance as a coordinate object.
  26469. *
  26470. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
  26471. */
  26472. goog.dom.getDocumentScroll = function() {
  26473. return goog.dom.getDocumentScroll_(document);
  26474. };
  26475. /**
  26476. * Helper for {@code getDocumentScroll}.
  26477. *
  26478. * @param {!Document} doc The document to get the scroll for.
  26479. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
  26480. * @private
  26481. */
  26482. goog.dom.getDocumentScroll_ = function(doc) {
  26483. var el = goog.dom.getDocumentScrollElement_(doc);
  26484. var win = goog.dom.getWindow_(doc);
  26485. if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') &&
  26486. win.pageYOffset != el.scrollTop) {
  26487. // The keyboard on IE10 touch devices shifts the page using the pageYOffset
  26488. // without modifying scrollTop. For this case, we want the body scroll
  26489. // offsets.
  26490. return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);
  26491. }
  26492. return new goog.math.Coordinate(win.pageXOffset || el.scrollLeft,
  26493. win.pageYOffset || el.scrollTop);
  26494. };
  26495. /**
  26496. * Gets the document scroll element.
  26497. * @return {!Element} Scrolling element.
  26498. */
  26499. goog.dom.getDocumentScrollElement = function() {
  26500. return goog.dom.getDocumentScrollElement_(document);
  26501. };
  26502. /**
  26503. * Helper for {@code getDocumentScrollElement}.
  26504. * @param {!Document} doc The document to get the scroll element for.
  26505. * @return {!Element} Scrolling element.
  26506. * @private
  26507. */
  26508. goog.dom.getDocumentScrollElement_ = function(doc) {
  26509. // Old WebKit needs body.scrollLeft in both quirks mode and strict mode. We
  26510. // also default to the documentElement if the document does not have a body
  26511. // (e.g. a SVG document).
  26512. // Uses http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement to
  26513. // avoid trying to guess about browser behavior from the UA string.
  26514. if (doc.scrollingElement) {
  26515. return doc.scrollingElement;
  26516. }
  26517. if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) {
  26518. return doc.documentElement;
  26519. }
  26520. return doc.body || doc.documentElement;
  26521. };
  26522. /**
  26523. * Gets the window object associated with the given document.
  26524. *
  26525. * @param {Document=} opt_doc Document object to get window for.
  26526. * @return {!Window} The window associated with the given document.
  26527. */
  26528. goog.dom.getWindow = function(opt_doc) {
  26529. // TODO(arv): This should not take an argument.
  26530. return opt_doc ? goog.dom.getWindow_(opt_doc) : window;
  26531. };
  26532. /**
  26533. * Helper for {@code getWindow}.
  26534. *
  26535. * @param {!Document} doc Document object to get window for.
  26536. * @return {!Window} The window associated with the given document.
  26537. * @private
  26538. */
  26539. goog.dom.getWindow_ = function(doc) {
  26540. return doc.parentWindow || doc.defaultView;
  26541. };
  26542. /**
  26543. * Returns a dom node with a set of attributes. This function accepts varargs
  26544. * for subsequent nodes to be added. Subsequent nodes will be added to the
  26545. * first node as childNodes.
  26546. *
  26547. * So:
  26548. * <code>createDom('div', null, createDom('p'), createDom('p'));</code>
  26549. * would return a div with two child paragraphs
  26550. *
  26551. * @param {string} tagName Tag to create.
  26552. * @param {(Object|Array<string>|string)=} opt_attributes If object, then a map
  26553. * of name-value pairs for attributes. If a string, then this is the
  26554. * className of the new element. If an array, the elements will be joined
  26555. * together as the className of the new element.
  26556. * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
  26557. * strings for text nodes. If one of the var_args is an array or NodeList,
  26558. * its elements will be added as childNodes instead.
  26559. * @return {!Element} Reference to a DOM node.
  26560. */
  26561. goog.dom.createDom = function(tagName, opt_attributes, var_args) {
  26562. return goog.dom.createDom_(document, arguments);
  26563. };
  26564. /**
  26565. * Helper for {@code createDom}.
  26566. * @param {!Document} doc The document to create the DOM in.
  26567. * @param {!Arguments} args Argument object passed from the callers. See
  26568. * {@code goog.dom.createDom} for details.
  26569. * @return {!Element} Reference to a DOM node.
  26570. * @private
  26571. */
  26572. goog.dom.createDom_ = function(doc, args) {
  26573. var tagName = args[0];
  26574. var attributes = args[1];
  26575. // Internet Explorer is dumb:
  26576. // name: https://msdn.microsoft.com/en-us/library/ms534184(v=vs.85).aspx
  26577. // type: https://msdn.microsoft.com/en-us/library/ms534700(v=vs.85).aspx
  26578. // Also does not allow setting of 'type' attribute on 'input' or 'button'.
  26579. if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&
  26580. (attributes.name || attributes.type)) {
  26581. var tagNameArr = ['<', tagName];
  26582. if (attributes.name) {
  26583. tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name), '"');
  26584. }
  26585. if (attributes.type) {
  26586. tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type), '"');
  26587. // Clone attributes map to remove 'type' without mutating the input.
  26588. var clone = {};
  26589. goog.object.extend(clone, attributes);
  26590. // JSCompiler can't see how goog.object.extend added this property,
  26591. // because it was essentially added by reflection.
  26592. // So it needs to be quoted.
  26593. delete clone['type'];
  26594. attributes = clone;
  26595. }
  26596. tagNameArr.push('>');
  26597. tagName = tagNameArr.join('');
  26598. }
  26599. var element = doc.createElement(tagName);
  26600. if (attributes) {
  26601. if (goog.isString(attributes)) {
  26602. element.className = attributes;
  26603. } else if (goog.isArray(attributes)) {
  26604. element.className = attributes.join(' ');
  26605. } else {
  26606. goog.dom.setProperties(element, attributes);
  26607. }
  26608. }
  26609. if (args.length > 2) {
  26610. goog.dom.append_(doc, element, args, 2);
  26611. }
  26612. return element;
  26613. };
  26614. /**
  26615. * Appends a node with text or other nodes.
  26616. * @param {!Document} doc The document to create new nodes in.
  26617. * @param {!Node} parent The node to append nodes to.
  26618. * @param {!Arguments} args The values to add. See {@code goog.dom.append}.
  26619. * @param {number} startIndex The index of the array to start from.
  26620. * @private
  26621. */
  26622. goog.dom.append_ = function(doc, parent, args, startIndex) {
  26623. function childHandler(child) {
  26624. // TODO(user): More coercion, ala MochiKit?
  26625. if (child) {
  26626. parent.appendChild(goog.isString(child) ?
  26627. doc.createTextNode(child) : child);
  26628. }
  26629. }
  26630. for (var i = startIndex; i < args.length; i++) {
  26631. var arg = args[i];
  26632. // TODO(attila): Fix isArrayLike to return false for a text node.
  26633. if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {
  26634. // If the argument is a node list, not a real array, use a clone,
  26635. // because forEach can't be used to mutate a NodeList.
  26636. goog.array.forEach(goog.dom.isNodeList(arg) ?
  26637. goog.array.toArray(arg) : arg,
  26638. childHandler);
  26639. } else {
  26640. childHandler(arg);
  26641. }
  26642. }
  26643. };
  26644. /**
  26645. * Alias for {@code createDom}.
  26646. * @param {string} tagName Tag to create.
  26647. * @param {(string|Object)=} opt_attributes If object, then a map of name-value
  26648. * pairs for attributes. If a string, then this is the className of the new
  26649. * element.
  26650. * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
  26651. * strings for text nodes. If one of the var_args is an array, its
  26652. * children will be added as childNodes instead.
  26653. * @return {!Element} Reference to a DOM node.
  26654. * @deprecated Use {@link goog.dom.createDom} instead.
  26655. */
  26656. goog.dom.$dom = goog.dom.createDom;
  26657. /**
  26658. * Creates a new element.
  26659. * @param {string} name Tag name.
  26660. * @return {!Element} The new element.
  26661. */
  26662. goog.dom.createElement = function(name) {
  26663. return document.createElement(name);
  26664. };
  26665. /**
  26666. * Creates a new text node.
  26667. * @param {number|string} content Content.
  26668. * @return {!Text} The new text node.
  26669. */
  26670. goog.dom.createTextNode = function(content) {
  26671. return document.createTextNode(String(content));
  26672. };
  26673. /**
  26674. * Create a table.
  26675. * @param {number} rows The number of rows in the table. Must be >= 1.
  26676. * @param {number} columns The number of columns in the table. Must be >= 1.
  26677. * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
  26678. * {@code goog.string.Unicode.NBSP} characters.
  26679. * @return {!Element} The created table.
  26680. */
  26681. goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {
  26682. // TODO(user): Return HTMLTableElement, also in prototype function.
  26683. // Callers need to be updated to e.g. not assign numbers to table.cellSpacing.
  26684. return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);
  26685. };
  26686. /**
  26687. * Create a table.
  26688. * @param {!Document} doc Document object to use to create the table.
  26689. * @param {number} rows The number of rows in the table. Must be >= 1.
  26690. * @param {number} columns The number of columns in the table. Must be >= 1.
  26691. * @param {boolean} fillWithNbsp If true, fills table entries with
  26692. * {@code goog.string.Unicode.NBSP} characters.
  26693. * @return {!HTMLTableElement} The created table.
  26694. * @private
  26695. */
  26696. goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {
  26697. var table = /** @type {!HTMLTableElement} */
  26698. (doc.createElement(goog.dom.TagName.TABLE));
  26699. var tbody = table.appendChild(doc.createElement(goog.dom.TagName.TBODY));
  26700. for (var i = 0; i < rows; i++) {
  26701. var tr = doc.createElement(goog.dom.TagName.TR);
  26702. for (var j = 0; j < columns; j++) {
  26703. var td = doc.createElement(goog.dom.TagName.TD);
  26704. // IE <= 9 will create a text node if we set text content to the empty
  26705. // string, so we avoid doing it unless necessary. This ensures that the
  26706. // same DOM tree is returned on all browsers.
  26707. if (fillWithNbsp) {
  26708. goog.dom.setTextContent(td, goog.string.Unicode.NBSP);
  26709. }
  26710. tr.appendChild(td);
  26711. }
  26712. tbody.appendChild(tr);
  26713. }
  26714. return table;
  26715. };
  26716. /**
  26717. * Converts HTML markup into a node.
  26718. * @param {!goog.html.SafeHtml} html The HTML markup to convert.
  26719. * @return {!Node} The resulting node.
  26720. */
  26721. goog.dom.safeHtmlToNode = function(html) {
  26722. return goog.dom.safeHtmlToNode_(document, html);
  26723. };
  26724. /**
  26725. * Helper for {@code safeHtmlToNode}.
  26726. * @param {!Document} doc The document.
  26727. * @param {!goog.html.SafeHtml} html The HTML markup to convert.
  26728. * @return {!Node} The resulting node.
  26729. * @private
  26730. */
  26731. goog.dom.safeHtmlToNode_ = function(doc, html) {
  26732. var tempDiv = doc.createElement(goog.dom.TagName.DIV);
  26733. if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
  26734. goog.dom.safe.setInnerHtml(tempDiv,
  26735. goog.html.SafeHtml.concat(goog.html.SafeHtml.create('br'), html));
  26736. tempDiv.removeChild(tempDiv.firstChild);
  26737. } else {
  26738. goog.dom.safe.setInnerHtml(tempDiv, html);
  26739. }
  26740. return goog.dom.childrenToNode_(doc, tempDiv);
  26741. };
  26742. /**
  26743. * Converts an HTML string into a document fragment. The string must be
  26744. * sanitized in order to avoid cross-site scripting. For example
  26745. * {@code goog.dom.htmlToDocumentFragment('&lt;img src=x onerror=alert(0)&gt;')}
  26746. * triggers an alert in all browsers, even if the returned document fragment
  26747. * is thrown away immediately.
  26748. *
  26749. * NOTE: This method doesn't work if your htmlString contains elements that
  26750. * can't be contained in a <div>. For example, <tr>.
  26751. *
  26752. * @param {string} htmlString The HTML string to convert.
  26753. * @return {!Node} The resulting document fragment.
  26754. */
  26755. goog.dom.htmlToDocumentFragment = function(htmlString) {
  26756. return goog.dom.htmlToDocumentFragment_(document, htmlString);
  26757. };
  26758. // TODO(jakubvrana): Merge with {@code safeHtmlToNode_}.
  26759. /**
  26760. * Helper for {@code htmlToDocumentFragment}.
  26761. *
  26762. * @param {!Document} doc The document.
  26763. * @param {string} htmlString The HTML string to convert.
  26764. * @return {!Node} The resulting document fragment.
  26765. * @private
  26766. */
  26767. goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) {
  26768. var tempDiv = doc.createElement(goog.dom.TagName.DIV);
  26769. if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
  26770. tempDiv.innerHTML = '<br>' + htmlString;
  26771. tempDiv.removeChild(tempDiv.firstChild);
  26772. } else {
  26773. tempDiv.innerHTML = htmlString;
  26774. }
  26775. return goog.dom.childrenToNode_(doc, tempDiv);
  26776. };
  26777. /**
  26778. * Helper for {@code htmlToDocumentFragment_}.
  26779. * @param {!Document} doc The document.
  26780. * @param {!Node} tempDiv The input node.
  26781. * @return {!Node} The resulting node.
  26782. * @private
  26783. */
  26784. goog.dom.childrenToNode_ = function(doc, tempDiv) {
  26785. if (tempDiv.childNodes.length == 1) {
  26786. return tempDiv.removeChild(tempDiv.firstChild);
  26787. } else {
  26788. var fragment = doc.createDocumentFragment();
  26789. while (tempDiv.firstChild) {
  26790. fragment.appendChild(tempDiv.firstChild);
  26791. }
  26792. return fragment;
  26793. }
  26794. };
  26795. /**
  26796. * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
  26797. * mode, false otherwise.
  26798. * @return {boolean} True if in CSS1-compatible mode.
  26799. */
  26800. goog.dom.isCss1CompatMode = function() {
  26801. return goog.dom.isCss1CompatMode_(document);
  26802. };
  26803. /**
  26804. * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
  26805. * mode, false otherwise.
  26806. * @param {!Document} doc The document to check.
  26807. * @return {boolean} True if in CSS1-compatible mode.
  26808. * @private
  26809. */
  26810. goog.dom.isCss1CompatMode_ = function(doc) {
  26811. if (goog.dom.COMPAT_MODE_KNOWN_) {
  26812. return goog.dom.ASSUME_STANDARDS_MODE;
  26813. }
  26814. return doc.compatMode == 'CSS1Compat';
  26815. };
  26816. /**
  26817. * Determines if the given node can contain children, intended to be used for
  26818. * HTML generation.
  26819. *
  26820. * IE natively supports node.canHaveChildren but has inconsistent behavior.
  26821. * Prior to IE8 the base tag allows children and in IE9 all nodes return true
  26822. * for canHaveChildren.
  26823. *
  26824. * In practice all non-IE browsers allow you to add children to any node, but
  26825. * the behavior is inconsistent:
  26826. *
  26827. * <pre>
  26828. * var a = document.createElement(goog.dom.TagName.BR);
  26829. * a.appendChild(document.createTextNode('foo'));
  26830. * a.appendChild(document.createTextNode('bar'));
  26831. * console.log(a.childNodes.length); // 2
  26832. * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"
  26833. * </pre>
  26834. *
  26835. * For more information, see:
  26836. * http://dev.w3.org/html5/markup/syntax.html#syntax-elements
  26837. *
  26838. * TODO(user): Rename shouldAllowChildren() ?
  26839. *
  26840. * @param {Node} node The node to check.
  26841. * @return {boolean} Whether the node can contain children.
  26842. */
  26843. goog.dom.canHaveChildren = function(node) {
  26844. if (node.nodeType != goog.dom.NodeType.ELEMENT) {
  26845. return false;
  26846. }
  26847. switch (/** @type {!Element} */ (node).tagName) {
  26848. case goog.dom.TagName.APPLET:
  26849. case goog.dom.TagName.AREA:
  26850. case goog.dom.TagName.BASE:
  26851. case goog.dom.TagName.BR:
  26852. case goog.dom.TagName.COL:
  26853. case goog.dom.TagName.COMMAND:
  26854. case goog.dom.TagName.EMBED:
  26855. case goog.dom.TagName.FRAME:
  26856. case goog.dom.TagName.HR:
  26857. case goog.dom.TagName.IMG:
  26858. case goog.dom.TagName.INPUT:
  26859. case goog.dom.TagName.IFRAME:
  26860. case goog.dom.TagName.ISINDEX:
  26861. case goog.dom.TagName.KEYGEN:
  26862. case goog.dom.TagName.LINK:
  26863. case goog.dom.TagName.NOFRAMES:
  26864. case goog.dom.TagName.NOSCRIPT:
  26865. case goog.dom.TagName.META:
  26866. case goog.dom.TagName.OBJECT:
  26867. case goog.dom.TagName.PARAM:
  26868. case goog.dom.TagName.SCRIPT:
  26869. case goog.dom.TagName.SOURCE:
  26870. case goog.dom.TagName.STYLE:
  26871. case goog.dom.TagName.TRACK:
  26872. case goog.dom.TagName.WBR:
  26873. return false;
  26874. }
  26875. return true;
  26876. };
  26877. /**
  26878. * Appends a child to a node.
  26879. * @param {Node} parent Parent.
  26880. * @param {Node} child Child.
  26881. */
  26882. goog.dom.appendChild = function(parent, child) {
  26883. parent.appendChild(child);
  26884. };
  26885. /**
  26886. * Appends a node with text or other nodes.
  26887. * @param {!Node} parent The node to append nodes to.
  26888. * @param {...goog.dom.Appendable} var_args The things to append to the node.
  26889. * If this is a Node it is appended as is.
  26890. * If this is a string then a text node is appended.
  26891. * If this is an array like object then fields 0 to length - 1 are appended.
  26892. */
  26893. goog.dom.append = function(parent, var_args) {
  26894. goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);
  26895. };
  26896. /**
  26897. * Removes all the child nodes on a DOM node.
  26898. * @param {Node} node Node to remove children from.
  26899. */
  26900. goog.dom.removeChildren = function(node) {
  26901. // Note: Iterations over live collections can be slow, this is the fastest
  26902. // we could find. The double parenthesis are used to prevent JsCompiler and
  26903. // strict warnings.
  26904. var child;
  26905. while ((child = node.firstChild)) {
  26906. node.removeChild(child);
  26907. }
  26908. };
  26909. /**
  26910. * Inserts a new node before an existing reference node (i.e. as the previous
  26911. * sibling). If the reference node has no parent, then does nothing.
  26912. * @param {Node} newNode Node to insert.
  26913. * @param {Node} refNode Reference node to insert before.
  26914. */
  26915. goog.dom.insertSiblingBefore = function(newNode, refNode) {
  26916. if (refNode.parentNode) {
  26917. refNode.parentNode.insertBefore(newNode, refNode);
  26918. }
  26919. };
  26920. /**
  26921. * Inserts a new node after an existing reference node (i.e. as the next
  26922. * sibling). If the reference node has no parent, then does nothing.
  26923. * @param {Node} newNode Node to insert.
  26924. * @param {Node} refNode Reference node to insert after.
  26925. */
  26926. goog.dom.insertSiblingAfter = function(newNode, refNode) {
  26927. if (refNode.parentNode) {
  26928. refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
  26929. }
  26930. };
  26931. /**
  26932. * Insert a child at a given index. If index is larger than the number of child
  26933. * nodes that the parent currently has, the node is inserted as the last child
  26934. * node.
  26935. * @param {Element} parent The element into which to insert the child.
  26936. * @param {Node} child The element to insert.
  26937. * @param {number} index The index at which to insert the new child node. Must
  26938. * not be negative.
  26939. */
  26940. goog.dom.insertChildAt = function(parent, child, index) {
  26941. // Note that if the second argument is null, insertBefore
  26942. // will append the child at the end of the list of children.
  26943. parent.insertBefore(child, parent.childNodes[index] || null);
  26944. };
  26945. /**
  26946. * Removes a node from its parent.
  26947. * @param {Node} node The node to remove.
  26948. * @return {Node} The node removed if removed; else, null.
  26949. */
  26950. goog.dom.removeNode = function(node) {
  26951. return node && node.parentNode ? node.parentNode.removeChild(node) : null;
  26952. };
  26953. /**
  26954. * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
  26955. * parent.
  26956. * @param {Node} newNode Node to insert.
  26957. * @param {Node} oldNode Node to replace.
  26958. */
  26959. goog.dom.replaceNode = function(newNode, oldNode) {
  26960. var parent = oldNode.parentNode;
  26961. if (parent) {
  26962. parent.replaceChild(newNode, oldNode);
  26963. }
  26964. };
  26965. /**
  26966. * Flattens an element. That is, removes it and replace it with its children.
  26967. * Does nothing if the element is not in the document.
  26968. * @param {Element} element The element to flatten.
  26969. * @return {Element|undefined} The original element, detached from the document
  26970. * tree, sans children; or undefined, if the element was not in the document
  26971. * to begin with.
  26972. */
  26973. goog.dom.flattenElement = function(element) {
  26974. var child, parent = element.parentNode;
  26975. if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
  26976. // Use IE DOM method (supported by Opera too) if available
  26977. if (element.removeNode) {
  26978. return /** @type {Element} */ (element.removeNode(false));
  26979. } else {
  26980. // Move all children of the original node up one level.
  26981. while ((child = element.firstChild)) {
  26982. parent.insertBefore(child, element);
  26983. }
  26984. // Detach the original element.
  26985. return /** @type {Element} */ (goog.dom.removeNode(element));
  26986. }
  26987. }
  26988. };
  26989. /**
  26990. * Returns an array containing just the element children of the given element.
  26991. * @param {Element} element The element whose element children we want.
  26992. * @return {!(Array|NodeList)} An array or array-like list of just the element
  26993. * children of the given element.
  26994. */
  26995. goog.dom.getChildren = function(element) {
  26996. // We check if the children attribute is supported for child elements
  26997. // since IE8 misuses the attribute by also including comments.
  26998. if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&
  26999. element.children != undefined) {
  27000. return element.children;
  27001. }
  27002. // Fall back to manually filtering the element's child nodes.
  27003. return goog.array.filter(element.childNodes, function(node) {
  27004. return node.nodeType == goog.dom.NodeType.ELEMENT;
  27005. });
  27006. };
  27007. /**
  27008. * Returns the first child node that is an element.
  27009. * @param {Node} node The node to get the first child element of.
  27010. * @return {Element} The first child node of {@code node} that is an element.
  27011. */
  27012. goog.dom.getFirstElementChild = function(node) {
  27013. if (goog.isDef(node.firstElementChild)) {
  27014. return /** @type {!Element} */(node).firstElementChild;
  27015. }
  27016. return goog.dom.getNextElementNode_(node.firstChild, true);
  27017. };
  27018. /**
  27019. * Returns the last child node that is an element.
  27020. * @param {Node} node The node to get the last child element of.
  27021. * @return {Element} The last child node of {@code node} that is an element.
  27022. */
  27023. goog.dom.getLastElementChild = function(node) {
  27024. if (goog.isDef(node.lastElementChild)) {
  27025. return /** @type {!Element} */(node).lastElementChild;
  27026. }
  27027. return goog.dom.getNextElementNode_(node.lastChild, false);
  27028. };
  27029. /**
  27030. * Returns the first next sibling that is an element.
  27031. * @param {Node} node The node to get the next sibling element of.
  27032. * @return {Element} The next sibling of {@code node} that is an element.
  27033. */
  27034. goog.dom.getNextElementSibling = function(node) {
  27035. if (goog.isDef(node.nextElementSibling)) {
  27036. return /** @type {!Element} */(node).nextElementSibling;
  27037. }
  27038. return goog.dom.getNextElementNode_(node.nextSibling, true);
  27039. };
  27040. /**
  27041. * Returns the first previous sibling that is an element.
  27042. * @param {Node} node The node to get the previous sibling element of.
  27043. * @return {Element} The first previous sibling of {@code node} that is
  27044. * an element.
  27045. */
  27046. goog.dom.getPreviousElementSibling = function(node) {
  27047. if (goog.isDef(node.previousElementSibling)) {
  27048. return /** @type {!Element} */(node).previousElementSibling;
  27049. }
  27050. return goog.dom.getNextElementNode_(node.previousSibling, false);
  27051. };
  27052. /**
  27053. * Returns the first node that is an element in the specified direction,
  27054. * starting with {@code node}.
  27055. * @param {Node} node The node to get the next element from.
  27056. * @param {boolean} forward Whether to look forwards or backwards.
  27057. * @return {Element} The first element.
  27058. * @private
  27059. */
  27060. goog.dom.getNextElementNode_ = function(node, forward) {
  27061. while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {
  27062. node = forward ? node.nextSibling : node.previousSibling;
  27063. }
  27064. return /** @type {Element} */ (node);
  27065. };
  27066. /**
  27067. * Returns the next node in source order from the given node.
  27068. * @param {Node} node The node.
  27069. * @return {Node} The next node in the DOM tree, or null if this was the last
  27070. * node.
  27071. */
  27072. goog.dom.getNextNode = function(node) {
  27073. if (!node) {
  27074. return null;
  27075. }
  27076. if (node.firstChild) {
  27077. return node.firstChild;
  27078. }
  27079. while (node && !node.nextSibling) {
  27080. node = node.parentNode;
  27081. }
  27082. return node ? node.nextSibling : null;
  27083. };
  27084. /**
  27085. * Returns the previous node in source order from the given node.
  27086. * @param {Node} node The node.
  27087. * @return {Node} The previous node in the DOM tree, or null if this was the
  27088. * first node.
  27089. */
  27090. goog.dom.getPreviousNode = function(node) {
  27091. if (!node) {
  27092. return null;
  27093. }
  27094. if (!node.previousSibling) {
  27095. return node.parentNode;
  27096. }
  27097. node = node.previousSibling;
  27098. while (node && node.lastChild) {
  27099. node = node.lastChild;
  27100. }
  27101. return node;
  27102. };
  27103. /**
  27104. * Whether the object looks like a DOM node.
  27105. * @param {?} obj The object being tested for node likeness.
  27106. * @return {boolean} Whether the object looks like a DOM node.
  27107. */
  27108. goog.dom.isNodeLike = function(obj) {
  27109. return goog.isObject(obj) && obj.nodeType > 0;
  27110. };
  27111. /**
  27112. * Whether the object looks like an Element.
  27113. * @param {?} obj The object being tested for Element likeness.
  27114. * @return {boolean} Whether the object looks like an Element.
  27115. */
  27116. goog.dom.isElement = function(obj) {
  27117. return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;
  27118. };
  27119. /**
  27120. * Returns true if the specified value is a Window object. This includes the
  27121. * global window for HTML pages, and iframe windows.
  27122. * @param {?} obj Variable to test.
  27123. * @return {boolean} Whether the variable is a window.
  27124. */
  27125. goog.dom.isWindow = function(obj) {
  27126. return goog.isObject(obj) && obj['window'] == obj;
  27127. };
  27128. /**
  27129. * Returns an element's parent, if it's an Element.
  27130. * @param {Element} element The DOM element.
  27131. * @return {Element} The parent, or null if not an Element.
  27132. */
  27133. goog.dom.getParentElement = function(element) {
  27134. var parent;
  27135. if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {
  27136. var isIe9 = goog.userAgent.IE &&
  27137. goog.userAgent.isVersionOrHigher('9') &&
  27138. !goog.userAgent.isVersionOrHigher('10');
  27139. // SVG elements in IE9 can't use the parentElement property.
  27140. // goog.global['SVGElement'] is not defined in IE9 quirks mode.
  27141. if (!(isIe9 && goog.global['SVGElement'] &&
  27142. element instanceof goog.global['SVGElement'])) {
  27143. parent = element.parentElement;
  27144. if (parent) {
  27145. return parent;
  27146. }
  27147. }
  27148. }
  27149. parent = element.parentNode;
  27150. return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;
  27151. };
  27152. /**
  27153. * Whether a node contains another node.
  27154. * @param {Node} parent The node that should contain the other node.
  27155. * @param {Node} descendant The node to test presence of.
  27156. * @return {boolean} Whether the parent node contains the descendent node.
  27157. */
  27158. goog.dom.contains = function(parent, descendant) {
  27159. // We use browser specific methods for this if available since it is faster
  27160. // that way.
  27161. // IE DOM
  27162. if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {
  27163. return parent == descendant || parent.contains(descendant);
  27164. }
  27165. // W3C DOM Level 3
  27166. if (typeof parent.compareDocumentPosition != 'undefined') {
  27167. return parent == descendant ||
  27168. Boolean(parent.compareDocumentPosition(descendant) & 16);
  27169. }
  27170. // W3C DOM Level 1
  27171. while (descendant && parent != descendant) {
  27172. descendant = descendant.parentNode;
  27173. }
  27174. return descendant == parent;
  27175. };
  27176. /**
  27177. * Compares the document order of two nodes, returning 0 if they are the same
  27178. * node, a negative number if node1 is before node2, and a positive number if
  27179. * node2 is before node1. Note that we compare the order the tags appear in the
  27180. * document so in the tree <b><i>text</i></b> the B node is considered to be
  27181. * before the I node.
  27182. *
  27183. * @param {Node} node1 The first node to compare.
  27184. * @param {Node} node2 The second node to compare.
  27185. * @return {number} 0 if the nodes are the same node, a negative number if node1
  27186. * is before node2, and a positive number if node2 is before node1.
  27187. */
  27188. goog.dom.compareNodeOrder = function(node1, node2) {
  27189. // Fall out quickly for equality.
  27190. if (node1 == node2) {
  27191. return 0;
  27192. }
  27193. // Use compareDocumentPosition where available
  27194. if (node1.compareDocumentPosition) {
  27195. // 4 is the bitmask for FOLLOWS.
  27196. return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;
  27197. }
  27198. // Special case for document nodes on IE 7 and 8.
  27199. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {
  27200. if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {
  27201. return -1;
  27202. }
  27203. if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {
  27204. return 1;
  27205. }
  27206. }
  27207. // Process in IE using sourceIndex - we check to see if the first node has
  27208. // a source index or if its parent has one.
  27209. if ('sourceIndex' in node1 ||
  27210. (node1.parentNode && 'sourceIndex' in node1.parentNode)) {
  27211. var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;
  27212. var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;
  27213. if (isElement1 && isElement2) {
  27214. return node1.sourceIndex - node2.sourceIndex;
  27215. } else {
  27216. var parent1 = node1.parentNode;
  27217. var parent2 = node2.parentNode;
  27218. if (parent1 == parent2) {
  27219. return goog.dom.compareSiblingOrder_(node1, node2);
  27220. }
  27221. if (!isElement1 && goog.dom.contains(parent1, node2)) {
  27222. return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);
  27223. }
  27224. if (!isElement2 && goog.dom.contains(parent2, node1)) {
  27225. return goog.dom.compareParentsDescendantNodeIe_(node2, node1);
  27226. }
  27227. return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -
  27228. (isElement2 ? node2.sourceIndex : parent2.sourceIndex);
  27229. }
  27230. }
  27231. // For Safari, we compare ranges.
  27232. var doc = goog.dom.getOwnerDocument(node1);
  27233. var range1, range2;
  27234. range1 = doc.createRange();
  27235. range1.selectNode(node1);
  27236. range1.collapse(true);
  27237. range2 = doc.createRange();
  27238. range2.selectNode(node2);
  27239. range2.collapse(true);
  27240. return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END,
  27241. range2);
  27242. };
  27243. /**
  27244. * Utility function to compare the position of two nodes, when
  27245. * {@code textNode}'s parent is an ancestor of {@code node}. If this entry
  27246. * condition is not met, this function will attempt to reference a null object.
  27247. * @param {!Node} textNode The textNode to compare.
  27248. * @param {Node} node The node to compare.
  27249. * @return {number} -1 if node is before textNode, +1 otherwise.
  27250. * @private
  27251. */
  27252. goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {
  27253. var parent = textNode.parentNode;
  27254. if (parent == node) {
  27255. // If textNode is a child of node, then node comes first.
  27256. return -1;
  27257. }
  27258. var sibling = node;
  27259. while (sibling.parentNode != parent) {
  27260. sibling = sibling.parentNode;
  27261. }
  27262. return goog.dom.compareSiblingOrder_(sibling, textNode);
  27263. };
  27264. /**
  27265. * Utility function to compare the position of two nodes known to be non-equal
  27266. * siblings.
  27267. * @param {Node} node1 The first node to compare.
  27268. * @param {!Node} node2 The second node to compare.
  27269. * @return {number} -1 if node1 is before node2, +1 otherwise.
  27270. * @private
  27271. */
  27272. goog.dom.compareSiblingOrder_ = function(node1, node2) {
  27273. var s = node2;
  27274. while ((s = s.previousSibling)) {
  27275. if (s == node1) {
  27276. // We just found node1 before node2.
  27277. return -1;
  27278. }
  27279. }
  27280. // Since we didn't find it, node1 must be after node2.
  27281. return 1;
  27282. };
  27283. /**
  27284. * Find the deepest common ancestor of the given nodes.
  27285. * @param {...Node} var_args The nodes to find a common ancestor of.
  27286. * @return {Node} The common ancestor of the nodes, or null if there is none.
  27287. * null will only be returned if two or more of the nodes are from different
  27288. * documents.
  27289. */
  27290. goog.dom.findCommonAncestor = function(var_args) {
  27291. var i, count = arguments.length;
  27292. if (!count) {
  27293. return null;
  27294. } else if (count == 1) {
  27295. return arguments[0];
  27296. }
  27297. var paths = [];
  27298. var minLength = Infinity;
  27299. for (i = 0; i < count; i++) {
  27300. // Compute the list of ancestors.
  27301. var ancestors = [];
  27302. var node = arguments[i];
  27303. while (node) {
  27304. ancestors.unshift(node);
  27305. node = node.parentNode;
  27306. }
  27307. // Save the list for comparison.
  27308. paths.push(ancestors);
  27309. minLength = Math.min(minLength, ancestors.length);
  27310. }
  27311. var output = null;
  27312. for (i = 0; i < minLength; i++) {
  27313. var first = paths[0][i];
  27314. for (var j = 1; j < count; j++) {
  27315. if (first != paths[j][i]) {
  27316. return output;
  27317. }
  27318. }
  27319. output = first;
  27320. }
  27321. return output;
  27322. };
  27323. /**
  27324. * Returns the owner document for a node.
  27325. * @param {Node|Window} node The node to get the document for.
  27326. * @return {!Document} The document owning the node.
  27327. */
  27328. goog.dom.getOwnerDocument = function(node) {
  27329. // TODO(nnaze): Update param signature to be non-nullable.
  27330. goog.asserts.assert(node, 'Node cannot be null or undefined.');
  27331. return /** @type {!Document} */ (
  27332. node.nodeType == goog.dom.NodeType.DOCUMENT ? node :
  27333. node.ownerDocument || node.document);
  27334. };
  27335. /**
  27336. * Cross-browser function for getting the document element of a frame or iframe.
  27337. * @param {Element} frame Frame element.
  27338. * @return {!Document} The frame content document.
  27339. */
  27340. goog.dom.getFrameContentDocument = function(frame) {
  27341. var doc = frame.contentDocument || frame.contentWindow.document;
  27342. return doc;
  27343. };
  27344. /**
  27345. * Cross-browser function for getting the window of a frame or iframe.
  27346. * @param {Element} frame Frame element.
  27347. * @return {Window} The window associated with the given frame.
  27348. */
  27349. goog.dom.getFrameContentWindow = function(frame) {
  27350. return frame.contentWindow ||
  27351. goog.dom.getWindow(goog.dom.getFrameContentDocument(frame));
  27352. };
  27353. /**
  27354. * Sets the text content of a node, with cross-browser support.
  27355. * @param {Node} node The node to change the text content of.
  27356. * @param {string|number} text The value that should replace the node's content.
  27357. */
  27358. goog.dom.setTextContent = function(node, text) {
  27359. goog.asserts.assert(node != null,
  27360. 'goog.dom.setTextContent expects a non-null value for node');
  27361. if ('textContent' in node) {
  27362. node.textContent = text;
  27363. } else if (node.nodeType == goog.dom.NodeType.TEXT) {
  27364. node.data = text;
  27365. } else if (node.firstChild &&
  27366. node.firstChild.nodeType == goog.dom.NodeType.TEXT) {
  27367. // If the first child is a text node we just change its data and remove the
  27368. // rest of the children.
  27369. while (node.lastChild != node.firstChild) {
  27370. node.removeChild(node.lastChild);
  27371. }
  27372. node.firstChild.data = text;
  27373. } else {
  27374. goog.dom.removeChildren(node);
  27375. var doc = goog.dom.getOwnerDocument(node);
  27376. node.appendChild(doc.createTextNode(String(text)));
  27377. }
  27378. };
  27379. /**
  27380. * Gets the outerHTML of a node, which islike innerHTML, except that it
  27381. * actually contains the HTML of the node itself.
  27382. * @param {Element} element The element to get the HTML of.
  27383. * @return {string} The outerHTML of the given element.
  27384. */
  27385. goog.dom.getOuterHtml = function(element) {
  27386. // IE, Opera and WebKit all have outerHTML.
  27387. if ('outerHTML' in element) {
  27388. return element.outerHTML;
  27389. } else {
  27390. var doc = goog.dom.getOwnerDocument(element);
  27391. var div = doc.createElement(goog.dom.TagName.DIV);
  27392. div.appendChild(element.cloneNode(true));
  27393. return div.innerHTML;
  27394. }
  27395. };
  27396. /**
  27397. * Finds the first descendant node that matches the filter function, using
  27398. * a depth first search. This function offers the most general purpose way
  27399. * of finding a matching element. You may also wish to consider
  27400. * {@code goog.dom.query} which can express many matching criteria using
  27401. * CSS selector expressions. These expressions often result in a more
  27402. * compact representation of the desired result.
  27403. * @see goog.dom.query
  27404. *
  27405. * @param {Node} root The root of the tree to search.
  27406. * @param {function(Node) : boolean} p The filter function.
  27407. * @return {Node|undefined} The found node or undefined if none is found.
  27408. */
  27409. goog.dom.findNode = function(root, p) {
  27410. var rv = [];
  27411. var found = goog.dom.findNodes_(root, p, rv, true);
  27412. return found ? rv[0] : undefined;
  27413. };
  27414. /**
  27415. * Finds all the descendant nodes that match the filter function, using a
  27416. * a depth first search. This function offers the most general-purpose way
  27417. * of finding a set of matching elements. You may also wish to consider
  27418. * {@code goog.dom.query} which can express many matching criteria using
  27419. * CSS selector expressions. These expressions often result in a more
  27420. * compact representation of the desired result.
  27421. * @param {Node} root The root of the tree to search.
  27422. * @param {function(Node) : boolean} p The filter function.
  27423. * @return {!Array<!Node>} The found nodes or an empty array if none are found.
  27424. */
  27425. goog.dom.findNodes = function(root, p) {
  27426. var rv = [];
  27427. goog.dom.findNodes_(root, p, rv, false);
  27428. return rv;
  27429. };
  27430. /**
  27431. * Finds the first or all the descendant nodes that match the filter function,
  27432. * using a depth first search.
  27433. * @param {Node} root The root of the tree to search.
  27434. * @param {function(Node) : boolean} p The filter function.
  27435. * @param {!Array<!Node>} rv The found nodes are added to this array.
  27436. * @param {boolean} findOne If true we exit after the first found node.
  27437. * @return {boolean} Whether the search is complete or not. True in case findOne
  27438. * is true and the node is found. False otherwise.
  27439. * @private
  27440. */
  27441. goog.dom.findNodes_ = function(root, p, rv, findOne) {
  27442. if (root != null) {
  27443. var child = root.firstChild;
  27444. while (child) {
  27445. if (p(child)) {
  27446. rv.push(child);
  27447. if (findOne) {
  27448. return true;
  27449. }
  27450. }
  27451. if (goog.dom.findNodes_(child, p, rv, findOne)) {
  27452. return true;
  27453. }
  27454. child = child.nextSibling;
  27455. }
  27456. }
  27457. return false;
  27458. };
  27459. /**
  27460. * Map of tags whose content to ignore when calculating text length.
  27461. * @private {!Object<string, number>}
  27462. * @const
  27463. */
  27464. goog.dom.TAGS_TO_IGNORE_ = {
  27465. 'SCRIPT': 1,
  27466. 'STYLE': 1,
  27467. 'HEAD': 1,
  27468. 'IFRAME': 1,
  27469. 'OBJECT': 1
  27470. };
  27471. /**
  27472. * Map of tags which have predefined values with regard to whitespace.
  27473. * @private {!Object<string, string>}
  27474. * @const
  27475. */
  27476. goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'};
  27477. /**
  27478. * Returns true if the element has a tab index that allows it to receive
  27479. * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
  27480. * natively support keyboard focus, even if they have no tab index.
  27481. * @param {!Element} element Element to check.
  27482. * @return {boolean} Whether the element has a tab index that allows keyboard
  27483. * focus.
  27484. * @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
  27485. */
  27486. goog.dom.isFocusableTabIndex = function(element) {
  27487. return goog.dom.hasSpecifiedTabIndex_(element) &&
  27488. goog.dom.isTabIndexFocusable_(element);
  27489. };
  27490. /**
  27491. * Enables or disables keyboard focus support on the element via its tab index.
  27492. * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
  27493. * (or elements that natively support keyboard focus, like form elements) can
  27494. * receive keyboard focus. See http://go/tabindex for more info.
  27495. * @param {Element} element Element whose tab index is to be changed.
  27496. * @param {boolean} enable Whether to set or remove a tab index on the element
  27497. * that supports keyboard focus.
  27498. */
  27499. goog.dom.setFocusableTabIndex = function(element, enable) {
  27500. if (enable) {
  27501. element.tabIndex = 0;
  27502. } else {
  27503. // Set tabIndex to -1 first, then remove it. This is a workaround for
  27504. // Safari (confirmed in version 4 on Windows). When removing the attribute
  27505. // without setting it to -1 first, the element remains keyboard focusable
  27506. // despite not having a tabIndex attribute anymore.
  27507. element.tabIndex = -1;
  27508. element.removeAttribute('tabIndex'); // Must be camelCase!
  27509. }
  27510. };
  27511. /**
  27512. * Returns true if the element can be focused, i.e. it has a tab index that
  27513. * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
  27514. * that natively supports keyboard focus.
  27515. * @param {!Element} element Element to check.
  27516. * @return {boolean} Whether the element allows keyboard focus.
  27517. */
  27518. goog.dom.isFocusable = function(element) {
  27519. var focusable;
  27520. // Some elements can have unspecified tab index and still receive focus.
  27521. if (goog.dom.nativelySupportsFocus_(element)) {
  27522. // Make sure the element is not disabled ...
  27523. focusable = !element.disabled &&
  27524. // ... and if a tab index is specified, it allows focus.
  27525. (!goog.dom.hasSpecifiedTabIndex_(element) ||
  27526. goog.dom.isTabIndexFocusable_(element));
  27527. } else {
  27528. focusable = goog.dom.isFocusableTabIndex(element);
  27529. }
  27530. // IE requires elements to be visible in order to focus them.
  27531. return focusable && goog.userAgent.IE ?
  27532. goog.dom.hasNonZeroBoundingRect_(element) : focusable;
  27533. };
  27534. /**
  27535. * Returns true if the element has a specified tab index.
  27536. * @param {!Element} element Element to check.
  27537. * @return {boolean} Whether the element has a specified tab index.
  27538. * @private
  27539. */
  27540. goog.dom.hasSpecifiedTabIndex_ = function(element) {
  27541. // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),
  27542. // which returns an object with a 'specified' property if tabIndex is
  27543. // specified. This works on other browsers, too.
  27544. var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
  27545. return goog.isDefAndNotNull(attrNode) && attrNode.specified;
  27546. };
  27547. /**
  27548. * Returns true if the element's tab index allows the element to be focused.
  27549. * @param {!Element} element Element to check.
  27550. * @return {boolean} Whether the element's tab index allows focus.
  27551. * @private
  27552. */
  27553. goog.dom.isTabIndexFocusable_ = function(element) {
  27554. var index = element.tabIndex;
  27555. // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.
  27556. return goog.isNumber(index) && index >= 0 && index < 32768;
  27557. };
  27558. /**
  27559. * Returns true if the element is focusable even when tabIndex is not set.
  27560. * @param {!Element} element Element to check.
  27561. * @return {boolean} Whether the element natively supports focus.
  27562. * @private
  27563. */
  27564. goog.dom.nativelySupportsFocus_ = function(element) {
  27565. return element.tagName == goog.dom.TagName.A ||
  27566. element.tagName == goog.dom.TagName.INPUT ||
  27567. element.tagName == goog.dom.TagName.TEXTAREA ||
  27568. element.tagName == goog.dom.TagName.SELECT ||
  27569. element.tagName == goog.dom.TagName.BUTTON;
  27570. };
  27571. /**
  27572. * Returns true if the element has a bounding rectangle that would be visible
  27573. * (i.e. its width and height are greater than zero).
  27574. * @param {!Element} element Element to check.
  27575. * @return {boolean} Whether the element has a non-zero bounding rectangle.
  27576. * @private
  27577. */
  27578. goog.dom.hasNonZeroBoundingRect_ = function(element) {
  27579. var rect = goog.isFunction(element['getBoundingClientRect']) ?
  27580. element.getBoundingClientRect() :
  27581. {'height': element.offsetHeight, 'width': element.offsetWidth};
  27582. return goog.isDefAndNotNull(rect) && rect.height > 0 && rect.width > 0;
  27583. };
  27584. /**
  27585. * Returns the text content of the current node, without markup and invisible
  27586. * symbols. New lines are stripped and whitespace is collapsed,
  27587. * such that each character would be visible.
  27588. *
  27589. * In browsers that support it, innerText is used. Other browsers attempt to
  27590. * simulate it via node traversal. Line breaks are canonicalized in IE.
  27591. *
  27592. * @param {Node} node The node from which we are getting content.
  27593. * @return {string} The text content.
  27594. */
  27595. goog.dom.getTextContent = function(node) {
  27596. var textContent;
  27597. // Note(arv): IE9, Opera, and Safari 3 support innerText but they include
  27598. // text nodes in script tags. So we revert to use a user agent test here.
  27599. if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) {
  27600. textContent = goog.string.canonicalizeNewlines(node.innerText);
  27601. // Unfortunately .innerText() returns text with &shy; symbols
  27602. // We need to filter it out and then remove duplicate whitespaces
  27603. } else {
  27604. var buf = [];
  27605. goog.dom.getTextContent_(node, buf, true);
  27606. textContent = buf.join('');
  27607. }
  27608. // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.
  27609. textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');
  27610. // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.
  27611. textContent = textContent.replace(/\u200B/g, '');
  27612. // Skip this replacement on old browsers with working innerText, which
  27613. // automatically turns &nbsp; into ' ' and / +/ into ' ' when reading
  27614. // innerText.
  27615. if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {
  27616. textContent = textContent.replace(/ +/g, ' ');
  27617. }
  27618. if (textContent != ' ') {
  27619. textContent = textContent.replace(/^\s*/, '');
  27620. }
  27621. return textContent;
  27622. };
  27623. /**
  27624. * Returns the text content of the current node, without markup.
  27625. *
  27626. * Unlike {@code getTextContent} this method does not collapse whitespaces
  27627. * or normalize lines breaks.
  27628. *
  27629. * @param {Node} node The node from which we are getting content.
  27630. * @return {string} The raw text content.
  27631. */
  27632. goog.dom.getRawTextContent = function(node) {
  27633. var buf = [];
  27634. goog.dom.getTextContent_(node, buf, false);
  27635. return buf.join('');
  27636. };
  27637. /**
  27638. * Recursive support function for text content retrieval.
  27639. *
  27640. * @param {Node} node The node from which we are getting content.
  27641. * @param {Array<string>} buf string buffer.
  27642. * @param {boolean} normalizeWhitespace Whether to normalize whitespace.
  27643. * @private
  27644. */
  27645. goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {
  27646. if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {
  27647. // ignore certain tags
  27648. } else if (node.nodeType == goog.dom.NodeType.TEXT) {
  27649. if (normalizeWhitespace) {
  27650. buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
  27651. } else {
  27652. buf.push(node.nodeValue);
  27653. }
  27654. } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
  27655. buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);
  27656. } else {
  27657. var child = node.firstChild;
  27658. while (child) {
  27659. goog.dom.getTextContent_(child, buf, normalizeWhitespace);
  27660. child = child.nextSibling;
  27661. }
  27662. }
  27663. };
  27664. /**
  27665. * Returns the text length of the text contained in a node, without markup. This
  27666. * is equivalent to the selection length if the node was selected, or the number
  27667. * of cursor movements to traverse the node. Images & BRs take one space. New
  27668. * lines are ignored.
  27669. *
  27670. * @param {Node} node The node whose text content length is being calculated.
  27671. * @return {number} The length of {@code node}'s text content.
  27672. */
  27673. goog.dom.getNodeTextLength = function(node) {
  27674. return goog.dom.getTextContent(node).length;
  27675. };
  27676. /**
  27677. * Returns the text offset of a node relative to one of its ancestors. The text
  27678. * length is the same as the length calculated by goog.dom.getNodeTextLength.
  27679. *
  27680. * @param {Node} node The node whose offset is being calculated.
  27681. * @param {Node=} opt_offsetParent The node relative to which the offset will
  27682. * be calculated. Defaults to the node's owner document's body.
  27683. * @return {number} The text offset.
  27684. */
  27685. goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {
  27686. var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;
  27687. var buf = [];
  27688. while (node && node != root) {
  27689. var cur = node;
  27690. while ((cur = cur.previousSibling)) {
  27691. buf.unshift(goog.dom.getTextContent(cur));
  27692. }
  27693. node = node.parentNode;
  27694. }
  27695. // Trim left to deal with FF cases when there might be line breaks and empty
  27696. // nodes at the front of the text
  27697. return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;
  27698. };
  27699. /**
  27700. * Returns the node at a given offset in a parent node. If an object is
  27701. * provided for the optional third parameter, the node and the remainder of the
  27702. * offset will stored as properties of this object.
  27703. * @param {Node} parent The parent node.
  27704. * @param {number} offset The offset into the parent node.
  27705. * @param {Object=} opt_result Object to be used to store the return value. The
  27706. * return value will be stored in the form {node: Node, remainder: number}
  27707. * if this object is provided.
  27708. * @return {Node} The node at the given offset.
  27709. */
  27710. goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {
  27711. var stack = [parent], pos = 0, cur = null;
  27712. while (stack.length > 0 && pos < offset) {
  27713. cur = stack.pop();
  27714. if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {
  27715. // ignore certain tags
  27716. } else if (cur.nodeType == goog.dom.NodeType.TEXT) {
  27717. var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');
  27718. pos += text.length;
  27719. } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
  27720. pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;
  27721. } else {
  27722. for (var i = cur.childNodes.length - 1; i >= 0; i--) {
  27723. stack.push(cur.childNodes[i]);
  27724. }
  27725. }
  27726. }
  27727. if (goog.isObject(opt_result)) {
  27728. opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;
  27729. opt_result.node = cur;
  27730. }
  27731. return cur;
  27732. };
  27733. /**
  27734. * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
  27735. * the object must have a numeric length property and an item function (which
  27736. * has type 'string' on IE for some reason).
  27737. * @param {Object} val Object to test.
  27738. * @return {boolean} Whether the object is a NodeList.
  27739. */
  27740. goog.dom.isNodeList = function(val) {
  27741. // TODO(attila): Now the isNodeList is part of goog.dom we can use
  27742. // goog.userAgent to make this simpler.
  27743. // A NodeList must have a length property of type 'number' on all platforms.
  27744. if (val && typeof val.length == 'number') {
  27745. // A NodeList is an object everywhere except Safari, where it's a function.
  27746. if (goog.isObject(val)) {
  27747. // A NodeList must have an item function (on non-IE platforms) or an item
  27748. // property of type 'string' (on IE).
  27749. return typeof val.item == 'function' || typeof val.item == 'string';
  27750. } else if (goog.isFunction(val)) {
  27751. // On Safari, a NodeList is a function with an item property that is also
  27752. // a function.
  27753. return typeof val.item == 'function';
  27754. }
  27755. }
  27756. // Not a NodeList.
  27757. return false;
  27758. };
  27759. /**
  27760. * Walks up the DOM hierarchy returning the first ancestor that has the passed
  27761. * tag name and/or class name. If the passed element matches the specified
  27762. * criteria, the element itself is returned.
  27763. * @param {Node} element The DOM node to start with.
  27764. * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
  27765. * null/undefined to match only based on class name).
  27766. * @param {?string=} opt_class The class name to match (or null/undefined to
  27767. * match only based on tag name).
  27768. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  27769. * dom.
  27770. * @return {Element} The first ancestor that matches the passed criteria, or
  27771. * null if no match is found.
  27772. */
  27773. goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class,
  27774. opt_maxSearchSteps) {
  27775. if (!opt_tag && !opt_class) {
  27776. return null;
  27777. }
  27778. var tagName = opt_tag ? opt_tag.toUpperCase() : null;
  27779. return /** @type {Element} */ (goog.dom.getAncestor(element,
  27780. function(node) {
  27781. return (!tagName || node.nodeName == tagName) &&
  27782. (!opt_class || goog.isString(node.className) &&
  27783. goog.array.contains(node.className.split(/\s+/), opt_class));
  27784. }, true, opt_maxSearchSteps));
  27785. };
  27786. /**
  27787. * Walks up the DOM hierarchy returning the first ancestor that has the passed
  27788. * class name. If the passed element matches the specified criteria, the
  27789. * element itself is returned.
  27790. * @param {Node} element The DOM node to start with.
  27791. * @param {string} className The class name to match.
  27792. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  27793. * dom.
  27794. * @return {Element} The first ancestor that matches the passed criteria, or
  27795. * null if none match.
  27796. */
  27797. goog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) {
  27798. return goog.dom.getAncestorByTagNameAndClass(element, null, className,
  27799. opt_maxSearchSteps);
  27800. };
  27801. /**
  27802. * Walks up the DOM hierarchy returning the first ancestor that passes the
  27803. * matcher function.
  27804. * @param {Node} element The DOM node to start with.
  27805. * @param {function(Node) : boolean} matcher A function that returns true if the
  27806. * passed node matches the desired criteria.
  27807. * @param {boolean=} opt_includeNode If true, the node itself is included in
  27808. * the search (the first call to the matcher will pass startElement as
  27809. * the node to test).
  27810. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  27811. * dom.
  27812. * @return {Node} DOM node that matched the matcher, or null if there was
  27813. * no match.
  27814. */
  27815. goog.dom.getAncestor = function(
  27816. element, matcher, opt_includeNode, opt_maxSearchSteps) {
  27817. if (!opt_includeNode) {
  27818. element = element.parentNode;
  27819. }
  27820. var ignoreSearchSteps = opt_maxSearchSteps == null;
  27821. var steps = 0;
  27822. while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) {
  27823. goog.asserts.assert(element.name != 'parentNode');
  27824. if (matcher(element)) {
  27825. return element;
  27826. }
  27827. element = element.parentNode;
  27828. steps++;
  27829. }
  27830. // Reached the root of the DOM without a match
  27831. return null;
  27832. };
  27833. /**
  27834. * Determines the active element in the given document.
  27835. * @param {Document} doc The document to look in.
  27836. * @return {Element} The active element.
  27837. */
  27838. goog.dom.getActiveElement = function(doc) {
  27839. try {
  27840. return doc && doc.activeElement;
  27841. } catch (e) {
  27842. // NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE
  27843. // throws an exception. I'm not 100% sure why, but I suspect it chokes
  27844. // on document.activeElement if the activeElement has been recently
  27845. // removed from the DOM by a JS operation.
  27846. //
  27847. // We assume that an exception here simply means
  27848. // "there is no active element."
  27849. }
  27850. return null;
  27851. };
  27852. /**
  27853. * Gives the current devicePixelRatio.
  27854. *
  27855. * By default, this is the value of window.devicePixelRatio (which should be
  27856. * preferred if present).
  27857. *
  27858. * If window.devicePixelRatio is not present, the ratio is calculated with
  27859. * window.matchMedia, if present. Otherwise, gives 1.0.
  27860. *
  27861. * Some browsers (including Chrome) consider the browser zoom level in the pixel
  27862. * ratio, so the value may change across multiple calls.
  27863. *
  27864. * @return {number} The number of actual pixels per virtual pixel.
  27865. */
  27866. goog.dom.getPixelRatio = function() {
  27867. var win = goog.dom.getWindow();
  27868. if (goog.isDef(win.devicePixelRatio)) {
  27869. return win.devicePixelRatio;
  27870. } else if (win.matchMedia) {
  27871. return goog.dom.matchesPixelRatio_(.75) ||
  27872. goog.dom.matchesPixelRatio_(1.5) ||
  27873. goog.dom.matchesPixelRatio_(2) ||
  27874. goog.dom.matchesPixelRatio_(3) || 1;
  27875. }
  27876. return 1;
  27877. };
  27878. /**
  27879. * Calculates a mediaQuery to check if the current device supports the
  27880. * given actual to virtual pixel ratio.
  27881. * @param {number} pixelRatio The ratio of actual pixels to virtual pixels.
  27882. * @return {number} pixelRatio if applicable, otherwise 0.
  27883. * @private
  27884. */
  27885. goog.dom.matchesPixelRatio_ = function(pixelRatio) {
  27886. var win = goog.dom.getWindow();
  27887. var query = ('(-webkit-min-device-pixel-ratio: ' + pixelRatio + '),' +
  27888. '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +
  27889. '(min-resolution: ' + pixelRatio + 'dppx)');
  27890. return win.matchMedia(query).matches ? pixelRatio : 0;
  27891. };
  27892. /**
  27893. * Create an instance of a DOM helper with a new document object.
  27894. * @param {Document=} opt_document Document object to associate with this
  27895. * DOM helper.
  27896. * @constructor
  27897. */
  27898. goog.dom.DomHelper = function(opt_document) {
  27899. /**
  27900. * Reference to the document object to use
  27901. * @type {!Document}
  27902. * @private
  27903. */
  27904. this.document_ = opt_document || goog.global.document || document;
  27905. };
  27906. /**
  27907. * Gets the dom helper object for the document where the element resides.
  27908. * @param {Node=} opt_node If present, gets the DomHelper for this node.
  27909. * @return {!goog.dom.DomHelper} The DomHelper.
  27910. */
  27911. goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;
  27912. /**
  27913. * Sets the document object.
  27914. * @param {!Document} document Document object.
  27915. */
  27916. goog.dom.DomHelper.prototype.setDocument = function(document) {
  27917. this.document_ = document;
  27918. };
  27919. /**
  27920. * Gets the document object being used by the dom library.
  27921. * @return {!Document} Document object.
  27922. */
  27923. goog.dom.DomHelper.prototype.getDocument = function() {
  27924. return this.document_;
  27925. };
  27926. /**
  27927. * Alias for {@code getElementById}. If a DOM node is passed in then we just
  27928. * return that.
  27929. * @param {string|Element} element Element ID or a DOM node.
  27930. * @return {Element} The element with the given ID, or the node passed in.
  27931. */
  27932. goog.dom.DomHelper.prototype.getElement = function(element) {
  27933. return goog.dom.getElementHelper_(this.document_, element);
  27934. };
  27935. /**
  27936. * Gets an element by id, asserting that the element is found.
  27937. *
  27938. * This is used when an element is expected to exist, and should fail with
  27939. * an assertion error if it does not (if assertions are enabled).
  27940. *
  27941. * @param {string} id Element ID.
  27942. * @return {!Element} The element with the given ID, if it exists.
  27943. */
  27944. goog.dom.DomHelper.prototype.getRequiredElement = function(id) {
  27945. return goog.dom.getRequiredElementHelper_(this.document_, id);
  27946. };
  27947. /**
  27948. * Alias for {@code getElement}.
  27949. * @param {string|Element} element Element ID or a DOM node.
  27950. * @return {Element} The element with the given ID, or the node passed in.
  27951. * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.
  27952. */
  27953. goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;
  27954. /**
  27955. * Looks up elements by both tag and class name, using browser native functions
  27956. * ({@code querySelectorAll}, {@code getElementsByTagName} or
  27957. * {@code getElementsByClassName}) where possible. The returned array is a live
  27958. * NodeList or a static list depending on the code path taken.
  27959. *
  27960. * @see goog.dom.query
  27961. *
  27962. * @param {?string=} opt_tag Element tag name or * for all tags.
  27963. * @param {?string=} opt_class Optional class name.
  27964. * @param {(Document|Element)=} opt_el Optional element to look in.
  27965. * @return { {length: number} } Array-like list of elements (only a length
  27966. * property and numerical indices are guaranteed to exist).
  27967. */
  27968. goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag,
  27969. opt_class,
  27970. opt_el) {
  27971. return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag,
  27972. opt_class, opt_el);
  27973. };
  27974. /**
  27975. * Returns an array of all the elements with the provided className.
  27976. * @see {goog.dom.query}
  27977. * @param {string} className the name of the class to look for.
  27978. * @param {Element|Document=} opt_el Optional element to look in.
  27979. * @return { {length: number} } The items found with the class name provided.
  27980. */
  27981. goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {
  27982. var doc = opt_el || this.document_;
  27983. return goog.dom.getElementsByClass(className, doc);
  27984. };
  27985. /**
  27986. * Returns the first element we find matching the provided class name.
  27987. * @see {goog.dom.query}
  27988. * @param {string} className the name of the class to look for.
  27989. * @param {(Element|Document)=} opt_el Optional element to look in.
  27990. * @return {Element} The first item found with the class name provided.
  27991. */
  27992. goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {
  27993. var doc = opt_el || this.document_;
  27994. return goog.dom.getElementByClass(className, doc);
  27995. };
  27996. /**
  27997. * Ensures an element with the given className exists, and then returns the
  27998. * first element with the provided className.
  27999. * @see {goog.dom.query}
  28000. * @param {string} className the name of the class to look for.
  28001. * @param {(!Element|!Document)=} opt_root Optional element or document to look
  28002. * in.
  28003. * @return {!Element} The first item found with the class name provided.
  28004. * @throws {goog.asserts.AssertionError} Thrown if no element is found.
  28005. */
  28006. goog.dom.DomHelper.prototype.getRequiredElementByClass = function(className,
  28007. opt_root) {
  28008. var root = opt_root || this.document_;
  28009. return goog.dom.getRequiredElementByClass(className, root);
  28010. };
  28011. /**
  28012. * Alias for {@code getElementsByTagNameAndClass}.
  28013. * @deprecated Use DomHelper getElementsByTagNameAndClass.
  28014. * @see goog.dom.query
  28015. *
  28016. * @param {?string=} opt_tag Element tag name.
  28017. * @param {?string=} opt_class Optional class name.
  28018. * @param {Element=} opt_el Optional element to look in.
  28019. * @return { {length: number} } Array-like list of elements (only a length
  28020. * property and numerical indices are guaranteed to exist).
  28021. */
  28022. goog.dom.DomHelper.prototype.$$ =
  28023. goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;
  28024. /**
  28025. * Sets a number of properties on a node.
  28026. * @param {Element} element DOM node to set properties on.
  28027. * @param {Object} properties Hash of property:value pairs.
  28028. */
  28029. goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;
  28030. /**
  28031. * Gets the dimensions of the viewport.
  28032. * @param {Window=} opt_window Optional window element to test. Defaults to
  28033. * the window of the Dom Helper.
  28034. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  28035. */
  28036. goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {
  28037. // TODO(arv): This should not take an argument. That breaks the rule of a
  28038. // a DomHelper representing a single frame/window/document.
  28039. return goog.dom.getViewportSize(opt_window || this.getWindow());
  28040. };
  28041. /**
  28042. * Calculates the height of the document.
  28043. *
  28044. * @return {number} The height of the document.
  28045. */
  28046. goog.dom.DomHelper.prototype.getDocumentHeight = function() {
  28047. return goog.dom.getDocumentHeight_(this.getWindow());
  28048. };
  28049. /**
  28050. * Typedef for use with goog.dom.createDom and goog.dom.append.
  28051. * @typedef {Object|string|Array|NodeList}
  28052. */
  28053. goog.dom.Appendable;
  28054. /**
  28055. * Returns a dom node with a set of attributes. This function accepts varargs
  28056. * for subsequent nodes to be added. Subsequent nodes will be added to the
  28057. * first node as childNodes.
  28058. *
  28059. * So:
  28060. * <code>createDom('div', null, createDom('p'), createDom('p'));</code>
  28061. * would return a div with two child paragraphs
  28062. *
  28063. * An easy way to move all child nodes of an existing element to a new parent
  28064. * element is:
  28065. * <code>createDom('div', null, oldElement.childNodes);</code>
  28066. * which will remove all child nodes from the old element and add them as
  28067. * child nodes of the new DIV.
  28068. *
  28069. * @param {string} tagName Tag to create.
  28070. * @param {Object|string=} opt_attributes If object, then a map of name-value
  28071. * pairs for attributes. If a string, then this is the className of the new
  28072. * element.
  28073. * @param {...goog.dom.Appendable} var_args Further DOM nodes or
  28074. * strings for text nodes. If one of the var_args is an array or
  28075. * NodeList, its elements will be added as childNodes instead.
  28076. * @return {!Element} Reference to a DOM node.
  28077. */
  28078. goog.dom.DomHelper.prototype.createDom = function(tagName,
  28079. opt_attributes,
  28080. var_args) {
  28081. return goog.dom.createDom_(this.document_, arguments);
  28082. };
  28083. /**
  28084. * Alias for {@code createDom}.
  28085. * @param {string} tagName Tag to create.
  28086. * @param {(Object|string)=} opt_attributes If object, then a map of name-value
  28087. * pairs for attributes. If a string, then this is the className of the new
  28088. * element.
  28089. * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for
  28090. * text nodes. If one of the var_args is an array, its children will be
  28091. * added as childNodes instead.
  28092. * @return {!Element} Reference to a DOM node.
  28093. * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.
  28094. */
  28095. goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;
  28096. /**
  28097. * Creates a new element.
  28098. * @param {string} name Tag name.
  28099. * @return {!Element} The new element.
  28100. */
  28101. goog.dom.DomHelper.prototype.createElement = function(name) {
  28102. return this.document_.createElement(name);
  28103. };
  28104. /**
  28105. * Creates a new text node.
  28106. * @param {number|string} content Content.
  28107. * @return {!Text} The new text node.
  28108. */
  28109. goog.dom.DomHelper.prototype.createTextNode = function(content) {
  28110. return this.document_.createTextNode(String(content));
  28111. };
  28112. /**
  28113. * Create a table.
  28114. * @param {number} rows The number of rows in the table. Must be >= 1.
  28115. * @param {number} columns The number of columns in the table. Must be >= 1.
  28116. * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
  28117. * {@code goog.string.Unicode.NBSP} characters.
  28118. * @return {!HTMLElement} The created table.
  28119. */
  28120. goog.dom.DomHelper.prototype.createTable = function(rows, columns,
  28121. opt_fillWithNbsp) {
  28122. return goog.dom.createTable_(this.document_, rows, columns,
  28123. !!opt_fillWithNbsp);
  28124. };
  28125. /**
  28126. * Converts an HTML into a node or a document fragment. A single Node is used if
  28127. * {@code html} only generates a single node. If {@code html} generates multiple
  28128. * nodes then these are put inside a {@code DocumentFragment}.
  28129. * @param {!goog.html.SafeHtml} html The HTML markup to convert.
  28130. * @return {!Node} The resulting node.
  28131. */
  28132. goog.dom.DomHelper.prototype.safeHtmlToNode = function(html) {
  28133. return goog.dom.safeHtmlToNode_(this.document_, html);
  28134. };
  28135. /**
  28136. * Converts an HTML string into a node or a document fragment. A single Node
  28137. * is used if the {@code htmlString} only generates a single node. If the
  28138. * {@code htmlString} generates multiple nodes then these are put inside a
  28139. * {@code DocumentFragment}.
  28140. *
  28141. * @param {string} htmlString The HTML string to convert.
  28142. * @return {!Node} The resulting node.
  28143. */
  28144. goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) {
  28145. return goog.dom.htmlToDocumentFragment_(this.document_, htmlString);
  28146. };
  28147. /**
  28148. * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
  28149. * mode, false otherwise.
  28150. * @return {boolean} True if in CSS1-compatible mode.
  28151. */
  28152. goog.dom.DomHelper.prototype.isCss1CompatMode = function() {
  28153. return goog.dom.isCss1CompatMode_(this.document_);
  28154. };
  28155. /**
  28156. * Gets the window object associated with the document.
  28157. * @return {!Window} The window associated with the given document.
  28158. */
  28159. goog.dom.DomHelper.prototype.getWindow = function() {
  28160. return goog.dom.getWindow_(this.document_);
  28161. };
  28162. /**
  28163. * Gets the document scroll element.
  28164. * @return {!Element} Scrolling element.
  28165. */
  28166. goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {
  28167. return goog.dom.getDocumentScrollElement_(this.document_);
  28168. };
  28169. /**
  28170. * Gets the document scroll distance as a coordinate object.
  28171. * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.
  28172. */
  28173. goog.dom.DomHelper.prototype.getDocumentScroll = function() {
  28174. return goog.dom.getDocumentScroll_(this.document_);
  28175. };
  28176. /**
  28177. * Determines the active element in the given document.
  28178. * @param {Document=} opt_doc The document to look in.
  28179. * @return {Element} The active element.
  28180. */
  28181. goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {
  28182. return goog.dom.getActiveElement(opt_doc || this.document_);
  28183. };
  28184. /**
  28185. * Appends a child to a node.
  28186. * @param {Node} parent Parent.
  28187. * @param {Node} child Child.
  28188. */
  28189. goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;
  28190. /**
  28191. * Appends a node with text or other nodes.
  28192. * @param {!Node} parent The node to append nodes to.
  28193. * @param {...goog.dom.Appendable} var_args The things to append to the node.
  28194. * If this is a Node it is appended as is.
  28195. * If this is a string then a text node is appended.
  28196. * If this is an array like object then fields 0 to length - 1 are appended.
  28197. */
  28198. goog.dom.DomHelper.prototype.append = goog.dom.append;
  28199. /**
  28200. * Determines if the given node can contain children, intended to be used for
  28201. * HTML generation.
  28202. *
  28203. * @param {Node} node The node to check.
  28204. * @return {boolean} Whether the node can contain children.
  28205. */
  28206. goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;
  28207. /**
  28208. * Removes all the child nodes on a DOM node.
  28209. * @param {Node} node Node to remove children from.
  28210. */
  28211. goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;
  28212. /**
  28213. * Inserts a new node before an existing reference node (i.e., as the previous
  28214. * sibling). If the reference node has no parent, then does nothing.
  28215. * @param {Node} newNode Node to insert.
  28216. * @param {Node} refNode Reference node to insert before.
  28217. */
  28218. goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;
  28219. /**
  28220. * Inserts a new node after an existing reference node (i.e., as the next
  28221. * sibling). If the reference node has no parent, then does nothing.
  28222. * @param {Node} newNode Node to insert.
  28223. * @param {Node} refNode Reference node to insert after.
  28224. */
  28225. goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;
  28226. /**
  28227. * Insert a child at a given index. If index is larger than the number of child
  28228. * nodes that the parent currently has, the node is inserted as the last child
  28229. * node.
  28230. * @param {Element} parent The element into which to insert the child.
  28231. * @param {Node} child The element to insert.
  28232. * @param {number} index The index at which to insert the new child node. Must
  28233. * not be negative.
  28234. */
  28235. goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;
  28236. /**
  28237. * Removes a node from its parent.
  28238. * @param {Node} node The node to remove.
  28239. * @return {Node} The node removed if removed; else, null.
  28240. */
  28241. goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;
  28242. /**
  28243. * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
  28244. * parent.
  28245. * @param {Node} newNode Node to insert.
  28246. * @param {Node} oldNode Node to replace.
  28247. */
  28248. goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;
  28249. /**
  28250. * Flattens an element. That is, removes it and replace it with its children.
  28251. * @param {Element} element The element to flatten.
  28252. * @return {Element|undefined} The original element, detached from the document
  28253. * tree, sans children, or undefined if the element was already not in the
  28254. * document.
  28255. */
  28256. goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;
  28257. /**
  28258. * Returns an array containing just the element children of the given element.
  28259. * @param {Element} element The element whose element children we want.
  28260. * @return {!(Array|NodeList)} An array or array-like list of just the element
  28261. * children of the given element.
  28262. */
  28263. goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;
  28264. /**
  28265. * Returns the first child node that is an element.
  28266. * @param {Node} node The node to get the first child element of.
  28267. * @return {Element} The first child node of {@code node} that is an element.
  28268. */
  28269. goog.dom.DomHelper.prototype.getFirstElementChild =
  28270. goog.dom.getFirstElementChild;
  28271. /**
  28272. * Returns the last child node that is an element.
  28273. * @param {Node} node The node to get the last child element of.
  28274. * @return {Element} The last child node of {@code node} that is an element.
  28275. */
  28276. goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;
  28277. /**
  28278. * Returns the first next sibling that is an element.
  28279. * @param {Node} node The node to get the next sibling element of.
  28280. * @return {Element} The next sibling of {@code node} that is an element.
  28281. */
  28282. goog.dom.DomHelper.prototype.getNextElementSibling =
  28283. goog.dom.getNextElementSibling;
  28284. /**
  28285. * Returns the first previous sibling that is an element.
  28286. * @param {Node} node The node to get the previous sibling element of.
  28287. * @return {Element} The first previous sibling of {@code node} that is
  28288. * an element.
  28289. */
  28290. goog.dom.DomHelper.prototype.getPreviousElementSibling =
  28291. goog.dom.getPreviousElementSibling;
  28292. /**
  28293. * Returns the next node in source order from the given node.
  28294. * @param {Node} node The node.
  28295. * @return {Node} The next node in the DOM tree, or null if this was the last
  28296. * node.
  28297. */
  28298. goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;
  28299. /**
  28300. * Returns the previous node in source order from the given node.
  28301. * @param {Node} node The node.
  28302. * @return {Node} The previous node in the DOM tree, or null if this was the
  28303. * first node.
  28304. */
  28305. goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;
  28306. /**
  28307. * Whether the object looks like a DOM node.
  28308. * @param {?} obj The object being tested for node likeness.
  28309. * @return {boolean} Whether the object looks like a DOM node.
  28310. */
  28311. goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;
  28312. /**
  28313. * Whether the object looks like an Element.
  28314. * @param {?} obj The object being tested for Element likeness.
  28315. * @return {boolean} Whether the object looks like an Element.
  28316. */
  28317. goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;
  28318. /**
  28319. * Returns true if the specified value is a Window object. This includes the
  28320. * global window for HTML pages, and iframe windows.
  28321. * @param {?} obj Variable to test.
  28322. * @return {boolean} Whether the variable is a window.
  28323. */
  28324. goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;
  28325. /**
  28326. * Returns an element's parent, if it's an Element.
  28327. * @param {Element} element The DOM element.
  28328. * @return {Element} The parent, or null if not an Element.
  28329. */
  28330. goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;
  28331. /**
  28332. * Whether a node contains another node.
  28333. * @param {Node} parent The node that should contain the other node.
  28334. * @param {Node} descendant The node to test presence of.
  28335. * @return {boolean} Whether the parent node contains the descendent node.
  28336. */
  28337. goog.dom.DomHelper.prototype.contains = goog.dom.contains;
  28338. /**
  28339. * Compares the document order of two nodes, returning 0 if they are the same
  28340. * node, a negative number if node1 is before node2, and a positive number if
  28341. * node2 is before node1. Note that we compare the order the tags appear in the
  28342. * document so in the tree <b><i>text</i></b> the B node is considered to be
  28343. * before the I node.
  28344. *
  28345. * @param {Node} node1 The first node to compare.
  28346. * @param {Node} node2 The second node to compare.
  28347. * @return {number} 0 if the nodes are the same node, a negative number if node1
  28348. * is before node2, and a positive number if node2 is before node1.
  28349. */
  28350. goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;
  28351. /**
  28352. * Find the deepest common ancestor of the given nodes.
  28353. * @param {...Node} var_args The nodes to find a common ancestor of.
  28354. * @return {Node} The common ancestor of the nodes, or null if there is none.
  28355. * null will only be returned if two or more of the nodes are from different
  28356. * documents.
  28357. */
  28358. goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;
  28359. /**
  28360. * Returns the owner document for a node.
  28361. * @param {Node} node The node to get the document for.
  28362. * @return {!Document} The document owning the node.
  28363. */
  28364. goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;
  28365. /**
  28366. * Cross browser function for getting the document element of an iframe.
  28367. * @param {Element} iframe Iframe element.
  28368. * @return {!Document} The frame content document.
  28369. */
  28370. goog.dom.DomHelper.prototype.getFrameContentDocument =
  28371. goog.dom.getFrameContentDocument;
  28372. /**
  28373. * Cross browser function for getting the window of a frame or iframe.
  28374. * @param {Element} frame Frame element.
  28375. * @return {Window} The window associated with the given frame.
  28376. */
  28377. goog.dom.DomHelper.prototype.getFrameContentWindow =
  28378. goog.dom.getFrameContentWindow;
  28379. /**
  28380. * Sets the text content of a node, with cross-browser support.
  28381. * @param {Node} node The node to change the text content of.
  28382. * @param {string|number} text The value that should replace the node's content.
  28383. */
  28384. goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;
  28385. /**
  28386. * Gets the outerHTML of a node, which islike innerHTML, except that it
  28387. * actually contains the HTML of the node itself.
  28388. * @param {Element} element The element to get the HTML of.
  28389. * @return {string} The outerHTML of the given element.
  28390. */
  28391. goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;
  28392. /**
  28393. * Finds the first descendant node that matches the filter function. This does
  28394. * a depth first search.
  28395. * @param {Node} root The root of the tree to search.
  28396. * @param {function(Node) : boolean} p The filter function.
  28397. * @return {Node|undefined} The found node or undefined if none is found.
  28398. */
  28399. goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;
  28400. /**
  28401. * Finds all the descendant nodes that matches the filter function. This does a
  28402. * depth first search.
  28403. * @param {Node} root The root of the tree to search.
  28404. * @param {function(Node) : boolean} p The filter function.
  28405. * @return {Array<Node>} The found nodes or an empty array if none are found.
  28406. */
  28407. goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;
  28408. /**
  28409. * Returns true if the element has a tab index that allows it to receive
  28410. * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
  28411. * natively support keyboard focus, even if they have no tab index.
  28412. * @param {!Element} element Element to check.
  28413. * @return {boolean} Whether the element has a tab index that allows keyboard
  28414. * focus.
  28415. */
  28416. goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;
  28417. /**
  28418. * Enables or disables keyboard focus support on the element via its tab index.
  28419. * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
  28420. * (or elements that natively support keyboard focus, like form elements) can
  28421. * receive keyboard focus. See http://go/tabindex for more info.
  28422. * @param {Element} element Element whose tab index is to be changed.
  28423. * @param {boolean} enable Whether to set or remove a tab index on the element
  28424. * that supports keyboard focus.
  28425. */
  28426. goog.dom.DomHelper.prototype.setFocusableTabIndex =
  28427. goog.dom.setFocusableTabIndex;
  28428. /**
  28429. * Returns true if the element can be focused, i.e. it has a tab index that
  28430. * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
  28431. * that natively supports keyboard focus.
  28432. * @param {!Element} element Element to check.
  28433. * @return {boolean} Whether the element allows keyboard focus.
  28434. */
  28435. goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;
  28436. /**
  28437. * Returns the text contents of the current node, without markup. New lines are
  28438. * stripped and whitespace is collapsed, such that each character would be
  28439. * visible.
  28440. *
  28441. * In browsers that support it, innerText is used. Other browsers attempt to
  28442. * simulate it via node traversal. Line breaks are canonicalized in IE.
  28443. *
  28444. * @param {Node} node The node from which we are getting content.
  28445. * @return {string} The text content.
  28446. */
  28447. goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;
  28448. /**
  28449. * Returns the text length of the text contained in a node, without markup. This
  28450. * is equivalent to the selection length if the node was selected, or the number
  28451. * of cursor movements to traverse the node. Images & BRs take one space. New
  28452. * lines are ignored.
  28453. *
  28454. * @param {Node} node The node whose text content length is being calculated.
  28455. * @return {number} The length of {@code node}'s text content.
  28456. */
  28457. goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;
  28458. /**
  28459. * Returns the text offset of a node relative to one of its ancestors. The text
  28460. * length is the same as the length calculated by
  28461. * {@code goog.dom.getNodeTextLength}.
  28462. *
  28463. * @param {Node} node The node whose offset is being calculated.
  28464. * @param {Node=} opt_offsetParent Defaults to the node's owner document's body.
  28465. * @return {number} The text offset.
  28466. */
  28467. goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;
  28468. /**
  28469. * Returns the node at a given offset in a parent node. If an object is
  28470. * provided for the optional third parameter, the node and the remainder of the
  28471. * offset will stored as properties of this object.
  28472. * @param {Node} parent The parent node.
  28473. * @param {number} offset The offset into the parent node.
  28474. * @param {Object=} opt_result Object to be used to store the return value. The
  28475. * return value will be stored in the form {node: Node, remainder: number}
  28476. * if this object is provided.
  28477. * @return {Node} The node at the given offset.
  28478. */
  28479. goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;
  28480. /**
  28481. * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
  28482. * the object must have a numeric length property and an item function (which
  28483. * has type 'string' on IE for some reason).
  28484. * @param {Object} val Object to test.
  28485. * @return {boolean} Whether the object is a NodeList.
  28486. */
  28487. goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;
  28488. /**
  28489. * Walks up the DOM hierarchy returning the first ancestor that has the passed
  28490. * tag name and/or class name. If the passed element matches the specified
  28491. * criteria, the element itself is returned.
  28492. * @param {Node} element The DOM node to start with.
  28493. * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
  28494. * null/undefined to match only based on class name).
  28495. * @param {?string=} opt_class The class name to match (or null/undefined to
  28496. * match only based on tag name).
  28497. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  28498. * dom.
  28499. * @return {Element} The first ancestor that matches the passed criteria, or
  28500. * null if no match is found.
  28501. */
  28502. goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =
  28503. goog.dom.getAncestorByTagNameAndClass;
  28504. /**
  28505. * Walks up the DOM hierarchy returning the first ancestor that has the passed
  28506. * class name. If the passed element matches the specified criteria, the
  28507. * element itself is returned.
  28508. * @param {Node} element The DOM node to start with.
  28509. * @param {string} class The class name to match.
  28510. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  28511. * dom.
  28512. * @return {Element} The first ancestor that matches the passed criteria, or
  28513. * null if none match.
  28514. */
  28515. goog.dom.DomHelper.prototype.getAncestorByClass =
  28516. goog.dom.getAncestorByClass;
  28517. /**
  28518. * Walks up the DOM hierarchy returning the first ancestor that passes the
  28519. * matcher function.
  28520. * @param {Node} element The DOM node to start with.
  28521. * @param {function(Node) : boolean} matcher A function that returns true if the
  28522. * passed node matches the desired criteria.
  28523. * @param {boolean=} opt_includeNode If true, the node itself is included in
  28524. * the search (the first call to the matcher will pass startElement as
  28525. * the node to test).
  28526. * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
  28527. * dom.
  28528. * @return {Node} DOM node that matched the matcher, or null if there was
  28529. * no match.
  28530. */
  28531. goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;
  28532. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  28533. //
  28534. // Licensed under the Apache License, Version 2.0 (the "License");
  28535. // you may not use this file except in compliance with the License.
  28536. // You may obtain a copy of the License at
  28537. //
  28538. // http://www.apache.org/licenses/LICENSE-2.0
  28539. //
  28540. // Unless required by applicable law or agreed to in writing, software
  28541. // distributed under the License is distributed on an "AS-IS" BASIS,
  28542. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28543. // See the License for the specific language governing permissions and
  28544. // limitations under the License.
  28545. /**
  28546. * @fileoverview Utilities for detecting, adding and removing classes. Prefer
  28547. * this over goog.dom.classes for new code since it attempts to use classList
  28548. * (DOMTokenList: http://dom.spec.whatwg.org/#domtokenlist) which is faster
  28549. * and requires less code.
  28550. *
  28551. * Note: these utilities are meant to operate on HTMLElements
  28552. * and may have unexpected behavior on elements with differing interfaces
  28553. * (such as SVGElements).
  28554. */
  28555. goog.provide('goog.dom.classlist');
  28556. goog.require('goog.array');
  28557. /**
  28558. * Override this define at build-time if you know your target supports it.
  28559. * @define {boolean} Whether to use the classList property (DOMTokenList).
  28560. */
  28561. goog.define('goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST', false);
  28562. /**
  28563. * Gets an array-like object of class names on an element.
  28564. * @param {Element} element DOM node to get the classes of.
  28565. * @return {!goog.array.ArrayLike} Class names on {@code element}.
  28566. */
  28567. goog.dom.classlist.get = function(element) {
  28568. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28569. return element.classList;
  28570. }
  28571. var className = element.className;
  28572. // Some types of elements don't have a className in IE (e.g. iframes).
  28573. // Furthermore, in Firefox, className is not a string when the element is
  28574. // an SVG element.
  28575. return goog.isString(className) && className.match(/\S+/g) || [];
  28576. };
  28577. /**
  28578. * Sets the entire class name of an element.
  28579. * @param {Element} element DOM node to set class of.
  28580. * @param {string} className Class name(s) to apply to element.
  28581. */
  28582. goog.dom.classlist.set = function(element, className) {
  28583. element.className = className;
  28584. };
  28585. /**
  28586. * Returns true if an element has a class. This method may throw a DOM
  28587. * exception for an invalid or empty class name if DOMTokenList is used.
  28588. * @param {Element} element DOM node to test.
  28589. * @param {string} className Class name to test for.
  28590. * @return {boolean} Whether element has the class.
  28591. */
  28592. goog.dom.classlist.contains = function(element, className) {
  28593. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28594. return element.classList.contains(className);
  28595. }
  28596. return goog.array.contains(goog.dom.classlist.get(element), className);
  28597. };
  28598. /**
  28599. * Adds a class to an element. Does not add multiples of class names. This
  28600. * method may throw a DOM exception for an invalid or empty class name if
  28601. * DOMTokenList is used.
  28602. * @param {Element} element DOM node to add class to.
  28603. * @param {string} className Class name to add.
  28604. */
  28605. goog.dom.classlist.add = function(element, className) {
  28606. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28607. element.classList.add(className);
  28608. return;
  28609. }
  28610. if (!goog.dom.classlist.contains(element, className)) {
  28611. // Ensure we add a space if this is not the first class name added.
  28612. element.className += element.className.length > 0 ?
  28613. (' ' + className) : className;
  28614. }
  28615. };
  28616. /**
  28617. * Convenience method to add a number of class names at once.
  28618. * @param {Element} element The element to which to add classes.
  28619. * @param {goog.array.ArrayLike<string>} classesToAdd An array-like object
  28620. * containing a collection of class names to add to the element.
  28621. * This method may throw a DOM exception if classesToAdd contains invalid
  28622. * or empty class names.
  28623. */
  28624. goog.dom.classlist.addAll = function(element, classesToAdd) {
  28625. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28626. goog.array.forEach(classesToAdd, function(className) {
  28627. goog.dom.classlist.add(element, className);
  28628. });
  28629. return;
  28630. }
  28631. var classMap = {};
  28632. // Get all current class names into a map.
  28633. goog.array.forEach(goog.dom.classlist.get(element),
  28634. function(className) {
  28635. classMap[className] = true;
  28636. });
  28637. // Add new class names to the map.
  28638. goog.array.forEach(classesToAdd,
  28639. function(className) {
  28640. classMap[className] = true;
  28641. });
  28642. // Flatten the keys of the map into the className.
  28643. element.className = '';
  28644. for (var className in classMap) {
  28645. element.className += element.className.length > 0 ?
  28646. (' ' + className) : className;
  28647. }
  28648. };
  28649. /**
  28650. * Removes a class from an element. This method may throw a DOM exception
  28651. * for an invalid or empty class name if DOMTokenList is used.
  28652. * @param {Element} element DOM node to remove class from.
  28653. * @param {string} className Class name to remove.
  28654. */
  28655. goog.dom.classlist.remove = function(element, className) {
  28656. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28657. element.classList.remove(className);
  28658. return;
  28659. }
  28660. if (goog.dom.classlist.contains(element, className)) {
  28661. // Filter out the class name.
  28662. element.className = goog.array.filter(
  28663. goog.dom.classlist.get(element),
  28664. function(c) {
  28665. return c != className;
  28666. }).join(' ');
  28667. }
  28668. };
  28669. /**
  28670. * Removes a set of classes from an element. Prefer this call to
  28671. * repeatedly calling {@code goog.dom.classlist.remove} if you want to remove
  28672. * a large set of class names at once.
  28673. * @param {Element} element The element from which to remove classes.
  28674. * @param {goog.array.ArrayLike<string>} classesToRemove An array-like object
  28675. * containing a collection of class names to remove from the element.
  28676. * This method may throw a DOM exception if classesToRemove contains invalid
  28677. * or empty class names.
  28678. */
  28679. goog.dom.classlist.removeAll = function(element, classesToRemove) {
  28680. if (goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || element.classList) {
  28681. goog.array.forEach(classesToRemove, function(className) {
  28682. goog.dom.classlist.remove(element, className);
  28683. });
  28684. return;
  28685. }
  28686. // Filter out those classes in classesToRemove.
  28687. element.className = goog.array.filter(
  28688. goog.dom.classlist.get(element),
  28689. function(className) {
  28690. // If this class is not one we are trying to remove,
  28691. // add it to the array of new class names.
  28692. return !goog.array.contains(classesToRemove, className);
  28693. }).join(' ');
  28694. };
  28695. /**
  28696. * Adds or removes a class depending on the enabled argument. This method
  28697. * may throw a DOM exception for an invalid or empty class name if DOMTokenList
  28698. * is used.
  28699. * @param {Element} element DOM node to add or remove the class on.
  28700. * @param {string} className Class name to add or remove.
  28701. * @param {boolean} enabled Whether to add or remove the class (true adds,
  28702. * false removes).
  28703. */
  28704. goog.dom.classlist.enable = function(element, className, enabled) {
  28705. if (enabled) {
  28706. goog.dom.classlist.add(element, className);
  28707. } else {
  28708. goog.dom.classlist.remove(element, className);
  28709. }
  28710. };
  28711. /**
  28712. * Adds or removes a set of classes depending on the enabled argument. This
  28713. * method may throw a DOM exception for an invalid or empty class name if
  28714. * DOMTokenList is used.
  28715. * @param {!Element} element DOM node to add or remove the class on.
  28716. * @param {goog.array.ArrayLike<string>} classesToEnable An array-like object
  28717. * containing a collection of class names to add or remove from the element.
  28718. * @param {boolean} enabled Whether to add or remove the classes (true adds,
  28719. * false removes).
  28720. */
  28721. goog.dom.classlist.enableAll = function(element, classesToEnable, enabled) {
  28722. var f = enabled ? goog.dom.classlist.addAll :
  28723. goog.dom.classlist.removeAll;
  28724. f(element, classesToEnable);
  28725. };
  28726. /**
  28727. * Switches a class on an element from one to another without disturbing other
  28728. * classes. If the fromClass isn't removed, the toClass won't be added. This
  28729. * method may throw a DOM exception if the class names are empty or invalid.
  28730. * @param {Element} element DOM node to swap classes on.
  28731. * @param {string} fromClass Class to remove.
  28732. * @param {string} toClass Class to add.
  28733. * @return {boolean} Whether classes were switched.
  28734. */
  28735. goog.dom.classlist.swap = function(element, fromClass, toClass) {
  28736. if (goog.dom.classlist.contains(element, fromClass)) {
  28737. goog.dom.classlist.remove(element, fromClass);
  28738. goog.dom.classlist.add(element, toClass);
  28739. return true;
  28740. }
  28741. return false;
  28742. };
  28743. /**
  28744. * Removes a class if an element has it, and adds it the element doesn't have
  28745. * it. Won't affect other classes on the node. This method may throw a DOM
  28746. * exception if the class name is empty or invalid.
  28747. * @param {Element} element DOM node to toggle class on.
  28748. * @param {string} className Class to toggle.
  28749. * @return {boolean} True if class was added, false if it was removed
  28750. * (in other words, whether element has the class after this function has
  28751. * been called).
  28752. */
  28753. goog.dom.classlist.toggle = function(element, className) {
  28754. var add = !goog.dom.classlist.contains(element, className);
  28755. goog.dom.classlist.enable(element, className, add);
  28756. return add;
  28757. };
  28758. /**
  28759. * Adds and removes a class of an element. Unlike
  28760. * {@link goog.dom.classlist.swap}, this method adds the classToAdd regardless
  28761. * of whether the classToRemove was present and had been removed. This method
  28762. * may throw a DOM exception if the class names are empty or invalid.
  28763. *
  28764. * @param {Element} element DOM node to swap classes on.
  28765. * @param {string} classToRemove Class to remove.
  28766. * @param {string} classToAdd Class to add.
  28767. */
  28768. goog.dom.classlist.addRemove = function(element, classToRemove, classToAdd) {
  28769. goog.dom.classlist.remove(element, classToRemove);
  28770. goog.dom.classlist.add(element, classToAdd);
  28771. };
  28772. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  28773. //
  28774. // Licensed under the Apache License, Version 2.0 (the "License");
  28775. // you may not use this file except in compliance with the License.
  28776. // You may obtain a copy of the License at
  28777. //
  28778. // http://www.apache.org/licenses/LICENSE-2.0
  28779. //
  28780. // Unless required by applicable law or agreed to in writing, software
  28781. // distributed under the License is distributed on an "AS-IS" BASIS,
  28782. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28783. // See the License for the specific language governing permissions and
  28784. // limitations under the License.
  28785. /**
  28786. * @fileoverview Vendor prefix getters.
  28787. */
  28788. goog.provide('goog.dom.vendor');
  28789. goog.require('goog.string');
  28790. goog.require('goog.userAgent');
  28791. /**
  28792. * Returns the JS vendor prefix used in CSS properties. Different vendors
  28793. * use different methods of changing the case of the property names.
  28794. *
  28795. * @return {?string} The JS vendor prefix or null if there is none.
  28796. */
  28797. goog.dom.vendor.getVendorJsPrefix = function() {
  28798. if (goog.userAgent.WEBKIT) {
  28799. return 'Webkit';
  28800. } else if (goog.userAgent.GECKO) {
  28801. return 'Moz';
  28802. } else if (goog.userAgent.IE) {
  28803. return 'ms';
  28804. } else if (goog.userAgent.OPERA) {
  28805. return 'O';
  28806. }
  28807. return null;
  28808. };
  28809. /**
  28810. * Returns the vendor prefix used in CSS properties.
  28811. *
  28812. * @return {?string} The vendor prefix or null if there is none.
  28813. */
  28814. goog.dom.vendor.getVendorPrefix = function() {
  28815. if (goog.userAgent.WEBKIT) {
  28816. return '-webkit';
  28817. } else if (goog.userAgent.GECKO) {
  28818. return '-moz';
  28819. } else if (goog.userAgent.IE) {
  28820. return '-ms';
  28821. } else if (goog.userAgent.OPERA) {
  28822. return '-o';
  28823. }
  28824. return null;
  28825. };
  28826. /**
  28827. * @param {string} propertyName A property name.
  28828. * @param {!Object=} opt_object If provided, we verify if the property exists in
  28829. * the object.
  28830. * @return {?string} A vendor prefixed property name, or null if it does not
  28831. * exist.
  28832. */
  28833. goog.dom.vendor.getPrefixedPropertyName = function(propertyName, opt_object) {
  28834. // We first check for a non-prefixed property, if available.
  28835. if (opt_object && propertyName in opt_object) {
  28836. return propertyName;
  28837. }
  28838. var prefix = goog.dom.vendor.getVendorJsPrefix();
  28839. if (prefix) {
  28840. prefix = prefix.toLowerCase();
  28841. var prefixedPropertyName = prefix + goog.string.toTitleCase(propertyName);
  28842. return (!goog.isDef(opt_object) || prefixedPropertyName in opt_object) ?
  28843. prefixedPropertyName : null;
  28844. }
  28845. return null;
  28846. };
  28847. /**
  28848. * @param {string} eventType An event type.
  28849. * @return {string} A lower-cased vendor prefixed event type.
  28850. */
  28851. goog.dom.vendor.getPrefixedEventType = function(eventType) {
  28852. var prefix = goog.dom.vendor.getVendorJsPrefix() || '';
  28853. return (prefix + eventType).toLowerCase();
  28854. };
  28855. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  28856. //
  28857. // Licensed under the Apache License, Version 2.0 (the "License");
  28858. // you may not use this file except in compliance with the License.
  28859. // You may obtain a copy of the License at
  28860. //
  28861. // http://www.apache.org/licenses/LICENSE-2.0
  28862. //
  28863. // Unless required by applicable law or agreed to in writing, software
  28864. // distributed under the License is distributed on an "AS-IS" BASIS,
  28865. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28866. // See the License for the specific language governing permissions and
  28867. // limitations under the License.
  28868. /**
  28869. * @fileoverview A utility class for representing a numeric box.
  28870. */
  28871. goog.provide('goog.math.Box');
  28872. goog.require('goog.math.Coordinate');
  28873. /**
  28874. * Class for representing a box. A box is specified as a top, right, bottom,
  28875. * and left. A box is useful for representing margins and padding.
  28876. *
  28877. * This class assumes 'screen coordinates': larger Y coordinates are further
  28878. * from the top of the screen.
  28879. *
  28880. * @param {number} top Top.
  28881. * @param {number} right Right.
  28882. * @param {number} bottom Bottom.
  28883. * @param {number} left Left.
  28884. * @struct
  28885. * @constructor
  28886. */
  28887. goog.math.Box = function(top, right, bottom, left) {
  28888. /**
  28889. * Top
  28890. * @type {number}
  28891. */
  28892. this.top = top;
  28893. /**
  28894. * Right
  28895. * @type {number}
  28896. */
  28897. this.right = right;
  28898. /**
  28899. * Bottom
  28900. * @type {number}
  28901. */
  28902. this.bottom = bottom;
  28903. /**
  28904. * Left
  28905. * @type {number}
  28906. */
  28907. this.left = left;
  28908. };
  28909. /**
  28910. * Creates a Box by bounding a collection of goog.math.Coordinate objects
  28911. * @param {...goog.math.Coordinate} var_args Coordinates to be included inside
  28912. * the box.
  28913. * @return {!goog.math.Box} A Box containing all the specified Coordinates.
  28914. */
  28915. goog.math.Box.boundingBox = function(var_args) {
  28916. var box = new goog.math.Box(arguments[0].y, arguments[0].x,
  28917. arguments[0].y, arguments[0].x);
  28918. for (var i = 1; i < arguments.length; i++) {
  28919. box.expandToIncludeCoordinate(arguments[i]);
  28920. }
  28921. return box;
  28922. };
  28923. /**
  28924. * @return {number} width The width of this Box.
  28925. */
  28926. goog.math.Box.prototype.getWidth = function() {
  28927. return this.right - this.left;
  28928. };
  28929. /**
  28930. * @return {number} height The height of this Box.
  28931. */
  28932. goog.math.Box.prototype.getHeight = function() {
  28933. return this.bottom - this.top;
  28934. };
  28935. /**
  28936. * Creates a copy of the box with the same dimensions.
  28937. * @return {!goog.math.Box} A clone of this Box.
  28938. */
  28939. goog.math.Box.prototype.clone = function() {
  28940. return new goog.math.Box(this.top, this.right, this.bottom, this.left);
  28941. };
  28942. if (goog.DEBUG) {
  28943. /**
  28944. * Returns a nice string representing the box.
  28945. * @return {string} In the form (50t, 73r, 24b, 13l).
  28946. * @override
  28947. */
  28948. goog.math.Box.prototype.toString = function() {
  28949. return '(' + this.top + 't, ' + this.right + 'r, ' + this.bottom + 'b, ' +
  28950. this.left + 'l)';
  28951. };
  28952. }
  28953. /**
  28954. * Returns whether the box contains a coordinate or another box.
  28955. *
  28956. * @param {goog.math.Coordinate|goog.math.Box} other A Coordinate or a Box.
  28957. * @return {boolean} Whether the box contains the coordinate or other box.
  28958. */
  28959. goog.math.Box.prototype.contains = function(other) {
  28960. return goog.math.Box.contains(this, other);
  28961. };
  28962. /**
  28963. * Expands box with the given margins.
  28964. *
  28965. * @param {number|goog.math.Box} top Top margin or box with all margins.
  28966. * @param {number=} opt_right Right margin.
  28967. * @param {number=} opt_bottom Bottom margin.
  28968. * @param {number=} opt_left Left margin.
  28969. * @return {!goog.math.Box} A reference to this Box.
  28970. */
  28971. goog.math.Box.prototype.expand = function(top, opt_right, opt_bottom,
  28972. opt_left) {
  28973. if (goog.isObject(top)) {
  28974. this.top -= top.top;
  28975. this.right += top.right;
  28976. this.bottom += top.bottom;
  28977. this.left -= top.left;
  28978. } else {
  28979. this.top -= top;
  28980. this.right += opt_right;
  28981. this.bottom += opt_bottom;
  28982. this.left -= opt_left;
  28983. }
  28984. return this;
  28985. };
  28986. /**
  28987. * Expand this box to include another box.
  28988. * NOTE(user): This is used in code that needs to be very fast, please don't
  28989. * add functionality to this function at the expense of speed (variable
  28990. * arguments, accepting multiple argument types, etc).
  28991. * @param {goog.math.Box} box The box to include in this one.
  28992. */
  28993. goog.math.Box.prototype.expandToInclude = function(box) {
  28994. this.left = Math.min(this.left, box.left);
  28995. this.top = Math.min(this.top, box.top);
  28996. this.right = Math.max(this.right, box.right);
  28997. this.bottom = Math.max(this.bottom, box.bottom);
  28998. };
  28999. /**
  29000. * Expand this box to include the coordinate.
  29001. * @param {!goog.math.Coordinate} coord The coordinate to be included
  29002. * inside the box.
  29003. */
  29004. goog.math.Box.prototype.expandToIncludeCoordinate = function(coord) {
  29005. this.top = Math.min(this.top, coord.y);
  29006. this.right = Math.max(this.right, coord.x);
  29007. this.bottom = Math.max(this.bottom, coord.y);
  29008. this.left = Math.min(this.left, coord.x);
  29009. };
  29010. /**
  29011. * Compares boxes for equality.
  29012. * @param {goog.math.Box} a A Box.
  29013. * @param {goog.math.Box} b A Box.
  29014. * @return {boolean} True iff the boxes are equal, or if both are null.
  29015. */
  29016. goog.math.Box.equals = function(a, b) {
  29017. if (a == b) {
  29018. return true;
  29019. }
  29020. if (!a || !b) {
  29021. return false;
  29022. }
  29023. return a.top == b.top && a.right == b.right &&
  29024. a.bottom == b.bottom && a.left == b.left;
  29025. };
  29026. /**
  29027. * Returns whether a box contains a coordinate or another box.
  29028. *
  29029. * @param {goog.math.Box} box A Box.
  29030. * @param {goog.math.Coordinate|goog.math.Box} other A Coordinate or a Box.
  29031. * @return {boolean} Whether the box contains the coordinate or other box.
  29032. */
  29033. goog.math.Box.contains = function(box, other) {
  29034. if (!box || !other) {
  29035. return false;
  29036. }
  29037. if (other instanceof goog.math.Box) {
  29038. return other.left >= box.left && other.right <= box.right &&
  29039. other.top >= box.top && other.bottom <= box.bottom;
  29040. }
  29041. // other is a Coordinate.
  29042. return other.x >= box.left && other.x <= box.right &&
  29043. other.y >= box.top && other.y <= box.bottom;
  29044. };
  29045. /**
  29046. * Returns the relative x position of a coordinate compared to a box. Returns
  29047. * zero if the coordinate is inside the box.
  29048. *
  29049. * @param {goog.math.Box} box A Box.
  29050. * @param {goog.math.Coordinate} coord A Coordinate.
  29051. * @return {number} The x position of {@code coord} relative to the nearest
  29052. * side of {@code box}, or zero if {@code coord} is inside {@code box}.
  29053. */
  29054. goog.math.Box.relativePositionX = function(box, coord) {
  29055. if (coord.x < box.left) {
  29056. return coord.x - box.left;
  29057. } else if (coord.x > box.right) {
  29058. return coord.x - box.right;
  29059. }
  29060. return 0;
  29061. };
  29062. /**
  29063. * Returns the relative y position of a coordinate compared to a box. Returns
  29064. * zero if the coordinate is inside the box.
  29065. *
  29066. * @param {goog.math.Box} box A Box.
  29067. * @param {goog.math.Coordinate} coord A Coordinate.
  29068. * @return {number} The y position of {@code coord} relative to the nearest
  29069. * side of {@code box}, or zero if {@code coord} is inside {@code box}.
  29070. */
  29071. goog.math.Box.relativePositionY = function(box, coord) {
  29072. if (coord.y < box.top) {
  29073. return coord.y - box.top;
  29074. } else if (coord.y > box.bottom) {
  29075. return coord.y - box.bottom;
  29076. }
  29077. return 0;
  29078. };
  29079. /**
  29080. * Returns the distance between a coordinate and the nearest corner/side of a
  29081. * box. Returns zero if the coordinate is inside the box.
  29082. *
  29083. * @param {goog.math.Box} box A Box.
  29084. * @param {goog.math.Coordinate} coord A Coordinate.
  29085. * @return {number} The distance between {@code coord} and the nearest
  29086. * corner/side of {@code box}, or zero if {@code coord} is inside
  29087. * {@code box}.
  29088. */
  29089. goog.math.Box.distance = function(box, coord) {
  29090. var x = goog.math.Box.relativePositionX(box, coord);
  29091. var y = goog.math.Box.relativePositionY(box, coord);
  29092. return Math.sqrt(x * x + y * y);
  29093. };
  29094. /**
  29095. * Returns whether two boxes intersect.
  29096. *
  29097. * @param {goog.math.Box} a A Box.
  29098. * @param {goog.math.Box} b A second Box.
  29099. * @return {boolean} Whether the boxes intersect.
  29100. */
  29101. goog.math.Box.intersects = function(a, b) {
  29102. return (a.left <= b.right && b.left <= a.right &&
  29103. a.top <= b.bottom && b.top <= a.bottom);
  29104. };
  29105. /**
  29106. * Returns whether two boxes would intersect with additional padding.
  29107. *
  29108. * @param {goog.math.Box} a A Box.
  29109. * @param {goog.math.Box} b A second Box.
  29110. * @param {number} padding The additional padding.
  29111. * @return {boolean} Whether the boxes intersect.
  29112. */
  29113. goog.math.Box.intersectsWithPadding = function(a, b, padding) {
  29114. return (a.left <= b.right + padding && b.left <= a.right + padding &&
  29115. a.top <= b.bottom + padding && b.top <= a.bottom + padding);
  29116. };
  29117. /**
  29118. * Rounds the fields to the next larger integer values.
  29119. *
  29120. * @return {!goog.math.Box} This box with ceil'd fields.
  29121. */
  29122. goog.math.Box.prototype.ceil = function() {
  29123. this.top = Math.ceil(this.top);
  29124. this.right = Math.ceil(this.right);
  29125. this.bottom = Math.ceil(this.bottom);
  29126. this.left = Math.ceil(this.left);
  29127. return this;
  29128. };
  29129. /**
  29130. * Rounds the fields to the next smaller integer values.
  29131. *
  29132. * @return {!goog.math.Box} This box with floored fields.
  29133. */
  29134. goog.math.Box.prototype.floor = function() {
  29135. this.top = Math.floor(this.top);
  29136. this.right = Math.floor(this.right);
  29137. this.bottom = Math.floor(this.bottom);
  29138. this.left = Math.floor(this.left);
  29139. return this;
  29140. };
  29141. /**
  29142. * Rounds the fields to nearest integer values.
  29143. *
  29144. * @return {!goog.math.Box} This box with rounded fields.
  29145. */
  29146. goog.math.Box.prototype.round = function() {
  29147. this.top = Math.round(this.top);
  29148. this.right = Math.round(this.right);
  29149. this.bottom = Math.round(this.bottom);
  29150. this.left = Math.round(this.left);
  29151. return this;
  29152. };
  29153. /**
  29154. * Translates this box by the given offsets. If a {@code goog.math.Coordinate}
  29155. * is given, then the left and right values are translated by the coordinate's
  29156. * x value and the top and bottom values are translated by the coordinate's y
  29157. * value. Otherwise, {@code tx} and {@code opt_ty} are used to translate the x
  29158. * and y dimension values.
  29159. *
  29160. * @param {number|goog.math.Coordinate} tx The value to translate the x
  29161. * dimension values by or the the coordinate to translate this box by.
  29162. * @param {number=} opt_ty The value to translate y dimension values by.
  29163. * @return {!goog.math.Box} This box after translating.
  29164. */
  29165. goog.math.Box.prototype.translate = function(tx, opt_ty) {
  29166. if (tx instanceof goog.math.Coordinate) {
  29167. this.left += tx.x;
  29168. this.right += tx.x;
  29169. this.top += tx.y;
  29170. this.bottom += tx.y;
  29171. } else {
  29172. this.left += tx;
  29173. this.right += tx;
  29174. if (goog.isNumber(opt_ty)) {
  29175. this.top += opt_ty;
  29176. this.bottom += opt_ty;
  29177. }
  29178. }
  29179. return this;
  29180. };
  29181. /**
  29182. * Scales this coordinate by the given scale factors. The x and y dimension
  29183. * values are scaled by {@code sx} and {@code opt_sy} respectively.
  29184. * If {@code opt_sy} is not given, then {@code sx} is used for both x and y.
  29185. *
  29186. * @param {number} sx The scale factor to use for the x dimension.
  29187. * @param {number=} opt_sy The scale factor to use for the y dimension.
  29188. * @return {!goog.math.Box} This box after scaling.
  29189. */
  29190. goog.math.Box.prototype.scale = function(sx, opt_sy) {
  29191. var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
  29192. this.left *= sx;
  29193. this.right *= sx;
  29194. this.top *= sy;
  29195. this.bottom *= sy;
  29196. return this;
  29197. };
  29198. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  29199. //
  29200. // Licensed under the Apache License, Version 2.0 (the "License");
  29201. // you may not use this file except in compliance with the License.
  29202. // You may obtain a copy of the License at
  29203. //
  29204. // http://www.apache.org/licenses/LICENSE-2.0
  29205. //
  29206. // Unless required by applicable law or agreed to in writing, software
  29207. // distributed under the License is distributed on an "AS-IS" BASIS,
  29208. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29209. // See the License for the specific language governing permissions and
  29210. // limitations under the License.
  29211. /**
  29212. * @fileoverview A utility class for representing rectangles.
  29213. */
  29214. goog.provide('goog.math.Rect');
  29215. goog.require('goog.math.Box');
  29216. goog.require('goog.math.Coordinate');
  29217. goog.require('goog.math.Size');
  29218. /**
  29219. * Class for representing rectangular regions.
  29220. * @param {number} x Left.
  29221. * @param {number} y Top.
  29222. * @param {number} w Width.
  29223. * @param {number} h Height.
  29224. * @struct
  29225. * @constructor
  29226. */
  29227. goog.math.Rect = function(x, y, w, h) {
  29228. /** @type {number} */
  29229. this.left = x;
  29230. /** @type {number} */
  29231. this.top = y;
  29232. /** @type {number} */
  29233. this.width = w;
  29234. /** @type {number} */
  29235. this.height = h;
  29236. };
  29237. /**
  29238. * @return {!goog.math.Rect} A new copy of this Rectangle.
  29239. */
  29240. goog.math.Rect.prototype.clone = function() {
  29241. return new goog.math.Rect(this.left, this.top, this.width, this.height);
  29242. };
  29243. /**
  29244. * Returns a new Box object with the same position and dimensions as this
  29245. * rectangle.
  29246. * @return {!goog.math.Box} A new Box representation of this Rectangle.
  29247. */
  29248. goog.math.Rect.prototype.toBox = function() {
  29249. var right = this.left + this.width;
  29250. var bottom = this.top + this.height;
  29251. return new goog.math.Box(this.top,
  29252. right,
  29253. bottom,
  29254. this.left);
  29255. };
  29256. /**
  29257. * Creates a new Rect object with the position and size given.
  29258. * @param {!goog.math.Coordinate} position The top-left coordinate of the Rect
  29259. * @param {!goog.math.Size} size The size of the Rect
  29260. * @return {!goog.math.Rect} A new Rect initialized with the given position and
  29261. * size.
  29262. */
  29263. goog.math.Rect.createFromPositionAndSize = function(position, size) {
  29264. return new goog.math.Rect(position.x, position.y, size.width, size.height);
  29265. };
  29266. /**
  29267. * Creates a new Rect object with the same position and dimensions as a given
  29268. * Box. Note that this is only the inverse of toBox if left/top are defined.
  29269. * @param {goog.math.Box} box A box.
  29270. * @return {!goog.math.Rect} A new Rect initialized with the box's position
  29271. * and size.
  29272. */
  29273. goog.math.Rect.createFromBox = function(box) {
  29274. return new goog.math.Rect(box.left, box.top,
  29275. box.right - box.left, box.bottom - box.top);
  29276. };
  29277. if (goog.DEBUG) {
  29278. /**
  29279. * Returns a nice string representing size and dimensions of rectangle.
  29280. * @return {string} In the form (50, 73 - 75w x 25h).
  29281. * @override
  29282. */
  29283. goog.math.Rect.prototype.toString = function() {
  29284. return '(' + this.left + ', ' + this.top + ' - ' + this.width + 'w x ' +
  29285. this.height + 'h)';
  29286. };
  29287. }
  29288. /**
  29289. * Compares rectangles for equality.
  29290. * @param {goog.math.Rect} a A Rectangle.
  29291. * @param {goog.math.Rect} b A Rectangle.
  29292. * @return {boolean} True iff the rectangles have the same left, top, width,
  29293. * and height, or if both are null.
  29294. */
  29295. goog.math.Rect.equals = function(a, b) {
  29296. if (a == b) {
  29297. return true;
  29298. }
  29299. if (!a || !b) {
  29300. return false;
  29301. }
  29302. return a.left == b.left && a.width == b.width &&
  29303. a.top == b.top && a.height == b.height;
  29304. };
  29305. /**
  29306. * Computes the intersection of this rectangle and the rectangle parameter. If
  29307. * there is no intersection, returns false and leaves this rectangle as is.
  29308. * @param {goog.math.Rect} rect A Rectangle.
  29309. * @return {boolean} True iff this rectangle intersects with the parameter.
  29310. */
  29311. goog.math.Rect.prototype.intersection = function(rect) {
  29312. var x0 = Math.max(this.left, rect.left);
  29313. var x1 = Math.min(this.left + this.width, rect.left + rect.width);
  29314. if (x0 <= x1) {
  29315. var y0 = Math.max(this.top, rect.top);
  29316. var y1 = Math.min(this.top + this.height, rect.top + rect.height);
  29317. if (y0 <= y1) {
  29318. this.left = x0;
  29319. this.top = y0;
  29320. this.width = x1 - x0;
  29321. this.height = y1 - y0;
  29322. return true;
  29323. }
  29324. }
  29325. return false;
  29326. };
  29327. /**
  29328. * Returns the intersection of two rectangles. Two rectangles intersect if they
  29329. * touch at all, for example, two zero width and height rectangles would
  29330. * intersect if they had the same top and left.
  29331. * @param {goog.math.Rect} a A Rectangle.
  29332. * @param {goog.math.Rect} b A Rectangle.
  29333. * @return {goog.math.Rect} A new intersection rect (even if width and height
  29334. * are 0), or null if there is no intersection.
  29335. */
  29336. goog.math.Rect.intersection = function(a, b) {
  29337. // There is no nice way to do intersection via a clone, because any such
  29338. // clone might be unnecessary if this function returns null. So, we duplicate
  29339. // code from above.
  29340. var x0 = Math.max(a.left, b.left);
  29341. var x1 = Math.min(a.left + a.width, b.left + b.width);
  29342. if (x0 <= x1) {
  29343. var y0 = Math.max(a.top, b.top);
  29344. var y1 = Math.min(a.top + a.height, b.top + b.height);
  29345. if (y0 <= y1) {
  29346. return new goog.math.Rect(x0, y0, x1 - x0, y1 - y0);
  29347. }
  29348. }
  29349. return null;
  29350. };
  29351. /**
  29352. * Returns whether two rectangles intersect. Two rectangles intersect if they
  29353. * touch at all, for example, two zero width and height rectangles would
  29354. * intersect if they had the same top and left.
  29355. * @param {goog.math.Rect} a A Rectangle.
  29356. * @param {goog.math.Rect} b A Rectangle.
  29357. * @return {boolean} Whether a and b intersect.
  29358. */
  29359. goog.math.Rect.intersects = function(a, b) {
  29360. return (a.left <= b.left + b.width && b.left <= a.left + a.width &&
  29361. a.top <= b.top + b.height && b.top <= a.top + a.height);
  29362. };
  29363. /**
  29364. * Returns whether a rectangle intersects this rectangle.
  29365. * @param {goog.math.Rect} rect A rectangle.
  29366. * @return {boolean} Whether rect intersects this rectangle.
  29367. */
  29368. goog.math.Rect.prototype.intersects = function(rect) {
  29369. return goog.math.Rect.intersects(this, rect);
  29370. };
  29371. /**
  29372. * Computes the difference regions between two rectangles. The return value is
  29373. * an array of 0 to 4 rectangles defining the remaining regions of the first
  29374. * rectangle after the second has been subtracted.
  29375. * @param {goog.math.Rect} a A Rectangle.
  29376. * @param {goog.math.Rect} b A Rectangle.
  29377. * @return {!Array<!goog.math.Rect>} An array with 0 to 4 rectangles which
  29378. * together define the difference area of rectangle a minus rectangle b.
  29379. */
  29380. goog.math.Rect.difference = function(a, b) {
  29381. var intersection = goog.math.Rect.intersection(a, b);
  29382. if (!intersection || !intersection.height || !intersection.width) {
  29383. return [a.clone()];
  29384. }
  29385. var result = [];
  29386. var top = a.top;
  29387. var height = a.height;
  29388. var ar = a.left + a.width;
  29389. var ab = a.top + a.height;
  29390. var br = b.left + b.width;
  29391. var bb = b.top + b.height;
  29392. // Subtract off any area on top where A extends past B
  29393. if (b.top > a.top) {
  29394. result.push(new goog.math.Rect(a.left, a.top, a.width, b.top - a.top));
  29395. top = b.top;
  29396. // If we're moving the top down, we also need to subtract the height diff.
  29397. height -= b.top - a.top;
  29398. }
  29399. // Subtract off any area on bottom where A extends past B
  29400. if (bb < ab) {
  29401. result.push(new goog.math.Rect(a.left, bb, a.width, ab - bb));
  29402. height = bb - top;
  29403. }
  29404. // Subtract any area on left where A extends past B
  29405. if (b.left > a.left) {
  29406. result.push(new goog.math.Rect(a.left, top, b.left - a.left, height));
  29407. }
  29408. // Subtract any area on right where A extends past B
  29409. if (br < ar) {
  29410. result.push(new goog.math.Rect(br, top, ar - br, height));
  29411. }
  29412. return result;
  29413. };
  29414. /**
  29415. * Computes the difference regions between this rectangle and {@code rect}. The
  29416. * return value is an array of 0 to 4 rectangles defining the remaining regions
  29417. * of this rectangle after the other has been subtracted.
  29418. * @param {goog.math.Rect} rect A Rectangle.
  29419. * @return {!Array<!goog.math.Rect>} An array with 0 to 4 rectangles which
  29420. * together define the difference area of rectangle a minus rectangle b.
  29421. */
  29422. goog.math.Rect.prototype.difference = function(rect) {
  29423. return goog.math.Rect.difference(this, rect);
  29424. };
  29425. /**
  29426. * Expand this rectangle to also include the area of the given rectangle.
  29427. * @param {goog.math.Rect} rect The other rectangle.
  29428. */
  29429. goog.math.Rect.prototype.boundingRect = function(rect) {
  29430. // We compute right and bottom before we change left and top below.
  29431. var right = Math.max(this.left + this.width, rect.left + rect.width);
  29432. var bottom = Math.max(this.top + this.height, rect.top + rect.height);
  29433. this.left = Math.min(this.left, rect.left);
  29434. this.top = Math.min(this.top, rect.top);
  29435. this.width = right - this.left;
  29436. this.height = bottom - this.top;
  29437. };
  29438. /**
  29439. * Returns a new rectangle which completely contains both input rectangles.
  29440. * @param {goog.math.Rect} a A rectangle.
  29441. * @param {goog.math.Rect} b A rectangle.
  29442. * @return {goog.math.Rect} A new bounding rect, or null if either rect is
  29443. * null.
  29444. */
  29445. goog.math.Rect.boundingRect = function(a, b) {
  29446. if (!a || !b) {
  29447. return null;
  29448. }
  29449. var clone = a.clone();
  29450. clone.boundingRect(b);
  29451. return clone;
  29452. };
  29453. /**
  29454. * Tests whether this rectangle entirely contains another rectangle or
  29455. * coordinate.
  29456. *
  29457. * @param {goog.math.Rect|goog.math.Coordinate} another The rectangle or
  29458. * coordinate to test for containment.
  29459. * @return {boolean} Whether this rectangle contains given rectangle or
  29460. * coordinate.
  29461. */
  29462. goog.math.Rect.prototype.contains = function(another) {
  29463. if (another instanceof goog.math.Rect) {
  29464. return this.left <= another.left &&
  29465. this.left + this.width >= another.left + another.width &&
  29466. this.top <= another.top &&
  29467. this.top + this.height >= another.top + another.height;
  29468. } else { // (another instanceof goog.math.Coordinate)
  29469. return another.x >= this.left &&
  29470. another.x <= this.left + this.width &&
  29471. another.y >= this.top &&
  29472. another.y <= this.top + this.height;
  29473. }
  29474. };
  29475. /**
  29476. * @param {!goog.math.Coordinate} point A coordinate.
  29477. * @return {number} The squared distance between the point and the closest
  29478. * point inside the rectangle. Returns 0 if the point is inside the
  29479. * rectangle.
  29480. */
  29481. goog.math.Rect.prototype.squaredDistance = function(point) {
  29482. var dx = point.x < this.left ?
  29483. this.left - point.x : Math.max(point.x - (this.left + this.width), 0);
  29484. var dy = point.y < this.top ?
  29485. this.top - point.y : Math.max(point.y - (this.top + this.height), 0);
  29486. return dx * dx + dy * dy;
  29487. };
  29488. /**
  29489. * @param {!goog.math.Coordinate} point A coordinate.
  29490. * @return {number} The distance between the point and the closest point
  29491. * inside the rectangle. Returns 0 if the point is inside the rectangle.
  29492. */
  29493. goog.math.Rect.prototype.distance = function(point) {
  29494. return Math.sqrt(this.squaredDistance(point));
  29495. };
  29496. /**
  29497. * @return {!goog.math.Size} The size of this rectangle.
  29498. */
  29499. goog.math.Rect.prototype.getSize = function() {
  29500. return new goog.math.Size(this.width, this.height);
  29501. };
  29502. /**
  29503. * @return {!goog.math.Coordinate} A new coordinate for the top-left corner of
  29504. * the rectangle.
  29505. */
  29506. goog.math.Rect.prototype.getTopLeft = function() {
  29507. return new goog.math.Coordinate(this.left, this.top);
  29508. };
  29509. /**
  29510. * @return {!goog.math.Coordinate} A new coordinate for the center of the
  29511. * rectangle.
  29512. */
  29513. goog.math.Rect.prototype.getCenter = function() {
  29514. return new goog.math.Coordinate(
  29515. this.left + this.width / 2, this.top + this.height / 2);
  29516. };
  29517. /**
  29518. * @return {!goog.math.Coordinate} A new coordinate for the bottom-right corner
  29519. * of the rectangle.
  29520. */
  29521. goog.math.Rect.prototype.getBottomRight = function() {
  29522. return new goog.math.Coordinate(
  29523. this.left + this.width, this.top + this.height);
  29524. };
  29525. /**
  29526. * Rounds the fields to the next larger integer values.
  29527. * @return {!goog.math.Rect} This rectangle with ceil'd fields.
  29528. */
  29529. goog.math.Rect.prototype.ceil = function() {
  29530. this.left = Math.ceil(this.left);
  29531. this.top = Math.ceil(this.top);
  29532. this.width = Math.ceil(this.width);
  29533. this.height = Math.ceil(this.height);
  29534. return this;
  29535. };
  29536. /**
  29537. * Rounds the fields to the next smaller integer values.
  29538. * @return {!goog.math.Rect} This rectangle with floored fields.
  29539. */
  29540. goog.math.Rect.prototype.floor = function() {
  29541. this.left = Math.floor(this.left);
  29542. this.top = Math.floor(this.top);
  29543. this.width = Math.floor(this.width);
  29544. this.height = Math.floor(this.height);
  29545. return this;
  29546. };
  29547. /**
  29548. * Rounds the fields to nearest integer values.
  29549. * @return {!goog.math.Rect} This rectangle with rounded fields.
  29550. */
  29551. goog.math.Rect.prototype.round = function() {
  29552. this.left = Math.round(this.left);
  29553. this.top = Math.round(this.top);
  29554. this.width = Math.round(this.width);
  29555. this.height = Math.round(this.height);
  29556. return this;
  29557. };
  29558. /**
  29559. * Translates this rectangle by the given offsets. If a
  29560. * {@code goog.math.Coordinate} is given, then the left and top values are
  29561. * translated by the coordinate's x and y values. Otherwise, top and left are
  29562. * translated by {@code tx} and {@code opt_ty} respectively.
  29563. * @param {number|goog.math.Coordinate} tx The value to translate left by or the
  29564. * the coordinate to translate this rect by.
  29565. * @param {number=} opt_ty The value to translate top by.
  29566. * @return {!goog.math.Rect} This rectangle after translating.
  29567. */
  29568. goog.math.Rect.prototype.translate = function(tx, opt_ty) {
  29569. if (tx instanceof goog.math.Coordinate) {
  29570. this.left += tx.x;
  29571. this.top += tx.y;
  29572. } else {
  29573. this.left += tx;
  29574. if (goog.isNumber(opt_ty)) {
  29575. this.top += opt_ty;
  29576. }
  29577. }
  29578. return this;
  29579. };
  29580. /**
  29581. * Scales this rectangle by the given scale factors. The left and width values
  29582. * are scaled by {@code sx} and the top and height values are scaled by
  29583. * {@code opt_sy}. If {@code opt_sy} is not given, then all fields are scaled
  29584. * by {@code sx}.
  29585. * @param {number} sx The scale factor to use for the x dimension.
  29586. * @param {number=} opt_sy The scale factor to use for the y dimension.
  29587. * @return {!goog.math.Rect} This rectangle after scaling.
  29588. */
  29589. goog.math.Rect.prototype.scale = function(sx, opt_sy) {
  29590. var sy = goog.isNumber(opt_sy) ? opt_sy : sx;
  29591. this.left *= sx;
  29592. this.width *= sx;
  29593. this.top *= sy;
  29594. this.height *= sy;
  29595. return this;
  29596. };
  29597. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  29598. //
  29599. // Licensed under the Apache License, Version 2.0 (the "License");
  29600. // you may not use this file except in compliance with the License.
  29601. // You may obtain a copy of the License at
  29602. //
  29603. // http://www.apache.org/licenses/LICENSE-2.0
  29604. //
  29605. // Unless required by applicable law or agreed to in writing, software
  29606. // distributed under the License is distributed on an "AS-IS" BASIS,
  29607. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  29608. // See the License for the specific language governing permissions and
  29609. // limitations under the License.
  29610. /**
  29611. * @fileoverview Utilities for element styles.
  29612. *
  29613. * @author arv@google.com (Erik Arvidsson)
  29614. * @author eae@google.com (Emil A Eklund)
  29615. * @see ../demos/inline_block_quirks.html
  29616. * @see ../demos/inline_block_standards.html
  29617. * @see ../demos/style_viewport.html
  29618. */
  29619. goog.provide('goog.style');
  29620. goog.require('goog.array');
  29621. goog.require('goog.asserts');
  29622. goog.require('goog.dom');
  29623. goog.require('goog.dom.NodeType');
  29624. goog.require('goog.dom.TagName');
  29625. goog.require('goog.dom.vendor');
  29626. goog.require('goog.math.Box');
  29627. goog.require('goog.math.Coordinate');
  29628. goog.require('goog.math.Rect');
  29629. goog.require('goog.math.Size');
  29630. goog.require('goog.object');
  29631. goog.require('goog.string');
  29632. goog.require('goog.userAgent');
  29633. goog.forwardDeclare('goog.events.BrowserEvent');
  29634. goog.forwardDeclare('goog.events.Event');
  29635. /**
  29636. * Sets a style value on an element.
  29637. *
  29638. * This function is not indended to patch issues in the browser's style
  29639. * handling, but to allow easy programmatic access to setting dash-separated
  29640. * style properties. An example is setting a batch of properties from a data
  29641. * object without overwriting old styles. When possible, use native APIs:
  29642. * elem.style.propertyKey = 'value' or (if obliterating old styles is fine)
  29643. * elem.style.cssText = 'property1: value1; property2: value2'.
  29644. *
  29645. * @param {Element} element The element to change.
  29646. * @param {string|Object} style If a string, a style name. If an object, a hash
  29647. * of style names to style values.
  29648. * @param {string|number|boolean=} opt_value If style was a string, then this
  29649. * should be the value.
  29650. */
  29651. goog.style.setStyle = function(element, style, opt_value) {
  29652. if (goog.isString(style)) {
  29653. goog.style.setStyle_(element, opt_value, style);
  29654. } else {
  29655. for (var key in style) {
  29656. goog.style.setStyle_(element, style[key], key);
  29657. }
  29658. }
  29659. };
  29660. /**
  29661. * Sets a style value on an element, with parameters swapped to work with
  29662. * {@code goog.object.forEach()}. Prepends a vendor-specific prefix when
  29663. * necessary.
  29664. * @param {Element} element The element to change.
  29665. * @param {string|number|boolean|undefined} value Style value.
  29666. * @param {string} style Style name.
  29667. * @private
  29668. */
  29669. goog.style.setStyle_ = function(element, value, style) {
  29670. var propertyName = goog.style.getVendorJsStyleName_(element, style);
  29671. if (propertyName) {
  29672. element.style[propertyName] = value;
  29673. }
  29674. };
  29675. /**
  29676. * Style name cache that stores previous property name lookups.
  29677. *
  29678. * This is used by setStyle to speed up property lookups, entries look like:
  29679. * { StyleName: ActualPropertyName }
  29680. *
  29681. * @private {!Object<string, string>}
  29682. */
  29683. goog.style.styleNameCache_ = {};
  29684. /**
  29685. * Returns the style property name in camel-case. If it does not exist and a
  29686. * vendor-specific version of the property does exist, then return the vendor-
  29687. * specific property name instead.
  29688. * @param {Element} element The element to change.
  29689. * @param {string} style Style name.
  29690. * @return {string} Vendor-specific style.
  29691. * @private
  29692. */
  29693. goog.style.getVendorJsStyleName_ = function(element, style) {
  29694. var propertyName = goog.style.styleNameCache_[style];
  29695. if (!propertyName) {
  29696. var camelStyle = goog.string.toCamelCase(style);
  29697. propertyName = camelStyle;
  29698. if (element.style[camelStyle] === undefined) {
  29699. var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() +
  29700. goog.string.toTitleCase(camelStyle);
  29701. if (element.style[prefixedStyle] !== undefined) {
  29702. propertyName = prefixedStyle;
  29703. }
  29704. }
  29705. goog.style.styleNameCache_[style] = propertyName;
  29706. }
  29707. return propertyName;
  29708. };
  29709. /**
  29710. * Returns the style property name in CSS notation. If it does not exist and a
  29711. * vendor-specific version of the property does exist, then return the vendor-
  29712. * specific property name instead.
  29713. * @param {Element} element The element to change.
  29714. * @param {string} style Style name.
  29715. * @return {string} Vendor-specific style.
  29716. * @private
  29717. */
  29718. goog.style.getVendorStyleName_ = function(element, style) {
  29719. var camelStyle = goog.string.toCamelCase(style);
  29720. if (element.style[camelStyle] === undefined) {
  29721. var prefixedStyle = goog.dom.vendor.getVendorJsPrefix() +
  29722. goog.string.toTitleCase(camelStyle);
  29723. if (element.style[prefixedStyle] !== undefined) {
  29724. return goog.dom.vendor.getVendorPrefix() + '-' + style;
  29725. }
  29726. }
  29727. return style;
  29728. };
  29729. /**
  29730. * Retrieves an explicitly-set style value of a node. This returns '' if there
  29731. * isn't a style attribute on the element or if this style property has not been
  29732. * explicitly set in script.
  29733. *
  29734. * @param {Element} element Element to get style of.
  29735. * @param {string} property Property to get, css-style (if you have a camel-case
  29736. * property, use element.style[style]).
  29737. * @return {string} Style value.
  29738. */
  29739. goog.style.getStyle = function(element, property) {
  29740. // element.style is '' for well-known properties which are unset.
  29741. // For for browser specific styles as 'filter' is undefined
  29742. // so we need to return '' explicitly to make it consistent across
  29743. // browsers.
  29744. var styleValue = element.style[goog.string.toCamelCase(property)];
  29745. // Using typeof here because of a bug in Safari 5.1, where this value
  29746. // was undefined, but === undefined returned false.
  29747. if (typeof(styleValue) !== 'undefined') {
  29748. return styleValue;
  29749. }
  29750. return element.style[goog.style.getVendorJsStyleName_(element, property)] ||
  29751. '';
  29752. };
  29753. /**
  29754. * Retrieves a computed style value of a node. It returns empty string if the
  29755. * value cannot be computed (which will be the case in Internet Explorer) or
  29756. * "none" if the property requested is an SVG one and it has not been
  29757. * explicitly set (firefox and webkit).
  29758. *
  29759. * @param {Element} element Element to get style of.
  29760. * @param {string} property Property to get (camel-case).
  29761. * @return {string} Style value.
  29762. */
  29763. goog.style.getComputedStyle = function(element, property) {
  29764. var doc = goog.dom.getOwnerDocument(element);
  29765. if (doc.defaultView && doc.defaultView.getComputedStyle) {
  29766. var styles = doc.defaultView.getComputedStyle(element, null);
  29767. if (styles) {
  29768. // element.style[..] is undefined for browser specific styles
  29769. // as 'filter'.
  29770. return styles[property] || styles.getPropertyValue(property) || '';
  29771. }
  29772. }
  29773. return '';
  29774. };
  29775. /**
  29776. * Gets the cascaded style value of a node, or null if the value cannot be
  29777. * computed (only Internet Explorer can do this).
  29778. *
  29779. * @param {Element} element Element to get style of.
  29780. * @param {string} style Property to get (camel-case).
  29781. * @return {string} Style value.
  29782. */
  29783. goog.style.getCascadedStyle = function(element, style) {
  29784. // TODO(nicksantos): This should be documented to return null. #fixTypes
  29785. return element.currentStyle ? element.currentStyle[style] : null;
  29786. };
  29787. /**
  29788. * Cross-browser pseudo get computed style. It returns the computed style where
  29789. * available. If not available it tries the cascaded style value (IE
  29790. * currentStyle) and in worst case the inline style value. It shouldn't be
  29791. * called directly, see http://wiki/Main/ComputedStyleVsCascadedStyle for
  29792. * discussion.
  29793. *
  29794. * @param {Element} element Element to get style of.
  29795. * @param {string} style Property to get (must be camelCase, not css-style.).
  29796. * @return {string} Style value.
  29797. * @private
  29798. */
  29799. goog.style.getStyle_ = function(element, style) {
  29800. return goog.style.getComputedStyle(element, style) ||
  29801. goog.style.getCascadedStyle(element, style) ||
  29802. (element.style && element.style[style]);
  29803. };
  29804. /**
  29805. * Retrieves the computed value of the box-sizing CSS attribute.
  29806. * Browser support: http://caniuse.com/css3-boxsizing.
  29807. * @param {!Element} element The element whose box-sizing to get.
  29808. * @return {?string} 'content-box', 'border-box' or 'padding-box'. null if
  29809. * box-sizing is not supported (IE7 and below).
  29810. */
  29811. goog.style.getComputedBoxSizing = function(element) {
  29812. return goog.style.getStyle_(element, 'boxSizing') ||
  29813. goog.style.getStyle_(element, 'MozBoxSizing') ||
  29814. goog.style.getStyle_(element, 'WebkitBoxSizing') || null;
  29815. };
  29816. /**
  29817. * Retrieves the computed value of the position CSS attribute.
  29818. * @param {Element} element The element to get the position of.
  29819. * @return {string} Position value.
  29820. */
  29821. goog.style.getComputedPosition = function(element) {
  29822. return goog.style.getStyle_(element, 'position');
  29823. };
  29824. /**
  29825. * Retrieves the computed background color string for a given element. The
  29826. * string returned is suitable for assigning to another element's
  29827. * background-color, but is not guaranteed to be in any particular string
  29828. * format. Accessing the color in a numeric form may not be possible in all
  29829. * browsers or with all input.
  29830. *
  29831. * If the background color for the element is defined as a hexadecimal value,
  29832. * the resulting string can be parsed by goog.color.parse in all supported
  29833. * browsers.
  29834. *
  29835. * Whether named colors like "red" or "lightblue" get translated into a
  29836. * format which can be parsed is browser dependent. Calling this function on
  29837. * transparent elements will return "transparent" in most browsers or
  29838. * "rgba(0, 0, 0, 0)" in WebKit.
  29839. * @param {Element} element The element to get the background color of.
  29840. * @return {string} The computed string value of the background color.
  29841. */
  29842. goog.style.getBackgroundColor = function(element) {
  29843. return goog.style.getStyle_(element, 'backgroundColor');
  29844. };
  29845. /**
  29846. * Retrieves the computed value of the overflow-x CSS attribute.
  29847. * @param {Element} element The element to get the overflow-x of.
  29848. * @return {string} The computed string value of the overflow-x attribute.
  29849. */
  29850. goog.style.getComputedOverflowX = function(element) {
  29851. return goog.style.getStyle_(element, 'overflowX');
  29852. };
  29853. /**
  29854. * Retrieves the computed value of the overflow-y CSS attribute.
  29855. * @param {Element} element The element to get the overflow-y of.
  29856. * @return {string} The computed string value of the overflow-y attribute.
  29857. */
  29858. goog.style.getComputedOverflowY = function(element) {
  29859. return goog.style.getStyle_(element, 'overflowY');
  29860. };
  29861. /**
  29862. * Retrieves the computed value of the z-index CSS attribute.
  29863. * @param {Element} element The element to get the z-index of.
  29864. * @return {string|number} The computed value of the z-index attribute.
  29865. */
  29866. goog.style.getComputedZIndex = function(element) {
  29867. return goog.style.getStyle_(element, 'zIndex');
  29868. };
  29869. /**
  29870. * Retrieves the computed value of the text-align CSS attribute.
  29871. * @param {Element} element The element to get the text-align of.
  29872. * @return {string} The computed string value of the text-align attribute.
  29873. */
  29874. goog.style.getComputedTextAlign = function(element) {
  29875. return goog.style.getStyle_(element, 'textAlign');
  29876. };
  29877. /**
  29878. * Retrieves the computed value of the cursor CSS attribute.
  29879. * @param {Element} element The element to get the cursor of.
  29880. * @return {string} The computed string value of the cursor attribute.
  29881. */
  29882. goog.style.getComputedCursor = function(element) {
  29883. return goog.style.getStyle_(element, 'cursor');
  29884. };
  29885. /**
  29886. * Retrieves the computed value of the CSS transform attribute.
  29887. * @param {Element} element The element to get the transform of.
  29888. * @return {string} The computed string representation of the transform matrix.
  29889. */
  29890. goog.style.getComputedTransform = function(element) {
  29891. var property = goog.style.getVendorStyleName_(element, 'transform');
  29892. return goog.style.getStyle_(element, property) ||
  29893. goog.style.getStyle_(element, 'transform');
  29894. };
  29895. /**
  29896. * Sets the top/left values of an element. If no unit is specified in the
  29897. * argument then it will add px. The second argument is required if the first
  29898. * argument is a string or number and is ignored if the first argument
  29899. * is a coordinate.
  29900. * @param {Element} el Element to move.
  29901. * @param {string|number|goog.math.Coordinate} arg1 Left position or coordinate.
  29902. * @param {string|number=} opt_arg2 Top position.
  29903. */
  29904. goog.style.setPosition = function(el, arg1, opt_arg2) {
  29905. var x, y;
  29906. if (arg1 instanceof goog.math.Coordinate) {
  29907. x = arg1.x;
  29908. y = arg1.y;
  29909. } else {
  29910. x = arg1;
  29911. y = opt_arg2;
  29912. }
  29913. el.style.left = goog.style.getPixelStyleValue_(
  29914. /** @type {number|string} */ (x), false);
  29915. el.style.top = goog.style.getPixelStyleValue_(
  29916. /** @type {number|string} */ (y), false);
  29917. };
  29918. /**
  29919. * Gets the offsetLeft and offsetTop properties of an element and returns them
  29920. * in a Coordinate object
  29921. * @param {Element} element Element.
  29922. * @return {!goog.math.Coordinate} The position.
  29923. */
  29924. goog.style.getPosition = function(element) {
  29925. return new goog.math.Coordinate(
  29926. /** @type {!HTMLElement} */ (element).offsetLeft,
  29927. /** @type {!HTMLElement} */ (element).offsetTop);
  29928. };
  29929. /**
  29930. * Returns the viewport element for a particular document
  29931. * @param {Node=} opt_node DOM node (Document is OK) to get the viewport element
  29932. * of.
  29933. * @return {Element} document.documentElement or document.body.
  29934. */
  29935. goog.style.getClientViewportElement = function(opt_node) {
  29936. var doc;
  29937. if (opt_node) {
  29938. doc = goog.dom.getOwnerDocument(opt_node);
  29939. } else {
  29940. doc = goog.dom.getDocument();
  29941. }
  29942. // In old IE versions the document.body represented the viewport
  29943. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9) &&
  29944. !goog.dom.getDomHelper(doc).isCss1CompatMode()) {
  29945. return doc.body;
  29946. }
  29947. return doc.documentElement;
  29948. };
  29949. /**
  29950. * Calculates the viewport coordinates relative to the page/document
  29951. * containing the node. The viewport may be the browser viewport for
  29952. * non-iframe document, or the iframe container for iframe'd document.
  29953. * @param {!Document} doc The document to use as the reference point.
  29954. * @return {!goog.math.Coordinate} The page offset of the viewport.
  29955. */
  29956. goog.style.getViewportPageOffset = function(doc) {
  29957. var body = doc.body;
  29958. var documentElement = doc.documentElement;
  29959. var scrollLeft = body.scrollLeft || documentElement.scrollLeft;
  29960. var scrollTop = body.scrollTop || documentElement.scrollTop;
  29961. return new goog.math.Coordinate(scrollLeft, scrollTop);
  29962. };
  29963. /**
  29964. * Gets the client rectangle of the DOM element.
  29965. *
  29966. * getBoundingClientRect is part of a new CSS object model draft (with a
  29967. * long-time presence in IE), replacing the error-prone parent offset
  29968. * computation and the now-deprecated Gecko getBoxObjectFor.
  29969. *
  29970. * This utility patches common browser bugs in getBoundingClientRect. It
  29971. * will fail if getBoundingClientRect is unsupported.
  29972. *
  29973. * If the element is not in the DOM, the result is undefined, and an error may
  29974. * be thrown depending on user agent.
  29975. *
  29976. * @param {!Element} el The element whose bounding rectangle is being queried.
  29977. * @return {Object} A native bounding rectangle with numerical left, top,
  29978. * right, and bottom. Reported by Firefox to be of object type ClientRect.
  29979. * @private
  29980. */
  29981. goog.style.getBoundingClientRect_ = function(el) {
  29982. var rect;
  29983. try {
  29984. rect = el.getBoundingClientRect();
  29985. } catch (e) {
  29986. // In IE < 9, calling getBoundingClientRect on an orphan element raises an
  29987. // "Unspecified Error". All other browsers return zeros.
  29988. return {'left': 0, 'top': 0, 'right': 0, 'bottom': 0};
  29989. }
  29990. // Patch the result in IE only, so that this function can be inlined if
  29991. // compiled for non-IE.
  29992. if (goog.userAgent.IE && el.ownerDocument.body) {
  29993. // In IE, most of the time, 2 extra pixels are added to the top and left
  29994. // due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
  29995. // IE6 standards mode, this border can be overridden by setting the
  29996. // document element's border to zero -- thus, we cannot rely on the
  29997. // offset always being 2 pixels.
  29998. // In quirks mode, the offset can be determined by querying the body's
  29999. // clientLeft/clientTop, but in standards mode, it is found by querying
  30000. // the document element's clientLeft/clientTop. Since we already called
  30001. // getBoundingClientRect we have already forced a reflow, so it is not
  30002. // too expensive just to query them all.
  30003. // See: http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx
  30004. var doc = el.ownerDocument;
  30005. rect.left -= doc.documentElement.clientLeft + doc.body.clientLeft;
  30006. rect.top -= doc.documentElement.clientTop + doc.body.clientTop;
  30007. }
  30008. return rect;
  30009. };
  30010. /**
  30011. * Returns the first parent that could affect the position of a given element.
  30012. * @param {Element} element The element to get the offset parent for.
  30013. * @return {Element} The first offset parent or null if one cannot be found.
  30014. */
  30015. goog.style.getOffsetParent = function(element) {
  30016. // element.offsetParent does the right thing in IE7 and below. In other
  30017. // browsers it only includes elements with position absolute, relative or
  30018. // fixed, not elements with overflow set to auto or scroll.
  30019. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(8)) {
  30020. return element.offsetParent;
  30021. }
  30022. var doc = goog.dom.getOwnerDocument(element);
  30023. var positionStyle = goog.style.getStyle_(element, 'position');
  30024. var skipStatic = positionStyle == 'fixed' || positionStyle == 'absolute';
  30025. for (var parent = element.parentNode; parent && parent != doc;
  30026. parent = parent.parentNode) {
  30027. // Skip shadowDOM roots.
  30028. if (parent.nodeType == goog.dom.NodeType.DOCUMENT_FRAGMENT &&
  30029. parent.host) {
  30030. parent = parent.host;
  30031. }
  30032. positionStyle =
  30033. goog.style.getStyle_(/** @type {!Element} */ (parent), 'position');
  30034. skipStatic = skipStatic && positionStyle == 'static' &&
  30035. parent != doc.documentElement && parent != doc.body;
  30036. if (!skipStatic && (parent.scrollWidth > parent.clientWidth ||
  30037. parent.scrollHeight > parent.clientHeight ||
  30038. positionStyle == 'fixed' ||
  30039. positionStyle == 'absolute' ||
  30040. positionStyle == 'relative')) {
  30041. return /** @type {!Element} */ (parent);
  30042. }
  30043. }
  30044. return null;
  30045. };
  30046. /**
  30047. * Calculates and returns the visible rectangle for a given element. Returns a
  30048. * box describing the visible portion of the nearest scrollable offset ancestor.
  30049. * Coordinates are given relative to the document.
  30050. *
  30051. * @param {Element} element Element to get the visible rect for.
  30052. * @return {goog.math.Box} Bounding elementBox describing the visible rect or
  30053. * null if scrollable ancestor isn't inside the visible viewport.
  30054. */
  30055. goog.style.getVisibleRectForElement = function(element) {
  30056. var visibleRect = new goog.math.Box(0, Infinity, Infinity, 0);
  30057. var dom = goog.dom.getDomHelper(element);
  30058. var body = dom.getDocument().body;
  30059. var documentElement = dom.getDocument().documentElement;
  30060. var scrollEl = dom.getDocumentScrollElement();
  30061. // Determine the size of the visible rect by climbing the dom accounting for
  30062. // all scrollable containers.
  30063. for (var el = element; el = goog.style.getOffsetParent(el); ) {
  30064. // clientWidth is zero for inline block elements in IE.
  30065. // on WEBKIT, body element can have clientHeight = 0 and scrollHeight > 0
  30066. if ((!goog.userAgent.IE || el.clientWidth != 0) &&
  30067. (!goog.userAgent.WEBKIT || el.clientHeight != 0 || el != body) &&
  30068. // body may have overflow set on it, yet we still get the entire
  30069. // viewport. In some browsers, el.offsetParent may be
  30070. // document.documentElement, so check for that too.
  30071. (el != body && el != documentElement &&
  30072. goog.style.getStyle_(el, 'overflow') != 'visible')) {
  30073. var pos = goog.style.getPageOffset(el);
  30074. var client = goog.style.getClientLeftTop(el);
  30075. pos.x += client.x;
  30076. pos.y += client.y;
  30077. visibleRect.top = Math.max(visibleRect.top, pos.y);
  30078. visibleRect.right = Math.min(visibleRect.right,
  30079. pos.x + el.clientWidth);
  30080. visibleRect.bottom = Math.min(visibleRect.bottom,
  30081. pos.y + el.clientHeight);
  30082. visibleRect.left = Math.max(visibleRect.left, pos.x);
  30083. }
  30084. }
  30085. // Clip by window's viewport.
  30086. var scrollX = scrollEl.scrollLeft, scrollY = scrollEl.scrollTop;
  30087. visibleRect.left = Math.max(visibleRect.left, scrollX);
  30088. visibleRect.top = Math.max(visibleRect.top, scrollY);
  30089. var winSize = dom.getViewportSize();
  30090. visibleRect.right = Math.min(visibleRect.right, scrollX + winSize.width);
  30091. visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + winSize.height);
  30092. return visibleRect.top >= 0 && visibleRect.left >= 0 &&
  30093. visibleRect.bottom > visibleRect.top &&
  30094. visibleRect.right > visibleRect.left ?
  30095. visibleRect : null;
  30096. };
  30097. /**
  30098. * Calculate the scroll position of {@code container} with the minimum amount so
  30099. * that the content and the borders of the given {@code element} become visible.
  30100. * If the element is bigger than the container, its top left corner will be
  30101. * aligned as close to the container's top left corner as possible.
  30102. *
  30103. * @param {Element} element The element to make visible.
  30104. * @param {Element=} opt_container The container to scroll. If not set, then the
  30105. * document scroll element will be used.
  30106. * @param {boolean=} opt_center Whether to center the element in the container.
  30107. * Defaults to false.
  30108. * @return {!goog.math.Coordinate} The new scroll position of the container,
  30109. * in form of goog.math.Coordinate(scrollLeft, scrollTop).
  30110. */
  30111. goog.style.getContainerOffsetToScrollInto =
  30112. function(element, opt_container, opt_center) {
  30113. var container = opt_container || goog.dom.getDocumentScrollElement();
  30114. // Absolute position of the element's border's top left corner.
  30115. var elementPos = goog.style.getPageOffset(element);
  30116. // Absolute position of the container's border's top left corner.
  30117. var containerPos = goog.style.getPageOffset(container);
  30118. var containerBorder = goog.style.getBorderBox(container);
  30119. if (container == goog.dom.getDocumentScrollElement()) {
  30120. // The element position is calculated based on the page offset, and the
  30121. // document scroll element holds the scroll position within the page. We can
  30122. // use the scroll position to calculate the relative position from the
  30123. // element.
  30124. var relX = elementPos.x - container.scrollLeft;
  30125. var relY = elementPos.y - container.scrollTop;
  30126. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
  30127. // In older versions of IE getPageOffset(element) does not include the
  30128. // container border so it has to be added to accomodate.
  30129. relX += containerBorder.left;
  30130. relY += containerBorder.top;
  30131. }
  30132. } else {
  30133. // Relative pos. of the element's border box to the container's content box.
  30134. var relX = elementPos.x - containerPos.x - containerBorder.left;
  30135. var relY = elementPos.y - containerPos.y - containerBorder.top;
  30136. }
  30137. // How much the element can move in the container, i.e. the difference between
  30138. // the element's bottom-right-most and top-left-most position where it's
  30139. // fully visible.
  30140. var spaceX = container.clientWidth -
  30141. /** @type {HTMLElement} */ (element).offsetWidth;
  30142. var spaceY = container.clientHeight -
  30143. /** @type {HTMLElement} */ (element).offsetHeight;
  30144. var scrollLeft = container.scrollLeft;
  30145. var scrollTop = container.scrollTop;
  30146. if (opt_center) {
  30147. // All browsers round non-integer scroll positions down.
  30148. scrollLeft += relX - spaceX / 2;
  30149. scrollTop += relY - spaceY / 2;
  30150. } else {
  30151. // This formula was designed to give the correct scroll values in the
  30152. // following cases:
  30153. // - element is higher than container (spaceY < 0) => scroll down by relY
  30154. // - element is not higher that container (spaceY >= 0):
  30155. // - it is above container (relY < 0) => scroll up by abs(relY)
  30156. // - it is below container (relY > spaceY) => scroll down by relY - spaceY
  30157. // - it is in the container => don't scroll
  30158. scrollLeft += Math.min(relX, Math.max(relX - spaceX, 0));
  30159. scrollTop += Math.min(relY, Math.max(relY - spaceY, 0));
  30160. }
  30161. return new goog.math.Coordinate(scrollLeft, scrollTop);
  30162. };
  30163. /**
  30164. * Changes the scroll position of {@code container} with the minimum amount so
  30165. * that the content and the borders of the given {@code element} become visible.
  30166. * If the element is bigger than the container, its top left corner will be
  30167. * aligned as close to the container's top left corner as possible.
  30168. *
  30169. * @param {Element} element The element to make visible.
  30170. * @param {Element=} opt_container The container to scroll. If not set, then the
  30171. * document scroll element will be used.
  30172. * @param {boolean=} opt_center Whether to center the element in the container.
  30173. * Defaults to false.
  30174. */
  30175. goog.style.scrollIntoContainerView =
  30176. function(element, opt_container, opt_center) {
  30177. var container = opt_container || goog.dom.getDocumentScrollElement();
  30178. var offset =
  30179. goog.style.getContainerOffsetToScrollInto(element, container, opt_center);
  30180. container.scrollLeft = offset.x;
  30181. container.scrollTop = offset.y;
  30182. };
  30183. /**
  30184. * Returns clientLeft (width of the left border and, if the directionality is
  30185. * right to left, the vertical scrollbar) and clientTop as a coordinate object.
  30186. *
  30187. * @param {Element} el Element to get clientLeft for.
  30188. * @return {!goog.math.Coordinate} Client left and top.
  30189. */
  30190. goog.style.getClientLeftTop = function(el) {
  30191. return new goog.math.Coordinate(el.clientLeft, el.clientTop);
  30192. };
  30193. /**
  30194. * Returns a Coordinate object relative to the top-left of the HTML document.
  30195. * Implemented as a single function to save having to do two recursive loops in
  30196. * opera and safari just to get both coordinates. If you just want one value do
  30197. * use goog.style.getPageOffsetLeft() and goog.style.getPageOffsetTop(), but
  30198. * note if you call both those methods the tree will be analysed twice.
  30199. *
  30200. * @param {Element} el Element to get the page offset for.
  30201. * @return {!goog.math.Coordinate} The page offset.
  30202. */
  30203. goog.style.getPageOffset = function(el) {
  30204. var doc = goog.dom.getOwnerDocument(el);
  30205. // TODO(gboyer): Update the jsdoc in a way that doesn't break the universe.
  30206. goog.asserts.assertObject(el, 'Parameter is required');
  30207. // NOTE(arv): If element is hidden (display none or disconnected or any the
  30208. // ancestors are hidden) we get (0,0) by default but we still do the
  30209. // accumulation of scroll position.
  30210. // TODO(arv): Should we check if the node is disconnected and in that case
  30211. // return (0,0)?
  30212. var pos = new goog.math.Coordinate(0, 0);
  30213. var viewportElement = goog.style.getClientViewportElement(doc);
  30214. if (el == viewportElement) {
  30215. // viewport is always at 0,0 as that defined the coordinate system for this
  30216. // function - this avoids special case checks in the code below
  30217. return pos;
  30218. }
  30219. var box = goog.style.getBoundingClientRect_(el);
  30220. // Must add the scroll coordinates in to get the absolute page offset
  30221. // of element since getBoundingClientRect returns relative coordinates to
  30222. // the viewport.
  30223. var scrollCoord = goog.dom.getDomHelper(doc).getDocumentScroll();
  30224. pos.x = box.left + scrollCoord.x;
  30225. pos.y = box.top + scrollCoord.y;
  30226. return pos;
  30227. };
  30228. /**
  30229. * Returns the left coordinate of an element relative to the HTML document
  30230. * @param {Element} el Elements.
  30231. * @return {number} The left coordinate.
  30232. */
  30233. goog.style.getPageOffsetLeft = function(el) {
  30234. return goog.style.getPageOffset(el).x;
  30235. };
  30236. /**
  30237. * Returns the top coordinate of an element relative to the HTML document
  30238. * @param {Element} el Elements.
  30239. * @return {number} The top coordinate.
  30240. */
  30241. goog.style.getPageOffsetTop = function(el) {
  30242. return goog.style.getPageOffset(el).y;
  30243. };
  30244. /**
  30245. * Returns a Coordinate object relative to the top-left of an HTML document
  30246. * in an ancestor frame of this element. Used for measuring the position of
  30247. * an element inside a frame relative to a containing frame.
  30248. *
  30249. * @param {Element} el Element to get the page offset for.
  30250. * @param {Window} relativeWin The window to measure relative to. If relativeWin
  30251. * is not in the ancestor frame chain of the element, we measure relative to
  30252. * the top-most window.
  30253. * @return {!goog.math.Coordinate} The page offset.
  30254. */
  30255. goog.style.getFramedPageOffset = function(el, relativeWin) {
  30256. var position = new goog.math.Coordinate(0, 0);
  30257. // Iterate up the ancestor frame chain, keeping track of the current window
  30258. // and the current element in that window.
  30259. var currentWin = goog.dom.getWindow(goog.dom.getOwnerDocument(el));
  30260. var currentEl = el;
  30261. do {
  30262. // if we're at the top window, we want to get the page offset.
  30263. // if we're at an inner frame, we only want to get the window position
  30264. // so that we can determine the actual page offset in the context of
  30265. // the outer window.
  30266. var offset = currentWin == relativeWin ?
  30267. goog.style.getPageOffset(currentEl) :
  30268. goog.style.getClientPositionForElement_(
  30269. goog.asserts.assert(currentEl));
  30270. position.x += offset.x;
  30271. position.y += offset.y;
  30272. } while (currentWin && currentWin != relativeWin &&
  30273. currentWin != currentWin.parent &&
  30274. (currentEl = currentWin.frameElement) &&
  30275. (currentWin = currentWin.parent));
  30276. return position;
  30277. };
  30278. /**
  30279. * Translates the specified rect relative to origBase page, for newBase page.
  30280. * If origBase and newBase are the same, this function does nothing.
  30281. *
  30282. * @param {goog.math.Rect} rect The source rectangle relative to origBase page,
  30283. * and it will have the translated result.
  30284. * @param {goog.dom.DomHelper} origBase The DomHelper for the input rectangle.
  30285. * @param {goog.dom.DomHelper} newBase The DomHelper for the resultant
  30286. * coordinate. This must be a DOM for an ancestor frame of origBase
  30287. * or the same as origBase.
  30288. */
  30289. goog.style.translateRectForAnotherFrame = function(rect, origBase, newBase) {
  30290. if (origBase.getDocument() != newBase.getDocument()) {
  30291. var body = origBase.getDocument().body;
  30292. var pos = goog.style.getFramedPageOffset(body, newBase.getWindow());
  30293. // Adjust Body's margin.
  30294. pos = goog.math.Coordinate.difference(pos, goog.style.getPageOffset(body));
  30295. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9) &&
  30296. !origBase.isCss1CompatMode()) {
  30297. pos = goog.math.Coordinate.difference(pos, origBase.getDocumentScroll());
  30298. }
  30299. rect.left += pos.x;
  30300. rect.top += pos.y;
  30301. }
  30302. };
  30303. /**
  30304. * Returns the position of an element relative to another element in the
  30305. * document. A relative to B
  30306. * @param {Element|Event|goog.events.Event} a Element or mouse event whose
  30307. * position we're calculating.
  30308. * @param {Element|Event|goog.events.Event} b Element or mouse event position
  30309. * is relative to.
  30310. * @return {!goog.math.Coordinate} The relative position.
  30311. */
  30312. goog.style.getRelativePosition = function(a, b) {
  30313. var ap = goog.style.getClientPosition(a);
  30314. var bp = goog.style.getClientPosition(b);
  30315. return new goog.math.Coordinate(ap.x - bp.x, ap.y - bp.y);
  30316. };
  30317. /**
  30318. * Returns the position of the event or the element's border box relative to
  30319. * the client viewport.
  30320. * @param {!Element} el Element whose position to get.
  30321. * @return {!goog.math.Coordinate} The position.
  30322. * @private
  30323. */
  30324. goog.style.getClientPositionForElement_ = function(el) {
  30325. var box = goog.style.getBoundingClientRect_(el);
  30326. return new goog.math.Coordinate(box.left, box.top);
  30327. };
  30328. /**
  30329. * Returns the position of the event or the element's border box relative to
  30330. * the client viewport. If an event is passed, and if this event is a "touch"
  30331. * event, then the position of the first changedTouches will be returned.
  30332. * @param {Element|Event|goog.events.Event} el Element or a mouse / touch event.
  30333. * @return {!goog.math.Coordinate} The position.
  30334. */
  30335. goog.style.getClientPosition = function(el) {
  30336. goog.asserts.assert(el);
  30337. if (el.nodeType == goog.dom.NodeType.ELEMENT) {
  30338. return goog.style.getClientPositionForElement_(
  30339. /** @type {!Element} */ (el));
  30340. } else {
  30341. var targetEvent = el.changedTouches ? el.changedTouches[0] : el;
  30342. return new goog.math.Coordinate(
  30343. targetEvent.clientX,
  30344. targetEvent.clientY);
  30345. }
  30346. };
  30347. /**
  30348. * Moves an element to the given coordinates relative to the client viewport.
  30349. * @param {Element} el Absolutely positioned element to set page offset for.
  30350. * It must be in the document.
  30351. * @param {number|goog.math.Coordinate} x Left position of the element's margin
  30352. * box or a coordinate object.
  30353. * @param {number=} opt_y Top position of the element's margin box.
  30354. */
  30355. goog.style.setPageOffset = function(el, x, opt_y) {
  30356. // Get current pageoffset
  30357. var cur = goog.style.getPageOffset(el);
  30358. if (x instanceof goog.math.Coordinate) {
  30359. opt_y = x.y;
  30360. x = x.x;
  30361. }
  30362. // NOTE(arv): We cannot allow strings for x and y. We could but that would
  30363. // require us to manually transform between different units
  30364. // Work out deltas
  30365. var dx = x - cur.x;
  30366. var dy = opt_y - cur.y;
  30367. // Set position to current left/top + delta
  30368. goog.style.setPosition(el, /** @type {!HTMLElement} */ (el).offsetLeft + dx,
  30369. /** @type {!HTMLElement} */ (el).offsetTop + dy);
  30370. };
  30371. /**
  30372. * Sets the width/height values of an element. If an argument is numeric,
  30373. * or a goog.math.Size is passed, it is assumed to be pixels and will add
  30374. * 'px' after converting it to an integer in string form. (This just sets the
  30375. * CSS width and height properties so it might set content-box or border-box
  30376. * size depending on the box model the browser is using.)
  30377. *
  30378. * @param {Element} element Element to set the size of.
  30379. * @param {string|number|goog.math.Size} w Width of the element, or a
  30380. * size object.
  30381. * @param {string|number=} opt_h Height of the element. Required if w is not a
  30382. * size object.
  30383. */
  30384. goog.style.setSize = function(element, w, opt_h) {
  30385. var h;
  30386. if (w instanceof goog.math.Size) {
  30387. h = w.height;
  30388. w = w.width;
  30389. } else {
  30390. if (opt_h == undefined) {
  30391. throw Error('missing height argument');
  30392. }
  30393. h = opt_h;
  30394. }
  30395. goog.style.setWidth(element, /** @type {string|number} */ (w));
  30396. goog.style.setHeight(element, h);
  30397. };
  30398. /**
  30399. * Helper function to create a string to be set into a pixel-value style
  30400. * property of an element. Can round to the nearest integer value.
  30401. *
  30402. * @param {string|number} value The style value to be used. If a number,
  30403. * 'px' will be appended, otherwise the value will be applied directly.
  30404. * @param {boolean} round Whether to round the nearest integer (if property
  30405. * is a number).
  30406. * @return {string} The string value for the property.
  30407. * @private
  30408. */
  30409. goog.style.getPixelStyleValue_ = function(value, round) {
  30410. if (typeof value == 'number') {
  30411. value = (round ? Math.round(value) : value) + 'px';
  30412. }
  30413. return value;
  30414. };
  30415. /**
  30416. * Set the height of an element. Sets the element's style property.
  30417. * @param {Element} element Element to set the height of.
  30418. * @param {string|number} height The height value to set. If a number, 'px'
  30419. * will be appended, otherwise the value will be applied directly.
  30420. */
  30421. goog.style.setHeight = function(element, height) {
  30422. element.style.height = goog.style.getPixelStyleValue_(height, true);
  30423. };
  30424. /**
  30425. * Set the width of an element. Sets the element's style property.
  30426. * @param {Element} element Element to set the width of.
  30427. * @param {string|number} width The width value to set. If a number, 'px'
  30428. * will be appended, otherwise the value will be applied directly.
  30429. */
  30430. goog.style.setWidth = function(element, width) {
  30431. element.style.width = goog.style.getPixelStyleValue_(width, true);
  30432. };
  30433. /**
  30434. * Gets the height and width of an element, even if its display is none.
  30435. *
  30436. * Specifically, this returns the height and width of the border box,
  30437. * irrespective of the box model in effect.
  30438. *
  30439. * Note that this function does not take CSS transforms into account. Please see
  30440. * {@code goog.style.getTransformedSize}.
  30441. * @param {Element} element Element to get size of.
  30442. * @return {!goog.math.Size} Object with width/height properties.
  30443. */
  30444. goog.style.getSize = function(element) {
  30445. return goog.style.evaluateWithTemporaryDisplay_(
  30446. goog.style.getSizeWithDisplay_, /** @type {!Element} */ (element));
  30447. };
  30448. /**
  30449. * Call {@code fn} on {@code element} such that {@code element}'s dimensions are
  30450. * accurate when it's passed to {@code fn}.
  30451. * @param {function(!Element): T} fn Function to call with {@code element} as
  30452. * an argument after temporarily changing {@code element}'s display such
  30453. * that its dimensions are accurate.
  30454. * @param {!Element} element Element (which may have display none) to use as
  30455. * argument to {@code fn}.
  30456. * @return {T} Value returned by calling {@code fn} with {@code element}.
  30457. * @template T
  30458. * @private
  30459. */
  30460. goog.style.evaluateWithTemporaryDisplay_ = function(fn, element) {
  30461. if (goog.style.getStyle_(element, 'display') != 'none') {
  30462. return fn(element);
  30463. }
  30464. var style = element.style;
  30465. var originalDisplay = style.display;
  30466. var originalVisibility = style.visibility;
  30467. var originalPosition = style.position;
  30468. style.visibility = 'hidden';
  30469. style.position = 'absolute';
  30470. style.display = 'inline';
  30471. var retVal = fn(element);
  30472. style.display = originalDisplay;
  30473. style.position = originalPosition;
  30474. style.visibility = originalVisibility;
  30475. return retVal;
  30476. };
  30477. /**
  30478. * Gets the height and width of an element when the display is not none.
  30479. * @param {Element} element Element to get size of.
  30480. * @return {!goog.math.Size} Object with width/height properties.
  30481. * @private
  30482. */
  30483. goog.style.getSizeWithDisplay_ = function(element) {
  30484. var offsetWidth = /** @type {!HTMLElement} */ (element).offsetWidth;
  30485. var offsetHeight = /** @type {!HTMLElement} */ (element).offsetHeight;
  30486. var webkitOffsetsZero =
  30487. goog.userAgent.WEBKIT && !offsetWidth && !offsetHeight;
  30488. if ((!goog.isDef(offsetWidth) || webkitOffsetsZero) &&
  30489. element.getBoundingClientRect) {
  30490. // Fall back to calling getBoundingClientRect when offsetWidth or
  30491. // offsetHeight are not defined, or when they are zero in WebKit browsers.
  30492. // This makes sure that we return for the correct size for SVG elements, but
  30493. // will still return 0 on Webkit prior to 534.8, see
  30494. // http://trac.webkit.org/changeset/67252.
  30495. var clientRect = goog.style.getBoundingClientRect_(element);
  30496. return new goog.math.Size(clientRect.right - clientRect.left,
  30497. clientRect.bottom - clientRect.top);
  30498. }
  30499. return new goog.math.Size(offsetWidth, offsetHeight);
  30500. };
  30501. /**
  30502. * Gets the height and width of an element, post transform, even if its display
  30503. * is none.
  30504. *
  30505. * This is like {@code goog.style.getSize}, except:
  30506. * <ol>
  30507. * <li>Takes webkitTransforms such as rotate and scale into account.
  30508. * <li>Will return null if {@code element} doesn't respond to
  30509. * {@code getBoundingClientRect}.
  30510. * <li>Currently doesn't make sense on non-WebKit browsers which don't support
  30511. * webkitTransforms.
  30512. * </ol>
  30513. * @param {!Element} element Element to get size of.
  30514. * @return {goog.math.Size} Object with width/height properties.
  30515. */
  30516. goog.style.getTransformedSize = function(element) {
  30517. if (!element.getBoundingClientRect) {
  30518. return null;
  30519. }
  30520. var clientRect = goog.style.evaluateWithTemporaryDisplay_(
  30521. goog.style.getBoundingClientRect_, element);
  30522. return new goog.math.Size(clientRect.right - clientRect.left,
  30523. clientRect.bottom - clientRect.top);
  30524. };
  30525. /**
  30526. * Returns a bounding rectangle for a given element in page space.
  30527. * @param {Element} element Element to get bounds of. Must not be display none.
  30528. * @return {!goog.math.Rect} Bounding rectangle for the element.
  30529. */
  30530. goog.style.getBounds = function(element) {
  30531. var o = goog.style.getPageOffset(element);
  30532. var s = goog.style.getSize(element);
  30533. return new goog.math.Rect(o.x, o.y, s.width, s.height);
  30534. };
  30535. /**
  30536. * Converts a CSS selector in the form style-property to styleProperty.
  30537. * @param {*} selector CSS Selector.
  30538. * @return {string} Camel case selector.
  30539. * @deprecated Use goog.string.toCamelCase instead.
  30540. */
  30541. goog.style.toCamelCase = function(selector) {
  30542. return goog.string.toCamelCase(String(selector));
  30543. };
  30544. /**
  30545. * Converts a CSS selector in the form styleProperty to style-property.
  30546. * @param {string} selector Camel case selector.
  30547. * @return {string} Selector cased.
  30548. * @deprecated Use goog.string.toSelectorCase instead.
  30549. */
  30550. goog.style.toSelectorCase = function(selector) {
  30551. return goog.string.toSelectorCase(selector);
  30552. };
  30553. /**
  30554. * Gets the opacity of a node (x-browser). This gets the inline style opacity
  30555. * of the node, and does not take into account the cascaded or the computed
  30556. * style for this node.
  30557. * @param {Element} el Element whose opacity has to be found.
  30558. * @return {number|string} Opacity between 0 and 1 or an empty string {@code ''}
  30559. * if the opacity is not set.
  30560. */
  30561. goog.style.getOpacity = function(el) {
  30562. var style = el.style;
  30563. var result = '';
  30564. if ('opacity' in style) {
  30565. result = style.opacity;
  30566. } else if ('MozOpacity' in style) {
  30567. result = style.MozOpacity;
  30568. } else if ('filter' in style) {
  30569. var match = style.filter.match(/alpha\(opacity=([\d.]+)\)/);
  30570. if (match) {
  30571. result = String(match[1] / 100);
  30572. }
  30573. }
  30574. return result == '' ? result : Number(result);
  30575. };
  30576. /**
  30577. * Sets the opacity of a node (x-browser).
  30578. * @param {Element} el Elements whose opacity has to be set.
  30579. * @param {number|string} alpha Opacity between 0 and 1 or an empty string
  30580. * {@code ''} to clear the opacity.
  30581. */
  30582. goog.style.setOpacity = function(el, alpha) {
  30583. var style = el.style;
  30584. if ('opacity' in style) {
  30585. style.opacity = alpha;
  30586. } else if ('MozOpacity' in style) {
  30587. style.MozOpacity = alpha;
  30588. } else if ('filter' in style) {
  30589. // TODO(arv): Overwriting the filter might have undesired side effects.
  30590. if (alpha === '') {
  30591. style.filter = '';
  30592. } else {
  30593. style.filter = 'alpha(opacity=' + alpha * 100 + ')';
  30594. }
  30595. }
  30596. };
  30597. /**
  30598. * Sets the background of an element to a transparent image in a browser-
  30599. * independent manner.
  30600. *
  30601. * This function does not support repeating backgrounds or alternate background
  30602. * positions to match the behavior of Internet Explorer. It also does not
  30603. * support sizingMethods other than crop since they cannot be replicated in
  30604. * browsers other than Internet Explorer.
  30605. *
  30606. * @param {Element} el The element to set background on.
  30607. * @param {string} src The image source URL.
  30608. */
  30609. goog.style.setTransparentBackgroundImage = function(el, src) {
  30610. var style = el.style;
  30611. // It is safe to use the style.filter in IE only. In Safari 'filter' is in
  30612. // style object but access to style.filter causes it to throw an exception.
  30613. // Note: IE8 supports images with an alpha channel.
  30614. if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) {
  30615. // See TODO in setOpacity.
  30616. style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(' +
  30617. 'src="' + src + '", sizingMethod="crop")';
  30618. } else {
  30619. // Set style properties individually instead of using background shorthand
  30620. // to prevent overwriting a pre-existing background color.
  30621. style.backgroundImage = 'url(' + src + ')';
  30622. style.backgroundPosition = 'top left';
  30623. style.backgroundRepeat = 'no-repeat';
  30624. }
  30625. };
  30626. /**
  30627. * Clears the background image of an element in a browser independent manner.
  30628. * @param {Element} el The element to clear background image for.
  30629. */
  30630. goog.style.clearTransparentBackgroundImage = function(el) {
  30631. var style = el.style;
  30632. if ('filter' in style) {
  30633. // See TODO in setOpacity.
  30634. style.filter = '';
  30635. } else {
  30636. // Set style properties individually instead of using background shorthand
  30637. // to prevent overwriting a pre-existing background color.
  30638. style.backgroundImage = 'none';
  30639. }
  30640. };
  30641. /**
  30642. * Shows or hides an element from the page. Hiding the element is done by
  30643. * setting the display property to "none", removing the element from the
  30644. * rendering hierarchy so it takes up no space. To show the element, the default
  30645. * inherited display property is restored (defined either in stylesheets or by
  30646. * the browser's default style rules.)
  30647. *
  30648. * Caveat 1: if the inherited display property for the element is set to "none"
  30649. * by the stylesheets, that is the property that will be restored by a call to
  30650. * showElement(), effectively toggling the display between "none" and "none".
  30651. *
  30652. * Caveat 2: if the element display style is set inline (by setting either
  30653. * element.style.display or a style attribute in the HTML), a call to
  30654. * showElement will clear that setting and defer to the inherited style in the
  30655. * stylesheet.
  30656. * @param {Element} el Element to show or hide.
  30657. * @param {*} display True to render the element in its default style,
  30658. * false to disable rendering the element.
  30659. * @deprecated Use goog.style.setElementShown instead.
  30660. */
  30661. goog.style.showElement = function(el, display) {
  30662. goog.style.setElementShown(el, display);
  30663. };
  30664. /**
  30665. * Shows or hides an element from the page. Hiding the element is done by
  30666. * setting the display property to "none", removing the element from the
  30667. * rendering hierarchy so it takes up no space. To show the element, the default
  30668. * inherited display property is restored (defined either in stylesheets or by
  30669. * the browser's default style rules).
  30670. *
  30671. * Caveat 1: if the inherited display property for the element is set to "none"
  30672. * by the stylesheets, that is the property that will be restored by a call to
  30673. * setElementShown(), effectively toggling the display between "none" and
  30674. * "none".
  30675. *
  30676. * Caveat 2: if the element display style is set inline (by setting either
  30677. * element.style.display or a style attribute in the HTML), a call to
  30678. * setElementShown will clear that setting and defer to the inherited style in
  30679. * the stylesheet.
  30680. * @param {Element} el Element to show or hide.
  30681. * @param {*} isShown True to render the element in its default style,
  30682. * false to disable rendering the element.
  30683. */
  30684. goog.style.setElementShown = function(el, isShown) {
  30685. el.style.display = isShown ? '' : 'none';
  30686. };
  30687. /**
  30688. * Test whether the given element has been shown or hidden via a call to
  30689. * {@link #setElementShown}.
  30690. *
  30691. * Note this is strictly a companion method for a call
  30692. * to {@link #setElementShown} and the same caveats apply; in particular, this
  30693. * method does not guarantee that the return value will be consistent with
  30694. * whether or not the element is actually visible.
  30695. *
  30696. * @param {Element} el The element to test.
  30697. * @return {boolean} Whether the element has been shown.
  30698. * @see #setElementShown
  30699. */
  30700. goog.style.isElementShown = function(el) {
  30701. return el.style.display != 'none';
  30702. };
  30703. /**
  30704. * Installs the styles string into the window that contains opt_element. If
  30705. * opt_element is null, the main window is used.
  30706. * @param {string} stylesString The style string to install.
  30707. * @param {Node=} opt_node Node whose parent document should have the
  30708. * styles installed.
  30709. * @return {Element|StyleSheet} The style element created.
  30710. */
  30711. goog.style.installStyles = function(stylesString, opt_node) {
  30712. var dh = goog.dom.getDomHelper(opt_node);
  30713. var styleSheet = null;
  30714. // IE < 11 requires createStyleSheet. Note that doc.createStyleSheet will be
  30715. // undefined as of IE 11.
  30716. var doc = dh.getDocument();
  30717. if (goog.userAgent.IE && doc.createStyleSheet) {
  30718. styleSheet = doc.createStyleSheet();
  30719. goog.style.setStyles(styleSheet, stylesString);
  30720. } else {
  30721. var head = dh.getElementsByTagNameAndClass(goog.dom.TagName.HEAD)[0];
  30722. // In opera documents are not guaranteed to have a head element, thus we
  30723. // have to make sure one exists before using it.
  30724. if (!head) {
  30725. var body = dh.getElementsByTagNameAndClass(goog.dom.TagName.BODY)[0];
  30726. head = dh.createDom(goog.dom.TagName.HEAD);
  30727. body.parentNode.insertBefore(head, body);
  30728. }
  30729. styleSheet = dh.createDom(goog.dom.TagName.STYLE);
  30730. // NOTE(user): Setting styles after the style element has been appended
  30731. // to the head results in a nasty Webkit bug in certain scenarios. Please
  30732. // refer to https://bugs.webkit.org/show_bug.cgi?id=26307 for additional
  30733. // details.
  30734. goog.style.setStyles(styleSheet, stylesString);
  30735. dh.appendChild(head, styleSheet);
  30736. }
  30737. return styleSheet;
  30738. };
  30739. /**
  30740. * Removes the styles added by {@link #installStyles}.
  30741. * @param {Element|StyleSheet} styleSheet The value returned by
  30742. * {@link #installStyles}.
  30743. */
  30744. goog.style.uninstallStyles = function(styleSheet) {
  30745. var node = styleSheet.ownerNode || styleSheet.owningElement ||
  30746. /** @type {Element} */ (styleSheet);
  30747. goog.dom.removeNode(node);
  30748. };
  30749. /**
  30750. * Sets the content of a style element. The style element can be any valid
  30751. * style element. This element will have its content completely replaced by
  30752. * the new stylesString.
  30753. * @param {Element|StyleSheet} element A stylesheet element as returned by
  30754. * installStyles.
  30755. * @param {string} stylesString The new content of the stylesheet.
  30756. */
  30757. goog.style.setStyles = function(element, stylesString) {
  30758. if (goog.userAgent.IE && goog.isDef(element.cssText)) {
  30759. // Adding the selectors individually caused the browser to hang if the
  30760. // selector was invalid or there were CSS comments. Setting the cssText of
  30761. // the style node works fine and ignores CSS that IE doesn't understand.
  30762. // However IE >= 11 doesn't support cssText any more, so we make sure that
  30763. // cssText is a defined property and otherwise fall back to innerHTML.
  30764. element.cssText = stylesString;
  30765. } else {
  30766. element.innerHTML = stylesString;
  30767. }
  30768. };
  30769. /**
  30770. * Sets 'white-space: pre-wrap' for a node (x-browser).
  30771. *
  30772. * There are as many ways of specifying pre-wrap as there are browsers.
  30773. *
  30774. * CSS3/IE8: white-space: pre-wrap;
  30775. * Mozilla: white-space: -moz-pre-wrap;
  30776. * Opera: white-space: -o-pre-wrap;
  30777. * IE6/7: white-space: pre; word-wrap: break-word;
  30778. *
  30779. * @param {Element} el Element to enable pre-wrap for.
  30780. */
  30781. goog.style.setPreWrap = function(el) {
  30782. var style = el.style;
  30783. if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) {
  30784. style.whiteSpace = 'pre';
  30785. style.wordWrap = 'break-word';
  30786. } else if (goog.userAgent.GECKO) {
  30787. style.whiteSpace = '-moz-pre-wrap';
  30788. } else {
  30789. style.whiteSpace = 'pre-wrap';
  30790. }
  30791. };
  30792. /**
  30793. * Sets 'display: inline-block' for an element (cross-browser).
  30794. * @param {Element} el Element to which the inline-block display style is to be
  30795. * applied.
  30796. * @see ../demos/inline_block_quirks.html
  30797. * @see ../demos/inline_block_standards.html
  30798. */
  30799. goog.style.setInlineBlock = function(el) {
  30800. var style = el.style;
  30801. // Without position:relative, weirdness ensues. Just accept it and move on.
  30802. style.position = 'relative';
  30803. if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('8')) {
  30804. // IE8 supports inline-block so fall through to the else
  30805. // Zoom:1 forces hasLayout, display:inline gives inline behavior.
  30806. style.zoom = '1';
  30807. style.display = 'inline';
  30808. } else {
  30809. // Opera, Webkit, and Safari seem to do OK with the standard inline-block
  30810. // style.
  30811. style.display = 'inline-block';
  30812. }
  30813. };
  30814. /**
  30815. * Returns true if the element is using right to left (rtl) direction.
  30816. * @param {Element} el The element to test.
  30817. * @return {boolean} True for right to left, false for left to right.
  30818. */
  30819. goog.style.isRightToLeft = function(el) {
  30820. return 'rtl' == goog.style.getStyle_(el, 'direction');
  30821. };
  30822. /**
  30823. * The CSS style property corresponding to an element being
  30824. * unselectable on the current browser platform (null if none).
  30825. * Opera and IE instead use a DOM attribute 'unselectable'.
  30826. * @type {?string}
  30827. * @private
  30828. */
  30829. goog.style.unselectableStyle_ =
  30830. goog.userAgent.GECKO ? 'MozUserSelect' :
  30831. goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
  30832. null;
  30833. /**
  30834. * Returns true if the element is set to be unselectable, false otherwise.
  30835. * Note that on some platforms (e.g. Mozilla), even if an element isn't set
  30836. * to be unselectable, it will behave as such if any of its ancestors is
  30837. * unselectable.
  30838. * @param {Element} el Element to check.
  30839. * @return {boolean} Whether the element is set to be unselectable.
  30840. */
  30841. goog.style.isUnselectable = function(el) {
  30842. if (goog.style.unselectableStyle_) {
  30843. return el.style[goog.style.unselectableStyle_].toLowerCase() == 'none';
  30844. } else if (goog.userAgent.IE || goog.userAgent.OPERA) {
  30845. return el.getAttribute('unselectable') == 'on';
  30846. }
  30847. return false;
  30848. };
  30849. /**
  30850. * Makes the element and its descendants selectable or unselectable. Note
  30851. * that on some platforms (e.g. Mozilla), even if an element isn't set to
  30852. * be unselectable, it will behave as such if any of its ancestors is
  30853. * unselectable.
  30854. * @param {Element} el The element to alter.
  30855. * @param {boolean} unselectable Whether the element and its descendants
  30856. * should be made unselectable.
  30857. * @param {boolean=} opt_noRecurse Whether to only alter the element's own
  30858. * selectable state, and leave its descendants alone; defaults to false.
  30859. */
  30860. goog.style.setUnselectable = function(el, unselectable, opt_noRecurse) {
  30861. // TODO(attila): Do we need all of TR_DomUtil.makeUnselectable() in Closure?
  30862. var descendants = !opt_noRecurse ? el.getElementsByTagName('*') : null;
  30863. var name = goog.style.unselectableStyle_;
  30864. if (name) {
  30865. // Add/remove the appropriate CSS style to/from the element and its
  30866. // descendants.
  30867. var value = unselectable ? 'none' : '';
  30868. // MathML elements do not have a style property. Verify before setting.
  30869. if (el.style) {
  30870. el.style[name] = value;
  30871. }
  30872. if (descendants) {
  30873. for (var i = 0, descendant; descendant = descendants[i]; i++) {
  30874. if (descendant.style) {
  30875. descendant.style[name] = value;
  30876. }
  30877. }
  30878. }
  30879. } else if (goog.userAgent.IE || goog.userAgent.OPERA) {
  30880. // Toggle the 'unselectable' attribute on the element and its descendants.
  30881. var value = unselectable ? 'on' : '';
  30882. el.setAttribute('unselectable', value);
  30883. if (descendants) {
  30884. for (var i = 0, descendant; descendant = descendants[i]; i++) {
  30885. descendant.setAttribute('unselectable', value);
  30886. }
  30887. }
  30888. }
  30889. };
  30890. /**
  30891. * Gets the border box size for an element.
  30892. * @param {Element} element The element to get the size for.
  30893. * @return {!goog.math.Size} The border box size.
  30894. */
  30895. goog.style.getBorderBoxSize = function(element) {
  30896. return new goog.math.Size(
  30897. /** @type {!HTMLElement} */ (element).offsetWidth,
  30898. /** @type {!HTMLElement} */ (element).offsetHeight);
  30899. };
  30900. /**
  30901. * Sets the border box size of an element. This is potentially expensive in IE
  30902. * if the document is CSS1Compat mode
  30903. * @param {Element} element The element to set the size on.
  30904. * @param {goog.math.Size} size The new size.
  30905. */
  30906. goog.style.setBorderBoxSize = function(element, size) {
  30907. var doc = goog.dom.getOwnerDocument(element);
  30908. var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode();
  30909. if (goog.userAgent.IE &&
  30910. !goog.userAgent.isVersionOrHigher('10') &&
  30911. (!isCss1CompatMode || !goog.userAgent.isVersionOrHigher('8'))) {
  30912. var style = element.style;
  30913. if (isCss1CompatMode) {
  30914. var paddingBox = goog.style.getPaddingBox(element);
  30915. var borderBox = goog.style.getBorderBox(element);
  30916. style.pixelWidth = size.width - borderBox.left - paddingBox.left -
  30917. paddingBox.right - borderBox.right;
  30918. style.pixelHeight = size.height - borderBox.top - paddingBox.top -
  30919. paddingBox.bottom - borderBox.bottom;
  30920. } else {
  30921. style.pixelWidth = size.width;
  30922. style.pixelHeight = size.height;
  30923. }
  30924. } else {
  30925. goog.style.setBoxSizingSize_(element, size, 'border-box');
  30926. }
  30927. };
  30928. /**
  30929. * Gets the content box size for an element. This is potentially expensive in
  30930. * all browsers.
  30931. * @param {Element} element The element to get the size for.
  30932. * @return {!goog.math.Size} The content box size.
  30933. */
  30934. goog.style.getContentBoxSize = function(element) {
  30935. var doc = goog.dom.getOwnerDocument(element);
  30936. var ieCurrentStyle = goog.userAgent.IE && element.currentStyle;
  30937. if (ieCurrentStyle &&
  30938. goog.dom.getDomHelper(doc).isCss1CompatMode() &&
  30939. ieCurrentStyle.width != 'auto' && ieCurrentStyle.height != 'auto' &&
  30940. !ieCurrentStyle.boxSizing) {
  30941. // If IE in CSS1Compat mode than just use the width and height.
  30942. // If we have a boxSizing then fall back on measuring the borders etc.
  30943. var width = goog.style.getIePixelValue_(element, ieCurrentStyle.width,
  30944. 'width', 'pixelWidth');
  30945. var height = goog.style.getIePixelValue_(element, ieCurrentStyle.height,
  30946. 'height', 'pixelHeight');
  30947. return new goog.math.Size(width, height);
  30948. } else {
  30949. var borderBoxSize = goog.style.getBorderBoxSize(element);
  30950. var paddingBox = goog.style.getPaddingBox(element);
  30951. var borderBox = goog.style.getBorderBox(element);
  30952. return new goog.math.Size(borderBoxSize.width -
  30953. borderBox.left - paddingBox.left -
  30954. paddingBox.right - borderBox.right,
  30955. borderBoxSize.height -
  30956. borderBox.top - paddingBox.top -
  30957. paddingBox.bottom - borderBox.bottom);
  30958. }
  30959. };
  30960. /**
  30961. * Sets the content box size of an element. This is potentially expensive in IE
  30962. * if the document is BackCompat mode.
  30963. * @param {Element} element The element to set the size on.
  30964. * @param {goog.math.Size} size The new size.
  30965. */
  30966. goog.style.setContentBoxSize = function(element, size) {
  30967. var doc = goog.dom.getOwnerDocument(element);
  30968. var isCss1CompatMode = goog.dom.getDomHelper(doc).isCss1CompatMode();
  30969. if (goog.userAgent.IE &&
  30970. !goog.userAgent.isVersionOrHigher('10') &&
  30971. (!isCss1CompatMode || !goog.userAgent.isVersionOrHigher('8'))) {
  30972. var style = element.style;
  30973. if (isCss1CompatMode) {
  30974. style.pixelWidth = size.width;
  30975. style.pixelHeight = size.height;
  30976. } else {
  30977. var paddingBox = goog.style.getPaddingBox(element);
  30978. var borderBox = goog.style.getBorderBox(element);
  30979. style.pixelWidth = size.width + borderBox.left + paddingBox.left +
  30980. paddingBox.right + borderBox.right;
  30981. style.pixelHeight = size.height + borderBox.top + paddingBox.top +
  30982. paddingBox.bottom + borderBox.bottom;
  30983. }
  30984. } else {
  30985. goog.style.setBoxSizingSize_(element, size, 'content-box');
  30986. }
  30987. };
  30988. /**
  30989. * Helper function that sets the box sizing as well as the width and height
  30990. * @param {Element} element The element to set the size on.
  30991. * @param {goog.math.Size} size The new size to set.
  30992. * @param {string} boxSizing The box-sizing value.
  30993. * @private
  30994. */
  30995. goog.style.setBoxSizingSize_ = function(element, size, boxSizing) {
  30996. var style = element.style;
  30997. if (goog.userAgent.GECKO) {
  30998. style.MozBoxSizing = boxSizing;
  30999. } else if (goog.userAgent.WEBKIT) {
  31000. style.WebkitBoxSizing = boxSizing;
  31001. } else {
  31002. // Includes IE8 and Opera 9.50+
  31003. style.boxSizing = boxSizing;
  31004. }
  31005. // Setting this to a negative value will throw an exception on IE
  31006. // (and doesn't do anything different than setting it to 0).
  31007. style.width = Math.max(size.width, 0) + 'px';
  31008. style.height = Math.max(size.height, 0) + 'px';
  31009. };
  31010. /**
  31011. * IE specific function that converts a non pixel unit to pixels.
  31012. * @param {Element} element The element to convert the value for.
  31013. * @param {string} value The current value as a string. The value must not be
  31014. * ''.
  31015. * @param {string} name The CSS property name to use for the converstion. This
  31016. * should be 'left', 'top', 'width' or 'height'.
  31017. * @param {string} pixelName The CSS pixel property name to use to get the
  31018. * value in pixels.
  31019. * @return {number} The value in pixels.
  31020. * @private
  31021. */
  31022. goog.style.getIePixelValue_ = function(element, value, name, pixelName) {
  31023. // Try if we already have a pixel value. IE does not do half pixels so we
  31024. // only check if it matches a number followed by 'px'.
  31025. if (/^\d+px?$/.test(value)) {
  31026. return parseInt(value, 10);
  31027. } else {
  31028. var oldStyleValue = element.style[name];
  31029. var oldRuntimeValue = element.runtimeStyle[name];
  31030. // set runtime style to prevent changes
  31031. element.runtimeStyle[name] = element.currentStyle[name];
  31032. element.style[name] = value;
  31033. var pixelValue = element.style[pixelName];
  31034. // restore
  31035. element.style[name] = oldStyleValue;
  31036. element.runtimeStyle[name] = oldRuntimeValue;
  31037. return pixelValue;
  31038. }
  31039. };
  31040. /**
  31041. * Helper function for getting the pixel padding or margin for IE.
  31042. * @param {Element} element The element to get the padding for.
  31043. * @param {string} propName The property name.
  31044. * @return {number} The pixel padding.
  31045. * @private
  31046. */
  31047. goog.style.getIePixelDistance_ = function(element, propName) {
  31048. var value = goog.style.getCascadedStyle(element, propName);
  31049. return value ?
  31050. goog.style.getIePixelValue_(element, value, 'left', 'pixelLeft') : 0;
  31051. };
  31052. /**
  31053. * Gets the computed paddings or margins (on all sides) in pixels.
  31054. * @param {Element} element The element to get the padding for.
  31055. * @param {string} stylePrefix Pass 'padding' to retrieve the padding box,
  31056. * or 'margin' to retrieve the margin box.
  31057. * @return {!goog.math.Box} The computed paddings or margins.
  31058. * @private
  31059. */
  31060. goog.style.getBox_ = function(element, stylePrefix) {
  31061. if (goog.userAgent.IE) {
  31062. var left = goog.style.getIePixelDistance_(element, stylePrefix + 'Left');
  31063. var right = goog.style.getIePixelDistance_(element, stylePrefix + 'Right');
  31064. var top = goog.style.getIePixelDistance_(element, stylePrefix + 'Top');
  31065. var bottom = goog.style.getIePixelDistance_(
  31066. element, stylePrefix + 'Bottom');
  31067. return new goog.math.Box(top, right, bottom, left);
  31068. } else {
  31069. // On non-IE browsers, getComputedStyle is always non-null.
  31070. var left = goog.style.getComputedStyle(element, stylePrefix + 'Left');
  31071. var right = goog.style.getComputedStyle(element, stylePrefix + 'Right');
  31072. var top = goog.style.getComputedStyle(element, stylePrefix + 'Top');
  31073. var bottom = goog.style.getComputedStyle(element, stylePrefix + 'Bottom');
  31074. // NOTE(arv): Gecko can return floating point numbers for the computed
  31075. // style values.
  31076. return new goog.math.Box(parseFloat(top),
  31077. parseFloat(right),
  31078. parseFloat(bottom),
  31079. parseFloat(left));
  31080. }
  31081. };
  31082. /**
  31083. * Gets the computed paddings (on all sides) in pixels.
  31084. * @param {Element} element The element to get the padding for.
  31085. * @return {!goog.math.Box} The computed paddings.
  31086. */
  31087. goog.style.getPaddingBox = function(element) {
  31088. return goog.style.getBox_(element, 'padding');
  31089. };
  31090. /**
  31091. * Gets the computed margins (on all sides) in pixels.
  31092. * @param {Element} element The element to get the margins for.
  31093. * @return {!goog.math.Box} The computed margins.
  31094. */
  31095. goog.style.getMarginBox = function(element) {
  31096. return goog.style.getBox_(element, 'margin');
  31097. };
  31098. /**
  31099. * A map used to map the border width keywords to a pixel width.
  31100. * @type {Object}
  31101. * @private
  31102. */
  31103. goog.style.ieBorderWidthKeywords_ = {
  31104. 'thin': 2,
  31105. 'medium': 4,
  31106. 'thick': 6
  31107. };
  31108. /**
  31109. * Helper function for IE to get the pixel border.
  31110. * @param {Element} element The element to get the pixel border for.
  31111. * @param {string} prop The part of the property name.
  31112. * @return {number} The value in pixels.
  31113. * @private
  31114. */
  31115. goog.style.getIePixelBorder_ = function(element, prop) {
  31116. if (goog.style.getCascadedStyle(element, prop + 'Style') == 'none') {
  31117. return 0;
  31118. }
  31119. var width = goog.style.getCascadedStyle(element, prop + 'Width');
  31120. if (width in goog.style.ieBorderWidthKeywords_) {
  31121. return goog.style.ieBorderWidthKeywords_[width];
  31122. }
  31123. return goog.style.getIePixelValue_(element, width, 'left', 'pixelLeft');
  31124. };
  31125. /**
  31126. * Gets the computed border widths (on all sides) in pixels
  31127. * @param {Element} element The element to get the border widths for.
  31128. * @return {!goog.math.Box} The computed border widths.
  31129. */
  31130. goog.style.getBorderBox = function(element) {
  31131. if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {
  31132. var left = goog.style.getIePixelBorder_(element, 'borderLeft');
  31133. var right = goog.style.getIePixelBorder_(element, 'borderRight');
  31134. var top = goog.style.getIePixelBorder_(element, 'borderTop');
  31135. var bottom = goog.style.getIePixelBorder_(element, 'borderBottom');
  31136. return new goog.math.Box(top, right, bottom, left);
  31137. } else {
  31138. // On non-IE browsers, getComputedStyle is always non-null.
  31139. var left = goog.style.getComputedStyle(element, 'borderLeftWidth');
  31140. var right = goog.style.getComputedStyle(element, 'borderRightWidth');
  31141. var top = goog.style.getComputedStyle(element, 'borderTopWidth');
  31142. var bottom = goog.style.getComputedStyle(element, 'borderBottomWidth');
  31143. return new goog.math.Box(parseFloat(top),
  31144. parseFloat(right),
  31145. parseFloat(bottom),
  31146. parseFloat(left));
  31147. }
  31148. };
  31149. /**
  31150. * Returns the font face applied to a given node. Opera and IE should return
  31151. * the font actually displayed. Firefox returns the author's most-preferred
  31152. * font (whether the browser is capable of displaying it or not.)
  31153. * @param {Element} el The element whose font family is returned.
  31154. * @return {string} The font family applied to el.
  31155. */
  31156. goog.style.getFontFamily = function(el) {
  31157. var doc = goog.dom.getOwnerDocument(el);
  31158. var font = '';
  31159. // The moveToElementText method from the TextRange only works if the element
  31160. // is attached to the owner document.
  31161. if (doc.body.createTextRange && goog.dom.contains(doc, el)) {
  31162. var range = doc.body.createTextRange();
  31163. range.moveToElementText(el);
  31164. /** @preserveTry */
  31165. try {
  31166. font = range.queryCommandValue('FontName');
  31167. } catch (e) {
  31168. // This is a workaround for a awkward exception.
  31169. // On some IE, there is an exception coming from it.
  31170. // The error description from this exception is:
  31171. // This window has already been registered as a drop target
  31172. // This is bogus description, likely due to a bug in ie.
  31173. font = '';
  31174. }
  31175. }
  31176. if (!font) {
  31177. // Note if for some reason IE can't derive FontName with a TextRange, we
  31178. // fallback to using currentStyle
  31179. font = goog.style.getStyle_(el, 'fontFamily');
  31180. }
  31181. // Firefox returns the applied font-family string (author's list of
  31182. // preferred fonts.) We want to return the most-preferred font, in lieu of
  31183. // the *actually* applied font.
  31184. var fontsArray = font.split(',');
  31185. if (fontsArray.length > 1) font = fontsArray[0];
  31186. // Sanitize for x-browser consistency:
  31187. // Strip quotes because browsers aren't consistent with how they're
  31188. // applied; Opera always encloses, Firefox sometimes, and IE never.
  31189. return goog.string.stripQuotes(font, '"\'');
  31190. };
  31191. /**
  31192. * Regular expression used for getLengthUnits.
  31193. * @type {RegExp}
  31194. * @private
  31195. */
  31196. goog.style.lengthUnitRegex_ = /[^\d]+$/;
  31197. /**
  31198. * Returns the units used for a CSS length measurement.
  31199. * @param {string} value A CSS length quantity.
  31200. * @return {?string} The units of measurement.
  31201. */
  31202. goog.style.getLengthUnits = function(value) {
  31203. var units = value.match(goog.style.lengthUnitRegex_);
  31204. return units && units[0] || null;
  31205. };
  31206. /**
  31207. * Map of absolute CSS length units
  31208. * @type {Object}
  31209. * @private
  31210. */
  31211. goog.style.ABSOLUTE_CSS_LENGTH_UNITS_ = {
  31212. 'cm' : 1,
  31213. 'in' : 1,
  31214. 'mm' : 1,
  31215. 'pc' : 1,
  31216. 'pt' : 1
  31217. };
  31218. /**
  31219. * Map of relative CSS length units that can be accurately converted to px
  31220. * font-size values using getIePixelValue_. Only units that are defined in
  31221. * relation to a font size are convertible (%, small, etc. are not).
  31222. * @type {Object}
  31223. * @private
  31224. */
  31225. goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_ = {
  31226. 'em' : 1,
  31227. 'ex' : 1
  31228. };
  31229. /**
  31230. * Returns the font size, in pixels, of text in an element.
  31231. * @param {Element} el The element whose font size is returned.
  31232. * @return {number} The font size (in pixels).
  31233. */
  31234. goog.style.getFontSize = function(el) {
  31235. var fontSize = goog.style.getStyle_(el, 'fontSize');
  31236. var sizeUnits = goog.style.getLengthUnits(fontSize);
  31237. if (fontSize && 'px' == sizeUnits) {
  31238. // NOTE(user): This could be parseFloat instead, but IE doesn't return
  31239. // decimal fractions in getStyle_ and Firefox reports the fractions, but
  31240. // ignores them when rendering. Interestingly enough, when we force the
  31241. // issue and size something to e.g., 50% of 25px, the browsers round in
  31242. // opposite directions with Firefox reporting 12px and IE 13px. I punt.
  31243. return parseInt(fontSize, 10);
  31244. }
  31245. // In IE, we can convert absolute length units to a px value using
  31246. // goog.style.getIePixelValue_. Units defined in relation to a font size
  31247. // (em, ex) are applied relative to the element's parentNode and can also
  31248. // be converted.
  31249. if (goog.userAgent.IE) {
  31250. if (sizeUnits in goog.style.ABSOLUTE_CSS_LENGTH_UNITS_) {
  31251. return goog.style.getIePixelValue_(el,
  31252. fontSize,
  31253. 'left',
  31254. 'pixelLeft');
  31255. } else if (el.parentNode &&
  31256. el.parentNode.nodeType == goog.dom.NodeType.ELEMENT &&
  31257. sizeUnits in goog.style.CONVERTIBLE_RELATIVE_CSS_UNITS_) {
  31258. // Check the parent size - if it is the same it means the relative size
  31259. // value is inherited and we therefore don't want to count it twice. If
  31260. // it is different, this element either has explicit style or has a CSS
  31261. // rule applying to it.
  31262. var parentElement = /** @type {!Element} */ (el.parentNode);
  31263. var parentSize = goog.style.getStyle_(parentElement, 'fontSize');
  31264. return goog.style.getIePixelValue_(parentElement,
  31265. fontSize == parentSize ?
  31266. '1em' : fontSize,
  31267. 'left',
  31268. 'pixelLeft');
  31269. }
  31270. }
  31271. // Sometimes we can't cleanly find the font size (some units relative to a
  31272. // node's parent's font size are difficult: %, smaller et al), so we create
  31273. // an invisible, absolutely-positioned span sized to be the height of an 'M'
  31274. // rendered in its parent's (i.e., our target element's) font size. This is
  31275. // the definition of CSS's font size attribute.
  31276. var sizeElement = goog.dom.createDom(
  31277. goog.dom.TagName.SPAN,
  31278. {'style': 'visibility:hidden;position:absolute;' +
  31279. 'line-height:0;padding:0;margin:0;border:0;height:1em;'});
  31280. goog.dom.appendChild(el, sizeElement);
  31281. fontSize = sizeElement.offsetHeight;
  31282. goog.dom.removeNode(sizeElement);
  31283. return fontSize;
  31284. };
  31285. /**
  31286. * Parses a style attribute value. Converts CSS property names to camel case.
  31287. * @param {string} value The style attribute value.
  31288. * @return {!Object} Map of CSS properties to string values.
  31289. */
  31290. goog.style.parseStyleAttribute = function(value) {
  31291. var result = {};
  31292. goog.array.forEach(value.split(/\s*;\s*/), function(pair) {
  31293. var keyValue = pair.match(/\s*([\w-]+)\s*\:(.+)/);
  31294. if (keyValue) {
  31295. var styleName = keyValue[1];
  31296. var styleValue = goog.string.trim(keyValue[2]);
  31297. result[goog.string.toCamelCase(styleName.toLowerCase())] = styleValue;
  31298. }
  31299. });
  31300. return result;
  31301. };
  31302. /**
  31303. * Reverse of parseStyleAttribute; that is, takes a style object and returns the
  31304. * corresponding attribute value. Converts camel case property names to proper
  31305. * CSS selector names.
  31306. * @param {Object} obj Map of CSS properties to values.
  31307. * @return {string} The style attribute value.
  31308. */
  31309. goog.style.toStyleAttribute = function(obj) {
  31310. var buffer = [];
  31311. goog.object.forEach(obj, function(value, key) {
  31312. buffer.push(goog.string.toSelectorCase(key), ':', value, ';');
  31313. });
  31314. return buffer.join('');
  31315. };
  31316. /**
  31317. * Sets CSS float property on an element.
  31318. * @param {Element} el The element to set float property on.
  31319. * @param {string} value The value of float CSS property to set on this element.
  31320. */
  31321. goog.style.setFloat = function(el, value) {
  31322. el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] = value;
  31323. };
  31324. /**
  31325. * Gets value of explicitly-set float CSS property on an element.
  31326. * @param {Element} el The element to get float property of.
  31327. * @return {string} The value of explicitly-set float CSS property on this
  31328. * element.
  31329. */
  31330. goog.style.getFloat = function(el) {
  31331. return el.style[goog.userAgent.IE ? 'styleFloat' : 'cssFloat'] || '';
  31332. };
  31333. /**
  31334. * Returns the scroll bar width (represents the width of both horizontal
  31335. * and vertical scroll).
  31336. *
  31337. * @param {string=} opt_className An optional class name (or names) to apply
  31338. * to the invisible div created to measure the scrollbar. This is necessary
  31339. * if some scrollbars are styled differently than others.
  31340. * @return {number} The scroll bar width in px.
  31341. */
  31342. goog.style.getScrollbarWidth = function(opt_className) {
  31343. // Add two hidden divs. The child div is larger than the parent and
  31344. // forces scrollbars to appear on it.
  31345. // Using overflow:scroll does not work consistently with scrollbars that
  31346. // are styled with ::-webkit-scrollbar.
  31347. var outerDiv = goog.dom.createElement(goog.dom.TagName.DIV);
  31348. if (opt_className) {
  31349. outerDiv.className = opt_className;
  31350. }
  31351. outerDiv.style.cssText = 'overflow:auto;' +
  31352. 'position:absolute;top:0;width:100px;height:100px';
  31353. var innerDiv = goog.dom.createElement(goog.dom.TagName.DIV);
  31354. goog.style.setSize(innerDiv, '200px', '200px');
  31355. outerDiv.appendChild(innerDiv);
  31356. goog.dom.appendChild(goog.dom.getDocument().body, outerDiv);
  31357. var width = outerDiv.offsetWidth - outerDiv.clientWidth;
  31358. goog.dom.removeNode(outerDiv);
  31359. return width;
  31360. };
  31361. /**
  31362. * Regular expression to extract x and y translation components from a CSS
  31363. * transform Matrix representation.
  31364. *
  31365. * @type {!RegExp}
  31366. * @const
  31367. * @private
  31368. */
  31369. goog.style.MATRIX_TRANSLATION_REGEX_ =
  31370. new RegExp('matrix\\([0-9\\.\\-]+, [0-9\\.\\-]+, ' +
  31371. '[0-9\\.\\-]+, [0-9\\.\\-]+, ' +
  31372. '([0-9\\.\\-]+)p?x?, ([0-9\\.\\-]+)p?x?\\)');
  31373. /**
  31374. * Returns the x,y translation component of any CSS transforms applied to the
  31375. * element, in pixels.
  31376. *
  31377. * @param {!Element} element The element to get the translation of.
  31378. * @return {!goog.math.Coordinate} The CSS translation of the element in px.
  31379. */
  31380. goog.style.getCssTranslation = function(element) {
  31381. var transform = goog.style.getComputedTransform(element);
  31382. if (!transform) {
  31383. return new goog.math.Coordinate(0, 0);
  31384. }
  31385. var matches = transform.match(goog.style.MATRIX_TRANSLATION_REGEX_);
  31386. if (!matches) {
  31387. return new goog.math.Coordinate(0, 0);
  31388. }
  31389. return new goog.math.Coordinate(parseFloat(matches[1]),
  31390. parseFloat(matches[2]));
  31391. };
  31392. goog.provide('ol.MapEvent');
  31393. goog.provide('ol.MapEventType');
  31394. goog.require('goog.events.Event');
  31395. /**
  31396. * @enum {string}
  31397. */
  31398. ol.MapEventType = {
  31399. /**
  31400. * Triggered after a map frame is rendered.
  31401. * @event ol.MapEvent#postrender
  31402. * @api
  31403. */
  31404. POSTRENDER: 'postrender',
  31405. /**
  31406. * Triggered after the map is moved.
  31407. * @event ol.MapEvent#moveend
  31408. * @api stable
  31409. */
  31410. MOVEEND: 'moveend'
  31411. };
  31412. /**
  31413. * @classdesc
  31414. * Events emitted as map events are instances of this type.
  31415. * See {@link ol.Map} for which events trigger a map event.
  31416. *
  31417. * @constructor
  31418. * @extends {goog.events.Event}
  31419. * @implements {oli.MapEvent}
  31420. * @param {string} type Event type.
  31421. * @param {ol.Map} map Map.
  31422. * @param {?olx.FrameState=} opt_frameState Frame state.
  31423. */
  31424. ol.MapEvent = function(type, map, opt_frameState) {
  31425. goog.base(this, type);
  31426. /**
  31427. * The map where the event occurred.
  31428. * @type {ol.Map}
  31429. * @api stable
  31430. */
  31431. this.map = map;
  31432. /**
  31433. * The frame state at the time of the event.
  31434. * @type {?olx.FrameState}
  31435. * @api
  31436. */
  31437. this.frameState = opt_frameState !== undefined ? opt_frameState : null;
  31438. };
  31439. goog.inherits(ol.MapEvent, goog.events.Event);
  31440. goog.provide('ol.control.Control');
  31441. goog.require('goog.dom');
  31442. goog.require('goog.events');
  31443. goog.require('ol');
  31444. goog.require('ol.MapEventType');
  31445. goog.require('ol.Object');
  31446. /**
  31447. * @classdesc
  31448. * A control is a visible widget with a DOM element in a fixed position on the
  31449. * screen. They can involve user input (buttons), or be informational only;
  31450. * the position is determined using CSS. By default these are placed in the
  31451. * container with CSS class name `ol-overlaycontainer-stopevent`, but can use
  31452. * any outside DOM element.
  31453. *
  31454. * This is the base class for controls. You can use it for simple custom
  31455. * controls by creating the element with listeners, creating an instance:
  31456. * ```js
  31457. * var myControl = new ol.control.Control({element: myElement});
  31458. * ```
  31459. * and then adding this to the map.
  31460. *
  31461. * The main advantage of having this as a control rather than a simple separate
  31462. * DOM element is that preventing propagation is handled for you. Controls
  31463. * will also be `ol.Object`s in a `ol.Collection`, so you can use their
  31464. * methods.
  31465. *
  31466. * You can also extend this base for your own control class. See
  31467. * examples/custom-controls for an example of how to do this.
  31468. *
  31469. * @constructor
  31470. * @extends {ol.Object}
  31471. * @implements {oli.control.Control}
  31472. * @param {olx.control.ControlOptions} options Control options.
  31473. * @api stable
  31474. */
  31475. ol.control.Control = function(options) {
  31476. goog.base(this);
  31477. /**
  31478. * @protected
  31479. * @type {Element}
  31480. */
  31481. this.element = options.element ? options.element : null;
  31482. /**
  31483. * @private
  31484. * @type {Element}
  31485. */
  31486. this.target_ = null;
  31487. /**
  31488. * @private
  31489. * @type {ol.Map}
  31490. */
  31491. this.map_ = null;
  31492. /**
  31493. * @protected
  31494. * @type {!Array.<?number>}
  31495. */
  31496. this.listenerKeys = [];
  31497. /**
  31498. * @type {function(ol.MapEvent)}
  31499. */
  31500. this.render = options.render ? options.render : ol.nullFunction;
  31501. if (options.target) {
  31502. this.setTarget(options.target);
  31503. }
  31504. };
  31505. goog.inherits(ol.control.Control, ol.Object);
  31506. /**
  31507. * @inheritDoc
  31508. */
  31509. ol.control.Control.prototype.disposeInternal = function() {
  31510. goog.dom.removeNode(this.element);
  31511. goog.base(this, 'disposeInternal');
  31512. };
  31513. /**
  31514. * Get the map associated with this control.
  31515. * @return {ol.Map} Map.
  31516. * @api stable
  31517. */
  31518. ol.control.Control.prototype.getMap = function() {
  31519. return this.map_;
  31520. };
  31521. /**
  31522. * Remove the control from its current map and attach it to the new map.
  31523. * Subclasses may set up event handlers to get notified about changes to
  31524. * the map here.
  31525. * @param {ol.Map} map Map.
  31526. * @api stable
  31527. */
  31528. ol.control.Control.prototype.setMap = function(map) {
  31529. if (this.map_) {
  31530. goog.dom.removeNode(this.element);
  31531. }
  31532. if (this.listenerKeys.length > 0) {
  31533. this.listenerKeys.forEach(goog.events.unlistenByKey);
  31534. this.listenerKeys.length = 0;
  31535. }
  31536. this.map_ = map;
  31537. if (this.map_) {
  31538. var target = this.target_ ?
  31539. this.target_ : map.getOverlayContainerStopEvent();
  31540. target.appendChild(this.element);
  31541. if (this.render !== ol.nullFunction) {
  31542. this.listenerKeys.push(goog.events.listen(map,
  31543. ol.MapEventType.POSTRENDER, this.render, false, this));
  31544. }
  31545. map.render();
  31546. }
  31547. };
  31548. /**
  31549. * This function is used to set a target element for the control. It has no
  31550. * effect if it is called after the control has been added to the map (i.e.
  31551. * after `setMap` is called on the control). If no `target` is set in the
  31552. * options passed to the control constructor and if `setTarget` is not called
  31553. * then the control is added to the map's overlay container.
  31554. * @param {Element|string} target Target.
  31555. * @api
  31556. */
  31557. ol.control.Control.prototype.setTarget = function(target) {
  31558. this.target_ = goog.dom.getElement(target);
  31559. };
  31560. goog.provide('ol.css');
  31561. /**
  31562. * The CSS class for hidden feature.
  31563. *
  31564. * @const
  31565. * @type {string}
  31566. */
  31567. ol.css.CLASS_HIDDEN = 'ol-hidden';
  31568. /**
  31569. * The CSS class that we'll give the DOM elements to have them unselectable.
  31570. *
  31571. * @const
  31572. * @type {string}
  31573. */
  31574. ol.css.CLASS_UNSELECTABLE = 'ol-unselectable';
  31575. /**
  31576. * The CSS class for unsupported feature.
  31577. *
  31578. * @const
  31579. * @type {string}
  31580. */
  31581. ol.css.CLASS_UNSUPPORTED = 'ol-unsupported';
  31582. /**
  31583. * The CSS class for controls.
  31584. *
  31585. * @const
  31586. * @type {string}
  31587. */
  31588. ol.css.CLASS_CONTROL = 'ol-control';
  31589. goog.provide('ol.structs.LRUCache');
  31590. goog.require('goog.asserts');
  31591. goog.require('goog.object');
  31592. /**
  31593. * Implements a Least-Recently-Used cache where the keys do not conflict with
  31594. * Object's properties (e.g. 'hasOwnProperty' is not allowed as a key). Expiring
  31595. * items from the cache is the responsibility of the user.
  31596. * @constructor
  31597. * @struct
  31598. * @template T
  31599. */
  31600. ol.structs.LRUCache = function() {
  31601. /**
  31602. * @private
  31603. * @type {number}
  31604. */
  31605. this.count_ = 0;
  31606. /**
  31607. * @private
  31608. * @type {Object.<string, ol.structs.LRUCacheEntry>}
  31609. */
  31610. this.entries_ = {};
  31611. /**
  31612. * @private
  31613. * @type {?ol.structs.LRUCacheEntry}
  31614. */
  31615. this.oldest_ = null;
  31616. /**
  31617. * @private
  31618. * @type {?ol.structs.LRUCacheEntry}
  31619. */
  31620. this.newest_ = null;
  31621. };
  31622. /**
  31623. * FIXME empty description for jsdoc
  31624. */
  31625. ol.structs.LRUCache.prototype.assertValid = function() {
  31626. if (this.count_ === 0) {
  31627. goog.asserts.assert(goog.object.isEmpty(this.entries_),
  31628. 'entries must be an empty object (count = 0)');
  31629. goog.asserts.assert(!this.oldest_,
  31630. 'oldest must be null (count = 0)');
  31631. goog.asserts.assert(!this.newest_,
  31632. 'newest must be null (count = 0)');
  31633. } else {
  31634. goog.asserts.assert(goog.object.getCount(this.entries_) == this.count_,
  31635. 'number of entries matches count');
  31636. goog.asserts.assert(this.oldest_,
  31637. 'we have an oldest entry');
  31638. goog.asserts.assert(!this.oldest_.older,
  31639. 'no entry is older than oldest');
  31640. goog.asserts.assert(this.newest_,
  31641. 'we have a newest entry');
  31642. goog.asserts.assert(!this.newest_.newer,
  31643. 'no entry is newer than newest');
  31644. var i, entry;
  31645. var older = null;
  31646. i = 0;
  31647. for (entry = this.oldest_; entry; entry = entry.newer) {
  31648. goog.asserts.assert(entry.older === older,
  31649. 'entry.older links to correct older');
  31650. older = entry;
  31651. ++i;
  31652. }
  31653. goog.asserts.assert(i == this.count_, 'iterated correct amount of times');
  31654. var newer = null;
  31655. i = 0;
  31656. for (entry = this.newest_; entry; entry = entry.older) {
  31657. goog.asserts.assert(entry.newer === newer,
  31658. 'entry.newer links to correct newer');
  31659. newer = entry;
  31660. ++i;
  31661. }
  31662. goog.asserts.assert(i == this.count_, 'iterated correct amount of times');
  31663. }
  31664. };
  31665. /**
  31666. * FIXME empty description for jsdoc
  31667. */
  31668. ol.structs.LRUCache.prototype.clear = function() {
  31669. this.count_ = 0;
  31670. this.entries_ = {};
  31671. this.oldest_ = null;
  31672. this.newest_ = null;
  31673. };
  31674. /**
  31675. * @param {string} key Key.
  31676. * @return {boolean} Contains key.
  31677. */
  31678. ol.structs.LRUCache.prototype.containsKey = function(key) {
  31679. return this.entries_.hasOwnProperty(key);
  31680. };
  31681. /**
  31682. * @param {function(this: S, T, string, ol.structs.LRUCache): ?} f The function
  31683. * to call for every entry from the oldest to the newer. This function takes
  31684. * 3 arguments (the entry value, the entry key and the LRUCache object).
  31685. * The return value is ignored.
  31686. * @param {S=} opt_this The object to use as `this` in `f`.
  31687. * @template S
  31688. */
  31689. ol.structs.LRUCache.prototype.forEach = function(f, opt_this) {
  31690. var entry = this.oldest_;
  31691. while (entry) {
  31692. f.call(opt_this, entry.value_, entry.key_, this);
  31693. entry = entry.newer;
  31694. }
  31695. };
  31696. /**
  31697. * @param {string} key Key.
  31698. * @return {T} Value.
  31699. */
  31700. ol.structs.LRUCache.prototype.get = function(key) {
  31701. var entry = this.entries_[key];
  31702. goog.asserts.assert(entry !== undefined, 'an entry exists for key %s', key);
  31703. if (entry === this.newest_) {
  31704. return entry.value_;
  31705. } else if (entry === this.oldest_) {
  31706. this.oldest_ = this.oldest_.newer;
  31707. this.oldest_.older = null;
  31708. } else {
  31709. entry.newer.older = entry.older;
  31710. entry.older.newer = entry.newer;
  31711. }
  31712. entry.newer = null;
  31713. entry.older = this.newest_;
  31714. this.newest_.newer = entry;
  31715. this.newest_ = entry;
  31716. return entry.value_;
  31717. };
  31718. /**
  31719. * @return {number} Count.
  31720. */
  31721. ol.structs.LRUCache.prototype.getCount = function() {
  31722. return this.count_;
  31723. };
  31724. /**
  31725. * @return {Array.<string>} Keys.
  31726. */
  31727. ol.structs.LRUCache.prototype.getKeys = function() {
  31728. var keys = new Array(this.count_);
  31729. var i = 0;
  31730. var entry;
  31731. for (entry = this.newest_; entry; entry = entry.older) {
  31732. keys[i++] = entry.key_;
  31733. }
  31734. goog.asserts.assert(i == this.count_, 'iterated correct number of times');
  31735. return keys;
  31736. };
  31737. /**
  31738. * @return {Array.<T>} Values.
  31739. */
  31740. ol.structs.LRUCache.prototype.getValues = function() {
  31741. var values = new Array(this.count_);
  31742. var i = 0;
  31743. var entry;
  31744. for (entry = this.newest_; entry; entry = entry.older) {
  31745. values[i++] = entry.value_;
  31746. }
  31747. goog.asserts.assert(i == this.count_, 'iterated correct number of times');
  31748. return values;
  31749. };
  31750. /**
  31751. * @return {T} Last value.
  31752. */
  31753. ol.structs.LRUCache.prototype.peekLast = function() {
  31754. goog.asserts.assert(this.oldest_, 'oldest must not be null');
  31755. return this.oldest_.value_;
  31756. };
  31757. /**
  31758. * @return {string} Last key.
  31759. */
  31760. ol.structs.LRUCache.prototype.peekLastKey = function() {
  31761. goog.asserts.assert(this.oldest_, 'oldest must not be null');
  31762. return this.oldest_.key_;
  31763. };
  31764. /**
  31765. * @return {T} value Value.
  31766. */
  31767. ol.structs.LRUCache.prototype.pop = function() {
  31768. goog.asserts.assert(this.oldest_, 'oldest must not be null');
  31769. goog.asserts.assert(this.newest_, 'newest must not be null');
  31770. var entry = this.oldest_;
  31771. goog.asserts.assert(entry.key_ in this.entries_,
  31772. 'oldest is indexed in entries');
  31773. delete this.entries_[entry.key_];
  31774. if (entry.newer) {
  31775. entry.newer.older = null;
  31776. }
  31777. this.oldest_ = entry.newer;
  31778. if (!this.oldest_) {
  31779. this.newest_ = null;
  31780. }
  31781. --this.count_;
  31782. return entry.value_;
  31783. };
  31784. /**
  31785. * @param {string} key Key.
  31786. * @param {T} value Value.
  31787. */
  31788. ol.structs.LRUCache.prototype.set = function(key, value) {
  31789. goog.asserts.assert(!(key in {}),
  31790. 'key is not a standard property of objects (e.g. "__proto__")');
  31791. goog.asserts.assert(!(key in this.entries_),
  31792. 'key is not used already');
  31793. var entry = {
  31794. key_: key,
  31795. newer: null,
  31796. older: this.newest_,
  31797. value_: value
  31798. };
  31799. if (!this.newest_) {
  31800. this.oldest_ = entry;
  31801. } else {
  31802. this.newest_.newer = entry;
  31803. }
  31804. this.newest_ = entry;
  31805. this.entries_[key] = entry;
  31806. ++this.count_;
  31807. };
  31808. /**
  31809. * @typedef {{key_: string,
  31810. * newer: ol.structs.LRUCacheEntry,
  31811. * older: ol.structs.LRUCacheEntry,
  31812. * value_: *}}
  31813. */
  31814. ol.structs.LRUCacheEntry;
  31815. goog.provide('ol.TileCache');
  31816. goog.require('ol');
  31817. goog.require('ol.TileRange');
  31818. goog.require('ol.structs.LRUCache');
  31819. goog.require('ol.tilecoord');
  31820. /**
  31821. * @constructor
  31822. * @extends {ol.structs.LRUCache.<ol.Tile>}
  31823. * @param {number=} opt_highWaterMark High water mark.
  31824. * @struct
  31825. */
  31826. ol.TileCache = function(opt_highWaterMark) {
  31827. goog.base(this);
  31828. /**
  31829. * @private
  31830. * @type {number}
  31831. */
  31832. this.highWaterMark_ = opt_highWaterMark !== undefined ?
  31833. opt_highWaterMark : ol.DEFAULT_TILE_CACHE_HIGH_WATER_MARK;
  31834. };
  31835. goog.inherits(ol.TileCache, ol.structs.LRUCache);
  31836. /**
  31837. * @return {boolean} Can expire cache.
  31838. */
  31839. ol.TileCache.prototype.canExpireCache = function() {
  31840. return this.getCount() > this.highWaterMark_;
  31841. };
  31842. /**
  31843. * @param {Object.<string, ol.TileRange>} usedTiles Used tiles.
  31844. */
  31845. ol.TileCache.prototype.expireCache = function(usedTiles) {
  31846. var tile, zKey;
  31847. while (this.canExpireCache()) {
  31848. tile = this.peekLast();
  31849. zKey = tile.tileCoord[0].toString();
  31850. if (zKey in usedTiles && usedTiles[zKey].contains(tile.tileCoord)) {
  31851. break;
  31852. } else {
  31853. this.pop().dispose();
  31854. }
  31855. }
  31856. };
  31857. /**
  31858. * Remove a tile range from the cache, e.g. to invalidate tiles.
  31859. * @param {ol.TileRange} tileRange The tile range to prune.
  31860. */
  31861. ol.TileCache.prototype.pruneTileRange = function(tileRange) {
  31862. var i = this.getCount(),
  31863. key;
  31864. while (i--) {
  31865. key = this.peekLastKey();
  31866. if (tileRange.contains(ol.tilecoord.createFromString(key))) {
  31867. this.pop().dispose();
  31868. } else {
  31869. this.get(key);
  31870. }
  31871. }
  31872. };
  31873. goog.provide('ol.Tile');
  31874. goog.provide('ol.TileState');
  31875. goog.require('goog.events');
  31876. goog.require('goog.events.EventTarget');
  31877. goog.require('goog.events.EventType');
  31878. goog.require('ol.TileCoord');
  31879. /**
  31880. * @enum {number}
  31881. */
  31882. ol.TileState = {
  31883. IDLE: 0,
  31884. LOADING: 1,
  31885. LOADED: 2,
  31886. ERROR: 3,
  31887. EMPTY: 4
  31888. };
  31889. /**
  31890. * @classdesc
  31891. * Base class for tiles.
  31892. *
  31893. * @constructor
  31894. * @extends {goog.events.EventTarget}
  31895. * @param {ol.TileCoord} tileCoord Tile coordinate.
  31896. * @param {ol.TileState} state State.
  31897. */
  31898. ol.Tile = function(tileCoord, state) {
  31899. goog.base(this);
  31900. /**
  31901. * @type {ol.TileCoord}
  31902. */
  31903. this.tileCoord = tileCoord;
  31904. /**
  31905. * @protected
  31906. * @type {ol.TileState}
  31907. */
  31908. this.state = state;
  31909. };
  31910. goog.inherits(ol.Tile, goog.events.EventTarget);
  31911. /**
  31912. * @protected
  31913. */
  31914. ol.Tile.prototype.changed = function() {
  31915. this.dispatchEvent(goog.events.EventType.CHANGE);
  31916. };
  31917. /**
  31918. * Get the HTML image element for this tile (may be a Canvas, Image, or Video).
  31919. * @function
  31920. * @param {Object=} opt_context Object.
  31921. * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
  31922. */
  31923. ol.Tile.prototype.getImage = goog.abstractMethod;
  31924. /**
  31925. * @return {string} Key.
  31926. */
  31927. ol.Tile.prototype.getKey = function() {
  31928. return goog.getUid(this).toString();
  31929. };
  31930. /**
  31931. * Get the tile coordinate for this tile.
  31932. * @return {ol.TileCoord}
  31933. * @api
  31934. */
  31935. ol.Tile.prototype.getTileCoord = function() {
  31936. return this.tileCoord;
  31937. };
  31938. /**
  31939. * @return {ol.TileState} State.
  31940. */
  31941. ol.Tile.prototype.getState = function() {
  31942. return this.state;
  31943. };
  31944. /**
  31945. * FIXME empty description for jsdoc
  31946. */
  31947. ol.Tile.prototype.load = goog.abstractMethod;
  31948. goog.provide('ol.source.Source');
  31949. goog.provide('ol.source.State');
  31950. goog.require('ol');
  31951. goog.require('ol.Attribution');
  31952. goog.require('ol.Object');
  31953. goog.require('ol.proj');
  31954. /**
  31955. * State of the source, one of 'undefined', 'loading', 'ready' or 'error'.
  31956. * @enum {string}
  31957. * @api
  31958. */
  31959. ol.source.State = {
  31960. UNDEFINED: 'undefined',
  31961. LOADING: 'loading',
  31962. READY: 'ready',
  31963. ERROR: 'error'
  31964. };
  31965. /**
  31966. * @typedef {{attributions: (Array.<ol.Attribution>|undefined),
  31967. * logo: (string|olx.LogoOptions|undefined),
  31968. * projection: ol.proj.ProjectionLike,
  31969. * state: (ol.source.State|undefined),
  31970. * wrapX: (boolean|undefined)}}
  31971. */
  31972. ol.source.SourceOptions;
  31973. /**
  31974. * @classdesc
  31975. * Abstract base class; normally only used for creating subclasses and not
  31976. * instantiated in apps.
  31977. * Base class for {@link ol.layer.Layer} sources.
  31978. *
  31979. * A generic `change` event is triggered when the state of the source changes.
  31980. *
  31981. * @constructor
  31982. * @extends {ol.Object}
  31983. * @param {ol.source.SourceOptions} options Source options.
  31984. * @api stable
  31985. */
  31986. ol.source.Source = function(options) {
  31987. goog.base(this);
  31988. /**
  31989. * @private
  31990. * @type {ol.proj.Projection}
  31991. */
  31992. this.projection_ = ol.proj.get(options.projection);
  31993. /**
  31994. * @private
  31995. * @type {Array.<ol.Attribution>}
  31996. */
  31997. this.attributions_ = options.attributions !== undefined ?
  31998. options.attributions : null;
  31999. /**
  32000. * @private
  32001. * @type {string|olx.LogoOptions|undefined}
  32002. */
  32003. this.logo_ = options.logo;
  32004. /**
  32005. * @private
  32006. * @type {ol.source.State}
  32007. */
  32008. this.state_ = options.state !== undefined ?
  32009. options.state : ol.source.State.READY;
  32010. /**
  32011. * @private
  32012. * @type {boolean}
  32013. */
  32014. this.wrapX_ = options.wrapX !== undefined ? options.wrapX : false;
  32015. };
  32016. goog.inherits(ol.source.Source, ol.Object);
  32017. /**
  32018. * @param {ol.Coordinate} coordinate Coordinate.
  32019. * @param {number} resolution Resolution.
  32020. * @param {number} rotation Rotation.
  32021. * @param {Object.<string, boolean>} skippedFeatureUids Skipped feature uids.
  32022. * @param {function(ol.Feature): T} callback Feature callback.
  32023. * @return {T|undefined} Callback result.
  32024. * @template T
  32025. */
  32026. ol.source.Source.prototype.forEachFeatureAtCoordinate = ol.nullFunction;
  32027. /**
  32028. * Get the attributions of the source.
  32029. * @return {Array.<ol.Attribution>} Attributions.
  32030. * @api stable
  32031. */
  32032. ol.source.Source.prototype.getAttributions = function() {
  32033. return this.attributions_;
  32034. };
  32035. /**
  32036. * Get the logo of the source.
  32037. * @return {string|olx.LogoOptions|undefined} Logo.
  32038. * @api stable
  32039. */
  32040. ol.source.Source.prototype.getLogo = function() {
  32041. return this.logo_;
  32042. };
  32043. /**
  32044. * Get the projection of the source.
  32045. * @return {ol.proj.Projection} Projection.
  32046. * @api
  32047. */
  32048. ol.source.Source.prototype.getProjection = function() {
  32049. return this.projection_;
  32050. };
  32051. /**
  32052. * @return {Array.<number>|undefined} Resolutions.
  32053. */
  32054. ol.source.Source.prototype.getResolutions = goog.abstractMethod;
  32055. /**
  32056. * Get the state of the source, see {@link ol.source.State} for possible states.
  32057. * @return {ol.source.State} State.
  32058. * @api
  32059. */
  32060. ol.source.Source.prototype.getState = function() {
  32061. return this.state_;
  32062. };
  32063. /**
  32064. * @return {boolean|undefined} Wrap X.
  32065. */
  32066. ol.source.Source.prototype.getWrapX = function() {
  32067. return this.wrapX_;
  32068. };
  32069. /**
  32070. * Set the attributions of the source.
  32071. * @param {Array.<ol.Attribution>} attributions Attributions.
  32072. * @api
  32073. */
  32074. ol.source.Source.prototype.setAttributions = function(attributions) {
  32075. this.attributions_ = attributions;
  32076. this.changed();
  32077. };
  32078. /**
  32079. * Set the logo of the source.
  32080. * @param {string|olx.LogoOptions|undefined} logo Logo.
  32081. */
  32082. ol.source.Source.prototype.setLogo = function(logo) {
  32083. this.logo_ = logo;
  32084. };
  32085. /**
  32086. * Set the state of the source.
  32087. * @param {ol.source.State} state State.
  32088. * @protected
  32089. */
  32090. ol.source.Source.prototype.setState = function(state) {
  32091. this.state_ = state;
  32092. this.changed();
  32093. };
  32094. /**
  32095. * Set the projection of the source.
  32096. * @param {ol.proj.Projection} projection Projection.
  32097. */
  32098. ol.source.Source.prototype.setProjection = function(projection) {
  32099. this.projection_ = projection;
  32100. };
  32101. goog.provide('ol.tilegrid.TileGrid');
  32102. goog.require('goog.array');
  32103. goog.require('goog.asserts');
  32104. goog.require('goog.object');
  32105. goog.require('ol');
  32106. goog.require('ol.Coordinate');
  32107. goog.require('ol.TileCoord');
  32108. goog.require('ol.TileRange');
  32109. goog.require('ol.array');
  32110. goog.require('ol.extent');
  32111. goog.require('ol.extent.Corner');
  32112. goog.require('ol.math');
  32113. goog.require('ol.proj');
  32114. goog.require('ol.proj.METERS_PER_UNIT');
  32115. goog.require('ol.proj.Projection');
  32116. goog.require('ol.proj.Units');
  32117. goog.require('ol.size');
  32118. goog.require('ol.tilecoord');
  32119. /**
  32120. * @classdesc
  32121. * Base class for setting the grid pattern for sources accessing tiled-image
  32122. * servers.
  32123. *
  32124. * @constructor
  32125. * @param {olx.tilegrid.TileGridOptions} options Tile grid options.
  32126. * @struct
  32127. * @api stable
  32128. */
  32129. ol.tilegrid.TileGrid = function(options) {
  32130. /**
  32131. * @protected
  32132. * @type {number}
  32133. */
  32134. this.minZoom = options.minZoom !== undefined ? options.minZoom : 0;
  32135. /**
  32136. * @private
  32137. * @type {!Array.<number>}
  32138. */
  32139. this.resolutions_ = options.resolutions;
  32140. goog.asserts.assert(goog.array.isSorted(this.resolutions_, function(a, b) {
  32141. return b - a;
  32142. }, true), 'resolutions must be sorted in descending order');
  32143. /**
  32144. * @protected
  32145. * @type {number}
  32146. */
  32147. this.maxZoom = this.resolutions_.length - 1;
  32148. /**
  32149. * @private
  32150. * @type {ol.Coordinate}
  32151. */
  32152. this.origin_ = options.origin !== undefined ? options.origin : null;
  32153. /**
  32154. * @private
  32155. * @type {Array.<ol.Coordinate>}
  32156. */
  32157. this.origins_ = null;
  32158. if (options.origins !== undefined) {
  32159. this.origins_ = options.origins;
  32160. goog.asserts.assert(this.origins_.length == this.resolutions_.length,
  32161. 'number of origins and resolutions must be equal');
  32162. }
  32163. var extent = options.extent;
  32164. if (extent !== undefined &&
  32165. !this.origin_ && !this.origins_) {
  32166. this.origin_ = ol.extent.getTopLeft(extent);
  32167. }
  32168. goog.asserts.assert(
  32169. (!this.origin_ && this.origins_) ||
  32170. (this.origin_ && !this.origins_),
  32171. 'either origin or origins must be configured, never both');
  32172. /**
  32173. * @private
  32174. * @type {Array.<number|ol.Size>}
  32175. */
  32176. this.tileSizes_ = null;
  32177. if (options.tileSizes !== undefined) {
  32178. this.tileSizes_ = options.tileSizes;
  32179. goog.asserts.assert(this.tileSizes_.length == this.resolutions_.length,
  32180. 'number of tileSizes and resolutions must be equal');
  32181. }
  32182. /**
  32183. * @private
  32184. * @type {number|ol.Size}
  32185. */
  32186. this.tileSize_ = options.tileSize !== undefined ?
  32187. options.tileSize :
  32188. !this.tileSizes_ ? ol.DEFAULT_TILE_SIZE : null;
  32189. goog.asserts.assert(
  32190. (!this.tileSize_ && this.tileSizes_) ||
  32191. (this.tileSize_ && !this.tileSizes_),
  32192. 'either tileSize or tileSizes must be configured, never both');
  32193. /**
  32194. * @private
  32195. * @type {ol.Extent}
  32196. */
  32197. this.extent_ = extent !== undefined ? extent : null;
  32198. /**
  32199. * @private
  32200. * @type {Array.<ol.TileRange>}
  32201. */
  32202. this.fullTileRanges_ = null;
  32203. if (options.sizes !== undefined) {
  32204. goog.asserts.assert(options.sizes.length == this.resolutions_.length,
  32205. 'number of sizes and resolutions must be equal');
  32206. this.fullTileRanges_ = options.sizes.map(function(size, z) {
  32207. goog.asserts.assert(size[0] !== 0, 'width must not be 0');
  32208. goog.asserts.assert(size[1] !== 0, 'height must not be 0');
  32209. var tileRange = new ol.TileRange(
  32210. Math.min(0, size[0]), Math.max(size[0] - 1, -1),
  32211. Math.min(0, size[1]), Math.max(size[1] - 1, -1));
  32212. if (this.minZoom <= z && z <= this.maxZoom && extent !== undefined) {
  32213. goog.asserts.assert(tileRange.containsTileRange(
  32214. this.getTileRangeForExtentAndZ(extent, z)),
  32215. 'extent tile range must not exceed tilegrid width and height');
  32216. }
  32217. return tileRange;
  32218. }, this);
  32219. } else if (extent) {
  32220. this.calculateTileRanges_(extent);
  32221. }
  32222. /**
  32223. * @private
  32224. * @type {ol.Size}
  32225. */
  32226. this.tmpSize_ = [0, 0];
  32227. };
  32228. /**
  32229. * @private
  32230. * @type {ol.TileCoord}
  32231. */
  32232. ol.tilegrid.TileGrid.tmpTileCoord_ = [0, 0, 0];
  32233. /**
  32234. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32235. * @param {function(this: T, number, ol.TileRange): boolean} callback Callback.
  32236. * @param {T=} opt_this The object to use as `this` in `callback`.
  32237. * @param {ol.TileRange=} opt_tileRange Temporary ol.TileRange object.
  32238. * @param {ol.Extent=} opt_extent Temporary ol.Extent object.
  32239. * @return {boolean} Callback succeeded.
  32240. * @template T
  32241. */
  32242. ol.tilegrid.TileGrid.prototype.forEachTileCoordParentTileRange =
  32243. function(tileCoord, callback, opt_this, opt_tileRange, opt_extent) {
  32244. var tileCoordExtent = this.getTileCoordExtent(tileCoord, opt_extent);
  32245. var z = tileCoord[0] - 1;
  32246. while (z >= this.minZoom) {
  32247. if (callback.call(opt_this, z,
  32248. this.getTileRangeForExtentAndZ(tileCoordExtent, z, opt_tileRange))) {
  32249. return true;
  32250. }
  32251. --z;
  32252. }
  32253. return false;
  32254. };
  32255. /**
  32256. * Get the extent for this tile grid, if it was configured.
  32257. * @return {ol.Extent} Extent.
  32258. */
  32259. ol.tilegrid.TileGrid.prototype.getExtent = function() {
  32260. return this.extent_;
  32261. };
  32262. /**
  32263. * Get the maximum zoom level for the grid.
  32264. * @return {number} Max zoom.
  32265. * @api
  32266. */
  32267. ol.tilegrid.TileGrid.prototype.getMaxZoom = function() {
  32268. return this.maxZoom;
  32269. };
  32270. /**
  32271. * Get the minimum zoom level for the grid.
  32272. * @return {number} Min zoom.
  32273. * @api
  32274. */
  32275. ol.tilegrid.TileGrid.prototype.getMinZoom = function() {
  32276. return this.minZoom;
  32277. };
  32278. /**
  32279. * Get the origin for the grid at the given zoom level.
  32280. * @param {number} z Z.
  32281. * @return {ol.Coordinate} Origin.
  32282. * @api stable
  32283. */
  32284. ol.tilegrid.TileGrid.prototype.getOrigin = function(z) {
  32285. if (this.origin_) {
  32286. return this.origin_;
  32287. } else {
  32288. goog.asserts.assert(this.origins_,
  32289. 'origins cannot be null if origin is null');
  32290. goog.asserts.assert(this.minZoom <= z && z <= this.maxZoom,
  32291. 'given z is not in allowed range (%s <= %s <= %s)',
  32292. this.minZoom, z, this.maxZoom);
  32293. return this.origins_[z];
  32294. }
  32295. };
  32296. /**
  32297. * Get the resolution for the given zoom level.
  32298. * @param {number} z Z.
  32299. * @return {number} Resolution.
  32300. * @api stable
  32301. */
  32302. ol.tilegrid.TileGrid.prototype.getResolution = function(z) {
  32303. goog.asserts.assert(this.minZoom <= z && z <= this.maxZoom,
  32304. 'given z is not in allowed range (%s <= %s <= %s)',
  32305. this.minZoom, z, this.maxZoom);
  32306. return this.resolutions_[z];
  32307. };
  32308. /**
  32309. * Get the list of resolutions for the tile grid.
  32310. * @return {Array.<number>} Resolutions.
  32311. * @api stable
  32312. */
  32313. ol.tilegrid.TileGrid.prototype.getResolutions = function() {
  32314. return this.resolutions_;
  32315. };
  32316. /**
  32317. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32318. * @param {ol.TileRange=} opt_tileRange Temporary ol.TileRange object.
  32319. * @param {ol.Extent=} opt_extent Temporary ol.Extent object.
  32320. * @return {ol.TileRange} Tile range.
  32321. */
  32322. ol.tilegrid.TileGrid.prototype.getTileCoordChildTileRange =
  32323. function(tileCoord, opt_tileRange, opt_extent) {
  32324. if (tileCoord[0] < this.maxZoom) {
  32325. var tileCoordExtent = this.getTileCoordExtent(tileCoord, opt_extent);
  32326. return this.getTileRangeForExtentAndZ(
  32327. tileCoordExtent, tileCoord[0] + 1, opt_tileRange);
  32328. } else {
  32329. return null;
  32330. }
  32331. };
  32332. /**
  32333. * @param {number} z Z.
  32334. * @param {ol.TileRange} tileRange Tile range.
  32335. * @param {ol.Extent=} opt_extent Temporary ol.Extent object.
  32336. * @return {ol.Extent} Extent.
  32337. */
  32338. ol.tilegrid.TileGrid.prototype.getTileRangeExtent =
  32339. function(z, tileRange, opt_extent) {
  32340. var origin = this.getOrigin(z);
  32341. var resolution = this.getResolution(z);
  32342. var tileSize = ol.size.toSize(this.getTileSize(z), this.tmpSize_);
  32343. var minX = origin[0] + tileRange.minX * tileSize[0] * resolution;
  32344. var maxX = origin[0] + (tileRange.maxX + 1) * tileSize[0] * resolution;
  32345. var minY = origin[1] + tileRange.minY * tileSize[1] * resolution;
  32346. var maxY = origin[1] + (tileRange.maxY + 1) * tileSize[1] * resolution;
  32347. return ol.extent.createOrUpdate(minX, minY, maxX, maxY, opt_extent);
  32348. };
  32349. /**
  32350. * @param {ol.Extent} extent Extent.
  32351. * @param {number} resolution Resolution.
  32352. * @param {ol.TileRange=} opt_tileRange Temporary tile range object.
  32353. * @return {ol.TileRange} Tile range.
  32354. */
  32355. ol.tilegrid.TileGrid.prototype.getTileRangeForExtentAndResolution =
  32356. function(extent, resolution, opt_tileRange) {
  32357. var tileCoord = ol.tilegrid.TileGrid.tmpTileCoord_;
  32358. this.getTileCoordForXYAndResolution_(
  32359. extent[0], extent[1], resolution, false, tileCoord);
  32360. var minX = tileCoord[1];
  32361. var minY = tileCoord[2];
  32362. this.getTileCoordForXYAndResolution_(
  32363. extent[2], extent[3], resolution, true, tileCoord);
  32364. return ol.TileRange.createOrUpdate(
  32365. minX, tileCoord[1], minY, tileCoord[2], opt_tileRange);
  32366. };
  32367. /**
  32368. * @param {ol.Extent} extent Extent.
  32369. * @param {number} z Z.
  32370. * @param {ol.TileRange=} opt_tileRange Temporary tile range object.
  32371. * @return {ol.TileRange} Tile range.
  32372. */
  32373. ol.tilegrid.TileGrid.prototype.getTileRangeForExtentAndZ =
  32374. function(extent, z, opt_tileRange) {
  32375. var resolution = this.getResolution(z);
  32376. return this.getTileRangeForExtentAndResolution(
  32377. extent, resolution, opt_tileRange);
  32378. };
  32379. /**
  32380. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32381. * @return {ol.Coordinate} Tile center.
  32382. */
  32383. ol.tilegrid.TileGrid.prototype.getTileCoordCenter = function(tileCoord) {
  32384. var origin = this.getOrigin(tileCoord[0]);
  32385. var resolution = this.getResolution(tileCoord[0]);
  32386. var tileSize = ol.size.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);
  32387. return [
  32388. origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution,
  32389. origin[1] + (tileCoord[2] + 0.5) * tileSize[1] * resolution
  32390. ];
  32391. };
  32392. /**
  32393. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32394. * @param {ol.Extent=} opt_extent Temporary extent object.
  32395. * @return {ol.Extent} Extent.
  32396. */
  32397. ol.tilegrid.TileGrid.prototype.getTileCoordExtent =
  32398. function(tileCoord, opt_extent) {
  32399. var origin = this.getOrigin(tileCoord[0]);
  32400. var resolution = this.getResolution(tileCoord[0]);
  32401. var tileSize = ol.size.toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);
  32402. var minX = origin[0] + tileCoord[1] * tileSize[0] * resolution;
  32403. var minY = origin[1] + tileCoord[2] * tileSize[1] * resolution;
  32404. var maxX = minX + tileSize[0] * resolution;
  32405. var maxY = minY + tileSize[1] * resolution;
  32406. return ol.extent.createOrUpdate(minX, minY, maxX, maxY, opt_extent);
  32407. };
  32408. /**
  32409. * Get the tile coordinate for the given map coordinate and resolution. This
  32410. * method considers that coordinates that intersect tile boundaries should be
  32411. * assigned the higher tile coordinate.
  32412. *
  32413. * @param {ol.Coordinate} coordinate Coordinate.
  32414. * @param {number} resolution Resolution.
  32415. * @param {ol.TileCoord=} opt_tileCoord Destination ol.TileCoord object.
  32416. * @return {ol.TileCoord} Tile coordinate.
  32417. * @api
  32418. */
  32419. ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndResolution =
  32420. function(coordinate, resolution, opt_tileCoord) {
  32421. return this.getTileCoordForXYAndResolution_(
  32422. coordinate[0], coordinate[1], resolution, false, opt_tileCoord);
  32423. };
  32424. /**
  32425. * @param {number} x X.
  32426. * @param {number} y Y.
  32427. * @param {number} resolution Resolution.
  32428. * @param {boolean} reverseIntersectionPolicy Instead of letting edge
  32429. * intersections go to the higher tile coordinate, let edge intersections
  32430. * go to the lower tile coordinate.
  32431. * @param {ol.TileCoord=} opt_tileCoord Temporary ol.TileCoord object.
  32432. * @return {ol.TileCoord} Tile coordinate.
  32433. * @private
  32434. */
  32435. ol.tilegrid.TileGrid.prototype.getTileCoordForXYAndResolution_ = function(
  32436. x, y, resolution, reverseIntersectionPolicy, opt_tileCoord) {
  32437. var z = this.getZForResolution(resolution);
  32438. var scale = resolution / this.getResolution(z);
  32439. var origin = this.getOrigin(z);
  32440. var tileSize = ol.size.toSize(this.getTileSize(z), this.tmpSize_);
  32441. var adjustX = reverseIntersectionPolicy ? 0.5 : 0;
  32442. var adjustY = reverseIntersectionPolicy ? 0 : 0.5;
  32443. var xFromOrigin = Math.floor((x - origin[0]) / resolution + adjustX);
  32444. var yFromOrigin = Math.floor((y - origin[1]) / resolution + adjustY);
  32445. var tileCoordX = scale * xFromOrigin / tileSize[0];
  32446. var tileCoordY = scale * yFromOrigin / tileSize[1];
  32447. if (reverseIntersectionPolicy) {
  32448. tileCoordX = Math.ceil(tileCoordX) - 1;
  32449. tileCoordY = Math.ceil(tileCoordY) - 1;
  32450. } else {
  32451. tileCoordX = Math.floor(tileCoordX);
  32452. tileCoordY = Math.floor(tileCoordY);
  32453. }
  32454. return ol.tilecoord.createOrUpdate(z, tileCoordX, tileCoordY, opt_tileCoord);
  32455. };
  32456. /**
  32457. * Get a tile coordinate given a map coordinate and zoom level.
  32458. * @param {ol.Coordinate} coordinate Coordinate.
  32459. * @param {number} z Zoom level.
  32460. * @param {ol.TileCoord=} opt_tileCoord Destination ol.TileCoord object.
  32461. * @return {ol.TileCoord} Tile coordinate.
  32462. * @api
  32463. */
  32464. ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndZ =
  32465. function(coordinate, z, opt_tileCoord) {
  32466. var resolution = this.getResolution(z);
  32467. return this.getTileCoordForXYAndResolution_(
  32468. coordinate[0], coordinate[1], resolution, false, opt_tileCoord);
  32469. };
  32470. /**
  32471. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32472. * @return {number} Tile resolution.
  32473. */
  32474. ol.tilegrid.TileGrid.prototype.getTileCoordResolution = function(tileCoord) {
  32475. goog.asserts.assert(
  32476. this.minZoom <= tileCoord[0] && tileCoord[0] <= this.maxZoom,
  32477. 'z of given tilecoord is not in allowed range (%s <= %s <= %s',
  32478. this.minZoom, tileCoord[0], this.maxZoom);
  32479. return this.resolutions_[tileCoord[0]];
  32480. };
  32481. /**
  32482. * Get the tile size for a zoom level. The type of the return value matches the
  32483. * `tileSize` or `tileSizes` that the tile grid was configured with. To always
  32484. * get an `ol.Size`, run the result through `ol.size.toSize()`.
  32485. * @param {number} z Z.
  32486. * @return {number|ol.Size} Tile size.
  32487. * @api stable
  32488. */
  32489. ol.tilegrid.TileGrid.prototype.getTileSize = function(z) {
  32490. if (this.tileSize_) {
  32491. return this.tileSize_;
  32492. } else {
  32493. goog.asserts.assert(this.tileSizes_,
  32494. 'tileSizes cannot be null if tileSize is null');
  32495. goog.asserts.assert(this.minZoom <= z && z <= this.maxZoom,
  32496. 'z is not in allowed range (%s <= %s <= %s',
  32497. this.minZoom, z, this.maxZoom);
  32498. return this.tileSizes_[z];
  32499. }
  32500. };
  32501. /**
  32502. * @param {number} z Zoom level.
  32503. * @return {ol.TileRange} Extent tile range for the specified zoom level.
  32504. */
  32505. ol.tilegrid.TileGrid.prototype.getFullTileRange = function(z) {
  32506. if (!this.fullTileRanges_) {
  32507. return null;
  32508. } else {
  32509. goog.asserts.assert(this.minZoom <= z && z <= this.maxZoom,
  32510. 'z is not in allowed range (%s <= %s <= %s',
  32511. this.minZoom, z, this.maxZoom);
  32512. return this.fullTileRanges_[z];
  32513. }
  32514. };
  32515. /**
  32516. * @param {number} resolution Resolution.
  32517. * @return {number} Z.
  32518. */
  32519. ol.tilegrid.TileGrid.prototype.getZForResolution = function(resolution) {
  32520. var z = ol.array.linearFindNearest(this.resolutions_, resolution, 0);
  32521. return ol.math.clamp(z, this.minZoom, this.maxZoom);
  32522. };
  32523. /**
  32524. * @param {!ol.Extent} extent Extent for this tile grid.
  32525. * @private
  32526. */
  32527. ol.tilegrid.TileGrid.prototype.calculateTileRanges_ = function(extent) {
  32528. var length = this.resolutions_.length;
  32529. var fullTileRanges = new Array(length);
  32530. for (var z = this.minZoom; z < length; ++z) {
  32531. fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z);
  32532. }
  32533. this.fullTileRanges_ = fullTileRanges;
  32534. };
  32535. /**
  32536. * @param {ol.proj.Projection} projection Projection.
  32537. * @return {ol.tilegrid.TileGrid} Default tile grid for the passed projection.
  32538. */
  32539. ol.tilegrid.getForProjection = function(projection) {
  32540. var tileGrid = projection.getDefaultTileGrid();
  32541. if (!tileGrid) {
  32542. tileGrid = ol.tilegrid.createForProjection(projection);
  32543. projection.setDefaultTileGrid(tileGrid);
  32544. }
  32545. return tileGrid;
  32546. };
  32547. /**
  32548. * @param {ol.Extent} extent Extent.
  32549. * @param {number=} opt_maxZoom Maximum zoom level (default is
  32550. * ol.DEFAULT_MAX_ZOOM).
  32551. * @param {number|ol.Size=} opt_tileSize Tile size (default uses
  32552. * ol.DEFAULT_TILE_SIZE).
  32553. * @param {ol.extent.Corner=} opt_corner Extent corner (default is
  32554. * ol.extent.Corner.TOP_LEFT).
  32555. * @return {ol.tilegrid.TileGrid} TileGrid instance.
  32556. */
  32557. ol.tilegrid.createForExtent =
  32558. function(extent, opt_maxZoom, opt_tileSize, opt_corner) {
  32559. var corner = opt_corner !== undefined ?
  32560. opt_corner : ol.extent.Corner.TOP_LEFT;
  32561. var resolutions = ol.tilegrid.resolutionsFromExtent(
  32562. extent, opt_maxZoom, opt_tileSize);
  32563. return new ol.tilegrid.TileGrid({
  32564. extent: extent,
  32565. origin: ol.extent.getCorner(extent, corner),
  32566. resolutions: resolutions,
  32567. tileSize: opt_tileSize
  32568. });
  32569. };
  32570. /**
  32571. * Creates a tile grid with a standard XYZ tiling scheme.
  32572. * @param {olx.tilegrid.XYZOptions=} opt_options Tile grid options.
  32573. * @return {ol.tilegrid.TileGrid} Tile grid instance.
  32574. * @api
  32575. */
  32576. ol.tilegrid.createXYZ = function(opt_options) {
  32577. var options = /** @type {olx.tilegrid.TileGridOptions} */ ({});
  32578. goog.object.extend(options, opt_options !== undefined ?
  32579. opt_options : /** @type {olx.tilegrid.XYZOptions} */ ({}));
  32580. if (options.extent === undefined) {
  32581. options.extent = ol.proj.get('EPSG:3857').getExtent();
  32582. }
  32583. options.resolutions = ol.tilegrid.resolutionsFromExtent(
  32584. options.extent, options.maxZoom, options.tileSize);
  32585. delete options.maxZoom;
  32586. return new ol.tilegrid.TileGrid(options);
  32587. };
  32588. /**
  32589. * Create a resolutions array from an extent. A zoom factor of 2 is assumed.
  32590. * @param {ol.Extent} extent Extent.
  32591. * @param {number=} opt_maxZoom Maximum zoom level (default is
  32592. * ol.DEFAULT_MAX_ZOOM).
  32593. * @param {number|ol.Size=} opt_tileSize Tile size (default uses
  32594. * ol.DEFAULT_TILE_SIZE).
  32595. * @return {!Array.<number>} Resolutions array.
  32596. */
  32597. ol.tilegrid.resolutionsFromExtent =
  32598. function(extent, opt_maxZoom, opt_tileSize) {
  32599. var maxZoom = opt_maxZoom !== undefined ?
  32600. opt_maxZoom : ol.DEFAULT_MAX_ZOOM;
  32601. var height = ol.extent.getHeight(extent);
  32602. var width = ol.extent.getWidth(extent);
  32603. var tileSize = ol.size.toSize(opt_tileSize !== undefined ?
  32604. opt_tileSize : ol.DEFAULT_TILE_SIZE);
  32605. var maxResolution = Math.max(
  32606. width / tileSize[0], height / tileSize[1]);
  32607. var length = maxZoom + 1;
  32608. var resolutions = new Array(length);
  32609. for (var z = 0; z < length; ++z) {
  32610. resolutions[z] = maxResolution / Math.pow(2, z);
  32611. }
  32612. return resolutions;
  32613. };
  32614. /**
  32615. * @param {ol.proj.ProjectionLike} projection Projection.
  32616. * @param {number=} opt_maxZoom Maximum zoom level (default is
  32617. * ol.DEFAULT_MAX_ZOOM).
  32618. * @param {ol.Size=} opt_tileSize Tile size (default uses ol.DEFAULT_TILE_SIZE).
  32619. * @param {ol.extent.Corner=} opt_corner Extent corner (default is
  32620. * ol.extent.Corner.BOTTOM_LEFT).
  32621. * @return {ol.tilegrid.TileGrid} TileGrid instance.
  32622. */
  32623. ol.tilegrid.createForProjection =
  32624. function(projection, opt_maxZoom, opt_tileSize, opt_corner) {
  32625. var extent = ol.tilegrid.extentFromProjection(projection);
  32626. return ol.tilegrid.createForExtent(
  32627. extent, opt_maxZoom, opt_tileSize, opt_corner);
  32628. };
  32629. /**
  32630. * Generate a tile grid extent from a projection. If the projection has an
  32631. * extent, it is used. If not, a global extent is assumed.
  32632. * @param {ol.proj.ProjectionLike} projection Projection.
  32633. * @return {ol.Extent} Extent.
  32634. */
  32635. ol.tilegrid.extentFromProjection = function(projection) {
  32636. projection = ol.proj.get(projection);
  32637. var extent = projection.getExtent();
  32638. if (!extent) {
  32639. var half = 180 * ol.proj.METERS_PER_UNIT[ol.proj.Units.DEGREES] /
  32640. projection.getMetersPerUnit();
  32641. extent = ol.extent.createOrUpdate(-half, -half, half, half);
  32642. }
  32643. return extent;
  32644. };
  32645. goog.provide('ol.source.Tile');
  32646. goog.provide('ol.source.TileEvent');
  32647. goog.provide('ol.source.TileOptions');
  32648. goog.require('goog.asserts');
  32649. goog.require('goog.events.Event');
  32650. goog.require('ol');
  32651. goog.require('ol.Attribution');
  32652. goog.require('ol.Extent');
  32653. goog.require('ol.TileCache');
  32654. goog.require('ol.TileRange');
  32655. goog.require('ol.TileState');
  32656. goog.require('ol.size');
  32657. goog.require('ol.source.Source');
  32658. goog.require('ol.tilecoord');
  32659. goog.require('ol.tilegrid.TileGrid');
  32660. /**
  32661. * @typedef {{attributions: (Array.<ol.Attribution>|undefined),
  32662. * extent: (ol.Extent|undefined),
  32663. * logo: (string|olx.LogoOptions|undefined),
  32664. * opaque: (boolean|undefined),
  32665. * tilePixelRatio: (number|undefined),
  32666. * projection: ol.proj.ProjectionLike,
  32667. * state: (ol.source.State|undefined),
  32668. * tileGrid: (ol.tilegrid.TileGrid|undefined),
  32669. * wrapX: (boolean|undefined)}}
  32670. */
  32671. ol.source.TileOptions;
  32672. /**
  32673. * @classdesc
  32674. * Abstract base class; normally only used for creating subclasses and not
  32675. * instantiated in apps.
  32676. * Base class for sources providing images divided into a tile grid.
  32677. *
  32678. * @constructor
  32679. * @extends {ol.source.Source}
  32680. * @param {ol.source.TileOptions} options Tile source options.
  32681. * @api
  32682. */
  32683. ol.source.Tile = function(options) {
  32684. goog.base(this, {
  32685. attributions: options.attributions,
  32686. extent: options.extent,
  32687. logo: options.logo,
  32688. projection: options.projection,
  32689. state: options.state,
  32690. wrapX: options.wrapX
  32691. });
  32692. /**
  32693. * @private
  32694. * @type {boolean}
  32695. */
  32696. this.opaque_ = options.opaque !== undefined ? options.opaque : false;
  32697. /**
  32698. * @private
  32699. * @type {number}
  32700. */
  32701. this.tilePixelRatio_ = options.tilePixelRatio !== undefined ?
  32702. options.tilePixelRatio : 1;
  32703. /**
  32704. * @protected
  32705. * @type {ol.tilegrid.TileGrid}
  32706. */
  32707. this.tileGrid = options.tileGrid !== undefined ? options.tileGrid : null;
  32708. /**
  32709. * @protected
  32710. * @type {ol.TileCache}
  32711. */
  32712. this.tileCache = new ol.TileCache();
  32713. /**
  32714. * @protected
  32715. * @type {ol.Size}
  32716. */
  32717. this.tmpSize = [0, 0];
  32718. };
  32719. goog.inherits(ol.source.Tile, ol.source.Source);
  32720. /**
  32721. * @return {boolean} Can expire cache.
  32722. */
  32723. ol.source.Tile.prototype.canExpireCache = function() {
  32724. return this.tileCache.canExpireCache();
  32725. };
  32726. /**
  32727. * @param {Object.<string, ol.TileRange>} usedTiles Used tiles.
  32728. */
  32729. ol.source.Tile.prototype.expireCache = function(usedTiles) {
  32730. this.tileCache.expireCache(usedTiles);
  32731. };
  32732. /**
  32733. * @param {number} z Zoom level.
  32734. * @param {ol.TileRange} tileRange Tile range.
  32735. * @param {function(ol.Tile):(boolean|undefined)} callback Called with each
  32736. * loaded tile. If the callback returns `false`, the tile will not be
  32737. * considered loaded.
  32738. * @return {boolean} The tile range is fully covered with loaded tiles.
  32739. */
  32740. ol.source.Tile.prototype.forEachLoadedTile = function(z, tileRange, callback) {
  32741. var covered = true;
  32742. var tile, tileCoordKey, loaded;
  32743. for (var x = tileRange.minX; x <= tileRange.maxX; ++x) {
  32744. for (var y = tileRange.minY; y <= tileRange.maxY; ++y) {
  32745. tileCoordKey = this.getKeyZXY(z, x, y);
  32746. loaded = false;
  32747. if (this.tileCache.containsKey(tileCoordKey)) {
  32748. tile = /** @type {!ol.Tile} */ (this.tileCache.get(tileCoordKey));
  32749. loaded = tile.getState() === ol.TileState.LOADED;
  32750. if (loaded) {
  32751. loaded = (callback(tile) !== false);
  32752. }
  32753. }
  32754. if (!loaded) {
  32755. covered = false;
  32756. }
  32757. }
  32758. }
  32759. return covered;
  32760. };
  32761. /**
  32762. * @return {number} Gutter.
  32763. */
  32764. ol.source.Tile.prototype.getGutter = function() {
  32765. return 0;
  32766. };
  32767. /**
  32768. * @param {number} z Z.
  32769. * @param {number} x X.
  32770. * @param {number} y Y.
  32771. * @return {string} Key.
  32772. * @protected
  32773. */
  32774. ol.source.Tile.prototype.getKeyZXY = ol.tilecoord.getKeyZXY;
  32775. /**
  32776. * @return {boolean} Opaque.
  32777. */
  32778. ol.source.Tile.prototype.getOpaque = function() {
  32779. return this.opaque_;
  32780. };
  32781. /**
  32782. * @inheritDoc
  32783. */
  32784. ol.source.Tile.prototype.getResolutions = function() {
  32785. return this.tileGrid.getResolutions();
  32786. };
  32787. /**
  32788. * @param {number} z Tile coordinate z.
  32789. * @param {number} x Tile coordinate x.
  32790. * @param {number} y Tile coordinate y.
  32791. * @param {number} pixelRatio Pixel ratio.
  32792. * @param {ol.proj.Projection=} opt_projection Projection.
  32793. * @return {!ol.Tile} Tile.
  32794. */
  32795. ol.source.Tile.prototype.getTile = goog.abstractMethod;
  32796. /**
  32797. * Return the tile grid of the tile source.
  32798. * @return {ol.tilegrid.TileGrid} Tile grid.
  32799. * @api stable
  32800. */
  32801. ol.source.Tile.prototype.getTileGrid = function() {
  32802. return this.tileGrid;
  32803. };
  32804. /**
  32805. * @param {ol.proj.Projection} projection Projection.
  32806. * @return {ol.tilegrid.TileGrid} Tile grid.
  32807. */
  32808. ol.source.Tile.prototype.getTileGridForProjection = function(projection) {
  32809. if (!this.tileGrid) {
  32810. return ol.tilegrid.getForProjection(projection);
  32811. } else {
  32812. return this.tileGrid;
  32813. }
  32814. };
  32815. /**
  32816. * @param {number} z Z.
  32817. * @param {number} pixelRatio Pixel ratio.
  32818. * @param {ol.proj.Projection} projection Projection.
  32819. * @return {ol.Size} Tile size.
  32820. */
  32821. ol.source.Tile.prototype.getTilePixelSize =
  32822. function(z, pixelRatio, projection) {
  32823. var tileGrid = this.getTileGridForProjection(projection);
  32824. return ol.size.scale(ol.size.toSize(tileGrid.getTileSize(z), this.tmpSize),
  32825. this.tilePixelRatio_, this.tmpSize);
  32826. };
  32827. /**
  32828. * Returns a tile coordinate wrapped around the x-axis. When the tile coordinate
  32829. * is outside the resolution and extent range of the tile grid, `null` will be
  32830. * returned.
  32831. * @param {ol.TileCoord} tileCoord Tile coordinate.
  32832. * @param {ol.proj.Projection=} opt_projection Projection.
  32833. * @return {ol.TileCoord} Tile coordinate to be passed to the tileUrlFunction or
  32834. * null if no tile URL should be created for the passed `tileCoord`.
  32835. */
  32836. ol.source.Tile.prototype.getTileCoordForTileUrlFunction =
  32837. function(tileCoord, opt_projection) {
  32838. var projection = opt_projection !== undefined ?
  32839. opt_projection : this.getProjection();
  32840. var tileGrid = this.getTileGridForProjection(projection);
  32841. goog.asserts.assert(tileGrid, 'tile grid needed');
  32842. if (this.getWrapX() && projection.isGlobal()) {
  32843. tileCoord = ol.tilecoord.wrapX(tileCoord, tileGrid, projection);
  32844. }
  32845. return ol.tilecoord.withinExtentAndZ(tileCoord, tileGrid) ? tileCoord : null;
  32846. };
  32847. /**
  32848. * Marks a tile coord as being used, without triggering a load.
  32849. * @param {number} z Tile coordinate z.
  32850. * @param {number} x Tile coordinate x.
  32851. * @param {number} y Tile coordinate y.
  32852. */
  32853. ol.source.Tile.prototype.useTile = ol.nullFunction;
  32854. /**
  32855. * @classdesc
  32856. * Events emitted by {@link ol.source.Tile} instances are instances of this
  32857. * type.
  32858. *
  32859. * @constructor
  32860. * @extends {goog.events.Event}
  32861. * @implements {oli.source.TileEvent}
  32862. * @param {string} type Type.
  32863. * @param {ol.Tile} tile The tile.
  32864. */
  32865. ol.source.TileEvent = function(type, tile) {
  32866. goog.base(this, type);
  32867. /**
  32868. * The tile related to the event.
  32869. * @type {ol.Tile}
  32870. * @api
  32871. */
  32872. this.tile = tile;
  32873. };
  32874. goog.inherits(ol.source.TileEvent, goog.events.Event);
  32875. /**
  32876. * @enum {string}
  32877. */
  32878. ol.source.TileEventType = {
  32879. /**
  32880. * Triggered when a tile starts loading.
  32881. * @event ol.source.TileEvent#tileloadstart
  32882. * @api stable
  32883. */
  32884. TILELOADSTART: 'tileloadstart',
  32885. /**
  32886. * Triggered when a tile finishes loading.
  32887. * @event ol.source.TileEvent#tileloadend
  32888. * @api stable
  32889. */
  32890. TILELOADEND: 'tileloadend',
  32891. /**
  32892. * Triggered if tile loading results in an error.
  32893. * @event ol.source.TileEvent#tileloaderror
  32894. * @api stable
  32895. */
  32896. TILELOADERROR: 'tileloaderror'
  32897. };
  32898. // FIXME handle date line wrap
  32899. goog.provide('ol.control.Attribution');
  32900. goog.require('goog.asserts');
  32901. goog.require('goog.dom');
  32902. goog.require('goog.dom.TagName');
  32903. goog.require('goog.dom.classlist');
  32904. goog.require('goog.events');
  32905. goog.require('goog.events.EventType');
  32906. goog.require('goog.object');
  32907. goog.require('goog.style');
  32908. goog.require('ol');
  32909. goog.require('ol.Attribution');
  32910. goog.require('ol.control.Control');
  32911. goog.require('ol.css');
  32912. goog.require('ol.source.Tile');
  32913. /**
  32914. * @classdesc
  32915. * Control to show all the attributions associated with the layer sources
  32916. * in the map. This control is one of the default controls included in maps.
  32917. * By default it will show in the bottom right portion of the map, but this can
  32918. * be changed by using a css selector for `.ol-attribution`.
  32919. *
  32920. * @constructor
  32921. * @extends {ol.control.Control}
  32922. * @param {olx.control.AttributionOptions=} opt_options Attribution options.
  32923. * @api stable
  32924. */
  32925. ol.control.Attribution = function(opt_options) {
  32926. var options = opt_options ? opt_options : {};
  32927. /**
  32928. * @private
  32929. * @type {Element}
  32930. */
  32931. this.ulElement_ = goog.dom.createElement(goog.dom.TagName.UL);
  32932. /**
  32933. * @private
  32934. * @type {Element}
  32935. */
  32936. this.logoLi_ = goog.dom.createElement(goog.dom.TagName.LI);
  32937. this.ulElement_.appendChild(this.logoLi_);
  32938. goog.style.setElementShown(this.logoLi_, false);
  32939. /**
  32940. * @private
  32941. * @type {boolean}
  32942. */
  32943. this.collapsed_ = options.collapsed !== undefined ? options.collapsed : true;
  32944. /**
  32945. * @private
  32946. * @type {boolean}
  32947. */
  32948. this.collapsible_ = options.collapsible !== undefined ?
  32949. options.collapsible : true;
  32950. if (!this.collapsible_) {
  32951. this.collapsed_ = false;
  32952. }
  32953. var className = options.className ? options.className : 'ol-attribution';
  32954. var tipLabel = options.tipLabel ? options.tipLabel : 'Attributions';
  32955. var collapseLabel = options.collapseLabel ? options.collapseLabel : '\u00BB';
  32956. /**
  32957. * @private
  32958. * @type {Node}
  32959. */
  32960. this.collapseLabel_ = goog.isString(collapseLabel) ?
  32961. goog.dom.createDom(goog.dom.TagName.SPAN, {}, collapseLabel) :
  32962. collapseLabel;
  32963. var label = options.label ? options.label : 'i';
  32964. /**
  32965. * @private
  32966. * @type {Node}
  32967. */
  32968. this.label_ = goog.isString(label) ?
  32969. goog.dom.createDom(goog.dom.TagName.SPAN, {}, label) :
  32970. label;
  32971. var activeLabel = (this.collapsible_ && !this.collapsed_) ?
  32972. this.collapseLabel_ : this.label_;
  32973. var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  32974. 'type': 'button',
  32975. 'title': tipLabel
  32976. }, activeLabel);
  32977. goog.events.listen(button, goog.events.EventType.CLICK,
  32978. this.handleClick_, false, this);
  32979. goog.events.listen(button, [
  32980. goog.events.EventType.MOUSEOUT,
  32981. goog.events.EventType.FOCUSOUT
  32982. ], function() {
  32983. this.blur();
  32984. }, false);
  32985. var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
  32986. ol.css.CLASS_CONTROL +
  32987. (this.collapsed_ && this.collapsible_ ? ' ol-collapsed' : '') +
  32988. (this.collapsible_ ? '' : ' ol-uncollapsible');
  32989. var element = goog.dom.createDom(goog.dom.TagName.DIV,
  32990. cssClasses, this.ulElement_, button);
  32991. var render = options.render ? options.render : ol.control.Attribution.render;
  32992. goog.base(this, {
  32993. element: element,
  32994. render: render,
  32995. target: options.target
  32996. });
  32997. /**
  32998. * @private
  32999. * @type {boolean}
  33000. */
  33001. this.renderedVisible_ = true;
  33002. /**
  33003. * @private
  33004. * @type {Object.<string, Element>}
  33005. */
  33006. this.attributionElements_ = {};
  33007. /**
  33008. * @private
  33009. * @type {Object.<string, boolean>}
  33010. */
  33011. this.attributionElementRenderedVisible_ = {};
  33012. /**
  33013. * @private
  33014. * @type {Object.<string, Element>}
  33015. */
  33016. this.logoElements_ = {};
  33017. };
  33018. goog.inherits(ol.control.Attribution, ol.control.Control);
  33019. /**
  33020. * @param {?olx.FrameState} frameState Frame state.
  33021. * @return {Array.<Object.<string, ol.Attribution>>} Attributions.
  33022. */
  33023. ol.control.Attribution.prototype.getSourceAttributions = function(frameState) {
  33024. var i, ii, j, jj, tileRanges, source, sourceAttribution,
  33025. sourceAttributionKey, sourceAttributions, sourceKey;
  33026. var intersectsTileRange;
  33027. var layerStatesArray = frameState.layerStatesArray;
  33028. /** @type {Object.<string, ol.Attribution>} */
  33029. var attributions = goog.object.clone(frameState.attributions);
  33030. /** @type {Object.<string, ol.Attribution>} */
  33031. var hiddenAttributions = {};
  33032. var projection = frameState.viewState.projection;
  33033. goog.asserts.assert(projection, 'projection of viewState required');
  33034. for (i = 0, ii = layerStatesArray.length; i < ii; i++) {
  33035. source = layerStatesArray[i].layer.getSource();
  33036. if (!source) {
  33037. continue;
  33038. }
  33039. sourceKey = goog.getUid(source).toString();
  33040. sourceAttributions = source.getAttributions();
  33041. if (!sourceAttributions) {
  33042. continue;
  33043. }
  33044. for (j = 0, jj = sourceAttributions.length; j < jj; j++) {
  33045. sourceAttribution = sourceAttributions[j];
  33046. sourceAttributionKey = goog.getUid(sourceAttribution).toString();
  33047. if (sourceAttributionKey in attributions) {
  33048. continue;
  33049. }
  33050. tileRanges = frameState.usedTiles[sourceKey];
  33051. if (tileRanges) {
  33052. goog.asserts.assertInstanceof(source, ol.source.Tile,
  33053. 'source should be an ol.source.Tile');
  33054. var tileGrid = source.getTileGridForProjection(projection);
  33055. goog.asserts.assert(tileGrid, 'tileGrid required for projection');
  33056. intersectsTileRange = sourceAttribution.intersectsAnyTileRange(
  33057. tileRanges, tileGrid, projection);
  33058. } else {
  33059. intersectsTileRange = false;
  33060. }
  33061. if (intersectsTileRange) {
  33062. if (sourceAttributionKey in hiddenAttributions) {
  33063. delete hiddenAttributions[sourceAttributionKey];
  33064. }
  33065. attributions[sourceAttributionKey] = sourceAttribution;
  33066. } else {
  33067. hiddenAttributions[sourceAttributionKey] = sourceAttribution;
  33068. }
  33069. }
  33070. }
  33071. return [attributions, hiddenAttributions];
  33072. };
  33073. /**
  33074. * Update the attribution element.
  33075. * @param {ol.MapEvent} mapEvent Map event.
  33076. * @this {ol.control.Attribution}
  33077. * @api
  33078. */
  33079. ol.control.Attribution.render = function(mapEvent) {
  33080. this.updateElement_(mapEvent.frameState);
  33081. };
  33082. /**
  33083. * @private
  33084. * @param {?olx.FrameState} frameState Frame state.
  33085. */
  33086. ol.control.Attribution.prototype.updateElement_ = function(frameState) {
  33087. if (!frameState) {
  33088. if (this.renderedVisible_) {
  33089. goog.style.setElementShown(this.element, false);
  33090. this.renderedVisible_ = false;
  33091. }
  33092. return;
  33093. }
  33094. var attributions = this.getSourceAttributions(frameState);
  33095. /** @type {Object.<string, ol.Attribution>} */
  33096. var visibleAttributions = attributions[0];
  33097. /** @type {Object.<string, ol.Attribution>} */
  33098. var hiddenAttributions = attributions[1];
  33099. var attributionElement, attributionKey;
  33100. for (attributionKey in this.attributionElements_) {
  33101. if (attributionKey in visibleAttributions) {
  33102. if (!this.attributionElementRenderedVisible_[attributionKey]) {
  33103. goog.style.setElementShown(
  33104. this.attributionElements_[attributionKey], true);
  33105. this.attributionElementRenderedVisible_[attributionKey] = true;
  33106. }
  33107. delete visibleAttributions[attributionKey];
  33108. }
  33109. else if (attributionKey in hiddenAttributions) {
  33110. if (this.attributionElementRenderedVisible_[attributionKey]) {
  33111. goog.style.setElementShown(
  33112. this.attributionElements_[attributionKey], false);
  33113. delete this.attributionElementRenderedVisible_[attributionKey];
  33114. }
  33115. delete hiddenAttributions[attributionKey];
  33116. }
  33117. else {
  33118. goog.dom.removeNode(this.attributionElements_[attributionKey]);
  33119. delete this.attributionElements_[attributionKey];
  33120. delete this.attributionElementRenderedVisible_[attributionKey];
  33121. }
  33122. }
  33123. for (attributionKey in visibleAttributions) {
  33124. attributionElement = goog.dom.createElement(goog.dom.TagName.LI);
  33125. attributionElement.innerHTML =
  33126. visibleAttributions[attributionKey].getHTML();
  33127. this.ulElement_.appendChild(attributionElement);
  33128. this.attributionElements_[attributionKey] = attributionElement;
  33129. this.attributionElementRenderedVisible_[attributionKey] = true;
  33130. }
  33131. for (attributionKey in hiddenAttributions) {
  33132. attributionElement = goog.dom.createElement(goog.dom.TagName.LI);
  33133. attributionElement.innerHTML =
  33134. hiddenAttributions[attributionKey].getHTML();
  33135. goog.style.setElementShown(attributionElement, false);
  33136. this.ulElement_.appendChild(attributionElement);
  33137. this.attributionElements_[attributionKey] = attributionElement;
  33138. }
  33139. var renderVisible =
  33140. !goog.object.isEmpty(this.attributionElementRenderedVisible_) ||
  33141. !goog.object.isEmpty(frameState.logos);
  33142. if (this.renderedVisible_ != renderVisible) {
  33143. goog.style.setElementShown(this.element, renderVisible);
  33144. this.renderedVisible_ = renderVisible;
  33145. }
  33146. if (renderVisible &&
  33147. goog.object.isEmpty(this.attributionElementRenderedVisible_)) {
  33148. goog.dom.classlist.add(this.element, 'ol-logo-only');
  33149. } else {
  33150. goog.dom.classlist.remove(this.element, 'ol-logo-only');
  33151. }
  33152. this.insertLogos_(frameState);
  33153. };
  33154. /**
  33155. * @param {?olx.FrameState} frameState Frame state.
  33156. * @private
  33157. */
  33158. ol.control.Attribution.prototype.insertLogos_ = function(frameState) {
  33159. var logo;
  33160. var logos = frameState.logos;
  33161. var logoElements = this.logoElements_;
  33162. for (logo in logoElements) {
  33163. if (!(logo in logos)) {
  33164. goog.dom.removeNode(logoElements[logo]);
  33165. delete logoElements[logo];
  33166. }
  33167. }
  33168. var image, logoElement, logoKey;
  33169. for (logoKey in logos) {
  33170. if (!(logoKey in logoElements)) {
  33171. image = new Image();
  33172. image.src = logoKey;
  33173. var logoValue = logos[logoKey];
  33174. if (logoValue === '') {
  33175. logoElement = image;
  33176. } else {
  33177. logoElement = goog.dom.createDom(goog.dom.TagName.A, {
  33178. 'href': logoValue
  33179. });
  33180. logoElement.appendChild(image);
  33181. }
  33182. this.logoLi_.appendChild(logoElement);
  33183. logoElements[logoKey] = logoElement;
  33184. }
  33185. }
  33186. goog.style.setElementShown(this.logoLi_, !goog.object.isEmpty(logos));
  33187. };
  33188. /**
  33189. * @param {goog.events.BrowserEvent} event The event to handle
  33190. * @private
  33191. */
  33192. ol.control.Attribution.prototype.handleClick_ = function(event) {
  33193. event.preventDefault();
  33194. this.handleToggle_();
  33195. };
  33196. /**
  33197. * @private
  33198. */
  33199. ol.control.Attribution.prototype.handleToggle_ = function() {
  33200. goog.dom.classlist.toggle(this.element, 'ol-collapsed');
  33201. if (this.collapsed_) {
  33202. goog.dom.replaceNode(this.collapseLabel_, this.label_);
  33203. } else {
  33204. goog.dom.replaceNode(this.label_, this.collapseLabel_);
  33205. }
  33206. this.collapsed_ = !this.collapsed_;
  33207. };
  33208. /**
  33209. * Return `true` if the attribution is collapsible, `false` otherwise.
  33210. * @return {boolean} True if the widget is collapsible.
  33211. * @api stable
  33212. */
  33213. ol.control.Attribution.prototype.getCollapsible = function() {
  33214. return this.collapsible_;
  33215. };
  33216. /**
  33217. * Set whether the attribution should be collapsible.
  33218. * @param {boolean} collapsible True if the widget is collapsible.
  33219. * @api stable
  33220. */
  33221. ol.control.Attribution.prototype.setCollapsible = function(collapsible) {
  33222. if (this.collapsible_ === collapsible) {
  33223. return;
  33224. }
  33225. this.collapsible_ = collapsible;
  33226. goog.dom.classlist.toggle(this.element, 'ol-uncollapsible');
  33227. if (!collapsible && this.collapsed_) {
  33228. this.handleToggle_();
  33229. }
  33230. };
  33231. /**
  33232. * Collapse or expand the attribution according to the passed parameter. Will
  33233. * not do anything if the attribution isn't collapsible or if the current
  33234. * collapsed state is already the one requested.
  33235. * @param {boolean} collapsed True if the widget is collapsed.
  33236. * @api stable
  33237. */
  33238. ol.control.Attribution.prototype.setCollapsed = function(collapsed) {
  33239. if (!this.collapsible_ || this.collapsed_ === collapsed) {
  33240. return;
  33241. }
  33242. this.handleToggle_();
  33243. };
  33244. /**
  33245. * Return `true` when the attribution is currently collapsed or `false`
  33246. * otherwise.
  33247. * @return {boolean} True if the widget is collapsed.
  33248. * @api stable
  33249. */
  33250. ol.control.Attribution.prototype.getCollapsed = function() {
  33251. return this.collapsed_;
  33252. };
  33253. goog.provide('ol.control.Rotate');
  33254. goog.require('goog.dom');
  33255. goog.require('goog.dom.TagName');
  33256. goog.require('goog.dom.classlist');
  33257. goog.require('goog.events');
  33258. goog.require('goog.events.EventType');
  33259. goog.require('ol');
  33260. goog.require('ol.animation');
  33261. goog.require('ol.control.Control');
  33262. goog.require('ol.css');
  33263. goog.require('ol.easing');
  33264. /**
  33265. * @classdesc
  33266. * A button control to reset rotation to 0.
  33267. * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css
  33268. * selector is added to the button when the rotation is 0.
  33269. *
  33270. * @constructor
  33271. * @extends {ol.control.Control}
  33272. * @param {olx.control.RotateOptions=} opt_options Rotate options.
  33273. * @api stable
  33274. */
  33275. ol.control.Rotate = function(opt_options) {
  33276. var options = opt_options ? opt_options : {};
  33277. var className = options.className ?
  33278. options.className : 'ol-rotate';
  33279. var label = options.label ? options.label : '\u21E7';
  33280. /**
  33281. * @type {Element}
  33282. * @private
  33283. */
  33284. this.label_ = null;
  33285. if (goog.isString(label)) {
  33286. this.label_ = goog.dom.createDom(goog.dom.TagName.SPAN,
  33287. 'ol-compass', label);
  33288. } else {
  33289. this.label_ = label;
  33290. goog.dom.classlist.add(this.label_, 'ol-compass');
  33291. }
  33292. var tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';
  33293. var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  33294. 'class': className + '-reset',
  33295. 'type' : 'button',
  33296. 'title': tipLabel
  33297. }, this.label_);
  33298. goog.events.listen(button, goog.events.EventType.CLICK,
  33299. ol.control.Rotate.prototype.handleClick_, false, this);
  33300. var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
  33301. ol.css.CLASS_CONTROL;
  33302. var element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, button);
  33303. var render = options.render ? options.render : ol.control.Rotate.render;
  33304. goog.base(this, {
  33305. element: element,
  33306. render: render,
  33307. target: options.target
  33308. });
  33309. /**
  33310. * @type {number}
  33311. * @private
  33312. */
  33313. this.duration_ = options.duration ? options.duration : 250;
  33314. /**
  33315. * @type {boolean}
  33316. * @private
  33317. */
  33318. this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;
  33319. /**
  33320. * @private
  33321. * @type {number|undefined}
  33322. */
  33323. this.rotation_ = undefined;
  33324. if (this.autoHide_) {
  33325. goog.dom.classlist.add(this.element, ol.css.CLASS_HIDDEN);
  33326. }
  33327. };
  33328. goog.inherits(ol.control.Rotate, ol.control.Control);
  33329. /**
  33330. * @param {goog.events.BrowserEvent} event The event to handle
  33331. * @private
  33332. */
  33333. ol.control.Rotate.prototype.handleClick_ = function(event) {
  33334. event.preventDefault();
  33335. this.resetNorth_();
  33336. };
  33337. /**
  33338. * @private
  33339. */
  33340. ol.control.Rotate.prototype.resetNorth_ = function() {
  33341. var map = this.getMap();
  33342. var view = map.getView();
  33343. if (!view) {
  33344. // the map does not have a view, so we can't act
  33345. // upon it
  33346. return;
  33347. }
  33348. var currentRotation = view.getRotation();
  33349. if (currentRotation !== undefined) {
  33350. if (this.duration_ > 0) {
  33351. currentRotation = currentRotation % (2 * Math.PI);
  33352. if (currentRotation < -Math.PI) {
  33353. currentRotation += 2 * Math.PI;
  33354. }
  33355. if (currentRotation > Math.PI) {
  33356. currentRotation -= 2 * Math.PI;
  33357. }
  33358. map.beforeRender(ol.animation.rotate({
  33359. rotation: currentRotation,
  33360. duration: this.duration_,
  33361. easing: ol.easing.easeOut
  33362. }));
  33363. }
  33364. view.setRotation(0);
  33365. }
  33366. };
  33367. /**
  33368. * Update the rotate control element.
  33369. * @param {ol.MapEvent} mapEvent Map event.
  33370. * @this {ol.control.Rotate}
  33371. * @api
  33372. */
  33373. ol.control.Rotate.render = function(mapEvent) {
  33374. var frameState = mapEvent.frameState;
  33375. if (!frameState) {
  33376. return;
  33377. }
  33378. var rotation = frameState.viewState.rotation;
  33379. if (rotation != this.rotation_) {
  33380. var transform = 'rotate(' + rotation + 'rad)';
  33381. if (this.autoHide_) {
  33382. goog.dom.classlist.enable(
  33383. this.element, ol.css.CLASS_HIDDEN, rotation === 0);
  33384. }
  33385. this.label_.style.msTransform = transform;
  33386. this.label_.style.webkitTransform = transform;
  33387. this.label_.style.transform = transform;
  33388. }
  33389. this.rotation_ = rotation;
  33390. };
  33391. goog.provide('ol.control.Zoom');
  33392. goog.require('goog.dom');
  33393. goog.require('goog.dom.TagName');
  33394. goog.require('goog.events');
  33395. goog.require('goog.events.EventType');
  33396. goog.require('ol.animation');
  33397. goog.require('ol.control.Control');
  33398. goog.require('ol.css');
  33399. goog.require('ol.easing');
  33400. /**
  33401. * @classdesc
  33402. * A control with 2 buttons, one for zoom in and one for zoom out.
  33403. * This control is one of the default controls of a map. To style this control
  33404. * use css selectors `.ol-zoom-in` and `.ol-zoom-out`.
  33405. *
  33406. * @constructor
  33407. * @extends {ol.control.Control}
  33408. * @param {olx.control.ZoomOptions=} opt_options Zoom options.
  33409. * @api stable
  33410. */
  33411. ol.control.Zoom = function(opt_options) {
  33412. var options = opt_options ? opt_options : {};
  33413. var className = options.className ? options.className : 'ol-zoom';
  33414. var delta = options.delta ? options.delta : 1;
  33415. var zoomInLabel = options.zoomInLabel ? options.zoomInLabel : '+';
  33416. var zoomOutLabel = options.zoomOutLabel ? options.zoomOutLabel : '\u2212';
  33417. var zoomInTipLabel = options.zoomInTipLabel ?
  33418. options.zoomInTipLabel : 'Zoom in';
  33419. var zoomOutTipLabel = options.zoomOutTipLabel ?
  33420. options.zoomOutTipLabel : 'Zoom out';
  33421. var inElement = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  33422. 'class': className + '-in',
  33423. 'type' : 'button',
  33424. 'title': zoomInTipLabel
  33425. }, zoomInLabel);
  33426. goog.events.listen(inElement,
  33427. goog.events.EventType.CLICK, goog.partial(
  33428. ol.control.Zoom.prototype.handleClick_, delta), false, this);
  33429. var outElement = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  33430. 'class': className + '-out',
  33431. 'type' : 'button',
  33432. 'title': zoomOutTipLabel
  33433. }, zoomOutLabel);
  33434. goog.events.listen(outElement,
  33435. goog.events.EventType.CLICK, goog.partial(
  33436. ol.control.Zoom.prototype.handleClick_, -delta), false, this);
  33437. var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
  33438. ol.css.CLASS_CONTROL;
  33439. var element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, inElement,
  33440. outElement);
  33441. goog.base(this, {
  33442. element: element,
  33443. target: options.target
  33444. });
  33445. /**
  33446. * @type {number}
  33447. * @private
  33448. */
  33449. this.duration_ = options.duration ? options.duration : 250;
  33450. };
  33451. goog.inherits(ol.control.Zoom, ol.control.Control);
  33452. /**
  33453. * @param {number} delta Zoom delta.
  33454. * @param {goog.events.BrowserEvent} event The event to handle
  33455. * @private
  33456. */
  33457. ol.control.Zoom.prototype.handleClick_ = function(delta, event) {
  33458. event.preventDefault();
  33459. this.zoomByDelta_(delta);
  33460. };
  33461. /**
  33462. * @param {number} delta Zoom delta.
  33463. * @private
  33464. */
  33465. ol.control.Zoom.prototype.zoomByDelta_ = function(delta) {
  33466. var map = this.getMap();
  33467. var view = map.getView();
  33468. if (!view) {
  33469. // the map does not have a view, so we can't act
  33470. // upon it
  33471. return;
  33472. }
  33473. var currentResolution = view.getResolution();
  33474. if (currentResolution) {
  33475. if (this.duration_ > 0) {
  33476. map.beforeRender(ol.animation.zoom({
  33477. resolution: currentResolution,
  33478. duration: this.duration_,
  33479. easing: ol.easing.easeOut
  33480. }));
  33481. }
  33482. var newResolution = view.constrainResolution(currentResolution, delta);
  33483. view.setResolution(newResolution);
  33484. }
  33485. };
  33486. goog.provide('ol.control');
  33487. goog.require('ol');
  33488. goog.require('ol.Collection');
  33489. goog.require('ol.control.Attribution');
  33490. goog.require('ol.control.Rotate');
  33491. goog.require('ol.control.Zoom');
  33492. /**
  33493. * Set of controls included in maps by default. Unless configured otherwise,
  33494. * this returns a collection containing an instance of each of the following
  33495. * controls:
  33496. * * {@link ol.control.Zoom}
  33497. * * {@link ol.control.Rotate}
  33498. * * {@link ol.control.Attribution}
  33499. *
  33500. * @param {olx.control.DefaultsOptions=} opt_options Defaults options.
  33501. * @return {ol.Collection.<ol.control.Control>} Controls.
  33502. * @api stable
  33503. */
  33504. ol.control.defaults = function(opt_options) {
  33505. var options = opt_options ? opt_options : {};
  33506. var controls = new ol.Collection();
  33507. var zoomControl = options.zoom !== undefined ? options.zoom : true;
  33508. if (zoomControl) {
  33509. controls.push(new ol.control.Zoom(options.zoomOptions));
  33510. }
  33511. var rotateControl = options.rotate !== undefined ? options.rotate : true;
  33512. if (rotateControl) {
  33513. controls.push(new ol.control.Rotate(options.rotateOptions));
  33514. }
  33515. var attributionControl = options.attribution !== undefined ?
  33516. options.attribution : true;
  33517. if (attributionControl) {
  33518. controls.push(new ol.control.Attribution(options.attributionOptions));
  33519. }
  33520. return controls;
  33521. };
  33522. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  33523. //
  33524. // Licensed under the Apache License, Version 2.0 (the "License");
  33525. // you may not use this file except in compliance with the License.
  33526. // You may obtain a copy of the License at
  33527. //
  33528. // http://www.apache.org/licenses/LICENSE-2.0
  33529. //
  33530. // Unless required by applicable law or agreed to in writing, software
  33531. // distributed under the License is distributed on an "AS-IS" BASIS,
  33532. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  33533. // See the License for the specific language governing permissions and
  33534. // limitations under the License.
  33535. /**
  33536. * @fileoverview Functions for managing full screen status of the DOM.
  33537. *
  33538. */
  33539. goog.provide('goog.dom.fullscreen');
  33540. goog.provide('goog.dom.fullscreen.EventType');
  33541. goog.require('goog.dom');
  33542. goog.require('goog.userAgent');
  33543. /**
  33544. * Event types for full screen.
  33545. * @enum {string}
  33546. */
  33547. goog.dom.fullscreen.EventType = {
  33548. /** Dispatched by the Document when the fullscreen status changes. */
  33549. CHANGE: (function() {
  33550. if (goog.userAgent.WEBKIT) {
  33551. return 'webkitfullscreenchange';
  33552. }
  33553. if (goog.userAgent.GECKO) {
  33554. return 'mozfullscreenchange';
  33555. }
  33556. if (goog.userAgent.IE) {
  33557. return 'MSFullscreenChange';
  33558. }
  33559. // Opera 12-14, and W3C standard (Draft):
  33560. // https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
  33561. return 'fullscreenchange';
  33562. })()
  33563. };
  33564. /**
  33565. * Determines if full screen is supported.
  33566. * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
  33567. * queried. If not provided, use the current DOM.
  33568. * @return {boolean} True iff full screen is supported.
  33569. */
  33570. goog.dom.fullscreen.isSupported = function(opt_domHelper) {
  33571. var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  33572. var body = doc.body;
  33573. return !!(body.webkitRequestFullscreen ||
  33574. (body.mozRequestFullScreen && doc.mozFullScreenEnabled) ||
  33575. (body.msRequestFullscreen && doc.msFullscreenEnabled) ||
  33576. (body.requestFullscreen && doc.fullscreenEnabled));
  33577. };
  33578. /**
  33579. * Requests putting the element in full screen.
  33580. * @param {!Element} element The element to put full screen.
  33581. */
  33582. goog.dom.fullscreen.requestFullScreen = function(element) {
  33583. if (element.webkitRequestFullscreen) {
  33584. element.webkitRequestFullscreen();
  33585. } else if (element.mozRequestFullScreen) {
  33586. element.mozRequestFullScreen();
  33587. } else if (element.msRequestFullscreen) {
  33588. element.msRequestFullscreen();
  33589. } else if (element.requestFullscreen) {
  33590. element.requestFullscreen();
  33591. }
  33592. };
  33593. /**
  33594. * Requests putting the element in full screen with full keyboard access.
  33595. * @param {!Element} element The element to put full screen.
  33596. */
  33597. goog.dom.fullscreen.requestFullScreenWithKeys = function(
  33598. element) {
  33599. if (element.mozRequestFullScreenWithKeys) {
  33600. element.mozRequestFullScreenWithKeys();
  33601. } else if (element.webkitRequestFullscreen) {
  33602. element.webkitRequestFullscreen();
  33603. } else {
  33604. goog.dom.fullscreen.requestFullScreen(element);
  33605. }
  33606. };
  33607. /**
  33608. * Exits full screen.
  33609. * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
  33610. * queried. If not provided, use the current DOM.
  33611. */
  33612. goog.dom.fullscreen.exitFullScreen = function(opt_domHelper) {
  33613. var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  33614. if (doc.webkitCancelFullScreen) {
  33615. doc.webkitCancelFullScreen();
  33616. } else if (doc.mozCancelFullScreen) {
  33617. doc.mozCancelFullScreen();
  33618. } else if (doc.msExitFullscreen) {
  33619. doc.msExitFullscreen();
  33620. } else if (doc.exitFullscreen) {
  33621. doc.exitFullscreen();
  33622. }
  33623. };
  33624. /**
  33625. * Determines if the document is full screen.
  33626. * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
  33627. * queried. If not provided, use the current DOM.
  33628. * @return {boolean} Whether the document is full screen.
  33629. */
  33630. goog.dom.fullscreen.isFullScreen = function(opt_domHelper) {
  33631. var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  33632. // IE 11 doesn't have similar boolean property, so check whether
  33633. // document.msFullscreenElement is null instead.
  33634. return !!(doc.webkitIsFullScreen || doc.mozFullScreen ||
  33635. doc.msFullscreenElement || doc.fullscreenElement);
  33636. };
  33637. /**
  33638. * Get the root element in full screen mode.
  33639. * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
  33640. * queried. If not provided, use the current DOM.
  33641. * @return {?Element} The root element in full screen mode.
  33642. */
  33643. goog.dom.fullscreen.getFullScreenElement = function(opt_domHelper) {
  33644. var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  33645. var element_list = [
  33646. doc.webkitFullscreenElement,
  33647. doc.mozFullScreenElement,
  33648. doc.msFullscreenElement,
  33649. doc.fullscreenElement
  33650. ];
  33651. for (var i = 0; i < element_list.length; i++) {
  33652. if (element_list[i] != null) {
  33653. return element_list[i];
  33654. }
  33655. }
  33656. return null;
  33657. };
  33658. /**
  33659. * Gets the document object of the dom.
  33660. * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
  33661. * queried. If not provided, use the current DOM.
  33662. * @return {!Document} The dom document.
  33663. * @private
  33664. */
  33665. goog.dom.fullscreen.getDocument_ = function(opt_domHelper) {
  33666. return opt_domHelper ?
  33667. opt_domHelper.getDocument() :
  33668. goog.dom.getDomHelper().getDocument();
  33669. };
  33670. goog.provide('ol.control.FullScreen');
  33671. goog.require('goog.asserts');
  33672. goog.require('goog.dom');
  33673. goog.require('goog.dom.TagName');
  33674. goog.require('goog.dom.classlist');
  33675. goog.require('goog.dom.fullscreen');
  33676. goog.require('goog.dom.fullscreen.EventType');
  33677. goog.require('goog.events');
  33678. goog.require('goog.events.EventType');
  33679. goog.require('ol');
  33680. goog.require('ol.control.Control');
  33681. goog.require('ol.css');
  33682. /**
  33683. * @classdesc
  33684. * Provides a button that when clicked fills up the full screen with the map.
  33685. * When in full screen mode, a close button is shown to exit full screen mode.
  33686. * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to
  33687. * toggle the map in full screen mode.
  33688. *
  33689. *
  33690. * @constructor
  33691. * @extends {ol.control.Control}
  33692. * @param {olx.control.FullScreenOptions=} opt_options Options.
  33693. * @api stable
  33694. */
  33695. ol.control.FullScreen = function(opt_options) {
  33696. var options = opt_options ? opt_options : {};
  33697. /**
  33698. * @private
  33699. * @type {string}
  33700. */
  33701. this.cssClassName_ = options.className ? options.className : 'ol-full-screen';
  33702. var label = options.label ? options.label : '\u2194';
  33703. /**
  33704. * @private
  33705. * @type {Node}
  33706. */
  33707. this.labelNode_ = goog.isString(label) ?
  33708. goog.dom.createTextNode(label) : label;
  33709. var labelActive = options.labelActive ? options.labelActive : '\u00d7';
  33710. /**
  33711. * @private
  33712. * @type {Node}
  33713. */
  33714. this.labelActiveNode_ = goog.isString(labelActive) ?
  33715. goog.dom.createTextNode(labelActive) : labelActive;
  33716. var tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen';
  33717. var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  33718. 'class': this.cssClassName_ + '-' + goog.dom.fullscreen.isFullScreen(),
  33719. 'type': 'button',
  33720. 'title': tipLabel
  33721. }, this.labelNode_);
  33722. goog.events.listen(button, goog.events.EventType.CLICK,
  33723. this.handleClick_, false, this);
  33724. goog.events.listen(goog.global.document,
  33725. goog.dom.fullscreen.EventType.CHANGE,
  33726. this.handleFullScreenChange_, false, this);
  33727. var cssClasses = this.cssClassName_ + ' ' + ol.css.CLASS_UNSELECTABLE +
  33728. ' ' + ol.css.CLASS_CONTROL + ' ' +
  33729. (!goog.dom.fullscreen.isSupported() ? ol.css.CLASS_UNSUPPORTED : '');
  33730. var element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, button);
  33731. goog.base(this, {
  33732. element: element,
  33733. target: options.target
  33734. });
  33735. /**
  33736. * @private
  33737. * @type {boolean}
  33738. */
  33739. this.keys_ = options.keys !== undefined ? options.keys : false;
  33740. };
  33741. goog.inherits(ol.control.FullScreen, ol.control.Control);
  33742. /**
  33743. * @param {goog.events.BrowserEvent} event The event to handle
  33744. * @private
  33745. */
  33746. ol.control.FullScreen.prototype.handleClick_ = function(event) {
  33747. event.preventDefault();
  33748. this.handleFullScreen_();
  33749. };
  33750. /**
  33751. * @private
  33752. */
  33753. ol.control.FullScreen.prototype.handleFullScreen_ = function() {
  33754. if (!goog.dom.fullscreen.isSupported()) {
  33755. return;
  33756. }
  33757. var map = this.getMap();
  33758. if (!map) {
  33759. return;
  33760. }
  33761. if (goog.dom.fullscreen.isFullScreen()) {
  33762. goog.dom.fullscreen.exitFullScreen();
  33763. } else {
  33764. var target = map.getTarget();
  33765. goog.asserts.assert(target, 'target should be defined');
  33766. var element = goog.dom.getElement(target);
  33767. goog.asserts.assert(element, 'element should be defined');
  33768. if (this.keys_) {
  33769. goog.dom.fullscreen.requestFullScreenWithKeys(element);
  33770. } else {
  33771. goog.dom.fullscreen.requestFullScreen(element);
  33772. }
  33773. }
  33774. };
  33775. /**
  33776. * @private
  33777. */
  33778. ol.control.FullScreen.prototype.handleFullScreenChange_ = function() {
  33779. var opened = this.cssClassName_ + '-true';
  33780. var closed = this.cssClassName_ + '-false';
  33781. var button = goog.dom.getFirstElementChild(this.element);
  33782. var map = this.getMap();
  33783. if (goog.dom.fullscreen.isFullScreen()) {
  33784. goog.dom.classlist.swap(button, closed, opened);
  33785. goog.dom.replaceNode(this.labelActiveNode_, this.labelNode_);
  33786. } else {
  33787. goog.dom.classlist.swap(button, opened, closed);
  33788. goog.dom.replaceNode(this.labelNode_, this.labelActiveNode_);
  33789. }
  33790. if (map) {
  33791. map.updateSize();
  33792. }
  33793. };
  33794. goog.provide('ol.Pixel');
  33795. /**
  33796. * An array with two elements, representing a pixel. The first element is the
  33797. * x-coordinate, the second the y-coordinate of the pixel.
  33798. * @typedef {Array.<number>}
  33799. * @api stable
  33800. */
  33801. ol.Pixel;
  33802. // FIXME should listen on appropriate pane, once it is defined
  33803. goog.provide('ol.control.MousePosition');
  33804. goog.require('goog.dom');
  33805. goog.require('goog.dom.TagName');
  33806. goog.require('goog.events');
  33807. goog.require('goog.events.EventType');
  33808. goog.require('ol.CoordinateFormatType');
  33809. goog.require('ol.Object');
  33810. goog.require('ol.Pixel');
  33811. goog.require('ol.TransformFunction');
  33812. goog.require('ol.control.Control');
  33813. goog.require('ol.proj');
  33814. goog.require('ol.proj.Projection');
  33815. /**
  33816. * @enum {string}
  33817. */
  33818. ol.control.MousePositionProperty = {
  33819. PROJECTION: 'projection',
  33820. COORDINATE_FORMAT: 'coordinateFormat'
  33821. };
  33822. /**
  33823. * @classdesc
  33824. * A control to show the 2D coordinates of the mouse cursor. By default, these
  33825. * are in the view projection, but can be in any supported projection.
  33826. * By default the control is shown in the top right corner of the map, but this
  33827. * can be changed by using the css selector `.ol-mouse-position`.
  33828. *
  33829. * @constructor
  33830. * @extends {ol.control.Control}
  33831. * @param {olx.control.MousePositionOptions=} opt_options Mouse position
  33832. * options.
  33833. * @api stable
  33834. */
  33835. ol.control.MousePosition = function(opt_options) {
  33836. var options = opt_options ? opt_options : {};
  33837. var className = options.className ? options.className : 'ol-mouse-position';
  33838. var element = goog.dom.createDom(goog.dom.TagName.DIV, className);
  33839. var render = options.render ?
  33840. options.render : ol.control.MousePosition.render;
  33841. goog.base(this, {
  33842. element: element,
  33843. render: render,
  33844. target: options.target
  33845. });
  33846. goog.events.listen(this,
  33847. ol.Object.getChangeEventType(ol.control.MousePositionProperty.PROJECTION),
  33848. this.handleProjectionChanged_, false, this);
  33849. if (options.coordinateFormat) {
  33850. this.setCoordinateFormat(options.coordinateFormat);
  33851. }
  33852. if (options.projection) {
  33853. this.setProjection(ol.proj.get(options.projection));
  33854. }
  33855. /**
  33856. * @private
  33857. * @type {string}
  33858. */
  33859. this.undefinedHTML_ = options.undefinedHTML ? options.undefinedHTML : '';
  33860. /**
  33861. * @private
  33862. * @type {string}
  33863. */
  33864. this.renderedHTML_ = element.innerHTML;
  33865. /**
  33866. * @private
  33867. * @type {ol.proj.Projection}
  33868. */
  33869. this.mapProjection_ = null;
  33870. /**
  33871. * @private
  33872. * @type {?ol.TransformFunction}
  33873. */
  33874. this.transform_ = null;
  33875. /**
  33876. * @private
  33877. * @type {ol.Pixel}
  33878. */
  33879. this.lastMouseMovePixel_ = null;
  33880. };
  33881. goog.inherits(ol.control.MousePosition, ol.control.Control);
  33882. /**
  33883. * Update the mouseposition element.
  33884. * @param {ol.MapEvent} mapEvent Map event.
  33885. * @this {ol.control.MousePosition}
  33886. * @api
  33887. */
  33888. ol.control.MousePosition.render = function(mapEvent) {
  33889. var frameState = mapEvent.frameState;
  33890. if (!frameState) {
  33891. this.mapProjection_ = null;
  33892. } else {
  33893. if (this.mapProjection_ != frameState.viewState.projection) {
  33894. this.mapProjection_ = frameState.viewState.projection;
  33895. this.transform_ = null;
  33896. }
  33897. }
  33898. this.updateHTML_(this.lastMouseMovePixel_);
  33899. };
  33900. /**
  33901. * @private
  33902. */
  33903. ol.control.MousePosition.prototype.handleProjectionChanged_ = function() {
  33904. this.transform_ = null;
  33905. };
  33906. /**
  33907. * Return the coordinate format type used to render the current position or
  33908. * undefined.
  33909. * @return {ol.CoordinateFormatType|undefined} The format to render the current
  33910. * position in.
  33911. * @observable
  33912. * @api stable
  33913. */
  33914. ol.control.MousePosition.prototype.getCoordinateFormat = function() {
  33915. return /** @type {ol.CoordinateFormatType|undefined} */ (
  33916. this.get(ol.control.MousePositionProperty.COORDINATE_FORMAT));
  33917. };
  33918. /**
  33919. * Return the projection that is used to report the mouse position.
  33920. * @return {ol.proj.Projection|undefined} The projection to report mouse
  33921. * position in.
  33922. * @observable
  33923. * @api stable
  33924. */
  33925. ol.control.MousePosition.prototype.getProjection = function() {
  33926. return /** @type {ol.proj.Projection|undefined} */ (
  33927. this.get(ol.control.MousePositionProperty.PROJECTION));
  33928. };
  33929. /**
  33930. * @param {goog.events.BrowserEvent} browserEvent Browser event.
  33931. * @protected
  33932. */
  33933. ol.control.MousePosition.prototype.handleMouseMove = function(browserEvent) {
  33934. var map = this.getMap();
  33935. this.lastMouseMovePixel_ = map.getEventPixel(browserEvent.getBrowserEvent());
  33936. this.updateHTML_(this.lastMouseMovePixel_);
  33937. };
  33938. /**
  33939. * @param {goog.events.BrowserEvent} browserEvent Browser event.
  33940. * @protected
  33941. */
  33942. ol.control.MousePosition.prototype.handleMouseOut = function(browserEvent) {
  33943. this.updateHTML_(null);
  33944. this.lastMouseMovePixel_ = null;
  33945. };
  33946. /**
  33947. * @inheritDoc
  33948. * @api stable
  33949. */
  33950. ol.control.MousePosition.prototype.setMap = function(map) {
  33951. goog.base(this, 'setMap', map);
  33952. if (map) {
  33953. var viewport = map.getViewport();
  33954. this.listenerKeys.push(
  33955. goog.events.listen(viewport, goog.events.EventType.MOUSEMOVE,
  33956. this.handleMouseMove, false, this),
  33957. goog.events.listen(viewport, goog.events.EventType.MOUSEOUT,
  33958. this.handleMouseOut, false, this)
  33959. );
  33960. }
  33961. };
  33962. /**
  33963. * Set the coordinate format type used to render the current position.
  33964. * @param {ol.CoordinateFormatType} format The format to render the current
  33965. * position in.
  33966. * @observable
  33967. * @api stable
  33968. */
  33969. ol.control.MousePosition.prototype.setCoordinateFormat = function(format) {
  33970. this.set(ol.control.MousePositionProperty.COORDINATE_FORMAT, format);
  33971. };
  33972. /**
  33973. * Set the projection that is used to report the mouse position.
  33974. * @param {ol.proj.Projection} projection The projection to report mouse
  33975. * position in.
  33976. * @observable
  33977. * @api stable
  33978. */
  33979. ol.control.MousePosition.prototype.setProjection = function(projection) {
  33980. this.set(ol.control.MousePositionProperty.PROJECTION, projection);
  33981. };
  33982. /**
  33983. * @param {?ol.Pixel} pixel Pixel.
  33984. * @private
  33985. */
  33986. ol.control.MousePosition.prototype.updateHTML_ = function(pixel) {
  33987. var html = this.undefinedHTML_;
  33988. if (pixel && this.mapProjection_) {
  33989. if (!this.transform_) {
  33990. var projection = this.getProjection();
  33991. if (projection) {
  33992. this.transform_ = ol.proj.getTransformFromProjections(
  33993. this.mapProjection_, projection);
  33994. } else {
  33995. this.transform_ = ol.proj.identityTransform;
  33996. }
  33997. }
  33998. var map = this.getMap();
  33999. var coordinate = map.getCoordinateFromPixel(pixel);
  34000. if (coordinate) {
  34001. this.transform_(coordinate, coordinate);
  34002. var coordinateFormat = this.getCoordinateFormat();
  34003. if (coordinateFormat) {
  34004. html = coordinateFormat(coordinate);
  34005. } else {
  34006. html = coordinate.toString();
  34007. }
  34008. }
  34009. }
  34010. if (!this.renderedHTML_ || html != this.renderedHTML_) {
  34011. this.element.innerHTML = html;
  34012. this.renderedHTML_ = html;
  34013. }
  34014. };
  34015. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  34016. //
  34017. // Licensed under the Apache License, Version 2.0 (the "License");
  34018. // you may not use this file except in compliance with the License.
  34019. // You may obtain a copy of the License at
  34020. //
  34021. // http://www.apache.org/licenses/LICENSE-2.0
  34022. //
  34023. // Unless required by applicable law or agreed to in writing, software
  34024. // distributed under the License is distributed on an "AS-IS" BASIS,
  34025. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34026. // See the License for the specific language governing permissions and
  34027. // limitations under the License.
  34028. /**
  34029. * @fileoverview A delayed callback that pegs to the next animation frame
  34030. * instead of a user-configurable timeout.
  34031. *
  34032. * @author nicksantos@google.com (Nick Santos)
  34033. */
  34034. goog.provide('goog.async.AnimationDelay');
  34035. goog.require('goog.Disposable');
  34036. goog.require('goog.events');
  34037. goog.require('goog.functions');
  34038. // TODO(nicksantos): Should we factor out the common code between this and
  34039. // goog.async.Delay? I'm not sure if there's enough code for this to really
  34040. // make sense. Subclassing seems like the wrong approach for a variety of
  34041. // reasons. Maybe there should be a common interface?
  34042. /**
  34043. * A delayed callback that pegs to the next animation frame
  34044. * instead of a user configurable timeout. By design, this should have
  34045. * the same interface as goog.async.Delay.
  34046. *
  34047. * Uses requestAnimationFrame and friends when available, but falls
  34048. * back to a timeout of goog.async.AnimationDelay.TIMEOUT.
  34049. *
  34050. * For more on requestAnimationFrame and how you can use it to create smoother
  34051. * animations, see:
  34052. * @see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  34053. *
  34054. * @param {function(number)} listener Function to call when the delay completes.
  34055. * Will be passed the timestamp when it's called, in unix ms.
  34056. * @param {Window=} opt_window The window object to execute the delay in.
  34057. * Defaults to the global object.
  34058. * @param {Object=} opt_handler The object scope to invoke the function in.
  34059. * @constructor
  34060. * @struct
  34061. * @extends {goog.Disposable}
  34062. * @final
  34063. */
  34064. goog.async.AnimationDelay = function(listener, opt_window, opt_handler) {
  34065. goog.async.AnimationDelay.base(this, 'constructor');
  34066. /**
  34067. * Identifier of the active delay timeout, or event listener,
  34068. * or null when inactive.
  34069. * @private {goog.events.Key|number}
  34070. */
  34071. this.id_ = null;
  34072. /**
  34073. * If we're using dom listeners.
  34074. * @private {?boolean}
  34075. */
  34076. this.usingListeners_ = false;
  34077. /**
  34078. * The function that will be invoked after a delay.
  34079. * @private {function(number)}
  34080. */
  34081. this.listener_ = listener;
  34082. /**
  34083. * The object context to invoke the callback in.
  34084. * @private {Object|undefined}
  34085. */
  34086. this.handler_ = opt_handler;
  34087. /**
  34088. * @private {Window}
  34089. */
  34090. this.win_ = opt_window || window;
  34091. /**
  34092. * Cached callback function invoked when the delay finishes.
  34093. * @private {function()}
  34094. */
  34095. this.callback_ = goog.bind(this.doAction_, this);
  34096. };
  34097. goog.inherits(goog.async.AnimationDelay, goog.Disposable);
  34098. /**
  34099. * Default wait timeout for animations (in milliseconds). Only used for timed
  34100. * animation, which uses a timer (setTimeout) to schedule animation.
  34101. *
  34102. * @type {number}
  34103. * @const
  34104. */
  34105. goog.async.AnimationDelay.TIMEOUT = 20;
  34106. /**
  34107. * Name of event received from the requestAnimationFrame in Firefox.
  34108. *
  34109. * @type {string}
  34110. * @const
  34111. * @private
  34112. */
  34113. goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_ = 'MozBeforePaint';
  34114. /**
  34115. * Starts the delay timer. The provided listener function will be called
  34116. * before the next animation frame.
  34117. */
  34118. goog.async.AnimationDelay.prototype.start = function() {
  34119. this.stop();
  34120. this.usingListeners_ = false;
  34121. var raf = this.getRaf_();
  34122. var cancelRaf = this.getCancelRaf_();
  34123. if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
  34124. // Because Firefox (Gecko) runs animation in separate threads, it also saves
  34125. // time by running the requestAnimationFrame callbacks in that same thread.
  34126. // Sadly this breaks the assumption of implicit thread-safety in JS, and can
  34127. // thus create thread-based inconsistencies on counters etc.
  34128. //
  34129. // Calling cycleAnimations_ using the MozBeforePaint event instead of as
  34130. // callback fixes this.
  34131. //
  34132. // Trigger this condition only if the mozRequestAnimationFrame is available,
  34133. // but not the W3C requestAnimationFrame function (as in draft) or the
  34134. // equivalent cancel functions.
  34135. this.id_ = goog.events.listen(
  34136. this.win_,
  34137. goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_,
  34138. this.callback_);
  34139. this.win_.mozRequestAnimationFrame(null);
  34140. this.usingListeners_ = true;
  34141. } else if (raf && cancelRaf) {
  34142. this.id_ = raf.call(this.win_, this.callback_);
  34143. } else {
  34144. this.id_ = this.win_.setTimeout(
  34145. // Prior to Firefox 13, Gecko passed a non-standard parameter
  34146. // to the callback that we want to ignore.
  34147. goog.functions.lock(this.callback_),
  34148. goog.async.AnimationDelay.TIMEOUT);
  34149. }
  34150. };
  34151. /**
  34152. * Stops the delay timer if it is active. No action is taken if the timer is not
  34153. * in use.
  34154. */
  34155. goog.async.AnimationDelay.prototype.stop = function() {
  34156. if (this.isActive()) {
  34157. var raf = this.getRaf_();
  34158. var cancelRaf = this.getCancelRaf_();
  34159. if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
  34160. goog.events.unlistenByKey(this.id_);
  34161. } else if (raf && cancelRaf) {
  34162. cancelRaf.call(this.win_, /** @type {number} */ (this.id_));
  34163. } else {
  34164. this.win_.clearTimeout(/** @type {number} */ (this.id_));
  34165. }
  34166. }
  34167. this.id_ = null;
  34168. };
  34169. /**
  34170. * Fires delay's action even if timer has already gone off or has not been
  34171. * started yet; guarantees action firing. Stops the delay timer.
  34172. */
  34173. goog.async.AnimationDelay.prototype.fire = function() {
  34174. this.stop();
  34175. this.doAction_();
  34176. };
  34177. /**
  34178. * Fires delay's action only if timer is currently active. Stops the delay
  34179. * timer.
  34180. */
  34181. goog.async.AnimationDelay.prototype.fireIfActive = function() {
  34182. if (this.isActive()) {
  34183. this.fire();
  34184. }
  34185. };
  34186. /**
  34187. * @return {boolean} True if the delay is currently active, false otherwise.
  34188. */
  34189. goog.async.AnimationDelay.prototype.isActive = function() {
  34190. return this.id_ != null;
  34191. };
  34192. /**
  34193. * Invokes the callback function after the delay successfully completes.
  34194. * @private
  34195. */
  34196. goog.async.AnimationDelay.prototype.doAction_ = function() {
  34197. if (this.usingListeners_ && this.id_) {
  34198. goog.events.unlistenByKey(this.id_);
  34199. }
  34200. this.id_ = null;
  34201. // We are not using the timestamp returned by requestAnimationFrame
  34202. // because it may be either a Date.now-style time or a
  34203. // high-resolution time (depending on browser implementation). Using
  34204. // goog.now() will ensure that the timestamp used is consistent and
  34205. // compatible with goog.fx.Animation.
  34206. this.listener_.call(this.handler_, goog.now());
  34207. };
  34208. /** @override */
  34209. goog.async.AnimationDelay.prototype.disposeInternal = function() {
  34210. this.stop();
  34211. goog.async.AnimationDelay.base(this, 'disposeInternal');
  34212. };
  34213. /**
  34214. * @return {?function(function(number)): number} The requestAnimationFrame
  34215. * function, or null if not available on this browser.
  34216. * @private
  34217. */
  34218. goog.async.AnimationDelay.prototype.getRaf_ = function() {
  34219. var win = this.win_;
  34220. return win.requestAnimationFrame ||
  34221. win.webkitRequestAnimationFrame ||
  34222. win.mozRequestAnimationFrame ||
  34223. win.oRequestAnimationFrame ||
  34224. win.msRequestAnimationFrame ||
  34225. null;
  34226. };
  34227. /**
  34228. * @return {?function(number): number} The cancelAnimationFrame function,
  34229. * or null if not available on this browser.
  34230. * @private
  34231. */
  34232. goog.async.AnimationDelay.prototype.getCancelRaf_ = function() {
  34233. var win = this.win_;
  34234. return win.cancelAnimationFrame ||
  34235. win.cancelRequestAnimationFrame ||
  34236. win.webkitCancelRequestAnimationFrame ||
  34237. win.mozCancelRequestAnimationFrame ||
  34238. win.oCancelRequestAnimationFrame ||
  34239. win.msCancelRequestAnimationFrame ||
  34240. null;
  34241. };
  34242. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  34243. //
  34244. // Licensed under the Apache License, Version 2.0 (the "License");
  34245. // you may not use this file except in compliance with the License.
  34246. // You may obtain a copy of the License at
  34247. //
  34248. // http://www.apache.org/licenses/LICENSE-2.0
  34249. //
  34250. // Unless required by applicable law or agreed to in writing, software
  34251. // distributed under the License is distributed on an "AS-IS" BASIS,
  34252. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34253. // See the License for the specific language governing permissions and
  34254. // limitations under the License.
  34255. /**
  34256. * @fileoverview Provides a function to schedule running a function as soon
  34257. * as possible after the current JS execution stops and yields to the event
  34258. * loop.
  34259. *
  34260. */
  34261. goog.provide('goog.async.nextTick');
  34262. goog.provide('goog.async.throwException');
  34263. goog.require('goog.debug.entryPointRegistry');
  34264. goog.require('goog.dom.TagName');
  34265. goog.require('goog.functions');
  34266. goog.require('goog.labs.userAgent.browser');
  34267. goog.require('goog.labs.userAgent.engine');
  34268. /**
  34269. * Throw an item without interrupting the current execution context. For
  34270. * example, if processing a group of items in a loop, sometimes it is useful
  34271. * to report an error while still allowing the rest of the batch to be
  34272. * processed.
  34273. * @param {*} exception
  34274. */
  34275. goog.async.throwException = function(exception) {
  34276. // Each throw needs to be in its own context.
  34277. goog.global.setTimeout(function() { throw exception; }, 0);
  34278. };
  34279. /**
  34280. * Fires the provided callbacks as soon as possible after the current JS
  34281. * execution context. setTimeout(…, 0) takes at least 4ms when called from
  34282. * within another setTimeout(…, 0) for legacy reasons.
  34283. *
  34284. * This will not schedule the callback as a microtask (i.e. a task that can
  34285. * preempt user input or networking callbacks). It is meant to emulate what
  34286. * setTimeout(_, 0) would do if it were not throttled. If you desire microtask
  34287. * behavior, use {@see goog.Promise} instead.
  34288. *
  34289. * @param {function(this:SCOPE)} callback Callback function to fire as soon as
  34290. * possible.
  34291. * @param {SCOPE=} opt_context Object in whose scope to call the listener.
  34292. * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that
  34293. * ensures correctness at the cost of speed. See comments for details.
  34294. * @template SCOPE
  34295. */
  34296. goog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) {
  34297. var cb = callback;
  34298. if (opt_context) {
  34299. cb = goog.bind(callback, opt_context);
  34300. }
  34301. cb = goog.async.nextTick.wrapCallback_(cb);
  34302. // window.setImmediate was introduced and currently only supported by IE10+,
  34303. // but due to a bug in the implementation it is not guaranteed that
  34304. // setImmediate is faster than setTimeout nor that setImmediate N is before
  34305. // setImmediate N+1. That is why we do not use the native version if
  34306. // available. We do, however, call setImmediate if it is a normal function
  34307. // because that indicates that it has been replaced by goog.testing.MockClock
  34308. // which we do want to support.
  34309. // See
  34310. // http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10
  34311. //
  34312. // Note we do allow callers to also request setImmediate if they are willing
  34313. // to accept the possible tradeoffs of incorrectness in exchange for speed.
  34314. // The IE fallback of readystate change is much slower.
  34315. if (goog.isFunction(goog.global.setImmediate) &&
  34316. // Opt in.
  34317. (opt_useSetImmediate ||
  34318. // or it isn't a browser or the environment is weird
  34319. !goog.global.Window || !goog.global.Window.prototype ||
  34320. // or something redefined setImmediate in which case we (YOLO) decide
  34321. // to use it (This is so that we use the mockClock setImmediate. sigh).
  34322. goog.global.Window.prototype.setImmediate != goog.global.setImmediate)) {
  34323. goog.global.setImmediate(cb);
  34324. return;
  34325. }
  34326. // Look for and cache the custom fallback version of setImmediate.
  34327. if (!goog.async.nextTick.setImmediate_) {
  34328. goog.async.nextTick.setImmediate_ =
  34329. goog.async.nextTick.getSetImmediateEmulator_();
  34330. }
  34331. goog.async.nextTick.setImmediate_(cb);
  34332. };
  34333. /**
  34334. * Cache for the setImmediate implementation.
  34335. * @type {function(function())}
  34336. * @private
  34337. */
  34338. goog.async.nextTick.setImmediate_;
  34339. /**
  34340. * Determines the best possible implementation to run a function as soon as
  34341. * the JS event loop is idle.
  34342. * @return {function(function())} The "setImmediate" implementation.
  34343. * @private
  34344. */
  34345. goog.async.nextTick.getSetImmediateEmulator_ = function() {
  34346. // Create a private message channel and use it to postMessage empty messages
  34347. // to ourselves.
  34348. var Channel = goog.global['MessageChannel'];
  34349. // If MessageChannel is not available and we are in a browser, implement
  34350. // an iframe based polyfill in browsers that have postMessage and
  34351. // document.addEventListener. The latter excludes IE8 because it has a
  34352. // synchronous postMessage implementation.
  34353. if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&
  34354. window.postMessage && window.addEventListener &&
  34355. // Presto (The old pre-blink Opera engine) has problems with iframes
  34356. // and contentWindow.
  34357. !goog.labs.userAgent.engine.isPresto()) {
  34358. /** @constructor */
  34359. Channel = function() {
  34360. // Make an empty, invisible iframe.
  34361. var iframe = document.createElement(goog.dom.TagName.IFRAME);
  34362. iframe.style.display = 'none';
  34363. iframe.src = '';
  34364. document.documentElement.appendChild(iframe);
  34365. var win = iframe.contentWindow;
  34366. var doc = win.document;
  34367. doc.open();
  34368. doc.write('');
  34369. doc.close();
  34370. // Do not post anything sensitive over this channel, as the workaround for
  34371. // pages with file: origin could allow that information to be modified or
  34372. // intercepted.
  34373. var message = 'callImmediate' + Math.random();
  34374. // The same origin policy rejects attempts to postMessage from file: urls
  34375. // unless the origin is '*'.
  34376. // TODO(b/16335441): Use '*' origin for data: and other similar protocols.
  34377. var origin = win.location.protocol == 'file:' ?
  34378. '*' : win.location.protocol + '//' + win.location.host;
  34379. var onmessage = goog.bind(function(e) {
  34380. // Validate origin and message to make sure that this message was
  34381. // intended for us. If the origin is set to '*' (see above) only the
  34382. // message needs to match since, for example, '*' != 'file://'. Allowing
  34383. // the wildcard is ok, as we are not concerned with security here.
  34384. if ((origin != '*' && e.origin != origin) || e.data != message) {
  34385. return;
  34386. }
  34387. this['port1'].onmessage();
  34388. }, this);
  34389. win.addEventListener('message', onmessage, false);
  34390. this['port1'] = {};
  34391. this['port2'] = {
  34392. postMessage: function() {
  34393. win.postMessage(message, origin);
  34394. }
  34395. };
  34396. };
  34397. }
  34398. if (typeof Channel !== 'undefined' &&
  34399. (!goog.labs.userAgent.browser.isIE())) {
  34400. // Exclude all of IE due to
  34401. // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/
  34402. // which allows starving postMessage with a busy setTimeout loop.
  34403. // This currently affects IE10 and IE11 which would otherwise be able
  34404. // to use the postMessage based fallbacks.
  34405. var channel = new Channel();
  34406. // Use a fifo linked list to call callbacks in the right order.
  34407. var head = {};
  34408. var tail = head;
  34409. channel['port1'].onmessage = function() {
  34410. if (goog.isDef(head.next)) {
  34411. head = head.next;
  34412. var cb = head.cb;
  34413. head.cb = null;
  34414. cb();
  34415. }
  34416. };
  34417. return function(cb) {
  34418. tail.next = {
  34419. cb: cb
  34420. };
  34421. tail = tail.next;
  34422. channel['port2'].postMessage(0);
  34423. };
  34424. }
  34425. // Implementation for IE6+: Script elements fire an asynchronous
  34426. // onreadystatechange event when inserted into the DOM.
  34427. if (typeof document !== 'undefined' && 'onreadystatechange' in
  34428. document.createElement(goog.dom.TagName.SCRIPT)) {
  34429. return function(cb) {
  34430. var script = document.createElement(goog.dom.TagName.SCRIPT);
  34431. script.onreadystatechange = function() {
  34432. // Clean up and call the callback.
  34433. script.onreadystatechange = null;
  34434. script.parentNode.removeChild(script);
  34435. script = null;
  34436. cb();
  34437. cb = null;
  34438. };
  34439. document.documentElement.appendChild(script);
  34440. };
  34441. }
  34442. // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms
  34443. // or more.
  34444. return function(cb) {
  34445. goog.global.setTimeout(cb, 0);
  34446. };
  34447. };
  34448. /**
  34449. * Helper function that is overrided to protect callbacks with entry point
  34450. * monitor if the application monitors entry points.
  34451. * @param {function()} callback Callback function to fire as soon as possible.
  34452. * @return {function()} The wrapped callback.
  34453. * @private
  34454. */
  34455. goog.async.nextTick.wrapCallback_ = goog.functions.identity;
  34456. // Register the callback function as an entry point, so that it can be
  34457. // monitored for exception handling, etc. This has to be done in this file
  34458. // since it requires special code to handle all browsers.
  34459. goog.debug.entryPointRegistry.register(
  34460. /**
  34461. * @param {function(!Function): !Function} transformer The transforming
  34462. * function.
  34463. */
  34464. function(transformer) {
  34465. goog.async.nextTick.wrapCallback_ = transformer;
  34466. });
  34467. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  34468. //
  34469. // Licensed under the Apache License, Version 2.0 (the "License");
  34470. // you may not use this file except in compliance with the License.
  34471. // You may obtain a copy of the License at
  34472. //
  34473. // http://www.apache.org/licenses/LICENSE-2.0
  34474. //
  34475. // Unless required by applicable law or agreed to in writing, software
  34476. // distributed under the License is distributed on an "AS-IS" BASIS,
  34477. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34478. // See the License for the specific language governing permissions and
  34479. // limitations under the License.
  34480. /**
  34481. * @fileoverview The SafeScript type and its builders.
  34482. *
  34483. * TODO(xtof): Link to document stating type contract.
  34484. */
  34485. goog.provide('goog.html.SafeScript');
  34486. goog.require('goog.asserts');
  34487. goog.require('goog.string.Const');
  34488. goog.require('goog.string.TypedString');
  34489. /**
  34490. * A string-like object which represents JavaScript code and that carries the
  34491. * security type contract that its value, as a string, will not cause execution
  34492. * of unconstrained attacker controlled code (XSS) when evaluated as JavaScript
  34493. * in a browser.
  34494. *
  34495. * Instances of this type must be created via the factory method
  34496. * {@code goog.html.SafeScript.fromConstant} and not by invoking its
  34497. * constructor. The constructor intentionally takes no parameters and the type
  34498. * is immutable; hence only a default instance corresponding to the empty string
  34499. * can be obtained via constructor invocation.
  34500. *
  34501. * A SafeScript's string representation can safely be interpolated as the
  34502. * content of a script element within HTML. The SafeScript string should not be
  34503. * escaped before interpolation.
  34504. *
  34505. * Note that the SafeScript might contain text that is attacker-controlled but
  34506. * that text should have been interpolated with appropriate escaping,
  34507. * sanitization and/or validation into the right location in the script, such
  34508. * that it is highly constrained in its effect (for example, it had to match a
  34509. * set of whitelisted words).
  34510. *
  34511. * A SafeScript can be constructed via security-reviewed unchecked
  34512. * conversions. In this case producers of SafeScript must ensure themselves that
  34513. * the SafeScript does not contain unsafe script. Note in particular that
  34514. * {@code &lt;} is dangerous, even when inside JavaScript strings, and so should
  34515. * always be forbidden or JavaScript escaped in user controlled input. For
  34516. * example, if {@code &lt;/script&gt;&lt;script&gt;evil&lt;/script&gt;"} were
  34517. * interpolated inside a JavaScript string, it would break out of the context
  34518. * of the original script element and {@code evil} would execute. Also note
  34519. * that within an HTML script (raw text) element, HTML character references,
  34520. * such as "&lt;" are not allowed. See
  34521. * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements.
  34522. *
  34523. * @see goog.html.SafeScript#fromConstant
  34524. * @constructor
  34525. * @final
  34526. * @struct
  34527. * @implements {goog.string.TypedString}
  34528. */
  34529. goog.html.SafeScript = function() {
  34530. /**
  34531. * The contained value of this SafeScript. The field has a purposely
  34532. * ugly name to make (non-compiled) code that attempts to directly access this
  34533. * field stand out.
  34534. * @private {string}
  34535. */
  34536. this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = '';
  34537. /**
  34538. * A type marker used to implement additional run-time type checking.
  34539. * @see goog.html.SafeScript#unwrap
  34540. * @const
  34541. * @private
  34542. */
  34543. this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  34544. goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  34545. };
  34546. /**
  34547. * @override
  34548. * @const
  34549. */
  34550. goog.html.SafeScript.prototype.implementsGoogStringTypedString = true;
  34551. /**
  34552. * Type marker for the SafeScript type, used to implement additional
  34553. * run-time type checking.
  34554. * @const {!Object}
  34555. * @private
  34556. */
  34557. goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  34558. /**
  34559. * Creates a SafeScript object from a compile-time constant string.
  34560. *
  34561. * @param {!goog.string.Const} script A compile-time-constant string from which
  34562. * to create a SafeScript.
  34563. * @return {!goog.html.SafeScript} A SafeScript object initialized to
  34564. * {@code script}.
  34565. */
  34566. goog.html.SafeScript.fromConstant = function(script) {
  34567. var scriptString = goog.string.Const.unwrap(script);
  34568. if (scriptString.length === 0) {
  34569. return goog.html.SafeScript.EMPTY;
  34570. }
  34571. return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
  34572. scriptString);
  34573. };
  34574. /**
  34575. * Returns this SafeScript's value as a string.
  34576. *
  34577. * IMPORTANT: In code where it is security relevant that an object's type is
  34578. * indeed {@code SafeScript}, use {@code goog.html.SafeScript.unwrap} instead of
  34579. * this method. If in doubt, assume that it's security relevant. In particular,
  34580. * note that goog.html functions which return a goog.html type do not guarantee
  34581. * the returned instance is of the right type. For example:
  34582. *
  34583. * <pre>
  34584. * var fakeSafeHtml = new String('fake');
  34585. * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
  34586. * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
  34587. * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
  34588. * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
  34589. * // instanceof goog.html.SafeHtml.
  34590. * </pre>
  34591. *
  34592. * @see goog.html.SafeScript#unwrap
  34593. * @override
  34594. */
  34595. goog.html.SafeScript.prototype.getTypedStringValue = function() {
  34596. return this.privateDoNotAccessOrElseSafeScriptWrappedValue_;
  34597. };
  34598. if (goog.DEBUG) {
  34599. /**
  34600. * Returns a debug string-representation of this value.
  34601. *
  34602. * To obtain the actual string value wrapped in a SafeScript, use
  34603. * {@code goog.html.SafeScript.unwrap}.
  34604. *
  34605. * @see goog.html.SafeScript#unwrap
  34606. * @override
  34607. */
  34608. goog.html.SafeScript.prototype.toString = function() {
  34609. return 'SafeScript{' +
  34610. this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + '}';
  34611. };
  34612. }
  34613. /**
  34614. * Performs a runtime check that the provided object is indeed a
  34615. * SafeScript object, and returns its value.
  34616. *
  34617. * @param {!goog.html.SafeScript} safeScript The object to extract from.
  34618. * @return {string} The safeScript object's contained string, unless
  34619. * the run-time type check fails. In that case, {@code unwrap} returns an
  34620. * innocuous string, or, if assertions are enabled, throws
  34621. * {@code goog.asserts.AssertionError}.
  34622. */
  34623. goog.html.SafeScript.unwrap = function(safeScript) {
  34624. // Perform additional Run-time type-checking to ensure that
  34625. // safeScript is indeed an instance of the expected type. This
  34626. // provides some additional protection against security bugs due to
  34627. // application code that disables type checks.
  34628. // Specifically, the following checks are performed:
  34629. // 1. The object is an instance of the expected type.
  34630. // 2. The object is not an instance of a subclass.
  34631. // 3. The object carries a type marker for the expected type. "Faking" an
  34632. // object requires a reference to the type marker, which has names intended
  34633. // to stand out in code reviews.
  34634. if (safeScript instanceof goog.html.SafeScript &&
  34635. safeScript.constructor === goog.html.SafeScript &&
  34636. safeScript.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  34637. goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  34638. return safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_;
  34639. } else {
  34640. goog.asserts.fail(
  34641. 'expected object of type SafeScript, got \'' + safeScript + '\'');
  34642. return 'type_error:SafeScript';
  34643. }
  34644. };
  34645. /**
  34646. * Package-internal utility method to create SafeScript instances.
  34647. *
  34648. * @param {string} script The string to initialize the SafeScript object with.
  34649. * @return {!goog.html.SafeScript} The initialized SafeScript object.
  34650. * @package
  34651. */
  34652. goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse =
  34653. function(script) {
  34654. return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_(
  34655. script);
  34656. };
  34657. /**
  34658. * Called from createSafeScriptSecurityPrivateDoNotAccessOrElse(). This
  34659. * method exists only so that the compiler can dead code eliminate static
  34660. * fields (like EMPTY) when they're not accessed.
  34661. * @param {string} script
  34662. * @return {!goog.html.SafeScript}
  34663. * @private
  34664. */
  34665. goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
  34666. script) {
  34667. this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script;
  34668. return this;
  34669. };
  34670. /**
  34671. * A SafeScript instance corresponding to the empty string.
  34672. * @const {!goog.html.SafeScript}
  34673. */
  34674. goog.html.SafeScript.EMPTY =
  34675. goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse('');
  34676. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  34677. //
  34678. // Licensed under the Apache License, Version 2.0 (the "License");
  34679. // you may not use this file except in compliance with the License.
  34680. // You may obtain a copy of the License at
  34681. //
  34682. // http://www.apache.org/licenses/LICENSE-2.0
  34683. //
  34684. // Unless required by applicable law or agreed to in writing, software
  34685. // distributed under the License is distributed on an "AS-IS" BASIS,
  34686. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34687. // See the License for the specific language governing permissions and
  34688. // limitations under the License.
  34689. /**
  34690. * @fileoverview Unchecked conversions to create values of goog.html types from
  34691. * plain strings. Use of these functions could potentially result in instances
  34692. * of goog.html types that violate their type contracts, and hence result in
  34693. * security vulnerabilties.
  34694. *
  34695. * Therefore, all uses of the methods herein must be carefully security
  34696. * reviewed. Avoid use of the methods in this file whenever possible; instead
  34697. * prefer to create instances of goog.html types using inherently safe builders
  34698. * or template systems.
  34699. *
  34700. *
  34701. *
  34702. * @visibility {//closure/goog/html:approved_for_unchecked_conversion}
  34703. * @visibility {//closure/goog/bin/sizetests:__pkg__}
  34704. */
  34705. goog.provide('goog.html.uncheckedconversions');
  34706. goog.require('goog.asserts');
  34707. goog.require('goog.html.SafeHtml');
  34708. goog.require('goog.html.SafeScript');
  34709. goog.require('goog.html.SafeStyle');
  34710. goog.require('goog.html.SafeStyleSheet');
  34711. goog.require('goog.html.SafeUrl');
  34712. goog.require('goog.html.TrustedResourceUrl');
  34713. goog.require('goog.string');
  34714. goog.require('goog.string.Const');
  34715. /**
  34716. * Performs an "unchecked conversion" to SafeHtml from a plain string that is
  34717. * known to satisfy the SafeHtml type contract.
  34718. *
  34719. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34720. * that the value of {@code html} satisfies the SafeHtml type contract in all
  34721. * possible program states.
  34722. *
  34723. *
  34724. * @param {!goog.string.Const} justification A constant string explaining why
  34725. * this use of this method is safe. May include a security review ticket
  34726. * number.
  34727. * @param {string} html A string that is claimed to adhere to the SafeHtml
  34728. * contract.
  34729. * @param {?goog.i18n.bidi.Dir=} opt_dir The optional directionality of the
  34730. * SafeHtml to be constructed. A null or undefined value signifies an
  34731. * unknown directionality.
  34732. * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml
  34733. * object.
  34734. * @suppress {visibility} For access to SafeHtml.create... Note that this
  34735. * use is appropriate since this method is intended to be "package private"
  34736. * withing goog.html. DO NOT call SafeHtml.create... from outside this
  34737. * package; use appropriate wrappers instead.
  34738. */
  34739. goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract =
  34740. function(justification, html, opt_dir) {
  34741. // unwrap() called inside an assert so that justification can be optimized
  34742. // away in production code.
  34743. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34744. 'must provide justification');
  34745. goog.asserts.assert(
  34746. !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
  34747. 'must provide non-empty justification');
  34748. return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
  34749. html, opt_dir || null);
  34750. };
  34751. /**
  34752. * Performs an "unchecked conversion" to SafeScript from a plain string that is
  34753. * known to satisfy the SafeScript type contract.
  34754. *
  34755. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34756. * that the value of {@code script} satisfies the SafeScript type contract in
  34757. * all possible program states.
  34758. *
  34759. *
  34760. * @param {!goog.string.Const} justification A constant string explaining why
  34761. * this use of this method is safe. May include a security review ticket
  34762. * number.
  34763. * @param {string} script The string to wrap as a SafeScript.
  34764. * @return {!goog.html.SafeScript} The value of {@code script}, wrapped in a
  34765. * SafeScript object.
  34766. */
  34767. goog.html.uncheckedconversions.safeScriptFromStringKnownToSatisfyTypeContract =
  34768. function(justification, script) {
  34769. // unwrap() called inside an assert so that justification can be optimized
  34770. // away in production code.
  34771. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34772. 'must provide justification');
  34773. goog.asserts.assert(
  34774. !goog.string.isEmpty(goog.string.Const.unwrap(justification)),
  34775. 'must provide non-empty justification');
  34776. return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
  34777. script);
  34778. };
  34779. /**
  34780. * Performs an "unchecked conversion" to SafeStyle from a plain string that is
  34781. * known to satisfy the SafeStyle type contract.
  34782. *
  34783. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34784. * that the value of {@code style} satisfies the SafeUrl type contract in all
  34785. * possible program states.
  34786. *
  34787. *
  34788. * @param {!goog.string.Const} justification A constant string explaining why
  34789. * this use of this method is safe. May include a security review ticket
  34790. * number.
  34791. * @param {string} style The string to wrap as a SafeStyle.
  34792. * @return {!goog.html.SafeStyle} The value of {@code style}, wrapped in a
  34793. * SafeStyle object.
  34794. */
  34795. goog.html.uncheckedconversions.safeStyleFromStringKnownToSatisfyTypeContract =
  34796. function(justification, style) {
  34797. // unwrap() called inside an assert so that justification can be optimized
  34798. // away in production code.
  34799. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34800. 'must provide justification');
  34801. goog.asserts.assert(
  34802. !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
  34803. 'must provide non-empty justification');
  34804. return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
  34805. style);
  34806. };
  34807. /**
  34808. * Performs an "unchecked conversion" to SafeStyleSheet from a plain string
  34809. * that is known to satisfy the SafeStyleSheet type contract.
  34810. *
  34811. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34812. * that the value of {@code styleSheet} satisfies the SafeUrl type contract in
  34813. * all possible program states.
  34814. *
  34815. *
  34816. * @param {!goog.string.Const} justification A constant string explaining why
  34817. * this use of this method is safe. May include a security review ticket
  34818. * number.
  34819. * @param {string} styleSheet The string to wrap as a SafeStyleSheet.
  34820. * @return {!goog.html.SafeStyleSheet} The value of {@code styleSheet}, wrapped
  34821. * in a SafeStyleSheet object.
  34822. */
  34823. goog.html.uncheckedconversions.
  34824. safeStyleSheetFromStringKnownToSatisfyTypeContract =
  34825. function(justification, styleSheet) {
  34826. // unwrap() called inside an assert so that justification can be optimized
  34827. // away in production code.
  34828. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34829. 'must provide justification');
  34830. goog.asserts.assert(
  34831. !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
  34832. 'must provide non-empty justification');
  34833. return goog.html.SafeStyleSheet.
  34834. createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
  34835. };
  34836. /**
  34837. * Performs an "unchecked conversion" to SafeUrl from a plain string that is
  34838. * known to satisfy the SafeUrl type contract.
  34839. *
  34840. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34841. * that the value of {@code url} satisfies the SafeUrl type contract in all
  34842. * possible program states.
  34843. *
  34844. *
  34845. * @param {!goog.string.Const} justification A constant string explaining why
  34846. * this use of this method is safe. May include a security review ticket
  34847. * number.
  34848. * @param {string} url The string to wrap as a SafeUrl.
  34849. * @return {!goog.html.SafeUrl} The value of {@code url}, wrapped in a SafeUrl
  34850. * object.
  34851. */
  34852. goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract =
  34853. function(justification, url) {
  34854. // unwrap() called inside an assert so that justification can be optimized
  34855. // away in production code.
  34856. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34857. 'must provide justification');
  34858. goog.asserts.assert(
  34859. !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
  34860. 'must provide non-empty justification');
  34861. return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
  34862. };
  34863. /**
  34864. * Performs an "unchecked conversion" to TrustedResourceUrl from a plain string
  34865. * that is known to satisfy the TrustedResourceUrl type contract.
  34866. *
  34867. * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure
  34868. * that the value of {@code url} satisfies the TrustedResourceUrl type contract
  34869. * in all possible program states.
  34870. *
  34871. *
  34872. * @param {!goog.string.Const} justification A constant string explaining why
  34873. * this use of this method is safe. May include a security review ticket
  34874. * number.
  34875. * @param {string} url The string to wrap as a TrustedResourceUrl.
  34876. * @return {!goog.html.TrustedResourceUrl} The value of {@code url}, wrapped in
  34877. * a TrustedResourceUrl object.
  34878. */
  34879. goog.html.uncheckedconversions.
  34880. trustedResourceUrlFromStringKnownToSatisfyTypeContract =
  34881. function(justification, url) {
  34882. // unwrap() called inside an assert so that justification can be optimized
  34883. // away in production code.
  34884. goog.asserts.assertString(goog.string.Const.unwrap(justification),
  34885. 'must provide justification');
  34886. goog.asserts.assert(
  34887. !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)),
  34888. 'must provide non-empty justification');
  34889. return goog.html.TrustedResourceUrl.
  34890. createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
  34891. };
  34892. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  34893. //
  34894. // Licensed under the Apache License, Version 2.0 (the "License");
  34895. // you may not use this file except in compliance with the License.
  34896. // You may obtain a copy of the License at
  34897. //
  34898. // http://www.apache.org/licenses/LICENSE-2.0
  34899. //
  34900. // Unless required by applicable law or agreed to in writing, software
  34901. // distributed under the License is distributed on an "AS-IS" BASIS,
  34902. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34903. // See the License for the specific language governing permissions and
  34904. // limitations under the License.
  34905. /**
  34906. * @fileoverview Generics method for collection-like classes and objects.
  34907. *
  34908. * @author arv@google.com (Erik Arvidsson)
  34909. *
  34910. * This file contains functions to work with collections. It supports using
  34911. * Map, Set, Array and Object and other classes that implement collection-like
  34912. * methods.
  34913. */
  34914. goog.provide('goog.structs');
  34915. goog.require('goog.array');
  34916. goog.require('goog.object');
  34917. // We treat an object as a dictionary if it has getKeys or it is an object that
  34918. // isn't arrayLike.
  34919. /**
  34920. * Returns the number of values in the collection-like object.
  34921. * @param {Object} col The collection-like object.
  34922. * @return {number} The number of values in the collection-like object.
  34923. */
  34924. goog.structs.getCount = function(col) {
  34925. if (typeof col.getCount == 'function') {
  34926. return col.getCount();
  34927. }
  34928. if (goog.isArrayLike(col) || goog.isString(col)) {
  34929. return col.length;
  34930. }
  34931. return goog.object.getCount(col);
  34932. };
  34933. /**
  34934. * Returns the values of the collection-like object.
  34935. * @param {Object} col The collection-like object.
  34936. * @return {!Array<?>} The values in the collection-like object.
  34937. */
  34938. goog.structs.getValues = function(col) {
  34939. if (typeof col.getValues == 'function') {
  34940. return col.getValues();
  34941. }
  34942. if (goog.isString(col)) {
  34943. return col.split('');
  34944. }
  34945. if (goog.isArrayLike(col)) {
  34946. var rv = [];
  34947. var l = col.length;
  34948. for (var i = 0; i < l; i++) {
  34949. rv.push(col[i]);
  34950. }
  34951. return rv;
  34952. }
  34953. return goog.object.getValues(col);
  34954. };
  34955. /**
  34956. * Returns the keys of the collection. Some collections have no notion of
  34957. * keys/indexes and this function will return undefined in those cases.
  34958. * @param {Object} col The collection-like object.
  34959. * @return {!Array|undefined} The keys in the collection.
  34960. */
  34961. goog.structs.getKeys = function(col) {
  34962. if (typeof col.getKeys == 'function') {
  34963. return col.getKeys();
  34964. }
  34965. // if we have getValues but no getKeys we know this is a key-less collection
  34966. if (typeof col.getValues == 'function') {
  34967. return undefined;
  34968. }
  34969. if (goog.isArrayLike(col) || goog.isString(col)) {
  34970. var rv = [];
  34971. var l = col.length;
  34972. for (var i = 0; i < l; i++) {
  34973. rv.push(i);
  34974. }
  34975. return rv;
  34976. }
  34977. return goog.object.getKeys(col);
  34978. };
  34979. /**
  34980. * Whether the collection contains the given value. This is O(n) and uses
  34981. * equals (==) to test the existence.
  34982. * @param {Object} col The collection-like object.
  34983. * @param {*} val The value to check for.
  34984. * @return {boolean} True if the map contains the value.
  34985. */
  34986. goog.structs.contains = function(col, val) {
  34987. if (typeof col.contains == 'function') {
  34988. return col.contains(val);
  34989. }
  34990. if (typeof col.containsValue == 'function') {
  34991. return col.containsValue(val);
  34992. }
  34993. if (goog.isArrayLike(col) || goog.isString(col)) {
  34994. return goog.array.contains(/** @type {!Array<?>} */ (col), val);
  34995. }
  34996. return goog.object.containsValue(col, val);
  34997. };
  34998. /**
  34999. * Whether the collection is empty.
  35000. * @param {Object} col The collection-like object.
  35001. * @return {boolean} True if empty.
  35002. */
  35003. goog.structs.isEmpty = function(col) {
  35004. if (typeof col.isEmpty == 'function') {
  35005. return col.isEmpty();
  35006. }
  35007. // We do not use goog.string.isEmptyOrWhitespace because here we treat the string as
  35008. // collection and as such even whitespace matters
  35009. if (goog.isArrayLike(col) || goog.isString(col)) {
  35010. return goog.array.isEmpty(/** @type {!Array<?>} */ (col));
  35011. }
  35012. return goog.object.isEmpty(col);
  35013. };
  35014. /**
  35015. * Removes all the elements from the collection.
  35016. * @param {Object} col The collection-like object.
  35017. */
  35018. goog.structs.clear = function(col) {
  35019. // NOTE(arv): This should not contain strings because strings are immutable
  35020. if (typeof col.clear == 'function') {
  35021. col.clear();
  35022. } else if (goog.isArrayLike(col)) {
  35023. goog.array.clear(/** @type {goog.array.ArrayLike} */ (col));
  35024. } else {
  35025. goog.object.clear(col);
  35026. }
  35027. };
  35028. /**
  35029. * Calls a function for each value in a collection. The function takes
  35030. * three arguments; the value, the key and the collection.
  35031. *
  35032. * NOTE: This will be deprecated soon! Please use a more specific method if
  35033. * possible, e.g. goog.array.forEach, goog.object.forEach, etc.
  35034. *
  35035. * @param {S} col The collection-like object.
  35036. * @param {function(this:T,?,?,S):?} f The function to call for every value.
  35037. * This function takes
  35038. * 3 arguments (the value, the key or undefined if the collection has no
  35039. * notion of keys, and the collection) and the return value is irrelevant.
  35040. * @param {T=} opt_obj The object to be used as the value of 'this'
  35041. * within {@code f}.
  35042. * @template T,S
  35043. */
  35044. goog.structs.forEach = function(col, f, opt_obj) {
  35045. if (typeof col.forEach == 'function') {
  35046. col.forEach(f, opt_obj);
  35047. } else if (goog.isArrayLike(col) || goog.isString(col)) {
  35048. goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj);
  35049. } else {
  35050. var keys = goog.structs.getKeys(col);
  35051. var values = goog.structs.getValues(col);
  35052. var l = values.length;
  35053. for (var i = 0; i < l; i++) {
  35054. f.call(opt_obj, values[i], keys && keys[i], col);
  35055. }
  35056. }
  35057. };
  35058. /**
  35059. * Calls a function for every value in the collection. When a call returns true,
  35060. * adds the value to a new collection (Array is returned by default).
  35061. *
  35062. * @param {S} col The collection-like object.
  35063. * @param {function(this:T,?,?,S):boolean} f The function to call for every
  35064. * value. This function takes
  35065. * 3 arguments (the value, the key or undefined if the collection has no
  35066. * notion of keys, and the collection) and should return a Boolean. If the
  35067. * return value is true the value is added to the result collection. If it
  35068. * is false the value is not included.
  35069. * @param {T=} opt_obj The object to be used as the value of 'this'
  35070. * within {@code f}.
  35071. * @return {!Object|!Array<?>} A new collection where the passed values are
  35072. * present. If col is a key-less collection an array is returned. If col
  35073. * has keys and values a plain old JS object is returned.
  35074. * @template T,S
  35075. */
  35076. goog.structs.filter = function(col, f, opt_obj) {
  35077. if (typeof col.filter == 'function') {
  35078. return col.filter(f, opt_obj);
  35079. }
  35080. if (goog.isArrayLike(col) || goog.isString(col)) {
  35081. return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj);
  35082. }
  35083. var rv;
  35084. var keys = goog.structs.getKeys(col);
  35085. var values = goog.structs.getValues(col);
  35086. var l = values.length;
  35087. if (keys) {
  35088. rv = {};
  35089. for (var i = 0; i < l; i++) {
  35090. if (f.call(opt_obj, values[i], keys[i], col)) {
  35091. rv[keys[i]] = values[i];
  35092. }
  35093. }
  35094. } else {
  35095. // We should not use goog.array.filter here since we want to make sure that
  35096. // the index is undefined as well as make sure that col is passed to the
  35097. // function.
  35098. rv = [];
  35099. for (var i = 0; i < l; i++) {
  35100. if (f.call(opt_obj, values[i], undefined, col)) {
  35101. rv.push(values[i]);
  35102. }
  35103. }
  35104. }
  35105. return rv;
  35106. };
  35107. /**
  35108. * Calls a function for every value in the collection and adds the result into a
  35109. * new collection (defaults to creating a new Array).
  35110. *
  35111. * @param {S} col The collection-like object.
  35112. * @param {function(this:T,?,?,S):V} f The function to call for every value.
  35113. * This function takes 3 arguments (the value, the key or undefined if the
  35114. * collection has no notion of keys, and the collection) and should return
  35115. * something. The result will be used as the value in the new collection.
  35116. * @param {T=} opt_obj The object to be used as the value of 'this'
  35117. * within {@code f}.
  35118. * @return {!Object<V>|!Array<V>} A new collection with the new values. If
  35119. * col is a key-less collection an array is returned. If col has keys and
  35120. * values a plain old JS object is returned.
  35121. * @template T,S,V
  35122. */
  35123. goog.structs.map = function(col, f, opt_obj) {
  35124. if (typeof col.map == 'function') {
  35125. return col.map(f, opt_obj);
  35126. }
  35127. if (goog.isArrayLike(col) || goog.isString(col)) {
  35128. return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj);
  35129. }
  35130. var rv;
  35131. var keys = goog.structs.getKeys(col);
  35132. var values = goog.structs.getValues(col);
  35133. var l = values.length;
  35134. if (keys) {
  35135. rv = {};
  35136. for (var i = 0; i < l; i++) {
  35137. rv[keys[i]] = f.call(opt_obj, values[i], keys[i], col);
  35138. }
  35139. } else {
  35140. // We should not use goog.array.map here since we want to make sure that
  35141. // the index is undefined as well as make sure that col is passed to the
  35142. // function.
  35143. rv = [];
  35144. for (var i = 0; i < l; i++) {
  35145. rv[i] = f.call(opt_obj, values[i], undefined, col);
  35146. }
  35147. }
  35148. return rv;
  35149. };
  35150. /**
  35151. * Calls f for each value in a collection. If any call returns true this returns
  35152. * true (without checking the rest). If all returns false this returns false.
  35153. *
  35154. * @param {S} col The collection-like object.
  35155. * @param {function(this:T,?,?,S):boolean} f The function to call for every
  35156. * value. This function takes 3 arguments (the value, the key or undefined
  35157. * if the collection has no notion of keys, and the collection) and should
  35158. * return a boolean.
  35159. * @param {T=} opt_obj The object to be used as the value of 'this'
  35160. * within {@code f}.
  35161. * @return {boolean} True if any value passes the test.
  35162. * @template T,S
  35163. */
  35164. goog.structs.some = function(col, f, opt_obj) {
  35165. if (typeof col.some == 'function') {
  35166. return col.some(f, opt_obj);
  35167. }
  35168. if (goog.isArrayLike(col) || goog.isString(col)) {
  35169. return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj);
  35170. }
  35171. var keys = goog.structs.getKeys(col);
  35172. var values = goog.structs.getValues(col);
  35173. var l = values.length;
  35174. for (var i = 0; i < l; i++) {
  35175. if (f.call(opt_obj, values[i], keys && keys[i], col)) {
  35176. return true;
  35177. }
  35178. }
  35179. return false;
  35180. };
  35181. /**
  35182. * Calls f for each value in a collection. If all calls return true this return
  35183. * true this returns true. If any returns false this returns false at this point
  35184. * and does not continue to check the remaining values.
  35185. *
  35186. * @param {S} col The collection-like object.
  35187. * @param {function(this:T,?,?,S):boolean} f The function to call for every
  35188. * value. This function takes 3 arguments (the value, the key or
  35189. * undefined if the collection has no notion of keys, and the collection)
  35190. * and should return a boolean.
  35191. * @param {T=} opt_obj The object to be used as the value of 'this'
  35192. * within {@code f}.
  35193. * @return {boolean} True if all key-value pairs pass the test.
  35194. * @template T,S
  35195. */
  35196. goog.structs.every = function(col, f, opt_obj) {
  35197. if (typeof col.every == 'function') {
  35198. return col.every(f, opt_obj);
  35199. }
  35200. if (goog.isArrayLike(col) || goog.isString(col)) {
  35201. return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj);
  35202. }
  35203. var keys = goog.structs.getKeys(col);
  35204. var values = goog.structs.getValues(col);
  35205. var l = values.length;
  35206. for (var i = 0; i < l; i++) {
  35207. if (!f.call(opt_obj, values[i], keys && keys[i], col)) {
  35208. return false;
  35209. }
  35210. }
  35211. return true;
  35212. };
  35213. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  35214. //
  35215. // Licensed under the Apache License, Version 2.0 (the "License");
  35216. // you may not use this file except in compliance with the License.
  35217. // You may obtain a copy of the License at
  35218. //
  35219. // http://www.apache.org/licenses/LICENSE-2.0
  35220. //
  35221. // Unless required by applicable law or agreed to in writing, software
  35222. // distributed under the License is distributed on an "AS-IS" BASIS,
  35223. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  35224. // See the License for the specific language governing permissions and
  35225. // limitations under the License.
  35226. /**
  35227. * @fileoverview Defines the collection interface.
  35228. *
  35229. * @author nnaze@google.com (Nathan Naze)
  35230. */
  35231. goog.provide('goog.structs.Collection');
  35232. /**
  35233. * An interface for a collection of values.
  35234. * @interface
  35235. * @template T
  35236. */
  35237. goog.structs.Collection = function() {};
  35238. /**
  35239. * @param {T} value Value to add to the collection.
  35240. */
  35241. goog.structs.Collection.prototype.add;
  35242. /**
  35243. * @param {T} value Value to remove from the collection.
  35244. */
  35245. goog.structs.Collection.prototype.remove;
  35246. /**
  35247. * @param {T} value Value to find in the collection.
  35248. * @return {boolean} Whether the collection contains the specified value.
  35249. */
  35250. goog.structs.Collection.prototype.contains;
  35251. /**
  35252. * @return {number} The number of values stored in the collection.
  35253. */
  35254. goog.structs.Collection.prototype.getCount;
  35255. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  35256. //
  35257. // Licensed under the Apache License, Version 2.0 (the "License");
  35258. // you may not use this file except in compliance with the License.
  35259. // You may obtain a copy of the License at
  35260. //
  35261. // http://www.apache.org/licenses/LICENSE-2.0
  35262. //
  35263. // Unless required by applicable law or agreed to in writing, software
  35264. // distributed under the License is distributed on an "AS-IS" BASIS,
  35265. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  35266. // See the License for the specific language governing permissions and
  35267. // limitations under the License.
  35268. /**
  35269. * @fileoverview Python style iteration utilities.
  35270. * @author arv@google.com (Erik Arvidsson)
  35271. */
  35272. goog.provide('goog.iter');
  35273. goog.provide('goog.iter.Iterable');
  35274. goog.provide('goog.iter.Iterator');
  35275. goog.provide('goog.iter.StopIteration');
  35276. goog.require('goog.array');
  35277. goog.require('goog.asserts');
  35278. goog.require('goog.functions');
  35279. goog.require('goog.math');
  35280. /**
  35281. * @typedef {goog.iter.Iterator|{length:number}|{__iterator__}}
  35282. */
  35283. goog.iter.Iterable;
  35284. /**
  35285. * Singleton Error object that is used to terminate iterations.
  35286. * @const {!Error}
  35287. */
  35288. goog.iter.StopIteration = ('StopIteration' in goog.global) ?
  35289. // For script engines that support legacy iterators.
  35290. goog.global['StopIteration'] :
  35291. { message: 'StopIteration', stack: ''};
  35292. /**
  35293. * Class/interface for iterators. An iterator needs to implement a {@code next}
  35294. * method and it needs to throw a {@code goog.iter.StopIteration} when the
  35295. * iteration passes beyond the end. Iterators have no {@code hasNext} method.
  35296. * It is recommended to always use the helper functions to iterate over the
  35297. * iterator or in case you are only targeting JavaScript 1.7 for in loops.
  35298. * @constructor
  35299. * @template VALUE
  35300. */
  35301. goog.iter.Iterator = function() {};
  35302. /**
  35303. * Returns the next value of the iteration. This will throw the object
  35304. * {@see goog.iter#StopIteration} when the iteration passes the end.
  35305. * @return {VALUE} Any object or value.
  35306. */
  35307. goog.iter.Iterator.prototype.next = function() {
  35308. throw goog.iter.StopIteration;
  35309. };
  35310. /**
  35311. * Returns the {@code Iterator} object itself. This is used to implement
  35312. * the iterator protocol in JavaScript 1.7
  35313. * @param {boolean=} opt_keys Whether to return the keys or values. Default is
  35314. * to only return the values. This is being used by the for-in loop (true)
  35315. * and the for-each-in loop (false). Even though the param gives a hint
  35316. * about what the iterator will return there is no guarantee that it will
  35317. * return the keys when true is passed.
  35318. * @return {!goog.iter.Iterator<VALUE>} The object itself.
  35319. */
  35320. goog.iter.Iterator.prototype.__iterator__ = function(opt_keys) {
  35321. return this;
  35322. };
  35323. /**
  35324. * Returns an iterator that knows how to iterate over the values in the object.
  35325. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable If the
  35326. * object is an iterator it will be returned as is. If the object has an
  35327. * {@code __iterator__} method that will be called to get the value
  35328. * iterator. If the object is an array-like object we create an iterator
  35329. * for that.
  35330. * @return {!goog.iter.Iterator<VALUE>} An iterator that knows how to iterate
  35331. * over the values in {@code iterable}.
  35332. * @template VALUE
  35333. */
  35334. goog.iter.toIterator = function(iterable) {
  35335. if (iterable instanceof goog.iter.Iterator) {
  35336. return iterable;
  35337. }
  35338. if (typeof iterable.__iterator__ == 'function') {
  35339. return iterable.__iterator__(false);
  35340. }
  35341. if (goog.isArrayLike(iterable)) {
  35342. var i = 0;
  35343. var newIter = new goog.iter.Iterator;
  35344. newIter.next = function() {
  35345. while (true) {
  35346. if (i >= iterable.length) {
  35347. throw goog.iter.StopIteration;
  35348. }
  35349. // Don't include deleted elements.
  35350. if (!(i in iterable)) {
  35351. i++;
  35352. continue;
  35353. }
  35354. return iterable[i++];
  35355. }
  35356. };
  35357. return newIter;
  35358. }
  35359. // TODO(arv): Should we fall back on goog.structs.getValues()?
  35360. throw Error('Not implemented');
  35361. };
  35362. /**
  35363. * Calls a function for each element in the iterator with the element of the
  35364. * iterator passed as argument.
  35365. *
  35366. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35367. * to iterate over. If the iterable is an object {@code toIterator} will be
  35368. * called on it.
  35369. * @param {function(this:THIS,VALUE,?,!goog.iter.Iterator<VALUE>)} f
  35370. * The function to call for every element. This function takes 3 arguments
  35371. * (the element, undefined, and the iterator) and the return value is
  35372. * irrelevant. The reason for passing undefined as the second argument is
  35373. * so that the same function can be used in {@see goog.array#forEach} as
  35374. * well as others. The third parameter is of type "number" for
  35375. * arraylike objects, undefined, otherwise.
  35376. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35377. * {@code f}.
  35378. * @template THIS, VALUE
  35379. */
  35380. goog.iter.forEach = function(iterable, f, opt_obj) {
  35381. if (goog.isArrayLike(iterable)) {
  35382. /** @preserveTry */
  35383. try {
  35384. // NOTES: this passes the index number to the second parameter
  35385. // of the callback contrary to the documentation above.
  35386. goog.array.forEach(/** @type {goog.array.ArrayLike} */(iterable), f,
  35387. opt_obj);
  35388. } catch (ex) {
  35389. if (ex !== goog.iter.StopIteration) {
  35390. throw ex;
  35391. }
  35392. }
  35393. } else {
  35394. iterable = goog.iter.toIterator(iterable);
  35395. /** @preserveTry */
  35396. try {
  35397. while (true) {
  35398. f.call(opt_obj, iterable.next(), undefined, iterable);
  35399. }
  35400. } catch (ex) {
  35401. if (ex !== goog.iter.StopIteration) {
  35402. throw ex;
  35403. }
  35404. }
  35405. }
  35406. };
  35407. /**
  35408. * Calls a function for every element in the iterator, and if the function
  35409. * returns true adds the element to a new iterator.
  35410. *
  35411. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35412. * to iterate over.
  35413. * @param {
  35414. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35415. * The function to call for every element. This function takes 3 arguments
  35416. * (the element, undefined, and the iterator) and should return a boolean.
  35417. * If the return value is true the element will be included in the returned
  35418. * iterator. If it is false the element is not included.
  35419. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35420. * {@code f}.
  35421. * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements
  35422. * that passed the test are present.
  35423. * @template THIS, VALUE
  35424. */
  35425. goog.iter.filter = function(iterable, f, opt_obj) {
  35426. var iterator = goog.iter.toIterator(iterable);
  35427. var newIter = new goog.iter.Iterator;
  35428. newIter.next = function() {
  35429. while (true) {
  35430. var val = iterator.next();
  35431. if (f.call(opt_obj, val, undefined, iterator)) {
  35432. return val;
  35433. }
  35434. }
  35435. };
  35436. return newIter;
  35437. };
  35438. /**
  35439. * Calls a function for every element in the iterator, and if the function
  35440. * returns false adds the element to a new iterator.
  35441. *
  35442. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35443. * to iterate over.
  35444. * @param {
  35445. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35446. * The function to call for every element. This function takes 3 arguments
  35447. * (the element, undefined, and the iterator) and should return a boolean.
  35448. * If the return value is false the element will be included in the returned
  35449. * iterator. If it is true the element is not included.
  35450. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35451. * {@code f}.
  35452. * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements
  35453. * that did not pass the test are present.
  35454. * @template THIS, VALUE
  35455. */
  35456. goog.iter.filterFalse = function(iterable, f, opt_obj) {
  35457. return goog.iter.filter(iterable, goog.functions.not(f), opt_obj);
  35458. };
  35459. /**
  35460. * Creates a new iterator that returns the values in a range. This function
  35461. * can take 1, 2 or 3 arguments:
  35462. * <pre>
  35463. * range(5) same as range(0, 5, 1)
  35464. * range(2, 5) same as range(2, 5, 1)
  35465. * </pre>
  35466. *
  35467. * @param {number} startOrStop The stop value if only one argument is provided.
  35468. * The start value if 2 or more arguments are provided. If only one
  35469. * argument is used the start value is 0.
  35470. * @param {number=} opt_stop The stop value. If left out then the first
  35471. * argument is used as the stop value.
  35472. * @param {number=} opt_step The number to increment with between each call to
  35473. * next. This can be negative.
  35474. * @return {!goog.iter.Iterator<number>} A new iterator that returns the values
  35475. * in the range.
  35476. */
  35477. goog.iter.range = function(startOrStop, opt_stop, opt_step) {
  35478. var start = 0;
  35479. var stop = startOrStop;
  35480. var step = opt_step || 1;
  35481. if (arguments.length > 1) {
  35482. start = startOrStop;
  35483. stop = opt_stop;
  35484. }
  35485. if (step == 0) {
  35486. throw Error('Range step argument must not be zero');
  35487. }
  35488. var newIter = new goog.iter.Iterator;
  35489. newIter.next = function() {
  35490. if (step > 0 && start >= stop || step < 0 && start <= stop) {
  35491. throw goog.iter.StopIteration;
  35492. }
  35493. var rv = start;
  35494. start += step;
  35495. return rv;
  35496. };
  35497. return newIter;
  35498. };
  35499. /**
  35500. * Joins the values in a iterator with a delimiter.
  35501. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35502. * to get the values from.
  35503. * @param {string} deliminator The text to put between the values.
  35504. * @return {string} The joined value string.
  35505. * @template VALUE
  35506. */
  35507. goog.iter.join = function(iterable, deliminator) {
  35508. return goog.iter.toArray(iterable).join(deliminator);
  35509. };
  35510. /**
  35511. * For every element in the iterator call a function and return a new iterator
  35512. * with that value.
  35513. *
  35514. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  35515. * iterator to iterate over.
  35516. * @param {
  35517. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):RESULT} f
  35518. * The function to call for every element. This function takes 3 arguments
  35519. * (the element, undefined, and the iterator) and should return a new value.
  35520. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35521. * {@code f}.
  35522. * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the
  35523. * results of applying the function to each element in the original
  35524. * iterator.
  35525. * @template THIS, VALUE, RESULT
  35526. */
  35527. goog.iter.map = function(iterable, f, opt_obj) {
  35528. var iterator = goog.iter.toIterator(iterable);
  35529. var newIter = new goog.iter.Iterator;
  35530. newIter.next = function() {
  35531. var val = iterator.next();
  35532. return f.call(opt_obj, val, undefined, iterator);
  35533. };
  35534. return newIter;
  35535. };
  35536. /**
  35537. * Passes every element of an iterator into a function and accumulates the
  35538. * result.
  35539. *
  35540. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35541. * to iterate over.
  35542. * @param {function(this:THIS,VALUE,VALUE):VALUE} f The function to call for
  35543. * every element. This function takes 2 arguments (the function's previous
  35544. * result or the initial value, and the value of the current element).
  35545. * function(previousValue, currentElement) : newValue.
  35546. * @param {VALUE} val The initial value to pass into the function on the first
  35547. * call.
  35548. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35549. * f.
  35550. * @return {VALUE} Result of evaluating f repeatedly across the values of
  35551. * the iterator.
  35552. * @template THIS, VALUE
  35553. */
  35554. goog.iter.reduce = function(iterable, f, val, opt_obj) {
  35555. var rval = val;
  35556. goog.iter.forEach(iterable, function(val) {
  35557. rval = f.call(opt_obj, rval, val);
  35558. });
  35559. return rval;
  35560. };
  35561. /**
  35562. * Goes through the values in the iterator. Calls f for each of these, and if
  35563. * any of them returns true, this returns true (without checking the rest). If
  35564. * all return false this will return false.
  35565. *
  35566. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35567. * object.
  35568. * @param {
  35569. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35570. * The function to call for every value. This function takes 3 arguments
  35571. * (the value, undefined, and the iterator) and should return a boolean.
  35572. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35573. * {@code f}.
  35574. * @return {boolean} true if any value passes the test.
  35575. * @template THIS, VALUE
  35576. */
  35577. goog.iter.some = function(iterable, f, opt_obj) {
  35578. iterable = goog.iter.toIterator(iterable);
  35579. /** @preserveTry */
  35580. try {
  35581. while (true) {
  35582. if (f.call(opt_obj, iterable.next(), undefined, iterable)) {
  35583. return true;
  35584. }
  35585. }
  35586. } catch (ex) {
  35587. if (ex !== goog.iter.StopIteration) {
  35588. throw ex;
  35589. }
  35590. }
  35591. return false;
  35592. };
  35593. /**
  35594. * Goes through the values in the iterator. Calls f for each of these and if any
  35595. * of them returns false this returns false (without checking the rest). If all
  35596. * return true this will return true.
  35597. *
  35598. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35599. * object.
  35600. * @param {
  35601. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35602. * The function to call for every value. This function takes 3 arguments
  35603. * (the value, undefined, and the iterator) and should return a boolean.
  35604. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35605. * {@code f}.
  35606. * @return {boolean} true if every value passes the test.
  35607. * @template THIS, VALUE
  35608. */
  35609. goog.iter.every = function(iterable, f, opt_obj) {
  35610. iterable = goog.iter.toIterator(iterable);
  35611. /** @preserveTry */
  35612. try {
  35613. while (true) {
  35614. if (!f.call(opt_obj, iterable.next(), undefined, iterable)) {
  35615. return false;
  35616. }
  35617. }
  35618. } catch (ex) {
  35619. if (ex !== goog.iter.StopIteration) {
  35620. throw ex;
  35621. }
  35622. }
  35623. return true;
  35624. };
  35625. /**
  35626. * Takes zero or more iterables and returns one iterator that will iterate over
  35627. * them in the order chained.
  35628. * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any
  35629. * number of iterable objects.
  35630. * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will
  35631. * iterate over all the given iterables' contents.
  35632. * @template VALUE
  35633. */
  35634. goog.iter.chain = function(var_args) {
  35635. return goog.iter.chainFromIterable(arguments);
  35636. };
  35637. /**
  35638. * Takes a single iterable containing zero or more iterables and returns one
  35639. * iterator that will iterate over each one in the order given.
  35640. * @see http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable
  35641. * @param {goog.iter.Iterable} iterable The iterable of iterables to chain.
  35642. * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will
  35643. * iterate over all the contents of the iterables contained within
  35644. * {@code iterable}.
  35645. * @template VALUE
  35646. */
  35647. goog.iter.chainFromIterable = function(iterable) {
  35648. var iterator = goog.iter.toIterator(iterable);
  35649. var iter = new goog.iter.Iterator();
  35650. var current = null;
  35651. iter.next = function() {
  35652. while (true) {
  35653. if (current == null) {
  35654. var it = iterator.next();
  35655. current = goog.iter.toIterator(it);
  35656. }
  35657. try {
  35658. return current.next();
  35659. } catch (ex) {
  35660. if (ex !== goog.iter.StopIteration) {
  35661. throw ex;
  35662. }
  35663. current = null;
  35664. }
  35665. }
  35666. };
  35667. return iter;
  35668. };
  35669. /**
  35670. * Builds a new iterator that iterates over the original, but skips elements as
  35671. * long as a supplied function returns true.
  35672. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35673. * object.
  35674. * @param {
  35675. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35676. * The function to call for every value. This function takes 3 arguments
  35677. * (the value, undefined, and the iterator) and should return a boolean.
  35678. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  35679. * {@code f}.
  35680. * @return {!goog.iter.Iterator<VALUE>} A new iterator that drops elements from
  35681. * the original iterator as long as {@code f} is true.
  35682. * @template THIS, VALUE
  35683. */
  35684. goog.iter.dropWhile = function(iterable, f, opt_obj) {
  35685. var iterator = goog.iter.toIterator(iterable);
  35686. var newIter = new goog.iter.Iterator;
  35687. var dropping = true;
  35688. newIter.next = function() {
  35689. while (true) {
  35690. var val = iterator.next();
  35691. if (dropping && f.call(opt_obj, val, undefined, iterator)) {
  35692. continue;
  35693. } else {
  35694. dropping = false;
  35695. }
  35696. return val;
  35697. }
  35698. };
  35699. return newIter;
  35700. };
  35701. /**
  35702. * Builds a new iterator that iterates over the original, but only as long as a
  35703. * supplied function returns true.
  35704. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35705. * object.
  35706. * @param {
  35707. * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f
  35708. * The function to call for every value. This function takes 3 arguments
  35709. * (the value, undefined, and the iterator) and should return a boolean.
  35710. * @param {THIS=} opt_obj This is used as the 'this' object in f when called.
  35711. * @return {!goog.iter.Iterator<VALUE>} A new iterator that keeps elements in
  35712. * the original iterator as long as the function is true.
  35713. * @template THIS, VALUE
  35714. */
  35715. goog.iter.takeWhile = function(iterable, f, opt_obj) {
  35716. var iterator = goog.iter.toIterator(iterable);
  35717. var iter = new goog.iter.Iterator();
  35718. iter.next = function() {
  35719. var val = iterator.next();
  35720. if (f.call(opt_obj, val, undefined, iterator)) {
  35721. return val;
  35722. }
  35723. throw goog.iter.StopIteration;
  35724. };
  35725. return iter;
  35726. };
  35727. /**
  35728. * Converts the iterator to an array
  35729. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator
  35730. * to convert to an array.
  35731. * @return {!Array<VALUE>} An array of the elements the iterator iterates over.
  35732. * @template VALUE
  35733. */
  35734. goog.iter.toArray = function(iterable) {
  35735. // Fast path for array-like.
  35736. if (goog.isArrayLike(iterable)) {
  35737. return goog.array.toArray(/** @type {!goog.array.ArrayLike} */(iterable));
  35738. }
  35739. iterable = goog.iter.toIterator(iterable);
  35740. var array = [];
  35741. goog.iter.forEach(iterable, function(val) {
  35742. array.push(val);
  35743. });
  35744. return array;
  35745. };
  35746. /**
  35747. * Iterates over two iterables and returns true if they contain the same
  35748. * sequence of elements and have the same length.
  35749. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable1 The first
  35750. * iterable object.
  35751. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable2 The second
  35752. * iterable object.
  35753. * @param {function(VALUE,VALUE):boolean=} opt_equalsFn Optional comparison
  35754. * function.
  35755. * Should take two arguments to compare, and return true if the arguments
  35756. * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
  35757. * compares the elements using the built-in '===' operator.
  35758. * @return {boolean} true if the iterables contain the same sequence of elements
  35759. * and have the same length.
  35760. * @template VALUE
  35761. */
  35762. goog.iter.equals = function(iterable1, iterable2, opt_equalsFn) {
  35763. var fillValue = {};
  35764. var pairs = goog.iter.zipLongest(fillValue, iterable1, iterable2);
  35765. var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
  35766. return goog.iter.every(pairs, function(pair) {
  35767. return equalsFn(pair[0], pair[1]);
  35768. });
  35769. };
  35770. /**
  35771. * Advances the iterator to the next position, returning the given default value
  35772. * instead of throwing an exception if the iterator has no more entries.
  35773. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterable
  35774. * object.
  35775. * @param {VALUE} defaultValue The value to return if the iterator is empty.
  35776. * @return {VALUE} The next item in the iteration, or defaultValue if the
  35777. * iterator was empty.
  35778. * @template VALUE
  35779. */
  35780. goog.iter.nextOrValue = function(iterable, defaultValue) {
  35781. try {
  35782. return goog.iter.toIterator(iterable).next();
  35783. } catch (e) {
  35784. if (e != goog.iter.StopIteration) {
  35785. throw e;
  35786. }
  35787. return defaultValue;
  35788. }
  35789. };
  35790. /**
  35791. * Cartesian product of zero or more sets. Gives an iterator that gives every
  35792. * combination of one element chosen from each set. For example,
  35793. * ([1, 2], [3, 4]) gives ([1, 3], [1, 4], [2, 3], [2, 4]).
  35794. * @see http://docs.python.org/library/itertools.html#itertools.product
  35795. * @param {...!goog.array.ArrayLike<VALUE>} var_args Zero or more sets, as
  35796. * arrays.
  35797. * @return {!goog.iter.Iterator<!Array<VALUE>>} An iterator that gives each
  35798. * n-tuple (as an array).
  35799. * @template VALUE
  35800. */
  35801. goog.iter.product = function(var_args) {
  35802. var someArrayEmpty = goog.array.some(arguments, function(arr) {
  35803. return !arr.length;
  35804. });
  35805. // An empty set in a cartesian product gives an empty set.
  35806. if (someArrayEmpty || !arguments.length) {
  35807. return new goog.iter.Iterator();
  35808. }
  35809. var iter = new goog.iter.Iterator();
  35810. var arrays = arguments;
  35811. // The first indices are [0, 0, ...]
  35812. var indicies = goog.array.repeat(0, arrays.length);
  35813. iter.next = function() {
  35814. if (indicies) {
  35815. var retVal = goog.array.map(indicies, function(valueIndex, arrayIndex) {
  35816. return arrays[arrayIndex][valueIndex];
  35817. });
  35818. // Generate the next-largest indices for the next call.
  35819. // Increase the rightmost index. If it goes over, increase the next
  35820. // rightmost (like carry-over addition).
  35821. for (var i = indicies.length - 1; i >= 0; i--) {
  35822. // Assertion prevents compiler warning below.
  35823. goog.asserts.assert(indicies);
  35824. if (indicies[i] < arrays[i].length - 1) {
  35825. indicies[i]++;
  35826. break;
  35827. }
  35828. // We're at the last indices (the last element of every array), so
  35829. // the iteration is over on the next call.
  35830. if (i == 0) {
  35831. indicies = null;
  35832. break;
  35833. }
  35834. // Reset the index in this column and loop back to increment the
  35835. // next one.
  35836. indicies[i] = 0;
  35837. }
  35838. return retVal;
  35839. }
  35840. throw goog.iter.StopIteration;
  35841. };
  35842. return iter;
  35843. };
  35844. /**
  35845. * Create an iterator to cycle over the iterable's elements indefinitely.
  35846. * For example, ([1, 2, 3]) would return : 1, 2, 3, 1, 2, 3, ...
  35847. * @see: http://docs.python.org/library/itertools.html#itertools.cycle.
  35848. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  35849. * iterable object.
  35850. * @return {!goog.iter.Iterator<VALUE>} An iterator that iterates indefinitely
  35851. * over the values in {@code iterable}.
  35852. * @template VALUE
  35853. */
  35854. goog.iter.cycle = function(iterable) {
  35855. var baseIterator = goog.iter.toIterator(iterable);
  35856. // We maintain a cache to store the iterable elements as we iterate
  35857. // over them. The cache is used to return elements once we have
  35858. // iterated over the iterable once.
  35859. var cache = [];
  35860. var cacheIndex = 0;
  35861. var iter = new goog.iter.Iterator();
  35862. // This flag is set after the iterable is iterated over once
  35863. var useCache = false;
  35864. iter.next = function() {
  35865. var returnElement = null;
  35866. // Pull elements off the original iterator if not using cache
  35867. if (!useCache) {
  35868. try {
  35869. // Return the element from the iterable
  35870. returnElement = baseIterator.next();
  35871. cache.push(returnElement);
  35872. return returnElement;
  35873. } catch (e) {
  35874. // If an exception other than StopIteration is thrown
  35875. // or if there are no elements to iterate over (the iterable was empty)
  35876. // throw an exception
  35877. if (e != goog.iter.StopIteration || goog.array.isEmpty(cache)) {
  35878. throw e;
  35879. }
  35880. // set useCache to true after we know that a 'StopIteration' exception
  35881. // was thrown and the cache is not empty (to handle the 'empty iterable'
  35882. // use case)
  35883. useCache = true;
  35884. }
  35885. }
  35886. returnElement = cache[cacheIndex];
  35887. cacheIndex = (cacheIndex + 1) % cache.length;
  35888. return returnElement;
  35889. };
  35890. return iter;
  35891. };
  35892. /**
  35893. * Creates an iterator that counts indefinitely from a starting value.
  35894. * @see http://docs.python.org/2/library/itertools.html#itertools.count
  35895. * @param {number=} opt_start The starting value. Default is 0.
  35896. * @param {number=} opt_step The number to increment with between each call to
  35897. * next. Negative and floating point numbers are allowed. Default is 1.
  35898. * @return {!goog.iter.Iterator<number>} A new iterator that returns the values
  35899. * in the series.
  35900. */
  35901. goog.iter.count = function(opt_start, opt_step) {
  35902. var counter = opt_start || 0;
  35903. var step = goog.isDef(opt_step) ? opt_step : 1;
  35904. var iter = new goog.iter.Iterator();
  35905. iter.next = function() {
  35906. var returnValue = counter;
  35907. counter += step;
  35908. return returnValue;
  35909. };
  35910. return iter;
  35911. };
  35912. /**
  35913. * Creates an iterator that returns the same object or value repeatedly.
  35914. * @param {VALUE} value Any object or value to repeat.
  35915. * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the
  35916. * repeated value.
  35917. * @template VALUE
  35918. */
  35919. goog.iter.repeat = function(value) {
  35920. var iter = new goog.iter.Iterator();
  35921. iter.next = goog.functions.constant(value);
  35922. return iter;
  35923. };
  35924. /**
  35925. * Creates an iterator that returns running totals from the numbers in
  35926. * {@code iterable}. For example, the array {@code [1, 2, 3, 4, 5]} yields
  35927. * {@code 1 -> 3 -> 6 -> 10 -> 15}.
  35928. * @see http://docs.python.org/3.2/library/itertools.html#itertools.accumulate
  35929. * @param {!goog.iter.Iterable<number>} iterable The iterable of numbers to
  35930. * accumulate.
  35931. * @return {!goog.iter.Iterator<number>} A new iterator that returns the
  35932. * numbers in the series.
  35933. */
  35934. goog.iter.accumulate = function(iterable) {
  35935. var iterator = goog.iter.toIterator(iterable);
  35936. var total = 0;
  35937. var iter = new goog.iter.Iterator();
  35938. iter.next = function() {
  35939. total += iterator.next();
  35940. return total;
  35941. };
  35942. return iter;
  35943. };
  35944. /**
  35945. * Creates an iterator that returns arrays containing the ith elements from the
  35946. * provided iterables. The returned arrays will be the same size as the number
  35947. * of iterables given in {@code var_args}. Once the shortest iterable is
  35948. * exhausted, subsequent calls to {@code next()} will throw
  35949. * {@code goog.iter.StopIteration}.
  35950. * @see http://docs.python.org/2/library/itertools.html#itertools.izip
  35951. * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any
  35952. * number of iterable objects.
  35953. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns
  35954. * arrays of elements from the provided iterables.
  35955. * @template VALUE
  35956. */
  35957. goog.iter.zip = function(var_args) {
  35958. var args = arguments;
  35959. var iter = new goog.iter.Iterator();
  35960. if (args.length > 0) {
  35961. var iterators = goog.array.map(args, goog.iter.toIterator);
  35962. iter.next = function() {
  35963. var arr = goog.array.map(iterators, function(it) {
  35964. return it.next();
  35965. });
  35966. return arr;
  35967. };
  35968. }
  35969. return iter;
  35970. };
  35971. /**
  35972. * Creates an iterator that returns arrays containing the ith elements from the
  35973. * provided iterables. The returned arrays will be the same size as the number
  35974. * of iterables given in {@code var_args}. Shorter iterables will be extended
  35975. * with {@code fillValue}. Once the longest iterable is exhausted, subsequent
  35976. * calls to {@code next()} will throw {@code goog.iter.StopIteration}.
  35977. * @see http://docs.python.org/2/library/itertools.html#itertools.izip_longest
  35978. * @param {VALUE} fillValue The object or value used to fill shorter iterables.
  35979. * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any
  35980. * number of iterable objects.
  35981. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns
  35982. * arrays of elements from the provided iterables.
  35983. * @template VALUE
  35984. */
  35985. goog.iter.zipLongest = function(fillValue, var_args) {
  35986. var args = goog.array.slice(arguments, 1);
  35987. var iter = new goog.iter.Iterator();
  35988. if (args.length > 0) {
  35989. var iterators = goog.array.map(args, goog.iter.toIterator);
  35990. iter.next = function() {
  35991. var iteratorsHaveValues = false; // false when all iterators are empty.
  35992. var arr = goog.array.map(iterators, function(it) {
  35993. var returnValue;
  35994. try {
  35995. returnValue = it.next();
  35996. // Iterator had a value, so we've not exhausted the iterators.
  35997. // Set flag accordingly.
  35998. iteratorsHaveValues = true;
  35999. } catch (ex) {
  36000. if (ex !== goog.iter.StopIteration) {
  36001. throw ex;
  36002. }
  36003. returnValue = fillValue;
  36004. }
  36005. return returnValue;
  36006. });
  36007. if (!iteratorsHaveValues) {
  36008. throw goog.iter.StopIteration;
  36009. }
  36010. return arr;
  36011. };
  36012. }
  36013. return iter;
  36014. };
  36015. /**
  36016. * Creates an iterator that filters {@code iterable} based on a series of
  36017. * {@code selectors}. On each call to {@code next()}, one item is taken from
  36018. * both the {@code iterable} and {@code selectors} iterators. If the item from
  36019. * {@code selectors} evaluates to true, the item from {@code iterable} is given.
  36020. * Otherwise, it is skipped. Once either {@code iterable} or {@code selectors}
  36021. * is exhausted, subsequent calls to {@code next()} will throw
  36022. * {@code goog.iter.StopIteration}.
  36023. * @see http://docs.python.org/2/library/itertools.html#itertools.compress
  36024. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36025. * iterable to filter.
  36026. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} selectors An
  36027. * iterable of items to be evaluated in a boolean context to determine if
  36028. * the corresponding element in {@code iterable} should be included in the
  36029. * result.
  36030. * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the
  36031. * filtered values.
  36032. * @template VALUE
  36033. */
  36034. goog.iter.compress = function(iterable, selectors) {
  36035. var selectorIterator = goog.iter.toIterator(selectors);
  36036. return goog.iter.filter(iterable, function() {
  36037. return !!selectorIterator.next();
  36038. });
  36039. };
  36040. /**
  36041. * Implements the {@code goog.iter.groupBy} iterator.
  36042. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36043. * iterable to group.
  36044. * @param {function(...VALUE): KEY=} opt_keyFunc Optional function for
  36045. * determining the key value for each group in the {@code iterable}. Default
  36046. * is the identity function.
  36047. * @constructor
  36048. * @extends {goog.iter.Iterator<!Array<?>>}
  36049. * @template KEY, VALUE
  36050. * @private
  36051. */
  36052. goog.iter.GroupByIterator_ = function(iterable, opt_keyFunc) {
  36053. /**
  36054. * The iterable to group, coerced to an iterator.
  36055. * @type {!goog.iter.Iterator}
  36056. */
  36057. this.iterator = goog.iter.toIterator(iterable);
  36058. /**
  36059. * A function for determining the key value for each element in the iterable.
  36060. * If no function is provided, the identity function is used and returns the
  36061. * element unchanged.
  36062. * @type {function(...VALUE): KEY}
  36063. */
  36064. this.keyFunc = opt_keyFunc || goog.functions.identity;
  36065. /**
  36066. * The target key for determining the start of a group.
  36067. * @type {KEY}
  36068. */
  36069. this.targetKey;
  36070. /**
  36071. * The current key visited during iteration.
  36072. * @type {KEY}
  36073. */
  36074. this.currentKey;
  36075. /**
  36076. * The current value being added to the group.
  36077. * @type {VALUE}
  36078. */
  36079. this.currentValue;
  36080. };
  36081. goog.inherits(goog.iter.GroupByIterator_, goog.iter.Iterator);
  36082. /** @override */
  36083. goog.iter.GroupByIterator_.prototype.next = function() {
  36084. while (this.currentKey == this.targetKey) {
  36085. this.currentValue = this.iterator.next(); // Exits on StopIteration
  36086. this.currentKey = this.keyFunc(this.currentValue);
  36087. }
  36088. this.targetKey = this.currentKey;
  36089. return [this.currentKey, this.groupItems_(this.targetKey)];
  36090. };
  36091. /**
  36092. * Performs the grouping of objects using the given key.
  36093. * @param {KEY} targetKey The target key object for the group.
  36094. * @return {!Array<VALUE>} An array of grouped objects.
  36095. * @private
  36096. */
  36097. goog.iter.GroupByIterator_.prototype.groupItems_ = function(targetKey) {
  36098. var arr = [];
  36099. while (this.currentKey == targetKey) {
  36100. arr.push(this.currentValue);
  36101. try {
  36102. this.currentValue = this.iterator.next();
  36103. } catch (ex) {
  36104. if (ex !== goog.iter.StopIteration) {
  36105. throw ex;
  36106. }
  36107. break;
  36108. }
  36109. this.currentKey = this.keyFunc(this.currentValue);
  36110. }
  36111. return arr;
  36112. };
  36113. /**
  36114. * Creates an iterator that returns arrays containing elements from the
  36115. * {@code iterable} grouped by a key value. For iterables with repeated
  36116. * elements (i.e. sorted according to a particular key function), this function
  36117. * has a {@code uniq}-like effect. For example, grouping the array:
  36118. * {@code [A, B, B, C, C, A]} produces
  36119. * {@code [A, [A]], [B, [B, B]], [C, [C, C]], [A, [A]]}.
  36120. * @see http://docs.python.org/2/library/itertools.html#itertools.groupby
  36121. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36122. * iterable to group.
  36123. * @param {function(...VALUE): KEY=} opt_keyFunc Optional function for
  36124. * determining the key value for each group in the {@code iterable}. Default
  36125. * is the identity function.
  36126. * @return {!goog.iter.Iterator<!Array<?>>} A new iterator that returns
  36127. * arrays of consecutive key and groups.
  36128. * @template KEY, VALUE
  36129. */
  36130. goog.iter.groupBy = function(iterable, opt_keyFunc) {
  36131. return new goog.iter.GroupByIterator_(iterable, opt_keyFunc);
  36132. };
  36133. /**
  36134. * Gives an iterator that gives the result of calling the given function
  36135. * <code>f</code> with the arguments taken from the next element from
  36136. * <code>iterable</code> (the elements are expected to also be iterables).
  36137. *
  36138. * Similar to {@see goog.iter#map} but allows the function to accept multiple
  36139. * arguments from the iterable.
  36140. *
  36141. * @param {!goog.iter.Iterable<!goog.iter.Iterable>} iterable The iterable of
  36142. * iterables to iterate over.
  36143. * @param {function(this:THIS,...*):RESULT} f The function to call for every
  36144. * element. This function takes N+2 arguments, where N represents the
  36145. * number of items from the next element of the iterable. The two
  36146. * additional arguments passed to the function are undefined and the
  36147. * iterator itself. The function should return a new value.
  36148. * @param {THIS=} opt_obj The object to be used as the value of 'this' within
  36149. * {@code f}.
  36150. * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the
  36151. * results of applying the function to each element in the original
  36152. * iterator.
  36153. * @template THIS, RESULT
  36154. */
  36155. goog.iter.starMap = function(iterable, f, opt_obj) {
  36156. var iterator = goog.iter.toIterator(iterable);
  36157. var iter = new goog.iter.Iterator();
  36158. iter.next = function() {
  36159. var args = goog.iter.toArray(iterator.next());
  36160. return f.apply(opt_obj, goog.array.concat(args, undefined, iterator));
  36161. };
  36162. return iter;
  36163. };
  36164. /**
  36165. * Returns an array of iterators each of which can iterate over the values in
  36166. * {@code iterable} without advancing the others.
  36167. * @see http://docs.python.org/2/library/itertools.html#itertools.tee
  36168. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36169. * iterable to tee.
  36170. * @param {number=} opt_num The number of iterators to create. Default is 2.
  36171. * @return {!Array<goog.iter.Iterator<VALUE>>} An array of iterators.
  36172. * @template VALUE
  36173. */
  36174. goog.iter.tee = function(iterable, opt_num) {
  36175. var iterator = goog.iter.toIterator(iterable);
  36176. var num = goog.isNumber(opt_num) ? opt_num : 2;
  36177. var buffers = goog.array.map(goog.array.range(num), function() {
  36178. return [];
  36179. });
  36180. var addNextIteratorValueToBuffers = function() {
  36181. var val = iterator.next();
  36182. goog.array.forEach(buffers, function(buffer) {
  36183. buffer.push(val);
  36184. });
  36185. };
  36186. var createIterator = function(buffer) {
  36187. // Each tee'd iterator has an associated buffer (initially empty). When a
  36188. // tee'd iterator's buffer is empty, it calls
  36189. // addNextIteratorValueToBuffers(), adding the next value to all tee'd
  36190. // iterators' buffers, and then returns that value. This allows each
  36191. // iterator to be advanced independently.
  36192. var iter = new goog.iter.Iterator();
  36193. iter.next = function() {
  36194. if (goog.array.isEmpty(buffer)) {
  36195. addNextIteratorValueToBuffers();
  36196. }
  36197. goog.asserts.assert(!goog.array.isEmpty(buffer));
  36198. return buffer.shift();
  36199. };
  36200. return iter;
  36201. };
  36202. return goog.array.map(buffers, createIterator);
  36203. };
  36204. /**
  36205. * Creates an iterator that returns arrays containing a count and an element
  36206. * obtained from the given {@code iterable}.
  36207. * @see http://docs.python.org/2/library/functions.html#enumerate
  36208. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36209. * iterable to enumerate.
  36210. * @param {number=} opt_start Optional starting value. Default is 0.
  36211. * @return {!goog.iter.Iterator<!Array<?>>} A new iterator containing
  36212. * count/item pairs.
  36213. * @template VALUE
  36214. */
  36215. goog.iter.enumerate = function(iterable, opt_start) {
  36216. return goog.iter.zip(goog.iter.count(opt_start), iterable);
  36217. };
  36218. /**
  36219. * Creates an iterator that returns the first {@code limitSize} elements from an
  36220. * iterable. If this number is greater than the number of elements in the
  36221. * iterable, all the elements are returned.
  36222. * @see http://goo.gl/V0sihp Inspired by the limit iterator in Guava.
  36223. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36224. * iterable to limit.
  36225. * @param {number} limitSize The maximum number of elements to return.
  36226. * @return {!goog.iter.Iterator<VALUE>} A new iterator containing
  36227. * {@code limitSize} elements.
  36228. * @template VALUE
  36229. */
  36230. goog.iter.limit = function(iterable, limitSize) {
  36231. goog.asserts.assert(goog.math.isInt(limitSize) && limitSize >= 0);
  36232. var iterator = goog.iter.toIterator(iterable);
  36233. var iter = new goog.iter.Iterator();
  36234. var remaining = limitSize;
  36235. iter.next = function() {
  36236. if (remaining-- > 0) {
  36237. return iterator.next();
  36238. }
  36239. throw goog.iter.StopIteration;
  36240. };
  36241. return iter;
  36242. };
  36243. /**
  36244. * Creates an iterator that is advanced {@code count} steps ahead. Consumed
  36245. * values are silently discarded. If {@code count} is greater than the number
  36246. * of elements in {@code iterable}, an empty iterator is returned. Subsequent
  36247. * calls to {@code next()} will throw {@code goog.iter.StopIteration}.
  36248. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36249. * iterable to consume.
  36250. * @param {number} count The number of elements to consume from the iterator.
  36251. * @return {!goog.iter.Iterator<VALUE>} An iterator advanced zero or more steps
  36252. * ahead.
  36253. * @template VALUE
  36254. */
  36255. goog.iter.consume = function(iterable, count) {
  36256. goog.asserts.assert(goog.math.isInt(count) && count >= 0);
  36257. var iterator = goog.iter.toIterator(iterable);
  36258. while (count-- > 0) {
  36259. goog.iter.nextOrValue(iterator, null);
  36260. }
  36261. return iterator;
  36262. };
  36263. /**
  36264. * Creates an iterator that returns a range of elements from an iterable.
  36265. * Similar to {@see goog.array#slice} but does not support negative indexes.
  36266. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36267. * iterable to slice.
  36268. * @param {number} start The index of the first element to return.
  36269. * @param {number=} opt_end The index after the last element to return. If
  36270. * defined, must be greater than or equal to {@code start}.
  36271. * @return {!goog.iter.Iterator<VALUE>} A new iterator containing a slice of
  36272. * the original.
  36273. * @template VALUE
  36274. */
  36275. goog.iter.slice = function(iterable, start, opt_end) {
  36276. goog.asserts.assert(goog.math.isInt(start) && start >= 0);
  36277. var iterator = goog.iter.consume(iterable, start);
  36278. if (goog.isNumber(opt_end)) {
  36279. goog.asserts.assert(goog.math.isInt(opt_end) && opt_end >= start);
  36280. iterator = goog.iter.limit(iterator, opt_end - start /* limitSize */);
  36281. }
  36282. return iterator;
  36283. };
  36284. /**
  36285. * Checks an array for duplicate elements.
  36286. * @param {Array<VALUE>|goog.array.ArrayLike} arr The array to check for
  36287. * duplicates.
  36288. * @return {boolean} True, if the array contains duplicates, false otherwise.
  36289. * @private
  36290. * @template VALUE
  36291. */
  36292. // TODO(user): Consider moving this into goog.array as a public function.
  36293. goog.iter.hasDuplicates_ = function(arr) {
  36294. var deduped = [];
  36295. goog.array.removeDuplicates(arr, deduped);
  36296. return arr.length != deduped.length;
  36297. };
  36298. /**
  36299. * Creates an iterator that returns permutations of elements in
  36300. * {@code iterable}.
  36301. *
  36302. * Permutations are obtained by taking the Cartesian product of
  36303. * {@code opt_length} iterables and filtering out those with repeated
  36304. * elements. For example, the permutations of {@code [1,2,3]} are
  36305. * {@code [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]}.
  36306. * @see http://docs.python.org/2/library/itertools.html#itertools.permutations
  36307. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36308. * iterable from which to generate permutations.
  36309. * @param {number=} opt_length Length of each permutation. If omitted, defaults
  36310. * to the length of {@code iterable}.
  36311. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing the
  36312. * permutations of {@code iterable}.
  36313. * @template VALUE
  36314. */
  36315. goog.iter.permutations = function(iterable, opt_length) {
  36316. var elements = goog.iter.toArray(iterable);
  36317. var length = goog.isNumber(opt_length) ? opt_length : elements.length;
  36318. var sets = goog.array.repeat(elements, length);
  36319. var product = goog.iter.product.apply(undefined, sets);
  36320. return goog.iter.filter(product, function(arr) {
  36321. return !goog.iter.hasDuplicates_(arr);
  36322. });
  36323. };
  36324. /**
  36325. * Creates an iterator that returns combinations of elements from
  36326. * {@code iterable}.
  36327. *
  36328. * Combinations are obtained by taking the {@see goog.iter#permutations} of
  36329. * {@code iterable} and filtering those whose elements appear in the order they
  36330. * are encountered in {@code iterable}. For example, the 3-length combinations
  36331. * of {@code [0,1,2,3]} are {@code [[0,1,2], [0,1,3], [0,2,3], [1,2,3]]}.
  36332. * @see http://docs.python.org/2/library/itertools.html#itertools.combinations
  36333. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36334. * iterable from which to generate combinations.
  36335. * @param {number} length The length of each combination.
  36336. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing
  36337. * combinations from the {@code iterable}.
  36338. * @template VALUE
  36339. */
  36340. goog.iter.combinations = function(iterable, length) {
  36341. var elements = goog.iter.toArray(iterable);
  36342. var indexes = goog.iter.range(elements.length);
  36343. var indexIterator = goog.iter.permutations(indexes, length);
  36344. // sortedIndexIterator will now give arrays of with the given length that
  36345. // indicate what indexes into "elements" should be returned on each iteration.
  36346. var sortedIndexIterator = goog.iter.filter(indexIterator, function(arr) {
  36347. return goog.array.isSorted(arr);
  36348. });
  36349. var iter = new goog.iter.Iterator();
  36350. function getIndexFromElements(index) {
  36351. return elements[index];
  36352. }
  36353. iter.next = function() {
  36354. return goog.array.map(sortedIndexIterator.next(), getIndexFromElements);
  36355. };
  36356. return iter;
  36357. };
  36358. /**
  36359. * Creates an iterator that returns combinations of elements from
  36360. * {@code iterable}, with repeated elements possible.
  36361. *
  36362. * Combinations are obtained by taking the Cartesian product of {@code length}
  36363. * iterables and filtering those whose elements appear in the order they are
  36364. * encountered in {@code iterable}. For example, the 2-length combinations of
  36365. * {@code [1,2,3]} are {@code [[1,1], [1,2], [1,3], [2,2], [2,3], [3,3]]}.
  36366. * @see http://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement
  36367. * @see http://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition
  36368. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The
  36369. * iterable to combine.
  36370. * @param {number} length The length of each combination.
  36371. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing
  36372. * combinations from the {@code iterable}.
  36373. * @template VALUE
  36374. */
  36375. goog.iter.combinationsWithReplacement = function(iterable, length) {
  36376. var elements = goog.iter.toArray(iterable);
  36377. var indexes = goog.array.range(elements.length);
  36378. var sets = goog.array.repeat(indexes, length);
  36379. var indexIterator = goog.iter.product.apply(undefined, sets);
  36380. // sortedIndexIterator will now give arrays of with the given length that
  36381. // indicate what indexes into "elements" should be returned on each iteration.
  36382. var sortedIndexIterator = goog.iter.filter(indexIterator, function(arr) {
  36383. return goog.array.isSorted(arr);
  36384. });
  36385. var iter = new goog.iter.Iterator();
  36386. function getIndexFromElements(index) {
  36387. return elements[index];
  36388. }
  36389. iter.next = function() {
  36390. return goog.array.map(
  36391. /** @type {!Array<number>} */
  36392. (sortedIndexIterator.next()), getIndexFromElements);
  36393. };
  36394. return iter;
  36395. };
  36396. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  36397. //
  36398. // Licensed under the Apache License, Version 2.0 (the "License");
  36399. // you may not use this file except in compliance with the License.
  36400. // You may obtain a copy of the License at
  36401. //
  36402. // http://www.apache.org/licenses/LICENSE-2.0
  36403. //
  36404. // Unless required by applicable law or agreed to in writing, software
  36405. // distributed under the License is distributed on an "AS-IS" BASIS,
  36406. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36407. // See the License for the specific language governing permissions and
  36408. // limitations under the License.
  36409. /**
  36410. * @fileoverview Datastructure: Hash Map.
  36411. *
  36412. * @author arv@google.com (Erik Arvidsson)
  36413. *
  36414. * This file contains an implementation of a Map structure. It implements a lot
  36415. * of the methods used in goog.structs so those functions work on hashes. This
  36416. * is best suited for complex key types. For simple keys such as numbers and
  36417. * strings consider using the lighter-weight utilities in goog.object.
  36418. */
  36419. goog.provide('goog.structs.Map');
  36420. goog.require('goog.iter.Iterator');
  36421. goog.require('goog.iter.StopIteration');
  36422. goog.require('goog.object');
  36423. /**
  36424. * Class for Hash Map datastructure.
  36425. * @param {*=} opt_map Map or Object to initialize the map with.
  36426. * @param {...*} var_args If 2 or more arguments are present then they
  36427. * will be used as key-value pairs.
  36428. * @constructor
  36429. * @template K, V
  36430. */
  36431. goog.structs.Map = function(opt_map, var_args) {
  36432. /**
  36433. * Underlying JS object used to implement the map.
  36434. * @private {!Object}
  36435. */
  36436. this.map_ = {};
  36437. /**
  36438. * An array of keys. This is necessary for two reasons:
  36439. * 1. Iterating the keys using for (var key in this.map_) allocates an
  36440. * object for every key in IE which is really bad for IE6 GC perf.
  36441. * 2. Without a side data structure, we would need to escape all the keys
  36442. * as that would be the only way we could tell during iteration if the
  36443. * key was an internal key or a property of the object.
  36444. *
  36445. * This array can contain deleted keys so it's necessary to check the map
  36446. * as well to see if the key is still in the map (this doesn't require a
  36447. * memory allocation in IE).
  36448. * @private {!Array<string>}
  36449. */
  36450. this.keys_ = [];
  36451. /**
  36452. * The number of key value pairs in the map.
  36453. * @private {number}
  36454. */
  36455. this.count_ = 0;
  36456. /**
  36457. * Version used to detect changes while iterating.
  36458. * @private {number}
  36459. */
  36460. this.version_ = 0;
  36461. var argLength = arguments.length;
  36462. if (argLength > 1) {
  36463. if (argLength % 2) {
  36464. throw Error('Uneven number of arguments');
  36465. }
  36466. for (var i = 0; i < argLength; i += 2) {
  36467. this.set(arguments[i], arguments[i + 1]);
  36468. }
  36469. } else if (opt_map) {
  36470. this.addAll(/** @type {Object} */ (opt_map));
  36471. }
  36472. };
  36473. /**
  36474. * @return {number} The number of key-value pairs in the map.
  36475. */
  36476. goog.structs.Map.prototype.getCount = function() {
  36477. return this.count_;
  36478. };
  36479. /**
  36480. * Returns the values of the map.
  36481. * @return {!Array<V>} The values in the map.
  36482. */
  36483. goog.structs.Map.prototype.getValues = function() {
  36484. this.cleanupKeysArray_();
  36485. var rv = [];
  36486. for (var i = 0; i < this.keys_.length; i++) {
  36487. var key = this.keys_[i];
  36488. rv.push(this.map_[key]);
  36489. }
  36490. return rv;
  36491. };
  36492. /**
  36493. * Returns the keys of the map.
  36494. * @return {!Array<string>} Array of string values.
  36495. */
  36496. goog.structs.Map.prototype.getKeys = function() {
  36497. this.cleanupKeysArray_();
  36498. return /** @type {!Array<string>} */ (this.keys_.concat());
  36499. };
  36500. /**
  36501. * Whether the map contains the given key.
  36502. * @param {*} key The key to check for.
  36503. * @return {boolean} Whether the map contains the key.
  36504. */
  36505. goog.structs.Map.prototype.containsKey = function(key) {
  36506. return goog.structs.Map.hasKey_(this.map_, key);
  36507. };
  36508. /**
  36509. * Whether the map contains the given value. This is O(n).
  36510. * @param {V} val The value to check for.
  36511. * @return {boolean} Whether the map contains the value.
  36512. */
  36513. goog.structs.Map.prototype.containsValue = function(val) {
  36514. for (var i = 0; i < this.keys_.length; i++) {
  36515. var key = this.keys_[i];
  36516. if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {
  36517. return true;
  36518. }
  36519. }
  36520. return false;
  36521. };
  36522. /**
  36523. * Whether this map is equal to the argument map.
  36524. * @param {goog.structs.Map} otherMap The map against which to test equality.
  36525. * @param {function(V, V): boolean=} opt_equalityFn Optional equality function
  36526. * to test equality of values. If not specified, this will test whether
  36527. * the values contained in each map are identical objects.
  36528. * @return {boolean} Whether the maps are equal.
  36529. */
  36530. goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {
  36531. if (this === otherMap) {
  36532. return true;
  36533. }
  36534. if (this.count_ != otherMap.getCount()) {
  36535. return false;
  36536. }
  36537. var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;
  36538. this.cleanupKeysArray_();
  36539. for (var key, i = 0; key = this.keys_[i]; i++) {
  36540. if (!equalityFn(this.get(key), otherMap.get(key))) {
  36541. return false;
  36542. }
  36543. }
  36544. return true;
  36545. };
  36546. /**
  36547. * Default equality test for values.
  36548. * @param {*} a The first value.
  36549. * @param {*} b The second value.
  36550. * @return {boolean} Whether a and b reference the same object.
  36551. */
  36552. goog.structs.Map.defaultEquals = function(a, b) {
  36553. return a === b;
  36554. };
  36555. /**
  36556. * @return {boolean} Whether the map is empty.
  36557. */
  36558. goog.structs.Map.prototype.isEmpty = function() {
  36559. return this.count_ == 0;
  36560. };
  36561. /**
  36562. * Removes all key-value pairs from the map.
  36563. */
  36564. goog.structs.Map.prototype.clear = function() {
  36565. this.map_ = {};
  36566. this.keys_.length = 0;
  36567. this.count_ = 0;
  36568. this.version_ = 0;
  36569. };
  36570. /**
  36571. * Removes a key-value pair based on the key. This is O(logN) amortized due to
  36572. * updating the keys array whenever the count becomes half the size of the keys
  36573. * in the keys array.
  36574. * @param {*} key The key to remove.
  36575. * @return {boolean} Whether object was removed.
  36576. */
  36577. goog.structs.Map.prototype.remove = function(key) {
  36578. if (goog.structs.Map.hasKey_(this.map_, key)) {
  36579. delete this.map_[key];
  36580. this.count_--;
  36581. this.version_++;
  36582. // clean up the keys array if the threshhold is hit
  36583. if (this.keys_.length > 2 * this.count_) {
  36584. this.cleanupKeysArray_();
  36585. }
  36586. return true;
  36587. }
  36588. return false;
  36589. };
  36590. /**
  36591. * Cleans up the temp keys array by removing entries that are no longer in the
  36592. * map.
  36593. * @private
  36594. */
  36595. goog.structs.Map.prototype.cleanupKeysArray_ = function() {
  36596. if (this.count_ != this.keys_.length) {
  36597. // First remove keys that are no longer in the map.
  36598. var srcIndex = 0;
  36599. var destIndex = 0;
  36600. while (srcIndex < this.keys_.length) {
  36601. var key = this.keys_[srcIndex];
  36602. if (goog.structs.Map.hasKey_(this.map_, key)) {
  36603. this.keys_[destIndex++] = key;
  36604. }
  36605. srcIndex++;
  36606. }
  36607. this.keys_.length = destIndex;
  36608. }
  36609. if (this.count_ != this.keys_.length) {
  36610. // If the count still isn't correct, that means we have duplicates. This can
  36611. // happen when the same key is added and removed multiple times. Now we have
  36612. // to allocate one extra Object to remove the duplicates. This could have
  36613. // been done in the first pass, but in the common case, we can avoid
  36614. // allocating an extra object by only doing this when necessary.
  36615. var seen = {};
  36616. var srcIndex = 0;
  36617. var destIndex = 0;
  36618. while (srcIndex < this.keys_.length) {
  36619. var key = this.keys_[srcIndex];
  36620. if (!(goog.structs.Map.hasKey_(seen, key))) {
  36621. this.keys_[destIndex++] = key;
  36622. seen[key] = 1;
  36623. }
  36624. srcIndex++;
  36625. }
  36626. this.keys_.length = destIndex;
  36627. }
  36628. };
  36629. /**
  36630. * Returns the value for the given key. If the key is not found and the default
  36631. * value is not given this will return {@code undefined}.
  36632. * @param {*} key The key to get the value for.
  36633. * @param {DEFAULT=} opt_val The value to return if no item is found for the
  36634. * given key, defaults to undefined.
  36635. * @return {V|DEFAULT} The value for the given key.
  36636. * @template DEFAULT
  36637. */
  36638. goog.structs.Map.prototype.get = function(key, opt_val) {
  36639. if (goog.structs.Map.hasKey_(this.map_, key)) {
  36640. return this.map_[key];
  36641. }
  36642. return opt_val;
  36643. };
  36644. /**
  36645. * Adds a key-value pair to the map.
  36646. * @param {*} key The key.
  36647. * @param {V} value The value to add.
  36648. * @return {*} Some subclasses return a value.
  36649. */
  36650. goog.structs.Map.prototype.set = function(key, value) {
  36651. if (!(goog.structs.Map.hasKey_(this.map_, key))) {
  36652. this.count_++;
  36653. this.keys_.push(key);
  36654. // Only change the version if we add a new key.
  36655. this.version_++;
  36656. }
  36657. this.map_[key] = value;
  36658. };
  36659. /**
  36660. * Adds multiple key-value pairs from another goog.structs.Map or Object.
  36661. * @param {Object} map Object containing the data to add.
  36662. */
  36663. goog.structs.Map.prototype.addAll = function(map) {
  36664. var keys, values;
  36665. if (map instanceof goog.structs.Map) {
  36666. keys = map.getKeys();
  36667. values = map.getValues();
  36668. } else {
  36669. keys = goog.object.getKeys(map);
  36670. values = goog.object.getValues(map);
  36671. }
  36672. // we could use goog.array.forEach here but I don't want to introduce that
  36673. // dependency just for this.
  36674. for (var i = 0; i < keys.length; i++) {
  36675. this.set(keys[i], values[i]);
  36676. }
  36677. };
  36678. /**
  36679. * Calls the given function on each entry in the map.
  36680. * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f
  36681. * @param {T=} opt_obj The value of "this" inside f.
  36682. * @template T
  36683. */
  36684. goog.structs.Map.prototype.forEach = function(f, opt_obj) {
  36685. var keys = this.getKeys();
  36686. for (var i = 0; i < keys.length; i++) {
  36687. var key = keys[i];
  36688. var value = this.get(key);
  36689. f.call(opt_obj, value, key, this);
  36690. }
  36691. };
  36692. /**
  36693. * Clones a map and returns a new map.
  36694. * @return {!goog.structs.Map} A new map with the same key-value pairs.
  36695. */
  36696. goog.structs.Map.prototype.clone = function() {
  36697. return new goog.structs.Map(this);
  36698. };
  36699. /**
  36700. * Returns a new map in which all the keys and values are interchanged
  36701. * (keys become values and values become keys). If multiple keys map to the
  36702. * same value, the chosen transposed value is implementation-dependent.
  36703. *
  36704. * It acts very similarly to {goog.object.transpose(Object)}.
  36705. *
  36706. * @return {!goog.structs.Map} The transposed map.
  36707. */
  36708. goog.structs.Map.prototype.transpose = function() {
  36709. var transposed = new goog.structs.Map();
  36710. for (var i = 0; i < this.keys_.length; i++) {
  36711. var key = this.keys_[i];
  36712. var value = this.map_[key];
  36713. transposed.set(value, key);
  36714. }
  36715. return transposed;
  36716. };
  36717. /**
  36718. * @return {!Object} Object representation of the map.
  36719. */
  36720. goog.structs.Map.prototype.toObject = function() {
  36721. this.cleanupKeysArray_();
  36722. var obj = {};
  36723. for (var i = 0; i < this.keys_.length; i++) {
  36724. var key = this.keys_[i];
  36725. obj[key] = this.map_[key];
  36726. }
  36727. return obj;
  36728. };
  36729. /**
  36730. * Returns an iterator that iterates over the keys in the map. Removal of keys
  36731. * while iterating might have undesired side effects.
  36732. * @return {!goog.iter.Iterator} An iterator over the keys in the map.
  36733. */
  36734. goog.structs.Map.prototype.getKeyIterator = function() {
  36735. return this.__iterator__(true);
  36736. };
  36737. /**
  36738. * Returns an iterator that iterates over the values in the map. Removal of
  36739. * keys while iterating might have undesired side effects.
  36740. * @return {!goog.iter.Iterator} An iterator over the values in the map.
  36741. */
  36742. goog.structs.Map.prototype.getValueIterator = function() {
  36743. return this.__iterator__(false);
  36744. };
  36745. /**
  36746. * Returns an iterator that iterates over the values or the keys in the map.
  36747. * This throws an exception if the map was mutated since the iterator was
  36748. * created.
  36749. * @param {boolean=} opt_keys True to iterate over the keys. False to iterate
  36750. * over the values. The default value is false.
  36751. * @return {!goog.iter.Iterator} An iterator over the values or keys in the map.
  36752. */
  36753. goog.structs.Map.prototype.__iterator__ = function(opt_keys) {
  36754. // Clean up keys to minimize the risk of iterating over dead keys.
  36755. this.cleanupKeysArray_();
  36756. var i = 0;
  36757. var version = this.version_;
  36758. var selfObj = this;
  36759. var newIter = new goog.iter.Iterator;
  36760. newIter.next = function() {
  36761. if (version != selfObj.version_) {
  36762. throw Error('The map has changed since the iterator was created');
  36763. }
  36764. if (i >= selfObj.keys_.length) {
  36765. throw goog.iter.StopIteration;
  36766. }
  36767. var key = selfObj.keys_[i++];
  36768. return opt_keys ? key : selfObj.map_[key];
  36769. };
  36770. return newIter;
  36771. };
  36772. /**
  36773. * Safe way to test for hasOwnProperty. It even allows testing for
  36774. * 'hasOwnProperty'.
  36775. * @param {Object} obj The object to test for presence of the given key.
  36776. * @param {*} key The key to check for.
  36777. * @return {boolean} Whether the object has the key.
  36778. * @private
  36779. */
  36780. goog.structs.Map.hasKey_ = function(obj, key) {
  36781. return Object.prototype.hasOwnProperty.call(obj, key);
  36782. };
  36783. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  36784. //
  36785. // Licensed under the Apache License, Version 2.0 (the "License");
  36786. // you may not use this file except in compliance with the License.
  36787. // You may obtain a copy of the License at
  36788. //
  36789. // http://www.apache.org/licenses/LICENSE-2.0
  36790. //
  36791. // Unless required by applicable law or agreed to in writing, software
  36792. // distributed under the License is distributed on an "AS-IS" BASIS,
  36793. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36794. // See the License for the specific language governing permissions and
  36795. // limitations under the License.
  36796. /**
  36797. * @fileoverview Datastructure: Set.
  36798. *
  36799. * @author arv@google.com (Erik Arvidsson)
  36800. *
  36801. * This class implements a set data structure. Adding and removing is O(1). It
  36802. * supports both object and primitive values. Be careful because you can add
  36803. * both 1 and new Number(1), because these are not the same. You can even add
  36804. * multiple new Number(1) because these are not equal.
  36805. */
  36806. goog.provide('goog.structs.Set');
  36807. goog.require('goog.structs');
  36808. goog.require('goog.structs.Collection');
  36809. goog.require('goog.structs.Map');
  36810. /**
  36811. * A set that can contain both primitives and objects. Adding and removing
  36812. * elements is O(1). Primitives are treated as identical if they have the same
  36813. * type and convert to the same string. Objects are treated as identical only
  36814. * if they are references to the same object. WARNING: A goog.structs.Set can
  36815. * contain both 1 and (new Number(1)), because they are not the same. WARNING:
  36816. * Adding (new Number(1)) twice will yield two distinct elements, because they
  36817. * are two different objects. WARNING: Any object that is added to a
  36818. * goog.structs.Set will be modified! Because goog.getUid() is used to
  36819. * identify objects, every object in the set will be mutated.
  36820. * @param {Array<T>|Object<?,T>=} opt_values Initial values to start with.
  36821. * @constructor
  36822. * @implements {goog.structs.Collection<T>}
  36823. * @final
  36824. * @template T
  36825. */
  36826. goog.structs.Set = function(opt_values) {
  36827. this.map_ = new goog.structs.Map;
  36828. if (opt_values) {
  36829. this.addAll(opt_values);
  36830. }
  36831. };
  36832. /**
  36833. * Obtains a unique key for an element of the set. Primitives will yield the
  36834. * same key if they have the same type and convert to the same string. Object
  36835. * references will yield the same key only if they refer to the same object.
  36836. * @param {*} val Object or primitive value to get a key for.
  36837. * @return {string} A unique key for this value/object.
  36838. * @private
  36839. */
  36840. goog.structs.Set.getKey_ = function(val) {
  36841. var type = typeof val;
  36842. if (type == 'object' && val || type == 'function') {
  36843. return 'o' + goog.getUid(/** @type {Object} */ (val));
  36844. } else {
  36845. return type.substr(0, 1) + val;
  36846. }
  36847. };
  36848. /**
  36849. * @return {number} The number of elements in the set.
  36850. * @override
  36851. */
  36852. goog.structs.Set.prototype.getCount = function() {
  36853. return this.map_.getCount();
  36854. };
  36855. /**
  36856. * Add a primitive or an object to the set.
  36857. * @param {T} element The primitive or object to add.
  36858. * @override
  36859. */
  36860. goog.structs.Set.prototype.add = function(element) {
  36861. this.map_.set(goog.structs.Set.getKey_(element), element);
  36862. };
  36863. /**
  36864. * Adds all the values in the given collection to this set.
  36865. * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection
  36866. * containing the elements to add.
  36867. */
  36868. goog.structs.Set.prototype.addAll = function(col) {
  36869. var values = goog.structs.getValues(col);
  36870. var l = values.length;
  36871. for (var i = 0; i < l; i++) {
  36872. this.add(values[i]);
  36873. }
  36874. };
  36875. /**
  36876. * Removes all values in the given collection from this set.
  36877. * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection
  36878. * containing the elements to remove.
  36879. */
  36880. goog.structs.Set.prototype.removeAll = function(col) {
  36881. var values = goog.structs.getValues(col);
  36882. var l = values.length;
  36883. for (var i = 0; i < l; i++) {
  36884. this.remove(values[i]);
  36885. }
  36886. };
  36887. /**
  36888. * Removes the given element from this set.
  36889. * @param {T} element The primitive or object to remove.
  36890. * @return {boolean} Whether the element was found and removed.
  36891. * @override
  36892. */
  36893. goog.structs.Set.prototype.remove = function(element) {
  36894. return this.map_.remove(goog.structs.Set.getKey_(element));
  36895. };
  36896. /**
  36897. * Removes all elements from this set.
  36898. */
  36899. goog.structs.Set.prototype.clear = function() {
  36900. this.map_.clear();
  36901. };
  36902. /**
  36903. * Tests whether this set is empty.
  36904. * @return {boolean} True if there are no elements in this set.
  36905. */
  36906. goog.structs.Set.prototype.isEmpty = function() {
  36907. return this.map_.isEmpty();
  36908. };
  36909. /**
  36910. * Tests whether this set contains the given element.
  36911. * @param {T} element The primitive or object to test for.
  36912. * @return {boolean} True if this set contains the given element.
  36913. * @override
  36914. */
  36915. goog.structs.Set.prototype.contains = function(element) {
  36916. return this.map_.containsKey(goog.structs.Set.getKey_(element));
  36917. };
  36918. /**
  36919. * Tests whether this set contains all the values in a given collection.
  36920. * Repeated elements in the collection are ignored, e.g. (new
  36921. * goog.structs.Set([1, 2])).containsAll([1, 1]) is True.
  36922. * @param {goog.structs.Collection<T>|Object} col A collection-like object.
  36923. * @return {boolean} True if the set contains all elements.
  36924. */
  36925. goog.structs.Set.prototype.containsAll = function(col) {
  36926. return goog.structs.every(col, this.contains, this);
  36927. };
  36928. /**
  36929. * Finds all values that are present in both this set and the given collection.
  36930. * @param {Array<S>|Object<?,S>} col A collection.
  36931. * @return {!goog.structs.Set<T|S>} A new set containing all the values
  36932. * (primitives or objects) present in both this set and the given
  36933. * collection.
  36934. * @template S
  36935. */
  36936. goog.structs.Set.prototype.intersection = function(col) {
  36937. var result = new goog.structs.Set();
  36938. var values = goog.structs.getValues(col);
  36939. for (var i = 0; i < values.length; i++) {
  36940. var value = values[i];
  36941. if (this.contains(value)) {
  36942. result.add(value);
  36943. }
  36944. }
  36945. return result;
  36946. };
  36947. /**
  36948. * Finds all values that are present in this set and not in the given
  36949. * collection.
  36950. * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection.
  36951. * @return {!goog.structs.Set} A new set containing all the values
  36952. * (primitives or objects) present in this set but not in the given
  36953. * collection.
  36954. */
  36955. goog.structs.Set.prototype.difference = function(col) {
  36956. var result = this.clone();
  36957. result.removeAll(col);
  36958. return result;
  36959. };
  36960. /**
  36961. * Returns an array containing all the elements in this set.
  36962. * @return {!Array<T>} An array containing all the elements in this set.
  36963. */
  36964. goog.structs.Set.prototype.getValues = function() {
  36965. return this.map_.getValues();
  36966. };
  36967. /**
  36968. * Creates a shallow clone of this set.
  36969. * @return {!goog.structs.Set<T>} A new set containing all the same elements as
  36970. * this set.
  36971. */
  36972. goog.structs.Set.prototype.clone = function() {
  36973. return new goog.structs.Set(this);
  36974. };
  36975. /**
  36976. * Tests whether the given collection consists of the same elements as this set,
  36977. * regardless of order, without repetition. Primitives are treated as equal if
  36978. * they have the same type and convert to the same string; objects are treated
  36979. * as equal if they are references to the same object. This operation is O(n).
  36980. * @param {goog.structs.Collection<T>|Object} col A collection.
  36981. * @return {boolean} True if the given collection consists of the same elements
  36982. * as this set, regardless of order, without repetition.
  36983. */
  36984. goog.structs.Set.prototype.equals = function(col) {
  36985. return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col);
  36986. };
  36987. /**
  36988. * Tests whether the given collection contains all the elements in this set.
  36989. * Primitives are treated as equal if they have the same type and convert to the
  36990. * same string; objects are treated as equal if they are references to the same
  36991. * object. This operation is O(n).
  36992. * @param {goog.structs.Collection<T>|Object} col A collection.
  36993. * @return {boolean} True if this set is a subset of the given collection.
  36994. */
  36995. goog.structs.Set.prototype.isSubsetOf = function(col) {
  36996. var colCount = goog.structs.getCount(col);
  36997. if (this.getCount() > colCount) {
  36998. return false;
  36999. }
  37000. // TODO(user) Find the minimal collection size where the conversion makes
  37001. // the contains() method faster.
  37002. if (!(col instanceof goog.structs.Set) && colCount > 5) {
  37003. // Convert to a goog.structs.Set so that goog.structs.contains runs in
  37004. // O(1) time instead of O(n) time.
  37005. col = new goog.structs.Set(col);
  37006. }
  37007. return goog.structs.every(this, function(value) {
  37008. return goog.structs.contains(col, value);
  37009. });
  37010. };
  37011. /**
  37012. * Returns an iterator that iterates over the elements in this set.
  37013. * @param {boolean=} opt_keys This argument is ignored.
  37014. * @return {!goog.iter.Iterator} An iterator over the elements in this set.
  37015. */
  37016. goog.structs.Set.prototype.__iterator__ = function(opt_keys) {
  37017. return this.map_.__iterator__(false);
  37018. };
  37019. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  37020. //
  37021. // Licensed under the Apache License, Version 2.0 (the "License");
  37022. // you may not use this file except in compliance with the License.
  37023. // You may obtain a copy of the License at
  37024. //
  37025. // http://www.apache.org/licenses/LICENSE-2.0
  37026. //
  37027. // Unless required by applicable law or agreed to in writing, software
  37028. // distributed under the License is distributed on an "AS-IS" BASIS,
  37029. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37030. // See the License for the specific language governing permissions and
  37031. // limitations under the License.
  37032. /**
  37033. * @fileoverview Logging and debugging utilities.
  37034. *
  37035. * @see ../demos/debug.html
  37036. */
  37037. goog.provide('goog.debug');
  37038. goog.require('goog.array');
  37039. goog.require('goog.html.SafeHtml');
  37040. goog.require('goog.html.SafeUrl');
  37041. goog.require('goog.html.uncheckedconversions');
  37042. goog.require('goog.string.Const');
  37043. goog.require('goog.structs.Set');
  37044. goog.require('goog.userAgent');
  37045. /** @define {boolean} Whether logging should be enabled. */
  37046. goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG);
  37047. /**
  37048. * Catches onerror events fired by windows and similar objects.
  37049. * @param {function(Object)} logFunc The function to call with the error
  37050. * information.
  37051. * @param {boolean=} opt_cancel Whether to stop the error from reaching the
  37052. * browser.
  37053. * @param {Object=} opt_target Object that fires onerror events.
  37054. */
  37055. goog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) {
  37056. var target = opt_target || goog.global;
  37057. var oldErrorHandler = target.onerror;
  37058. var retVal = !!opt_cancel;
  37059. // Chrome interprets onerror return value backwards (http://crbug.com/92062)
  37060. // until it was fixed in webkit revision r94061 (Webkit 535.3). This
  37061. // workaround still needs to be skipped in Safari after the webkit change
  37062. // gets pushed out in Safari.
  37063. // See https://bugs.webkit.org/show_bug.cgi?id=67119
  37064. if (goog.userAgent.WEBKIT &&
  37065. !goog.userAgent.isVersionOrHigher('535.3')) {
  37066. retVal = !retVal;
  37067. }
  37068. /**
  37069. * New onerror handler for this target. This onerror handler follows the spec
  37070. * according to
  37071. * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors
  37072. * The spec was changed in August 2013 to support receiving column information
  37073. * and an error object for all scripts on the same origin or cross origin
  37074. * scripts with the proper headers. See
  37075. * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
  37076. *
  37077. * @param {string} message The error message. For cross-origin errors, this
  37078. * will be scrubbed to just "Script error.". For new browsers that have
  37079. * updated to follow the latest spec, errors that come from origins that
  37080. * have proper cross origin headers will not be scrubbed.
  37081. * @param {string} url The URL of the script that caused the error. The URL
  37082. * will be scrubbed to "" for cross origin scripts unless the script has
  37083. * proper cross origin headers and the browser has updated to the latest
  37084. * spec.
  37085. * @param {number} line The line number in the script that the error
  37086. * occurred on.
  37087. * @param {number=} opt_col The optional column number that the error
  37088. * occurred on. Only browsers that have updated to the latest spec will
  37089. * include this.
  37090. * @param {Error=} opt_error The optional actual error object for this
  37091. * error that should include the stack. Only browsers that have updated
  37092. * to the latest spec will inlude this parameter.
  37093. * @return {boolean} Whether to prevent the error from reaching the browser.
  37094. */
  37095. target.onerror = function(message, url, line, opt_col, opt_error) {
  37096. if (oldErrorHandler) {
  37097. oldErrorHandler(message, url, line, opt_col, opt_error);
  37098. }
  37099. logFunc({
  37100. message: message,
  37101. fileName: url,
  37102. line: line,
  37103. col: opt_col,
  37104. error: opt_error
  37105. });
  37106. return retVal;
  37107. };
  37108. };
  37109. /**
  37110. * Creates a string representing an object and all its properties.
  37111. * @param {Object|null|undefined} obj Object to expose.
  37112. * @param {boolean=} opt_showFn Show the functions as well as the properties,
  37113. * default is false.
  37114. * @return {string} The string representation of {@code obj}.
  37115. */
  37116. goog.debug.expose = function(obj, opt_showFn) {
  37117. if (typeof obj == 'undefined') {
  37118. return 'undefined';
  37119. }
  37120. if (obj == null) {
  37121. return 'NULL';
  37122. }
  37123. var str = [];
  37124. for (var x in obj) {
  37125. if (!opt_showFn && goog.isFunction(obj[x])) {
  37126. continue;
  37127. }
  37128. var s = x + ' = ';
  37129. /** @preserveTry */
  37130. try {
  37131. s += obj[x];
  37132. } catch (e) {
  37133. s += '*** ' + e + ' ***';
  37134. }
  37135. str.push(s);
  37136. }
  37137. return str.join('\n');
  37138. };
  37139. /**
  37140. * Creates a string representing a given primitive or object, and for an
  37141. * object, all its properties and nested objects. WARNING: If an object is
  37142. * given, it and all its nested objects will be modified. To detect reference
  37143. * cycles, this method identifies objects using goog.getUid() which mutates the
  37144. * object.
  37145. * @param {*} obj Object to expose.
  37146. * @param {boolean=} opt_showFn Also show properties that are functions (by
  37147. * default, functions are omitted).
  37148. * @return {string} A string representation of {@code obj}.
  37149. */
  37150. goog.debug.deepExpose = function(obj, opt_showFn) {
  37151. var str = [];
  37152. var helper = function(obj, space, parentSeen) {
  37153. var nestspace = space + ' ';
  37154. var seen = new goog.structs.Set(parentSeen);
  37155. var indentMultiline = function(str) {
  37156. return str.replace(/\n/g, '\n' + space);
  37157. };
  37158. /** @preserveTry */
  37159. try {
  37160. if (!goog.isDef(obj)) {
  37161. str.push('undefined');
  37162. } else if (goog.isNull(obj)) {
  37163. str.push('NULL');
  37164. } else if (goog.isString(obj)) {
  37165. str.push('"' + indentMultiline(obj) + '"');
  37166. } else if (goog.isFunction(obj)) {
  37167. str.push(indentMultiline(String(obj)));
  37168. } else if (goog.isObject(obj)) {
  37169. if (seen.contains(obj)) {
  37170. str.push('*** reference loop detected ***');
  37171. } else {
  37172. seen.add(obj);
  37173. str.push('{');
  37174. for (var x in obj) {
  37175. if (!opt_showFn && goog.isFunction(obj[x])) {
  37176. continue;
  37177. }
  37178. str.push('\n');
  37179. str.push(nestspace);
  37180. str.push(x + ' = ');
  37181. helper(obj[x], nestspace, seen);
  37182. }
  37183. str.push('\n' + space + '}');
  37184. }
  37185. } else {
  37186. str.push(obj);
  37187. }
  37188. } catch (e) {
  37189. str.push('*** ' + e + ' ***');
  37190. }
  37191. };
  37192. helper(obj, '', new goog.structs.Set());
  37193. return str.join('');
  37194. };
  37195. /**
  37196. * Recursively outputs a nested array as a string.
  37197. * @param {Array<?>} arr The array.
  37198. * @return {string} String representing nested array.
  37199. */
  37200. goog.debug.exposeArray = function(arr) {
  37201. var str = [];
  37202. for (var i = 0; i < arr.length; i++) {
  37203. if (goog.isArray(arr[i])) {
  37204. str.push(goog.debug.exposeArray(arr[i]));
  37205. } else {
  37206. str.push(arr[i]);
  37207. }
  37208. }
  37209. return '[ ' + str.join(', ') + ' ]';
  37210. };
  37211. /**
  37212. * Exposes an exception that has been caught by a try...catch and outputs the
  37213. * error as HTML with a stack trace.
  37214. * @param {Object} err Error object or string.
  37215. * @param {Function=} opt_fn Optional function to start stack trace from.
  37216. * @return {string} Details of exception, as HTML.
  37217. */
  37218. goog.debug.exposeException = function(err, opt_fn) {
  37219. var html = goog.debug.exposeExceptionAsHtml(err, opt_fn);
  37220. return goog.html.SafeHtml.unwrap(html);
  37221. };
  37222. /**
  37223. * Exposes an exception that has been caught by a try...catch and outputs the
  37224. * error with a stack trace.
  37225. * @param {Object} err Error object or string.
  37226. * @param {Function=} opt_fn Optional function to start stack trace from.
  37227. * @return {!goog.html.SafeHtml} Details of exception.
  37228. */
  37229. goog.debug.exposeExceptionAsHtml = function(err, opt_fn) {
  37230. /** @preserveTry */
  37231. try {
  37232. var e = goog.debug.normalizeErrorObject(err);
  37233. // Create the error message
  37234. var viewSourceUrl = goog.debug.createViewSourceUrl_(e.fileName);
  37235. var error = goog.html.SafeHtml.concat(
  37236. goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
  37237. 'Message: ' + e.message + '\nUrl: '),
  37238. goog.html.SafeHtml.create('a',
  37239. {href: viewSourceUrl, target: '_new'}, e.fileName),
  37240. goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
  37241. '\nLine: ' + e.lineNumber + '\n\nBrowser stack:\n' +
  37242. e.stack + '-> ' + '[end]\n\nJS stack traversal:\n' +
  37243. goog.debug.getStacktrace(opt_fn) + '-> '));
  37244. return error;
  37245. } catch (e2) {
  37246. return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
  37247. 'Exception trying to expose exception! You win, we lose. ' + e2);
  37248. }
  37249. };
  37250. /**
  37251. * @param {?string=} opt_fileName
  37252. * @return {!goog.html.SafeUrl} SafeUrl with view-source scheme, pointing at
  37253. * fileName.
  37254. * @private
  37255. */
  37256. goog.debug.createViewSourceUrl_ = function(opt_fileName) {
  37257. if (!goog.isDefAndNotNull(opt_fileName)) {
  37258. opt_fileName = '';
  37259. }
  37260. if (!/^https?:\/\//i.test(opt_fileName)) {
  37261. return goog.html.SafeUrl.fromConstant(
  37262. goog.string.Const.from('sanitizedviewsrc'));
  37263. }
  37264. var sanitizedFileName = goog.html.SafeUrl.sanitize(opt_fileName);
  37265. return goog.html.uncheckedconversions.
  37266. safeUrlFromStringKnownToSatisfyTypeContract(
  37267. goog.string.Const.from('view-source scheme plus HTTP/HTTPS URL'),
  37268. 'view-source:' + goog.html.SafeUrl.unwrap(sanitizedFileName));
  37269. };
  37270. /**
  37271. * Normalizes the error/exception object between browsers.
  37272. * @param {Object} err Raw error object.
  37273. * @return {!Object} Normalized error object.
  37274. */
  37275. goog.debug.normalizeErrorObject = function(err) {
  37276. var href = goog.getObjectByName('window.location.href');
  37277. if (goog.isString(err)) {
  37278. return {
  37279. 'message': err,
  37280. 'name': 'Unknown error',
  37281. 'lineNumber': 'Not available',
  37282. 'fileName': href,
  37283. 'stack': 'Not available'
  37284. };
  37285. }
  37286. var lineNumber, fileName;
  37287. var threwError = false;
  37288. try {
  37289. lineNumber = err.lineNumber || err.line || 'Not available';
  37290. } catch (e) {
  37291. // Firefox 2 sometimes throws an error when accessing 'lineNumber':
  37292. // Message: Permission denied to get property UnnamedClass.lineNumber
  37293. lineNumber = 'Not available';
  37294. threwError = true;
  37295. }
  37296. try {
  37297. fileName = err.fileName || err.filename || err.sourceURL ||
  37298. // $googDebugFname may be set before a call to eval to set the filename
  37299. // that the eval is supposed to present.
  37300. goog.global['$googDebugFname'] || href;
  37301. } catch (e) {
  37302. // Firefox 2 may also throw an error when accessing 'filename'.
  37303. fileName = 'Not available';
  37304. threwError = true;
  37305. }
  37306. // The IE Error object contains only the name and the message.
  37307. // The Safari Error object uses the line and sourceURL fields.
  37308. if (threwError || !err.lineNumber || !err.fileName || !err.stack ||
  37309. !err.message || !err.name) {
  37310. return {
  37311. 'message': err.message || 'Not available',
  37312. 'name': err.name || 'UnknownError',
  37313. 'lineNumber': lineNumber,
  37314. 'fileName': fileName,
  37315. 'stack': err.stack || 'Not available'
  37316. };
  37317. }
  37318. // Standards error object
  37319. return err;
  37320. };
  37321. /**
  37322. * Converts an object to an Error if it's a String,
  37323. * adds a stacktrace if there isn't one,
  37324. * and optionally adds an extra message.
  37325. * @param {Error|string} err the original thrown object or string.
  37326. * @param {string=} opt_message optional additional message to add to the
  37327. * error.
  37328. * @return {!Error} If err is a string, it is used to create a new Error,
  37329. * which is enhanced and returned. Otherwise err itself is enhanced
  37330. * and returned.
  37331. */
  37332. goog.debug.enhanceError = function(err, opt_message) {
  37333. var error;
  37334. if (typeof err == 'string') {
  37335. error = Error(err);
  37336. if (Error.captureStackTrace) {
  37337. // Trim this function off the call stack, if we can.
  37338. Error.captureStackTrace(error, goog.debug.enhanceError);
  37339. }
  37340. } else {
  37341. error = err;
  37342. }
  37343. if (!error.stack) {
  37344. error.stack = goog.debug.getStacktrace(goog.debug.enhanceError);
  37345. }
  37346. if (opt_message) {
  37347. // find the first unoccupied 'messageX' property
  37348. var x = 0;
  37349. while (error['message' + x]) {
  37350. ++x;
  37351. }
  37352. error['message' + x] = String(opt_message);
  37353. }
  37354. return error;
  37355. };
  37356. /**
  37357. * Gets the current stack trace. Simple and iterative - doesn't worry about
  37358. * catching circular references or getting the args.
  37359. * @param {number=} opt_depth Optional maximum depth to trace back to.
  37360. * @return {string} A string with the function names of all functions in the
  37361. * stack, separated by \n.
  37362. * @suppress {es5Strict}
  37363. */
  37364. goog.debug.getStacktraceSimple = function(opt_depth) {
  37365. if (goog.STRICT_MODE_COMPATIBLE) {
  37366. var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple);
  37367. if (stack) {
  37368. return stack;
  37369. }
  37370. // NOTE: browsers that have strict mode support also have native "stack"
  37371. // properties. Fall-through for legacy browser support.
  37372. }
  37373. var sb = [];
  37374. var fn = arguments.callee.caller;
  37375. var depth = 0;
  37376. while (fn && (!opt_depth || depth < opt_depth)) {
  37377. sb.push(goog.debug.getFunctionName(fn));
  37378. sb.push('()\n');
  37379. /** @preserveTry */
  37380. try {
  37381. fn = fn.caller;
  37382. } catch (e) {
  37383. sb.push('[exception trying to get caller]\n');
  37384. break;
  37385. }
  37386. depth++;
  37387. if (depth >= goog.debug.MAX_STACK_DEPTH) {
  37388. sb.push('[...long stack...]');
  37389. break;
  37390. }
  37391. }
  37392. if (opt_depth && depth >= opt_depth) {
  37393. sb.push('[...reached max depth limit...]');
  37394. } else {
  37395. sb.push('[end]');
  37396. }
  37397. return sb.join('');
  37398. };
  37399. /**
  37400. * Max length of stack to try and output
  37401. * @type {number}
  37402. */
  37403. goog.debug.MAX_STACK_DEPTH = 50;
  37404. /**
  37405. * @param {Function} fn The function to start getting the trace from.
  37406. * @return {?string}
  37407. * @private
  37408. */
  37409. goog.debug.getNativeStackTrace_ = function(fn) {
  37410. var tempErr = new Error();
  37411. if (Error.captureStackTrace) {
  37412. Error.captureStackTrace(tempErr, fn);
  37413. return String(tempErr.stack);
  37414. } else {
  37415. // IE10, only adds stack traces when an exception is thrown.
  37416. try {
  37417. throw tempErr;
  37418. } catch (e) {
  37419. tempErr = e;
  37420. }
  37421. var stack = tempErr.stack;
  37422. if (stack) {
  37423. return String(stack);
  37424. }
  37425. }
  37426. return null;
  37427. };
  37428. /**
  37429. * Gets the current stack trace, either starting from the caller or starting
  37430. * from a specified function that's currently on the call stack.
  37431. * @param {Function=} opt_fn Optional function to start getting the trace from.
  37432. * If not provided, defaults to the function that called this.
  37433. * @return {string} Stack trace.
  37434. * @suppress {es5Strict}
  37435. */
  37436. goog.debug.getStacktrace = function(opt_fn) {
  37437. var stack;
  37438. if (goog.STRICT_MODE_COMPATIBLE) {
  37439. // Try to get the stack trace from the environment if it is available.
  37440. var contextFn = opt_fn || goog.debug.getStacktrace;
  37441. stack = goog.debug.getNativeStackTrace_(contextFn);
  37442. }
  37443. if (!stack) {
  37444. // NOTE: browsers that have strict mode support also have native "stack"
  37445. // properties. This function will throw in strict mode.
  37446. stack = goog.debug.getStacktraceHelper_(
  37447. opt_fn || arguments.callee.caller, []);
  37448. }
  37449. return stack;
  37450. };
  37451. /**
  37452. * Private helper for getStacktrace().
  37453. * @param {Function} fn Function to start getting the trace from.
  37454. * @param {Array<!Function>} visited List of functions visited so far.
  37455. * @return {string} Stack trace starting from function fn.
  37456. * @suppress {es5Strict}
  37457. * @private
  37458. */
  37459. goog.debug.getStacktraceHelper_ = function(fn, visited) {
  37460. var sb = [];
  37461. // Circular reference, certain functions like bind seem to cause a recursive
  37462. // loop so we need to catch circular references
  37463. if (goog.array.contains(visited, fn)) {
  37464. sb.push('[...circular reference...]');
  37465. // Traverse the call stack until function not found or max depth is reached
  37466. } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) {
  37467. sb.push(goog.debug.getFunctionName(fn) + '(');
  37468. var args = fn.arguments;
  37469. // Args may be null for some special functions such as host objects or eval.
  37470. for (var i = 0; args && i < args.length; i++) {
  37471. if (i > 0) {
  37472. sb.push(', ');
  37473. }
  37474. var argDesc;
  37475. var arg = args[i];
  37476. switch (typeof arg) {
  37477. case 'object':
  37478. argDesc = arg ? 'object' : 'null';
  37479. break;
  37480. case 'string':
  37481. argDesc = arg;
  37482. break;
  37483. case 'number':
  37484. argDesc = String(arg);
  37485. break;
  37486. case 'boolean':
  37487. argDesc = arg ? 'true' : 'false';
  37488. break;
  37489. case 'function':
  37490. argDesc = goog.debug.getFunctionName(arg);
  37491. argDesc = argDesc ? argDesc : '[fn]';
  37492. break;
  37493. case 'undefined':
  37494. default:
  37495. argDesc = typeof arg;
  37496. break;
  37497. }
  37498. if (argDesc.length > 40) {
  37499. argDesc = argDesc.substr(0, 40) + '...';
  37500. }
  37501. sb.push(argDesc);
  37502. }
  37503. visited.push(fn);
  37504. sb.push(')\n');
  37505. /** @preserveTry */
  37506. try {
  37507. sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited));
  37508. } catch (e) {
  37509. sb.push('[exception trying to get caller]\n');
  37510. }
  37511. } else if (fn) {
  37512. sb.push('[...long stack...]');
  37513. } else {
  37514. sb.push('[end]');
  37515. }
  37516. return sb.join('');
  37517. };
  37518. /**
  37519. * Set a custom function name resolver.
  37520. * @param {function(Function): string} resolver Resolves functions to their
  37521. * names.
  37522. */
  37523. goog.debug.setFunctionResolver = function(resolver) {
  37524. goog.debug.fnNameResolver_ = resolver;
  37525. };
  37526. /**
  37527. * Gets a function name
  37528. * @param {Function} fn Function to get name of.
  37529. * @return {string} Function's name.
  37530. */
  37531. goog.debug.getFunctionName = function(fn) {
  37532. if (goog.debug.fnNameCache_[fn]) {
  37533. return goog.debug.fnNameCache_[fn];
  37534. }
  37535. if (goog.debug.fnNameResolver_) {
  37536. var name = goog.debug.fnNameResolver_(fn);
  37537. if (name) {
  37538. goog.debug.fnNameCache_[fn] = name;
  37539. return name;
  37540. }
  37541. }
  37542. // Heuristically determine function name based on code.
  37543. var functionSource = String(fn);
  37544. if (!goog.debug.fnNameCache_[functionSource]) {
  37545. var matches = /function ([^\(]+)/.exec(functionSource);
  37546. if (matches) {
  37547. var method = matches[1];
  37548. goog.debug.fnNameCache_[functionSource] = method;
  37549. } else {
  37550. goog.debug.fnNameCache_[functionSource] = '[Anonymous]';
  37551. }
  37552. }
  37553. return goog.debug.fnNameCache_[functionSource];
  37554. };
  37555. /**
  37556. * Makes whitespace visible by replacing it with printable characters.
  37557. * This is useful in finding diffrences between the expected and the actual
  37558. * output strings of a testcase.
  37559. * @param {string} string whose whitespace needs to be made visible.
  37560. * @return {string} string whose whitespace is made visible.
  37561. */
  37562. goog.debug.makeWhitespaceVisible = function(string) {
  37563. return string.replace(/ /g, '[_]')
  37564. .replace(/\f/g, '[f]')
  37565. .replace(/\n/g, '[n]\n')
  37566. .replace(/\r/g, '[r]')
  37567. .replace(/\t/g, '[t]');
  37568. };
  37569. /**
  37570. * Returns the type of a value. If a constructor is passed, and a suitable
  37571. * string cannot be found, 'unknown type name' will be returned.
  37572. *
  37573. * <p>Forked rather than moved from {@link goog.asserts.getType_}
  37574. * to avoid adding a dependency to goog.asserts.
  37575. * @param {*} value A constructor, object, or primitive.
  37576. * @return {string} The best display name for the value, or 'unknown type name'.
  37577. */
  37578. goog.debug.runtimeType = function(value) {
  37579. if (value instanceof Function) {
  37580. return value.displayName || value.name || 'unknown type name';
  37581. } else if (value instanceof Object) {
  37582. return value.constructor.displayName || value.constructor.name ||
  37583. Object.prototype.toString.call(value);
  37584. } else {
  37585. return value === null ? 'null' : typeof value;
  37586. }
  37587. };
  37588. /**
  37589. * Hash map for storing function names that have already been looked up.
  37590. * @type {Object}
  37591. * @private
  37592. */
  37593. goog.debug.fnNameCache_ = {};
  37594. /**
  37595. * Resolves functions to their names. Resolved function names will be cached.
  37596. * @type {function(Function):string}
  37597. * @private
  37598. */
  37599. goog.debug.fnNameResolver_;
  37600. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  37601. //
  37602. // Licensed under the Apache License, Version 2.0 (the "License");
  37603. // you may not use this file except in compliance with the License.
  37604. // You may obtain a copy of the License at
  37605. //
  37606. // http://www.apache.org/licenses/LICENSE-2.0
  37607. //
  37608. // Unless required by applicable law or agreed to in writing, software
  37609. // distributed under the License is distributed on an "AS-IS" BASIS,
  37610. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37611. // See the License for the specific language governing permissions and
  37612. // limitations under the License.
  37613. /**
  37614. * @fileoverview Definition of the LogRecord class. Please minimize
  37615. * dependencies this file has on other closure classes as any dependency it
  37616. * takes won't be able to use the logging infrastructure.
  37617. *
  37618. */
  37619. goog.provide('goog.debug.LogRecord');
  37620. /**
  37621. * LogRecord objects are used to pass logging requests between
  37622. * the logging framework and individual log Handlers.
  37623. * @constructor
  37624. * @param {goog.debug.Logger.Level} level One of the level identifiers.
  37625. * @param {string} msg The string message.
  37626. * @param {string} loggerName The name of the source logger.
  37627. * @param {number=} opt_time Time this log record was created if other than now.
  37628. * If 0, we use #goog.now.
  37629. * @param {number=} opt_sequenceNumber Sequence number of this log record. This
  37630. * should only be passed in when restoring a log record from persistence.
  37631. */
  37632. goog.debug.LogRecord = function(level, msg, loggerName,
  37633. opt_time, opt_sequenceNumber) {
  37634. this.reset(level, msg, loggerName, opt_time, opt_sequenceNumber);
  37635. };
  37636. /**
  37637. * Time the LogRecord was created.
  37638. * @type {number}
  37639. * @private
  37640. */
  37641. goog.debug.LogRecord.prototype.time_;
  37642. /**
  37643. * Level of the LogRecord
  37644. * @type {goog.debug.Logger.Level}
  37645. * @private
  37646. */
  37647. goog.debug.LogRecord.prototype.level_;
  37648. /**
  37649. * Message associated with the record
  37650. * @type {string}
  37651. * @private
  37652. */
  37653. goog.debug.LogRecord.prototype.msg_;
  37654. /**
  37655. * Name of the logger that created the record.
  37656. * @type {string}
  37657. * @private
  37658. */
  37659. goog.debug.LogRecord.prototype.loggerName_;
  37660. /**
  37661. * Sequence number for the LogRecord. Each record has a unique sequence number
  37662. * that is greater than all log records created before it.
  37663. * @type {number}
  37664. * @private
  37665. */
  37666. goog.debug.LogRecord.prototype.sequenceNumber_ = 0;
  37667. /**
  37668. * Exception associated with the record
  37669. * @type {Object}
  37670. * @private
  37671. */
  37672. goog.debug.LogRecord.prototype.exception_ = null;
  37673. /**
  37674. * @define {boolean} Whether to enable log sequence numbers.
  37675. */
  37676. goog.define('goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS', true);
  37677. /**
  37678. * A sequence counter for assigning increasing sequence numbers to LogRecord
  37679. * objects.
  37680. * @type {number}
  37681. * @private
  37682. */
  37683. goog.debug.LogRecord.nextSequenceNumber_ = 0;
  37684. /**
  37685. * Sets all fields of the log record.
  37686. * @param {goog.debug.Logger.Level} level One of the level identifiers.
  37687. * @param {string} msg The string message.
  37688. * @param {string} loggerName The name of the source logger.
  37689. * @param {number=} opt_time Time this log record was created if other than now.
  37690. * If 0, we use #goog.now.
  37691. * @param {number=} opt_sequenceNumber Sequence number of this log record. This
  37692. * should only be passed in when restoring a log record from persistence.
  37693. */
  37694. goog.debug.LogRecord.prototype.reset = function(level, msg, loggerName,
  37695. opt_time, opt_sequenceNumber) {
  37696. if (goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS) {
  37697. this.sequenceNumber_ = typeof opt_sequenceNumber == 'number' ?
  37698. opt_sequenceNumber : goog.debug.LogRecord.nextSequenceNumber_++;
  37699. }
  37700. this.time_ = opt_time || goog.now();
  37701. this.level_ = level;
  37702. this.msg_ = msg;
  37703. this.loggerName_ = loggerName;
  37704. delete this.exception_;
  37705. };
  37706. /**
  37707. * Get the source Logger's name.
  37708. *
  37709. * @return {string} source logger name (may be null).
  37710. */
  37711. goog.debug.LogRecord.prototype.getLoggerName = function() {
  37712. return this.loggerName_;
  37713. };
  37714. /**
  37715. * Get the exception that is part of the log record.
  37716. *
  37717. * @return {Object} the exception.
  37718. */
  37719. goog.debug.LogRecord.prototype.getException = function() {
  37720. return this.exception_;
  37721. };
  37722. /**
  37723. * Set the exception that is part of the log record.
  37724. *
  37725. * @param {Object} exception the exception.
  37726. */
  37727. goog.debug.LogRecord.prototype.setException = function(exception) {
  37728. this.exception_ = exception;
  37729. };
  37730. /**
  37731. * Get the source Logger's name.
  37732. *
  37733. * @param {string} loggerName source logger name (may be null).
  37734. */
  37735. goog.debug.LogRecord.prototype.setLoggerName = function(loggerName) {
  37736. this.loggerName_ = loggerName;
  37737. };
  37738. /**
  37739. * Get the logging message level, for example Level.SEVERE.
  37740. * @return {goog.debug.Logger.Level} the logging message level.
  37741. */
  37742. goog.debug.LogRecord.prototype.getLevel = function() {
  37743. return this.level_;
  37744. };
  37745. /**
  37746. * Set the logging message level, for example Level.SEVERE.
  37747. * @param {goog.debug.Logger.Level} level the logging message level.
  37748. */
  37749. goog.debug.LogRecord.prototype.setLevel = function(level) {
  37750. this.level_ = level;
  37751. };
  37752. /**
  37753. * Get the "raw" log message, before localization or formatting.
  37754. *
  37755. * @return {string} the raw message string.
  37756. */
  37757. goog.debug.LogRecord.prototype.getMessage = function() {
  37758. return this.msg_;
  37759. };
  37760. /**
  37761. * Set the "raw" log message, before localization or formatting.
  37762. *
  37763. * @param {string} msg the raw message string.
  37764. */
  37765. goog.debug.LogRecord.prototype.setMessage = function(msg) {
  37766. this.msg_ = msg;
  37767. };
  37768. /**
  37769. * Get event time in milliseconds since 1970.
  37770. *
  37771. * @return {number} event time in millis since 1970.
  37772. */
  37773. goog.debug.LogRecord.prototype.getMillis = function() {
  37774. return this.time_;
  37775. };
  37776. /**
  37777. * Set event time in milliseconds since 1970.
  37778. *
  37779. * @param {number} time event time in millis since 1970.
  37780. */
  37781. goog.debug.LogRecord.prototype.setMillis = function(time) {
  37782. this.time_ = time;
  37783. };
  37784. /**
  37785. * Get the sequence number.
  37786. * <p>
  37787. * Sequence numbers are normally assigned in the LogRecord
  37788. * constructor, which assigns unique sequence numbers to
  37789. * each new LogRecord in increasing order.
  37790. * @return {number} the sequence number.
  37791. */
  37792. goog.debug.LogRecord.prototype.getSequenceNumber = function() {
  37793. return this.sequenceNumber_;
  37794. };
  37795. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  37796. //
  37797. // Licensed under the Apache License, Version 2.0 (the "License");
  37798. // you may not use this file except in compliance with the License.
  37799. // You may obtain a copy of the License at
  37800. //
  37801. // http://www.apache.org/licenses/LICENSE-2.0
  37802. //
  37803. // Unless required by applicable law or agreed to in writing, software
  37804. // distributed under the License is distributed on an "AS-IS" BASIS,
  37805. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37806. // See the License for the specific language governing permissions and
  37807. // limitations under the License.
  37808. /**
  37809. * @fileoverview A buffer for log records. The purpose of this is to improve
  37810. * logging performance by re-using old objects when the buffer becomes full and
  37811. * to eliminate the need for each app to implement their own log buffer. The
  37812. * disadvantage to doing this is that log handlers cannot maintain references to
  37813. * log records and expect that they are not overwriten at a later point.
  37814. *
  37815. * @author agrieve@google.com (Andrew Grieve)
  37816. */
  37817. goog.provide('goog.debug.LogBuffer');
  37818. goog.require('goog.asserts');
  37819. goog.require('goog.debug.LogRecord');
  37820. /**
  37821. * Creates the log buffer.
  37822. * @constructor
  37823. * @final
  37824. */
  37825. goog.debug.LogBuffer = function() {
  37826. goog.asserts.assert(goog.debug.LogBuffer.isBufferingEnabled(),
  37827. 'Cannot use goog.debug.LogBuffer without defining ' +
  37828. 'goog.debug.LogBuffer.CAPACITY.');
  37829. this.clear();
  37830. };
  37831. /**
  37832. * A static method that always returns the same instance of LogBuffer.
  37833. * @return {!goog.debug.LogBuffer} The LogBuffer singleton instance.
  37834. */
  37835. goog.debug.LogBuffer.getInstance = function() {
  37836. if (!goog.debug.LogBuffer.instance_) {
  37837. // This function is written with the return statement after the assignment
  37838. // to avoid the jscompiler StripCode bug described in http://b/2608064.
  37839. // After that bug is fixed this can be refactored.
  37840. goog.debug.LogBuffer.instance_ = new goog.debug.LogBuffer();
  37841. }
  37842. return goog.debug.LogBuffer.instance_;
  37843. };
  37844. /**
  37845. * @define {number} The number of log records to buffer. 0 means disable
  37846. * buffering.
  37847. */
  37848. goog.define('goog.debug.LogBuffer.CAPACITY', 0);
  37849. /**
  37850. * The array to store the records.
  37851. * @type {!Array<!goog.debug.LogRecord|undefined>}
  37852. * @private
  37853. */
  37854. goog.debug.LogBuffer.prototype.buffer_;
  37855. /**
  37856. * The index of the most recently added record or -1 if there are no records.
  37857. * @type {number}
  37858. * @private
  37859. */
  37860. goog.debug.LogBuffer.prototype.curIndex_;
  37861. /**
  37862. * Whether the buffer is at capacity.
  37863. * @type {boolean}
  37864. * @private
  37865. */
  37866. goog.debug.LogBuffer.prototype.isFull_;
  37867. /**
  37868. * Adds a log record to the buffer, possibly overwriting the oldest record.
  37869. * @param {goog.debug.Logger.Level} level One of the level identifiers.
  37870. * @param {string} msg The string message.
  37871. * @param {string} loggerName The name of the source logger.
  37872. * @return {!goog.debug.LogRecord} The log record.
  37873. */
  37874. goog.debug.LogBuffer.prototype.addRecord = function(level, msg, loggerName) {
  37875. var curIndex = (this.curIndex_ + 1) % goog.debug.LogBuffer.CAPACITY;
  37876. this.curIndex_ = curIndex;
  37877. if (this.isFull_) {
  37878. var ret = this.buffer_[curIndex];
  37879. ret.reset(level, msg, loggerName);
  37880. return ret;
  37881. }
  37882. this.isFull_ = curIndex == goog.debug.LogBuffer.CAPACITY - 1;
  37883. return this.buffer_[curIndex] =
  37884. new goog.debug.LogRecord(level, msg, loggerName);
  37885. };
  37886. /**
  37887. * @return {boolean} Whether the log buffer is enabled.
  37888. */
  37889. goog.debug.LogBuffer.isBufferingEnabled = function() {
  37890. return goog.debug.LogBuffer.CAPACITY > 0;
  37891. };
  37892. /**
  37893. * Removes all buffered log records.
  37894. */
  37895. goog.debug.LogBuffer.prototype.clear = function() {
  37896. this.buffer_ = new Array(goog.debug.LogBuffer.CAPACITY);
  37897. this.curIndex_ = -1;
  37898. this.isFull_ = false;
  37899. };
  37900. /**
  37901. * Calls the given function for each buffered log record, starting with the
  37902. * oldest one.
  37903. * @param {function(!goog.debug.LogRecord)} func The function to call.
  37904. */
  37905. goog.debug.LogBuffer.prototype.forEachRecord = function(func) {
  37906. var buffer = this.buffer_;
  37907. // Corner case: no records.
  37908. if (!buffer[0]) {
  37909. return;
  37910. }
  37911. var curIndex = this.curIndex_;
  37912. var i = this.isFull_ ? curIndex : -1;
  37913. do {
  37914. i = (i + 1) % goog.debug.LogBuffer.CAPACITY;
  37915. func(/** @type {!goog.debug.LogRecord} */ (buffer[i]));
  37916. } while (i != curIndex);
  37917. };
  37918. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  37919. //
  37920. // Licensed under the Apache License, Version 2.0 (the "License");
  37921. // you may not use this file except in compliance with the License.
  37922. // You may obtain a copy of the License at
  37923. //
  37924. // http://www.apache.org/licenses/LICENSE-2.0
  37925. //
  37926. // Unless required by applicable law or agreed to in writing, software
  37927. // distributed under the License is distributed on an "AS-IS" BASIS,
  37928. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37929. // See the License for the specific language governing permissions and
  37930. // limitations under the License.
  37931. /**
  37932. * @fileoverview Definition of the Logger class. Please minimize dependencies
  37933. * this file has on other closure classes as any dependency it takes won't be
  37934. * able to use the logging infrastructure.
  37935. *
  37936. * @see ../demos/debug.html
  37937. */
  37938. goog.provide('goog.debug.LogManager');
  37939. goog.provide('goog.debug.Loggable');
  37940. goog.provide('goog.debug.Logger');
  37941. goog.provide('goog.debug.Logger.Level');
  37942. goog.require('goog.array');
  37943. goog.require('goog.asserts');
  37944. goog.require('goog.debug');
  37945. goog.require('goog.debug.LogBuffer');
  37946. goog.require('goog.debug.LogRecord');
  37947. /**
  37948. * A message value that can be handled by a Logger.
  37949. *
  37950. * Functions are treated like callbacks, but are only called when the event's
  37951. * log level is enabled. This is useful for logging messages that are expensive
  37952. * to construct.
  37953. *
  37954. * @typedef {string|function(): string}
  37955. */
  37956. goog.debug.Loggable;
  37957. /**
  37958. * The Logger is an object used for logging debug messages. Loggers are
  37959. * normally named, using a hierarchical dot-separated namespace. Logger names
  37960. * can be arbitrary strings, but they should normally be based on the package
  37961. * name or class name of the logged component, such as goog.net.BrowserChannel.
  37962. *
  37963. * The Logger object is loosely based on the java class
  37964. * java.util.logging.Logger. It supports different levels of filtering for
  37965. * different loggers.
  37966. *
  37967. * The logger object should never be instantiated by application code. It
  37968. * should always use the goog.debug.Logger.getLogger function.
  37969. *
  37970. * @constructor
  37971. * @param {string} name The name of the Logger.
  37972. * @final
  37973. */
  37974. goog.debug.Logger = function(name) {
  37975. /**
  37976. * Name of the Logger. Generally a dot-separated namespace
  37977. * @private {string}
  37978. */
  37979. this.name_ = name;
  37980. /**
  37981. * Parent Logger.
  37982. * @private {goog.debug.Logger}
  37983. */
  37984. this.parent_ = null;
  37985. /**
  37986. * Level that this logger only filters above. Null indicates it should
  37987. * inherit from the parent.
  37988. * @private {goog.debug.Logger.Level}
  37989. */
  37990. this.level_ = null;
  37991. /**
  37992. * Map of children loggers. The keys are the leaf names of the children and
  37993. * the values are the child loggers.
  37994. * @private {Object}
  37995. */
  37996. this.children_ = null;
  37997. /**
  37998. * Handlers that are listening to this logger.
  37999. * @private {Array<Function>}
  38000. */
  38001. this.handlers_ = null;
  38002. };
  38003. /** @const */
  38004. goog.debug.Logger.ROOT_LOGGER_NAME = '';
  38005. /**
  38006. * @define {boolean} Toggles whether loggers other than the root logger can have
  38007. * log handlers attached to them and whether they can have their log level
  38008. * set. Logging is a bit faster when this is set to false.
  38009. */
  38010. goog.define('goog.debug.Logger.ENABLE_HIERARCHY', true);
  38011. if (!goog.debug.Logger.ENABLE_HIERARCHY) {
  38012. /**
  38013. * @type {!Array<Function>}
  38014. * @private
  38015. */
  38016. goog.debug.Logger.rootHandlers_ = [];
  38017. /**
  38018. * @type {goog.debug.Logger.Level}
  38019. * @private
  38020. */
  38021. goog.debug.Logger.rootLevel_;
  38022. }
  38023. /**
  38024. * The Level class defines a set of standard logging levels that
  38025. * can be used to control logging output. The logging Level objects
  38026. * are ordered and are specified by ordered integers. Enabling logging
  38027. * at a given level also enables logging at all higher levels.
  38028. * <p>
  38029. * Clients should normally use the predefined Level constants such
  38030. * as Level.SEVERE.
  38031. * <p>
  38032. * The levels in descending order are:
  38033. * <ul>
  38034. * <li>SEVERE (highest value)
  38035. * <li>WARNING
  38036. * <li>INFO
  38037. * <li>CONFIG
  38038. * <li>FINE
  38039. * <li>FINER
  38040. * <li>FINEST (lowest value)
  38041. * </ul>
  38042. * In addition there is a level OFF that can be used to turn
  38043. * off logging, and a level ALL that can be used to enable
  38044. * logging of all messages.
  38045. *
  38046. * @param {string} name The name of the level.
  38047. * @param {number} value The numeric value of the level.
  38048. * @constructor
  38049. * @final
  38050. */
  38051. goog.debug.Logger.Level = function(name, value) {
  38052. /**
  38053. * The name of the level
  38054. * @type {string}
  38055. */
  38056. this.name = name;
  38057. /**
  38058. * The numeric value of the level
  38059. * @type {number}
  38060. */
  38061. this.value = value;
  38062. };
  38063. /**
  38064. * @return {string} String representation of the logger level.
  38065. * @override
  38066. */
  38067. goog.debug.Logger.Level.prototype.toString = function() {
  38068. return this.name;
  38069. };
  38070. /**
  38071. * OFF is a special level that can be used to turn off logging.
  38072. * This level is initialized to <CODE>Infinity</CODE>.
  38073. * @type {!goog.debug.Logger.Level}
  38074. */
  38075. goog.debug.Logger.Level.OFF =
  38076. new goog.debug.Logger.Level('OFF', Infinity);
  38077. /**
  38078. * SHOUT is a message level for extra debugging loudness.
  38079. * This level is initialized to <CODE>1200</CODE>.
  38080. * @type {!goog.debug.Logger.Level}
  38081. */
  38082. goog.debug.Logger.Level.SHOUT = new goog.debug.Logger.Level('SHOUT', 1200);
  38083. /**
  38084. * SEVERE is a message level indicating a serious failure.
  38085. * This level is initialized to <CODE>1000</CODE>.
  38086. * @type {!goog.debug.Logger.Level}
  38087. */
  38088. goog.debug.Logger.Level.SEVERE = new goog.debug.Logger.Level('SEVERE', 1000);
  38089. /**
  38090. * WARNING is a message level indicating a potential problem.
  38091. * This level is initialized to <CODE>900</CODE>.
  38092. * @type {!goog.debug.Logger.Level}
  38093. */
  38094. goog.debug.Logger.Level.WARNING = new goog.debug.Logger.Level('WARNING', 900);
  38095. /**
  38096. * INFO is a message level for informational messages.
  38097. * This level is initialized to <CODE>800</CODE>.
  38098. * @type {!goog.debug.Logger.Level}
  38099. */
  38100. goog.debug.Logger.Level.INFO = new goog.debug.Logger.Level('INFO', 800);
  38101. /**
  38102. * CONFIG is a message level for static configuration messages.
  38103. * This level is initialized to <CODE>700</CODE>.
  38104. * @type {!goog.debug.Logger.Level}
  38105. */
  38106. goog.debug.Logger.Level.CONFIG = new goog.debug.Logger.Level('CONFIG', 700);
  38107. /**
  38108. * FINE is a message level providing tracing information.
  38109. * This level is initialized to <CODE>500</CODE>.
  38110. * @type {!goog.debug.Logger.Level}
  38111. */
  38112. goog.debug.Logger.Level.FINE = new goog.debug.Logger.Level('FINE', 500);
  38113. /**
  38114. * FINER indicates a fairly detailed tracing message.
  38115. * This level is initialized to <CODE>400</CODE>.
  38116. * @type {!goog.debug.Logger.Level}
  38117. */
  38118. goog.debug.Logger.Level.FINER = new goog.debug.Logger.Level('FINER', 400);
  38119. /**
  38120. * FINEST indicates a highly detailed tracing message.
  38121. * This level is initialized to <CODE>300</CODE>.
  38122. * @type {!goog.debug.Logger.Level}
  38123. */
  38124. goog.debug.Logger.Level.FINEST = new goog.debug.Logger.Level('FINEST', 300);
  38125. /**
  38126. * ALL indicates that all messages should be logged.
  38127. * This level is initialized to <CODE>0</CODE>.
  38128. * @type {!goog.debug.Logger.Level}
  38129. */
  38130. goog.debug.Logger.Level.ALL = new goog.debug.Logger.Level('ALL', 0);
  38131. /**
  38132. * The predefined levels.
  38133. * @type {!Array<!goog.debug.Logger.Level>}
  38134. * @final
  38135. */
  38136. goog.debug.Logger.Level.PREDEFINED_LEVELS = [
  38137. goog.debug.Logger.Level.OFF,
  38138. goog.debug.Logger.Level.SHOUT,
  38139. goog.debug.Logger.Level.SEVERE,
  38140. goog.debug.Logger.Level.WARNING,
  38141. goog.debug.Logger.Level.INFO,
  38142. goog.debug.Logger.Level.CONFIG,
  38143. goog.debug.Logger.Level.FINE,
  38144. goog.debug.Logger.Level.FINER,
  38145. goog.debug.Logger.Level.FINEST,
  38146. goog.debug.Logger.Level.ALL];
  38147. /**
  38148. * A lookup map used to find the level object based on the name or value of
  38149. * the level object.
  38150. * @type {Object}
  38151. * @private
  38152. */
  38153. goog.debug.Logger.Level.predefinedLevelsCache_ = null;
  38154. /**
  38155. * Creates the predefined levels cache and populates it.
  38156. * @private
  38157. */
  38158. goog.debug.Logger.Level.createPredefinedLevelsCache_ = function() {
  38159. goog.debug.Logger.Level.predefinedLevelsCache_ = {};
  38160. for (var i = 0, level; level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i];
  38161. i++) {
  38162. goog.debug.Logger.Level.predefinedLevelsCache_[level.value] = level;
  38163. goog.debug.Logger.Level.predefinedLevelsCache_[level.name] = level;
  38164. }
  38165. };
  38166. /**
  38167. * Gets the predefined level with the given name.
  38168. * @param {string} name The name of the level.
  38169. * @return {goog.debug.Logger.Level} The level, or null if none found.
  38170. */
  38171. goog.debug.Logger.Level.getPredefinedLevel = function(name) {
  38172. if (!goog.debug.Logger.Level.predefinedLevelsCache_) {
  38173. goog.debug.Logger.Level.createPredefinedLevelsCache_();
  38174. }
  38175. return goog.debug.Logger.Level.predefinedLevelsCache_[name] || null;
  38176. };
  38177. /**
  38178. * Gets the highest predefined level <= #value.
  38179. * @param {number} value Level value.
  38180. * @return {goog.debug.Logger.Level} The level, or null if none found.
  38181. */
  38182. goog.debug.Logger.Level.getPredefinedLevelByValue = function(value) {
  38183. if (!goog.debug.Logger.Level.predefinedLevelsCache_) {
  38184. goog.debug.Logger.Level.createPredefinedLevelsCache_();
  38185. }
  38186. if (value in goog.debug.Logger.Level.predefinedLevelsCache_) {
  38187. return goog.debug.Logger.Level.predefinedLevelsCache_[value];
  38188. }
  38189. for (var i = 0; i < goog.debug.Logger.Level.PREDEFINED_LEVELS.length; ++i) {
  38190. var level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i];
  38191. if (level.value <= value) {
  38192. return level;
  38193. }
  38194. }
  38195. return null;
  38196. };
  38197. /**
  38198. * Finds or creates a logger for a named subsystem. If a logger has already been
  38199. * created with the given name it is returned. Otherwise a new logger is
  38200. * created. If a new logger is created its log level will be configured based
  38201. * on the LogManager configuration and it will configured to also send logging
  38202. * output to its parent's handlers. It will be registered in the LogManager
  38203. * global namespace.
  38204. *
  38205. * @param {string} name A name for the logger. This should be a dot-separated
  38206. * name and should normally be based on the package name or class name of the
  38207. * subsystem, such as goog.net.BrowserChannel.
  38208. * @return {!goog.debug.Logger} The named logger.
  38209. * @deprecated use goog.log instead. http://go/goog-debug-logger-deprecated
  38210. */
  38211. goog.debug.Logger.getLogger = function(name) {
  38212. return goog.debug.LogManager.getLogger(name);
  38213. };
  38214. /**
  38215. * Logs a message to profiling tools, if available.
  38216. * {@see https://developers.google.com/web-toolkit/speedtracer/logging-api}
  38217. * {@see http://msdn.microsoft.com/en-us/library/dd433074(VS.85).aspx}
  38218. * @param {string} msg The message to log.
  38219. */
  38220. goog.debug.Logger.logToProfilers = function(msg) {
  38221. // Using goog.global, as loggers might be used in window-less contexts.
  38222. if (goog.global['console']) {
  38223. if (goog.global['console']['timeStamp']) {
  38224. // Logs a message to Firebug, Web Inspector, SpeedTracer, etc.
  38225. goog.global['console']['timeStamp'](msg);
  38226. } else if (goog.global['console']['markTimeline']) {
  38227. // TODO(user): markTimeline is deprecated. Drop this else clause entirely
  38228. // after Chrome M14 hits stable.
  38229. goog.global['console']['markTimeline'](msg);
  38230. }
  38231. }
  38232. if (goog.global['msWriteProfilerMark']) {
  38233. // Logs a message to the Microsoft profiler
  38234. goog.global['msWriteProfilerMark'](msg);
  38235. }
  38236. };
  38237. /**
  38238. * Gets the name of this logger.
  38239. * @return {string} The name of this logger.
  38240. */
  38241. goog.debug.Logger.prototype.getName = function() {
  38242. return this.name_;
  38243. };
  38244. /**
  38245. * Adds a handler to the logger. This doesn't use the event system because
  38246. * we want to be able to add logging to the event system.
  38247. * @param {Function} handler Handler function to add.
  38248. */
  38249. goog.debug.Logger.prototype.addHandler = function(handler) {
  38250. if (goog.debug.LOGGING_ENABLED) {
  38251. if (goog.debug.Logger.ENABLE_HIERARCHY) {
  38252. if (!this.handlers_) {
  38253. this.handlers_ = [];
  38254. }
  38255. this.handlers_.push(handler);
  38256. } else {
  38257. goog.asserts.assert(!this.name_,
  38258. 'Cannot call addHandler on a non-root logger when ' +
  38259. 'goog.debug.Logger.ENABLE_HIERARCHY is false.');
  38260. goog.debug.Logger.rootHandlers_.push(handler);
  38261. }
  38262. }
  38263. };
  38264. /**
  38265. * Removes a handler from the logger. This doesn't use the event system because
  38266. * we want to be able to add logging to the event system.
  38267. * @param {Function} handler Handler function to remove.
  38268. * @return {boolean} Whether the handler was removed.
  38269. */
  38270. goog.debug.Logger.prototype.removeHandler = function(handler) {
  38271. if (goog.debug.LOGGING_ENABLED) {
  38272. var handlers = goog.debug.Logger.ENABLE_HIERARCHY ? this.handlers_ :
  38273. goog.debug.Logger.rootHandlers_;
  38274. return !!handlers && goog.array.remove(handlers, handler);
  38275. } else {
  38276. return false;
  38277. }
  38278. };
  38279. /**
  38280. * Returns the parent of this logger.
  38281. * @return {goog.debug.Logger} The parent logger or null if this is the root.
  38282. */
  38283. goog.debug.Logger.prototype.getParent = function() {
  38284. return this.parent_;
  38285. };
  38286. /**
  38287. * Returns the children of this logger as a map of the child name to the logger.
  38288. * @return {!Object} The map where the keys are the child leaf names and the
  38289. * values are the Logger objects.
  38290. */
  38291. goog.debug.Logger.prototype.getChildren = function() {
  38292. if (!this.children_) {
  38293. this.children_ = {};
  38294. }
  38295. return this.children_;
  38296. };
  38297. /**
  38298. * Set the log level specifying which message levels will be logged by this
  38299. * logger. Message levels lower than this value will be discarded.
  38300. * The level value Level.OFF can be used to turn off logging. If the new level
  38301. * is null, it means that this node should inherit its level from its nearest
  38302. * ancestor with a specific (non-null) level value.
  38303. *
  38304. * @param {goog.debug.Logger.Level} level The new level.
  38305. */
  38306. goog.debug.Logger.prototype.setLevel = function(level) {
  38307. if (goog.debug.LOGGING_ENABLED) {
  38308. if (goog.debug.Logger.ENABLE_HIERARCHY) {
  38309. this.level_ = level;
  38310. } else {
  38311. goog.asserts.assert(!this.name_,
  38312. 'Cannot call setLevel() on a non-root logger when ' +
  38313. 'goog.debug.Logger.ENABLE_HIERARCHY is false.');
  38314. goog.debug.Logger.rootLevel_ = level;
  38315. }
  38316. }
  38317. };
  38318. /**
  38319. * Gets the log level specifying which message levels will be logged by this
  38320. * logger. Message levels lower than this value will be discarded.
  38321. * The level value Level.OFF can be used to turn off logging. If the level
  38322. * is null, it means that this node should inherit its level from its nearest
  38323. * ancestor with a specific (non-null) level value.
  38324. *
  38325. * @return {goog.debug.Logger.Level} The level.
  38326. */
  38327. goog.debug.Logger.prototype.getLevel = function() {
  38328. return goog.debug.LOGGING_ENABLED ?
  38329. this.level_ : goog.debug.Logger.Level.OFF;
  38330. };
  38331. /**
  38332. * Returns the effective level of the logger based on its ancestors' levels.
  38333. * @return {goog.debug.Logger.Level} The level.
  38334. */
  38335. goog.debug.Logger.prototype.getEffectiveLevel = function() {
  38336. if (!goog.debug.LOGGING_ENABLED) {
  38337. return goog.debug.Logger.Level.OFF;
  38338. }
  38339. if (!goog.debug.Logger.ENABLE_HIERARCHY) {
  38340. return goog.debug.Logger.rootLevel_;
  38341. }
  38342. if (this.level_) {
  38343. return this.level_;
  38344. }
  38345. if (this.parent_) {
  38346. return this.parent_.getEffectiveLevel();
  38347. }
  38348. goog.asserts.fail('Root logger has no level set.');
  38349. return null;
  38350. };
  38351. /**
  38352. * Checks if a message of the given level would actually be logged by this
  38353. * logger. This check is based on the Loggers effective level, which may be
  38354. * inherited from its parent.
  38355. * @param {goog.debug.Logger.Level} level The level to check.
  38356. * @return {boolean} Whether the message would be logged.
  38357. */
  38358. goog.debug.Logger.prototype.isLoggable = function(level) {
  38359. return goog.debug.LOGGING_ENABLED &&
  38360. level.value >= this.getEffectiveLevel().value;
  38361. };
  38362. /**
  38363. * Logs a message. If the logger is currently enabled for the
  38364. * given message level then the given message is forwarded to all the
  38365. * registered output Handler objects.
  38366. * @param {goog.debug.Logger.Level} level One of the level identifiers.
  38367. * @param {goog.debug.Loggable} msg The message to log.
  38368. * @param {Error|Object=} opt_exception An exception associated with the
  38369. * message.
  38370. */
  38371. goog.debug.Logger.prototype.log = function(level, msg, opt_exception) {
  38372. // java caches the effective level, not sure it's necessary here
  38373. if (goog.debug.LOGGING_ENABLED && this.isLoggable(level)) {
  38374. // Message callbacks can be useful when a log message is expensive to build.
  38375. if (goog.isFunction(msg)) {
  38376. msg = msg();
  38377. }
  38378. this.doLogRecord_(this.getLogRecord(level, msg, opt_exception));
  38379. }
  38380. };
  38381. /**
  38382. * Creates a new log record and adds the exception (if present) to it.
  38383. * @param {goog.debug.Logger.Level} level One of the level identifiers.
  38384. * @param {string} msg The string message.
  38385. * @param {Error|Object=} opt_exception An exception associated with the
  38386. * message.
  38387. * @return {!goog.debug.LogRecord} A log record.
  38388. * @suppress {es5Strict}
  38389. */
  38390. goog.debug.Logger.prototype.getLogRecord = function(
  38391. level, msg, opt_exception) {
  38392. if (goog.debug.LogBuffer.isBufferingEnabled()) {
  38393. var logRecord =
  38394. goog.debug.LogBuffer.getInstance().addRecord(level, msg, this.name_);
  38395. } else {
  38396. logRecord = new goog.debug.LogRecord(level, String(msg), this.name_);
  38397. }
  38398. if (opt_exception) {
  38399. logRecord.setException(opt_exception);
  38400. }
  38401. return logRecord;
  38402. };
  38403. /**
  38404. * Logs a message at the Logger.Level.SHOUT level.
  38405. * If the logger is currently enabled for the given message level then the
  38406. * given message is forwarded to all the registered output Handler objects.
  38407. * @param {goog.debug.Loggable} msg The message to log.
  38408. * @param {Error=} opt_exception An exception associated with the message.
  38409. */
  38410. goog.debug.Logger.prototype.shout = function(msg, opt_exception) {
  38411. if (goog.debug.LOGGING_ENABLED) {
  38412. this.log(goog.debug.Logger.Level.SHOUT, msg, opt_exception);
  38413. }
  38414. };
  38415. /**
  38416. * Logs a message at the Logger.Level.SEVERE level.
  38417. * If the logger is currently enabled for the given message level then the
  38418. * given message is forwarded to all the registered output Handler objects.
  38419. * @param {goog.debug.Loggable} msg The message to log.
  38420. * @param {Error=} opt_exception An exception associated with the message.
  38421. */
  38422. goog.debug.Logger.prototype.severe = function(msg, opt_exception) {
  38423. if (goog.debug.LOGGING_ENABLED) {
  38424. this.log(goog.debug.Logger.Level.SEVERE, msg, opt_exception);
  38425. }
  38426. };
  38427. /**
  38428. * Logs a message at the Logger.Level.WARNING level.
  38429. * If the logger is currently enabled for the given message level then the
  38430. * given message is forwarded to all the registered output Handler objects.
  38431. * @param {goog.debug.Loggable} msg The message to log.
  38432. * @param {Error=} opt_exception An exception associated with the message.
  38433. */
  38434. goog.debug.Logger.prototype.warning = function(msg, opt_exception) {
  38435. if (goog.debug.LOGGING_ENABLED) {
  38436. this.log(goog.debug.Logger.Level.WARNING, msg, opt_exception);
  38437. }
  38438. };
  38439. /**
  38440. * Logs a message at the Logger.Level.INFO level.
  38441. * If the logger is currently enabled for the given message level then the
  38442. * given message is forwarded to all the registered output Handler objects.
  38443. * @param {goog.debug.Loggable} msg The message to log.
  38444. * @param {Error=} opt_exception An exception associated with the message.
  38445. */
  38446. goog.debug.Logger.prototype.info = function(msg, opt_exception) {
  38447. if (goog.debug.LOGGING_ENABLED) {
  38448. this.log(goog.debug.Logger.Level.INFO, msg, opt_exception);
  38449. }
  38450. };
  38451. /**
  38452. * Logs a message at the Logger.Level.CONFIG level.
  38453. * If the logger is currently enabled for the given message level then the
  38454. * given message is forwarded to all the registered output Handler objects.
  38455. * @param {goog.debug.Loggable} msg The message to log.
  38456. * @param {Error=} opt_exception An exception associated with the message.
  38457. */
  38458. goog.debug.Logger.prototype.config = function(msg, opt_exception) {
  38459. if (goog.debug.LOGGING_ENABLED) {
  38460. this.log(goog.debug.Logger.Level.CONFIG, msg, opt_exception);
  38461. }
  38462. };
  38463. /**
  38464. * Logs a message at the Logger.Level.FINE level.
  38465. * If the logger is currently enabled for the given message level then the
  38466. * given message is forwarded to all the registered output Handler objects.
  38467. * @param {goog.debug.Loggable} msg The message to log.
  38468. * @param {Error=} opt_exception An exception associated with the message.
  38469. */
  38470. goog.debug.Logger.prototype.fine = function(msg, opt_exception) {
  38471. if (goog.debug.LOGGING_ENABLED) {
  38472. this.log(goog.debug.Logger.Level.FINE, msg, opt_exception);
  38473. }
  38474. };
  38475. /**
  38476. * Logs a message at the Logger.Level.FINER level.
  38477. * If the logger is currently enabled for the given message level then the
  38478. * given message is forwarded to all the registered output Handler objects.
  38479. * @param {goog.debug.Loggable} msg The message to log.
  38480. * @param {Error=} opt_exception An exception associated with the message.
  38481. */
  38482. goog.debug.Logger.prototype.finer = function(msg, opt_exception) {
  38483. if (goog.debug.LOGGING_ENABLED) {
  38484. this.log(goog.debug.Logger.Level.FINER, msg, opt_exception);
  38485. }
  38486. };
  38487. /**
  38488. * Logs a message at the Logger.Level.FINEST level.
  38489. * If the logger is currently enabled for the given message level then the
  38490. * given message is forwarded to all the registered output Handler objects.
  38491. * @param {goog.debug.Loggable} msg The message to log.
  38492. * @param {Error=} opt_exception An exception associated with the message.
  38493. */
  38494. goog.debug.Logger.prototype.finest = function(msg, opt_exception) {
  38495. if (goog.debug.LOGGING_ENABLED) {
  38496. this.log(goog.debug.Logger.Level.FINEST, msg, opt_exception);
  38497. }
  38498. };
  38499. /**
  38500. * Logs a LogRecord. If the logger is currently enabled for the
  38501. * given message level then the given message is forwarded to all the
  38502. * registered output Handler objects.
  38503. * @param {goog.debug.LogRecord} logRecord A log record to log.
  38504. */
  38505. goog.debug.Logger.prototype.logRecord = function(logRecord) {
  38506. if (goog.debug.LOGGING_ENABLED && this.isLoggable(logRecord.getLevel())) {
  38507. this.doLogRecord_(logRecord);
  38508. }
  38509. };
  38510. /**
  38511. * Logs a LogRecord.
  38512. * @param {goog.debug.LogRecord} logRecord A log record to log.
  38513. * @private
  38514. */
  38515. goog.debug.Logger.prototype.doLogRecord_ = function(logRecord) {
  38516. goog.debug.Logger.logToProfilers('log:' + logRecord.getMessage());
  38517. if (goog.debug.Logger.ENABLE_HIERARCHY) {
  38518. var target = this;
  38519. while (target) {
  38520. target.callPublish_(logRecord);
  38521. target = target.getParent();
  38522. }
  38523. } else {
  38524. for (var i = 0, handler; handler = goog.debug.Logger.rootHandlers_[i++]; ) {
  38525. handler(logRecord);
  38526. }
  38527. }
  38528. };
  38529. /**
  38530. * Calls the handlers for publish.
  38531. * @param {goog.debug.LogRecord} logRecord The log record to publish.
  38532. * @private
  38533. */
  38534. goog.debug.Logger.prototype.callPublish_ = function(logRecord) {
  38535. if (this.handlers_) {
  38536. for (var i = 0, handler; handler = this.handlers_[i]; i++) {
  38537. handler(logRecord);
  38538. }
  38539. }
  38540. };
  38541. /**
  38542. * Sets the parent of this logger. This is used for setting up the logger tree.
  38543. * @param {goog.debug.Logger} parent The parent logger.
  38544. * @private
  38545. */
  38546. goog.debug.Logger.prototype.setParent_ = function(parent) {
  38547. this.parent_ = parent;
  38548. };
  38549. /**
  38550. * Adds a child to this logger. This is used for setting up the logger tree.
  38551. * @param {string} name The leaf name of the child.
  38552. * @param {goog.debug.Logger} logger The child logger.
  38553. * @private
  38554. */
  38555. goog.debug.Logger.prototype.addChild_ = function(name, logger) {
  38556. this.getChildren()[name] = logger;
  38557. };
  38558. /**
  38559. * There is a single global LogManager object that is used to maintain a set of
  38560. * shared state about Loggers and log services. This is loosely based on the
  38561. * java class java.util.logging.LogManager.
  38562. * @const
  38563. */
  38564. goog.debug.LogManager = {};
  38565. /**
  38566. * Map of logger names to logger objects.
  38567. *
  38568. * @type {!Object<string, !goog.debug.Logger>}
  38569. * @private
  38570. */
  38571. goog.debug.LogManager.loggers_ = {};
  38572. /**
  38573. * The root logger which is the root of the logger tree.
  38574. * @type {goog.debug.Logger}
  38575. * @private
  38576. */
  38577. goog.debug.LogManager.rootLogger_ = null;
  38578. /**
  38579. * Initializes the LogManager if not already initialized.
  38580. */
  38581. goog.debug.LogManager.initialize = function() {
  38582. if (!goog.debug.LogManager.rootLogger_) {
  38583. goog.debug.LogManager.rootLogger_ = new goog.debug.Logger(
  38584. goog.debug.Logger.ROOT_LOGGER_NAME);
  38585. goog.debug.LogManager.loggers_[goog.debug.Logger.ROOT_LOGGER_NAME] =
  38586. goog.debug.LogManager.rootLogger_;
  38587. goog.debug.LogManager.rootLogger_.setLevel(goog.debug.Logger.Level.CONFIG);
  38588. }
  38589. };
  38590. /**
  38591. * Returns all the loggers.
  38592. * @return {!Object<string, !goog.debug.Logger>} Map of logger names to logger
  38593. * objects.
  38594. */
  38595. goog.debug.LogManager.getLoggers = function() {
  38596. return goog.debug.LogManager.loggers_;
  38597. };
  38598. /**
  38599. * Returns the root of the logger tree namespace, the logger with the empty
  38600. * string as its name.
  38601. *
  38602. * @return {!goog.debug.Logger} The root logger.
  38603. */
  38604. goog.debug.LogManager.getRoot = function() {
  38605. goog.debug.LogManager.initialize();
  38606. return /** @type {!goog.debug.Logger} */ (goog.debug.LogManager.rootLogger_);
  38607. };
  38608. /**
  38609. * Finds a named logger.
  38610. *
  38611. * @param {string} name A name for the logger. This should be a dot-separated
  38612. * name and should normally be based on the package name or class name of the
  38613. * subsystem, such as goog.net.BrowserChannel.
  38614. * @return {!goog.debug.Logger} The named logger.
  38615. */
  38616. goog.debug.LogManager.getLogger = function(name) {
  38617. goog.debug.LogManager.initialize();
  38618. var ret = goog.debug.LogManager.loggers_[name];
  38619. return ret || goog.debug.LogManager.createLogger_(name);
  38620. };
  38621. /**
  38622. * Creates a function that can be passed to goog.debug.catchErrors. The function
  38623. * will log all reported errors using the given logger.
  38624. * @param {goog.debug.Logger=} opt_logger The logger to log the errors to.
  38625. * Defaults to the root logger.
  38626. * @return {function(Object)} The created function.
  38627. */
  38628. goog.debug.LogManager.createFunctionForCatchErrors = function(opt_logger) {
  38629. return function(info) {
  38630. var logger = opt_logger || goog.debug.LogManager.getRoot();
  38631. logger.severe('Error: ' + info.message + ' (' + info.fileName +
  38632. ' @ Line: ' + info.line + ')');
  38633. };
  38634. };
  38635. /**
  38636. * Creates the named logger. Will also create the parents of the named logger
  38637. * if they don't yet exist.
  38638. * @param {string} name The name of the logger.
  38639. * @return {!goog.debug.Logger} The named logger.
  38640. * @private
  38641. */
  38642. goog.debug.LogManager.createLogger_ = function(name) {
  38643. // find parent logger
  38644. var logger = new goog.debug.Logger(name);
  38645. if (goog.debug.Logger.ENABLE_HIERARCHY) {
  38646. var lastDotIndex = name.lastIndexOf('.');
  38647. var parentName = name.substr(0, lastDotIndex);
  38648. var leafName = name.substr(lastDotIndex + 1);
  38649. var parentLogger = goog.debug.LogManager.getLogger(parentName);
  38650. // tell the parent about the child and the child about the parent
  38651. parentLogger.addChild_(leafName, logger);
  38652. logger.setParent_(parentLogger);
  38653. }
  38654. goog.debug.LogManager.loggers_[name] = logger;
  38655. return logger;
  38656. };
  38657. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  38658. //
  38659. // Licensed under the Apache License, Version 2.0 (the "License");
  38660. // you may not use this file except in compliance with the License.
  38661. // You may obtain a copy of the License at
  38662. //
  38663. // http://www.apache.org/licenses/LICENSE-2.0
  38664. //
  38665. // Unless required by applicable law or agreed to in writing, software
  38666. // distributed under the License is distributed on an "AS-IS" BASIS,
  38667. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38668. // See the License for the specific language governing permissions and
  38669. // limitations under the License.
  38670. /**
  38671. * @fileoverview Definition the goog.debug.RelativeTimeProvider class.
  38672. *
  38673. */
  38674. goog.provide('goog.debug.RelativeTimeProvider');
  38675. /**
  38676. * A simple object to keep track of a timestamp considered the start of
  38677. * something. The main use is for the logger system to maintain a start time
  38678. * that is occasionally reset. For example, in Gmail, we reset this relative
  38679. * time at the start of a user action so that timings are offset from the
  38680. * beginning of the action. This class also provides a singleton as the default
  38681. * behavior for most use cases is to share the same start time.
  38682. *
  38683. * @constructor
  38684. * @final
  38685. */
  38686. goog.debug.RelativeTimeProvider = function() {
  38687. /**
  38688. * The start time.
  38689. * @type {number}
  38690. * @private
  38691. */
  38692. this.relativeTimeStart_ = goog.now();
  38693. };
  38694. /**
  38695. * Default instance.
  38696. * @type {goog.debug.RelativeTimeProvider}
  38697. * @private
  38698. */
  38699. goog.debug.RelativeTimeProvider.defaultInstance_ =
  38700. new goog.debug.RelativeTimeProvider();
  38701. /**
  38702. * Sets the start time to the specified time.
  38703. * @param {number} timeStamp The start time.
  38704. */
  38705. goog.debug.RelativeTimeProvider.prototype.set = function(timeStamp) {
  38706. this.relativeTimeStart_ = timeStamp;
  38707. };
  38708. /**
  38709. * Resets the start time to now.
  38710. */
  38711. goog.debug.RelativeTimeProvider.prototype.reset = function() {
  38712. this.set(goog.now());
  38713. };
  38714. /**
  38715. * @return {number} The start time.
  38716. */
  38717. goog.debug.RelativeTimeProvider.prototype.get = function() {
  38718. return this.relativeTimeStart_;
  38719. };
  38720. /**
  38721. * @return {goog.debug.RelativeTimeProvider} The default instance.
  38722. */
  38723. goog.debug.RelativeTimeProvider.getDefaultInstance = function() {
  38724. return goog.debug.RelativeTimeProvider.defaultInstance_;
  38725. };
  38726. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  38727. //
  38728. // Licensed under the Apache License, Version 2.0 (the "License");
  38729. // you may not use this file except in compliance with the License.
  38730. // You may obtain a copy of the License at
  38731. //
  38732. // http://www.apache.org/licenses/LICENSE-2.0
  38733. //
  38734. // Unless required by applicable law or agreed to in writing, software
  38735. // distributed under the License is distributed on an "AS-IS" BASIS,
  38736. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38737. // See the License for the specific language governing permissions and
  38738. // limitations under the License.
  38739. /**
  38740. * @fileoverview Definition of various formatters for logging. Please minimize
  38741. * dependencies this file has on other closure classes as any dependency it
  38742. * takes won't be able to use the logging infrastructure.
  38743. *
  38744. */
  38745. goog.provide('goog.debug.Formatter');
  38746. goog.provide('goog.debug.HtmlFormatter');
  38747. goog.provide('goog.debug.TextFormatter');
  38748. goog.require('goog.debug');
  38749. goog.require('goog.debug.Logger');
  38750. goog.require('goog.debug.RelativeTimeProvider');
  38751. goog.require('goog.html.SafeHtml');
  38752. /**
  38753. * Base class for Formatters. A Formatter is used to format a LogRecord into
  38754. * something that can be displayed to the user.
  38755. *
  38756. * @param {string=} opt_prefix The prefix to place before text records.
  38757. * @constructor
  38758. */
  38759. goog.debug.Formatter = function(opt_prefix) {
  38760. this.prefix_ = opt_prefix || '';
  38761. /**
  38762. * A provider that returns the relative start time.
  38763. * @type {goog.debug.RelativeTimeProvider}
  38764. * @private
  38765. */
  38766. this.startTimeProvider_ =
  38767. goog.debug.RelativeTimeProvider.getDefaultInstance();
  38768. };
  38769. /**
  38770. * Whether to append newlines to the end of formatted log records.
  38771. * @type {boolean}
  38772. */
  38773. goog.debug.Formatter.prototype.appendNewline = true;
  38774. /**
  38775. * Whether to show absolute time in the DebugWindow.
  38776. * @type {boolean}
  38777. */
  38778. goog.debug.Formatter.prototype.showAbsoluteTime = true;
  38779. /**
  38780. * Whether to show relative time in the DebugWindow.
  38781. * @type {boolean}
  38782. */
  38783. goog.debug.Formatter.prototype.showRelativeTime = true;
  38784. /**
  38785. * Whether to show the logger name in the DebugWindow.
  38786. * @type {boolean}
  38787. */
  38788. goog.debug.Formatter.prototype.showLoggerName = true;
  38789. /**
  38790. * Whether to show the logger exception text.
  38791. * @type {boolean}
  38792. */
  38793. goog.debug.Formatter.prototype.showExceptionText = false;
  38794. /**
  38795. * Whether to show the severity level.
  38796. * @type {boolean}
  38797. */
  38798. goog.debug.Formatter.prototype.showSeverityLevel = false;
  38799. /**
  38800. * Formats a record.
  38801. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  38802. * @return {string} The formatted string.
  38803. */
  38804. goog.debug.Formatter.prototype.formatRecord = goog.abstractMethod;
  38805. /**
  38806. * Formats a record as SafeHtml.
  38807. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  38808. * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.
  38809. */
  38810. goog.debug.Formatter.prototype.formatRecordAsHtml = goog.abstractMethod;
  38811. /**
  38812. * Sets the start time provider. By default, this is the default instance
  38813. * but can be changed.
  38814. * @param {goog.debug.RelativeTimeProvider} provider The provider to use.
  38815. */
  38816. goog.debug.Formatter.prototype.setStartTimeProvider = function(provider) {
  38817. this.startTimeProvider_ = provider;
  38818. };
  38819. /**
  38820. * Returns the start time provider. By default, this is the default instance
  38821. * but can be changed.
  38822. * @return {goog.debug.RelativeTimeProvider} The start time provider.
  38823. */
  38824. goog.debug.Formatter.prototype.getStartTimeProvider = function() {
  38825. return this.startTimeProvider_;
  38826. };
  38827. /**
  38828. * Resets the start relative time.
  38829. */
  38830. goog.debug.Formatter.prototype.resetRelativeTimeStart = function() {
  38831. this.startTimeProvider_.reset();
  38832. };
  38833. /**
  38834. * Returns a string for the time/date of the LogRecord.
  38835. * @param {goog.debug.LogRecord} logRecord The record to get a time stamp for.
  38836. * @return {string} A string representation of the time/date of the LogRecord.
  38837. * @private
  38838. */
  38839. goog.debug.Formatter.getDateTimeStamp_ = function(logRecord) {
  38840. var time = new Date(logRecord.getMillis());
  38841. return goog.debug.Formatter.getTwoDigitString_((time.getFullYear() - 2000)) +
  38842. goog.debug.Formatter.getTwoDigitString_((time.getMonth() + 1)) +
  38843. goog.debug.Formatter.getTwoDigitString_(time.getDate()) + ' ' +
  38844. goog.debug.Formatter.getTwoDigitString_(time.getHours()) + ':' +
  38845. goog.debug.Formatter.getTwoDigitString_(time.getMinutes()) + ':' +
  38846. goog.debug.Formatter.getTwoDigitString_(time.getSeconds()) + '.' +
  38847. goog.debug.Formatter.getTwoDigitString_(
  38848. Math.floor(time.getMilliseconds() / 10));
  38849. };
  38850. /**
  38851. * Returns the number as a two-digit string, meaning it prepends a 0 if the
  38852. * number if less than 10.
  38853. * @param {number} n The number to format.
  38854. * @return {string} A two-digit string representation of {@code n}.
  38855. * @private
  38856. */
  38857. goog.debug.Formatter.getTwoDigitString_ = function(n) {
  38858. if (n < 10) {
  38859. return '0' + n;
  38860. }
  38861. return String(n);
  38862. };
  38863. /**
  38864. * Returns a string for the number of seconds relative to the start time.
  38865. * Prepads with spaces so that anything less than 1000 seconds takes up the
  38866. * same number of characters for better formatting.
  38867. * @param {goog.debug.LogRecord} logRecord The log to compare time to.
  38868. * @param {number} relativeTimeStart The start time to compare to.
  38869. * @return {string} The number of seconds of the LogRecord relative to the
  38870. * start time.
  38871. * @private
  38872. */
  38873. goog.debug.Formatter.getRelativeTime_ = function(logRecord,
  38874. relativeTimeStart) {
  38875. var ms = logRecord.getMillis() - relativeTimeStart;
  38876. var sec = ms / 1000;
  38877. var str = sec.toFixed(3);
  38878. var spacesToPrepend = 0;
  38879. if (sec < 1) {
  38880. spacesToPrepend = 2;
  38881. } else {
  38882. while (sec < 100) {
  38883. spacesToPrepend++;
  38884. sec *= 10;
  38885. }
  38886. }
  38887. while (spacesToPrepend-- > 0) {
  38888. str = ' ' + str;
  38889. }
  38890. return str;
  38891. };
  38892. /**
  38893. * Formatter that returns formatted html. See formatRecord for the classes
  38894. * it uses for various types of formatted output.
  38895. *
  38896. * @param {string=} opt_prefix The prefix to place before text records.
  38897. * @constructor
  38898. * @extends {goog.debug.Formatter}
  38899. */
  38900. goog.debug.HtmlFormatter = function(opt_prefix) {
  38901. goog.debug.Formatter.call(this, opt_prefix);
  38902. };
  38903. goog.inherits(goog.debug.HtmlFormatter, goog.debug.Formatter);
  38904. /**
  38905. * Whether to show the logger exception text
  38906. * @type {boolean}
  38907. * @override
  38908. */
  38909. goog.debug.HtmlFormatter.prototype.showExceptionText = true;
  38910. /**
  38911. * Formats a record
  38912. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  38913. * @return {string} The formatted string as html.
  38914. * @override
  38915. */
  38916. goog.debug.HtmlFormatter.prototype.formatRecord = function(logRecord) {
  38917. if (!logRecord) {
  38918. return '';
  38919. }
  38920. // OK not to use goog.html.SafeHtml.unwrap() here.
  38921. return this.formatRecordAsHtml(logRecord).getTypedStringValue();
  38922. };
  38923. /**
  38924. * Formats a record.
  38925. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  38926. * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.
  38927. * @override
  38928. */
  38929. goog.debug.HtmlFormatter.prototype.formatRecordAsHtml = function(logRecord) {
  38930. if (!logRecord) {
  38931. return goog.html.SafeHtml.EMPTY;
  38932. }
  38933. var className;
  38934. switch (logRecord.getLevel().value) {
  38935. case goog.debug.Logger.Level.SHOUT.value:
  38936. className = 'dbg-sh';
  38937. break;
  38938. case goog.debug.Logger.Level.SEVERE.value:
  38939. className = 'dbg-sev';
  38940. break;
  38941. case goog.debug.Logger.Level.WARNING.value:
  38942. className = 'dbg-w';
  38943. break;
  38944. case goog.debug.Logger.Level.INFO.value:
  38945. className = 'dbg-i';
  38946. break;
  38947. case goog.debug.Logger.Level.FINE.value:
  38948. default:
  38949. className = 'dbg-f';
  38950. break;
  38951. }
  38952. // HTML for user defined prefix, time, logger name, and severity.
  38953. var sb = [];
  38954. sb.push(this.prefix_, ' ');
  38955. if (this.showAbsoluteTime) {
  38956. sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');
  38957. }
  38958. if (this.showRelativeTime) {
  38959. sb.push('[',
  38960. goog.debug.Formatter.getRelativeTime_(
  38961. logRecord, this.startTimeProvider_.get()),
  38962. 's] ');
  38963. }
  38964. if (this.showLoggerName) {
  38965. sb.push('[', logRecord.getLoggerName(), '] ');
  38966. }
  38967. if (this.showSeverityLevel) {
  38968. sb.push('[', logRecord.getLevel().name, '] ');
  38969. }
  38970. var fullPrefixHtml =
  38971. goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(sb.join(''));
  38972. // HTML for exception text and log record.
  38973. var exceptionHtml = goog.html.SafeHtml.EMPTY;
  38974. if (this.showExceptionText && logRecord.getException()) {
  38975. exceptionHtml = goog.html.SafeHtml.concat(
  38976. goog.html.SafeHtml.create('br'),
  38977. goog.debug.exposeExceptionAsHtml(logRecord.getException()));
  38978. }
  38979. var logRecordHtml = goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
  38980. logRecord.getMessage());
  38981. var recordAndExceptionHtml = goog.html.SafeHtml.create(
  38982. 'span',
  38983. {'class': className},
  38984. goog.html.SafeHtml.concat(logRecordHtml, exceptionHtml));
  38985. // Combine both pieces of HTML and, if needed, append a final newline.
  38986. var html;
  38987. if (this.appendNewline) {
  38988. html = goog.html.SafeHtml.concat(fullPrefixHtml, recordAndExceptionHtml,
  38989. goog.html.SafeHtml.create('br'));
  38990. } else {
  38991. html = goog.html.SafeHtml.concat(fullPrefixHtml, recordAndExceptionHtml);
  38992. }
  38993. return html;
  38994. };
  38995. /**
  38996. * Formatter that returns formatted plain text
  38997. *
  38998. * @param {string=} opt_prefix The prefix to place before text records.
  38999. * @constructor
  39000. * @extends {goog.debug.Formatter}
  39001. * @final
  39002. */
  39003. goog.debug.TextFormatter = function(opt_prefix) {
  39004. goog.debug.Formatter.call(this, opt_prefix);
  39005. };
  39006. goog.inherits(goog.debug.TextFormatter, goog.debug.Formatter);
  39007. /**
  39008. * Formats a record as text
  39009. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  39010. * @return {string} The formatted string.
  39011. * @override
  39012. */
  39013. goog.debug.TextFormatter.prototype.formatRecord = function(logRecord) {
  39014. var sb = [];
  39015. sb.push(this.prefix_, ' ');
  39016. if (this.showAbsoluteTime) {
  39017. sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');
  39018. }
  39019. if (this.showRelativeTime) {
  39020. sb.push('[', goog.debug.Formatter.getRelativeTime_(logRecord,
  39021. this.startTimeProvider_.get()), 's] ');
  39022. }
  39023. if (this.showLoggerName) {
  39024. sb.push('[', logRecord.getLoggerName(), '] ');
  39025. }
  39026. if (this.showSeverityLevel) {
  39027. sb.push('[', logRecord.getLevel().name, '] ');
  39028. }
  39029. sb.push(logRecord.getMessage());
  39030. if (this.showExceptionText) {
  39031. var exception = logRecord.getException();
  39032. if (exception) {
  39033. var exceptionText = exception instanceof Error ?
  39034. exception.message :
  39035. exception.toString();
  39036. sb.push('\n', exceptionText);
  39037. }
  39038. }
  39039. if (this.appendNewline) {
  39040. sb.push('\n');
  39041. }
  39042. return sb.join('');
  39043. };
  39044. /**
  39045. * Formats a record as text
  39046. * @param {goog.debug.LogRecord} logRecord the logRecord to format.
  39047. * @return {!goog.html.SafeHtml} The formatted string as SafeHtml. This is
  39048. * just an HTML-escaped version of the text obtained from formatRecord().
  39049. * @override
  39050. */
  39051. goog.debug.TextFormatter.prototype.formatRecordAsHtml = function(logRecord) {
  39052. return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(
  39053. goog.debug.TextFormatter.prototype.formatRecord(logRecord));
  39054. };
  39055. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  39056. //
  39057. // Licensed under the Apache License, Version 2.0 (the "License");
  39058. // you may not use this file except in compliance with the License.
  39059. // You may obtain a copy of the License at
  39060. //
  39061. // http://www.apache.org/licenses/LICENSE-2.0
  39062. //
  39063. // Unless required by applicable law or agreed to in writing, software
  39064. // distributed under the License is distributed on an "AS-IS" BASIS,
  39065. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39066. // See the License for the specific language governing permissions and
  39067. // limitations under the License.
  39068. /**
  39069. * @fileoverview Simple logger that logs to the window console if available.
  39070. *
  39071. * Has an autoInstall option which can be put into initialization code, which
  39072. * will start logging if "Debug=true" is in document.location.href
  39073. *
  39074. */
  39075. goog.provide('goog.debug.Console');
  39076. goog.require('goog.debug.LogManager');
  39077. goog.require('goog.debug.Logger');
  39078. goog.require('goog.debug.TextFormatter');
  39079. /**
  39080. * Create and install a log handler that logs to window.console if available
  39081. * @constructor
  39082. */
  39083. goog.debug.Console = function() {
  39084. this.publishHandler_ = goog.bind(this.addLogRecord, this);
  39085. /**
  39086. * Formatter for formatted output.
  39087. * @type {!goog.debug.TextFormatter}
  39088. * @private
  39089. */
  39090. this.formatter_ = new goog.debug.TextFormatter();
  39091. this.formatter_.showAbsoluteTime = false;
  39092. this.formatter_.showExceptionText = false;
  39093. // The console logging methods automatically append a newline.
  39094. this.formatter_.appendNewline = false;
  39095. this.isCapturing_ = false;
  39096. this.logBuffer_ = '';
  39097. /**
  39098. * Loggers that we shouldn't output.
  39099. * @type {!Object<boolean>}
  39100. * @private
  39101. */
  39102. this.filteredLoggers_ = {};
  39103. };
  39104. /**
  39105. * Returns the text formatter used by this console
  39106. * @return {!goog.debug.TextFormatter} The text formatter.
  39107. */
  39108. goog.debug.Console.prototype.getFormatter = function() {
  39109. return this.formatter_;
  39110. };
  39111. /**
  39112. * Sets whether we are currently capturing logger output.
  39113. * @param {boolean} capturing Whether to capture logger output.
  39114. */
  39115. goog.debug.Console.prototype.setCapturing = function(capturing) {
  39116. if (capturing == this.isCapturing_) {
  39117. return;
  39118. }
  39119. // attach or detach handler from the root logger
  39120. var rootLogger = goog.debug.LogManager.getRoot();
  39121. if (capturing) {
  39122. rootLogger.addHandler(this.publishHandler_);
  39123. } else {
  39124. rootLogger.removeHandler(this.publishHandler_);
  39125. this.logBuffer = '';
  39126. }
  39127. this.isCapturing_ = capturing;
  39128. };
  39129. /**
  39130. * Adds a log record.
  39131. * @param {goog.debug.LogRecord} logRecord The log entry.
  39132. */
  39133. goog.debug.Console.prototype.addLogRecord = function(logRecord) {
  39134. // Check to see if the log record is filtered or not.
  39135. if (this.filteredLoggers_[logRecord.getLoggerName()]) {
  39136. return;
  39137. }
  39138. var record = this.formatter_.formatRecord(logRecord);
  39139. var console = goog.debug.Console.console_;
  39140. if (console) {
  39141. switch (logRecord.getLevel()) {
  39142. case goog.debug.Logger.Level.SHOUT:
  39143. goog.debug.Console.logToConsole_(console, 'info', record);
  39144. break;
  39145. case goog.debug.Logger.Level.SEVERE:
  39146. goog.debug.Console.logToConsole_(console, 'error', record);
  39147. break;
  39148. case goog.debug.Logger.Level.WARNING:
  39149. goog.debug.Console.logToConsole_(console, 'warn', record);
  39150. break;
  39151. default:
  39152. goog.debug.Console.logToConsole_(console, 'debug', record);
  39153. break;
  39154. }
  39155. } else {
  39156. this.logBuffer_ += record;
  39157. }
  39158. };
  39159. /**
  39160. * Adds a logger name to be filtered.
  39161. * @param {string} loggerName the logger name to add.
  39162. */
  39163. goog.debug.Console.prototype.addFilter = function(loggerName) {
  39164. this.filteredLoggers_[loggerName] = true;
  39165. };
  39166. /**
  39167. * Removes a logger name to be filtered.
  39168. * @param {string} loggerName the logger name to remove.
  39169. */
  39170. goog.debug.Console.prototype.removeFilter = function(loggerName) {
  39171. delete this.filteredLoggers_[loggerName];
  39172. };
  39173. /**
  39174. * Global console logger instance
  39175. * @type {goog.debug.Console}
  39176. */
  39177. goog.debug.Console.instance = null;
  39178. /**
  39179. * The console to which to log. This is a property so it can be mocked out in
  39180. * this unit test for goog.debug.Console. Using goog.global, as console might be
  39181. * used in window-less contexts.
  39182. * @type {Object}
  39183. * @private
  39184. */
  39185. goog.debug.Console.console_ = goog.global['console'];
  39186. /**
  39187. * Sets the console to which to log.
  39188. * @param {!Object} console The console to which to log.
  39189. */
  39190. goog.debug.Console.setConsole = function(console) {
  39191. goog.debug.Console.console_ = console;
  39192. };
  39193. /**
  39194. * Install the console and start capturing if "Debug=true" is in the page URL
  39195. */
  39196. goog.debug.Console.autoInstall = function() {
  39197. if (!goog.debug.Console.instance) {
  39198. goog.debug.Console.instance = new goog.debug.Console();
  39199. }
  39200. if (goog.global.location &&
  39201. goog.global.location.href.indexOf('Debug=true') != -1) {
  39202. goog.debug.Console.instance.setCapturing(true);
  39203. }
  39204. };
  39205. /**
  39206. * Show an alert with all of the captured debug information.
  39207. * Information is only captured if console is not available
  39208. */
  39209. goog.debug.Console.show = function() {
  39210. alert(goog.debug.Console.instance.logBuffer_);
  39211. };
  39212. /**
  39213. * Logs the record to the console using the given function. If the function is
  39214. * not available on the console object, the log function is used instead.
  39215. * @param {!Object} console The console object.
  39216. * @param {string} fnName The name of the function to use.
  39217. * @param {string} record The record to log.
  39218. * @private
  39219. */
  39220. goog.debug.Console.logToConsole_ = function(console, fnName, record) {
  39221. if (console[fnName]) {
  39222. console[fnName](record);
  39223. } else {
  39224. console.log(record);
  39225. }
  39226. };
  39227. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  39228. //
  39229. // Licensed under the Apache License, Version 2.0 (the "License");
  39230. // you may not use this file except in compliance with the License.
  39231. // You may obtain a copy of the License at
  39232. //
  39233. // http://www.apache.org/licenses/LICENSE-2.0
  39234. //
  39235. // Unless required by applicable law or agreed to in writing, software
  39236. // distributed under the License is distributed on an "AS-IS" BASIS,
  39237. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39238. // See the License for the specific language governing permissions and
  39239. // limitations under the License.
  39240. /**
  39241. * @fileoverview Utility class that monitors viewport size changes.
  39242. *
  39243. * @author attila@google.com (Attila Bodis)
  39244. * @see ../demos/viewportsizemonitor.html
  39245. */
  39246. goog.provide('goog.dom.ViewportSizeMonitor');
  39247. goog.require('goog.dom');
  39248. goog.require('goog.events');
  39249. goog.require('goog.events.EventTarget');
  39250. goog.require('goog.events.EventType');
  39251. goog.require('goog.math.Size');
  39252. /**
  39253. * This class can be used to monitor changes in the viewport size. Instances
  39254. * dispatch a {@link goog.events.EventType.RESIZE} event when the viewport size
  39255. * changes. Handlers can call {@link goog.dom.ViewportSizeMonitor#getSize} to
  39256. * get the new viewport size.
  39257. *
  39258. * Use this class if you want to execute resize/reflow logic each time the
  39259. * user resizes the browser window. This class is guaranteed to only dispatch
  39260. * {@code RESIZE} events when the pixel dimensions of the viewport change.
  39261. * (Internet Explorer fires resize events if any element on the page is resized,
  39262. * even if the viewport dimensions are unchanged, which can lead to infinite
  39263. * resize loops.)
  39264. *
  39265. * Example usage:
  39266. * <pre>
  39267. * var vsm = new goog.dom.ViewportSizeMonitor();
  39268. * goog.events.listen(vsm, goog.events.EventType.RESIZE, function(e) {
  39269. * alert('Viewport size changed to ' + vsm.getSize());
  39270. * });
  39271. * </pre>
  39272. *
  39273. * Manually verified on IE6, IE7, FF2, Opera 11, Safari 4 and Chrome.
  39274. *
  39275. * @param {Window=} opt_window The window to monitor; defaults to the window in
  39276. * which this code is executing.
  39277. * @constructor
  39278. * @extends {goog.events.EventTarget}
  39279. */
  39280. goog.dom.ViewportSizeMonitor = function(opt_window) {
  39281. goog.dom.ViewportSizeMonitor.base(this, 'constructor');
  39282. /**
  39283. * The window to monitor. Defaults to the window in which the code is running.
  39284. * @private {Window}
  39285. */
  39286. this.window_ = opt_window || window;
  39287. /**
  39288. * Event listener key for window the window resize handler, as returned by
  39289. * {@link goog.events.listen}.
  39290. * @private {goog.events.Key}
  39291. */
  39292. this.listenerKey_ = goog.events.listen(this.window_,
  39293. goog.events.EventType.RESIZE, this.handleResize_, false, this);
  39294. /**
  39295. * The most recently recorded size of the viewport, in pixels.
  39296. * @private {goog.math.Size}
  39297. */
  39298. this.size_ = goog.dom.getViewportSize(this.window_);
  39299. };
  39300. goog.inherits(goog.dom.ViewportSizeMonitor, goog.events.EventTarget);
  39301. /**
  39302. * Returns a viewport size monitor for the given window. A new one is created
  39303. * if it doesn't exist already. This prevents the unnecessary creation of
  39304. * multiple spooling monitors for a window.
  39305. * @param {Window=} opt_window The window to monitor; defaults to the window in
  39306. * which this code is executing.
  39307. * @return {!goog.dom.ViewportSizeMonitor} Monitor for the given window.
  39308. */
  39309. goog.dom.ViewportSizeMonitor.getInstanceForWindow = function(opt_window) {
  39310. var currentWindow = opt_window || window;
  39311. var uid = goog.getUid(currentWindow);
  39312. return goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid] =
  39313. goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid] ||
  39314. new goog.dom.ViewportSizeMonitor(currentWindow);
  39315. };
  39316. /**
  39317. * Removes and disposes a viewport size monitor for the given window if one
  39318. * exists.
  39319. * @param {Window=} opt_window The window whose monitor should be removed;
  39320. * defaults to the window in which this code is executing.
  39321. */
  39322. goog.dom.ViewportSizeMonitor.removeInstanceForWindow = function(opt_window) {
  39323. var uid = goog.getUid(opt_window || window);
  39324. goog.dispose(goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid]);
  39325. delete goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid];
  39326. };
  39327. /**
  39328. * Map of window hash code to viewport size monitor for that window, if
  39329. * created.
  39330. * @type {Object<number,goog.dom.ViewportSizeMonitor>}
  39331. * @private
  39332. */
  39333. goog.dom.ViewportSizeMonitor.windowInstanceMap_ = {};
  39334. /**
  39335. * Returns the most recently recorded size of the viewport, in pixels. May
  39336. * return null if no window resize event has been handled yet.
  39337. * @return {goog.math.Size} The viewport dimensions, in pixels.
  39338. */
  39339. goog.dom.ViewportSizeMonitor.prototype.getSize = function() {
  39340. // Return a clone instead of the original to preserve encapsulation.
  39341. return this.size_ ? this.size_.clone() : null;
  39342. };
  39343. /** @override */
  39344. goog.dom.ViewportSizeMonitor.prototype.disposeInternal = function() {
  39345. goog.dom.ViewportSizeMonitor.superClass_.disposeInternal.call(this);
  39346. if (this.listenerKey_) {
  39347. goog.events.unlistenByKey(this.listenerKey_);
  39348. this.listenerKey_ = null;
  39349. }
  39350. this.window_ = null;
  39351. this.size_ = null;
  39352. };
  39353. /**
  39354. * Handles window resize events by measuring the dimensions of the
  39355. * viewport and dispatching a {@link goog.events.EventType.RESIZE} event if the
  39356. * current dimensions are different from the previous ones.
  39357. * @param {goog.events.Event} event The window resize event to handle.
  39358. * @private
  39359. */
  39360. goog.dom.ViewportSizeMonitor.prototype.handleResize_ = function(event) {
  39361. var size = goog.dom.getViewportSize(this.window_);
  39362. if (!goog.math.Size.equals(size, this.size_)) {
  39363. this.size_ = size;
  39364. this.dispatchEvent(goog.events.EventType.RESIZE);
  39365. }
  39366. };
  39367. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  39368. //
  39369. // Licensed under the Apache License, Version 2.0 (the "License");
  39370. // you may not use this file except in compliance with the License.
  39371. // You may obtain a copy of the License at
  39372. //
  39373. // http://www.apache.org/licenses/LICENSE-2.0
  39374. //
  39375. // Unless required by applicable law or agreed to in writing, software
  39376. // distributed under the License is distributed on an "AS-IS" BASIS,
  39377. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39378. // See the License for the specific language governing permissions and
  39379. // limitations under the License.
  39380. /**
  39381. * @fileoverview Constant declarations for common key codes.
  39382. *
  39383. * @author eae@google.com (Emil A Eklund)
  39384. * @see ../demos/keyhandler.html
  39385. */
  39386. goog.provide('goog.events.KeyCodes');
  39387. goog.require('goog.userAgent');
  39388. goog.forwardDeclare('goog.events.BrowserEvent');
  39389. /**
  39390. * Key codes for common characters.
  39391. *
  39392. * This list is not localized and therefore some of the key codes are not
  39393. * correct for non US keyboard layouts. See comments below.
  39394. *
  39395. * @enum {number}
  39396. */
  39397. goog.events.KeyCodes = {
  39398. WIN_KEY_FF_LINUX: 0,
  39399. MAC_ENTER: 3,
  39400. BACKSPACE: 8,
  39401. TAB: 9,
  39402. NUM_CENTER: 12, // NUMLOCK on FF/Safari Mac
  39403. ENTER: 13,
  39404. SHIFT: 16,
  39405. CTRL: 17,
  39406. ALT: 18,
  39407. PAUSE: 19,
  39408. CAPS_LOCK: 20,
  39409. ESC: 27,
  39410. SPACE: 32,
  39411. PAGE_UP: 33, // also NUM_NORTH_EAST
  39412. PAGE_DOWN: 34, // also NUM_SOUTH_EAST
  39413. END: 35, // also NUM_SOUTH_WEST
  39414. HOME: 36, // also NUM_NORTH_WEST
  39415. LEFT: 37, // also NUM_WEST
  39416. UP: 38, // also NUM_NORTH
  39417. RIGHT: 39, // also NUM_EAST
  39418. DOWN: 40, // also NUM_SOUTH
  39419. PLUS_SIGN: 43, // NOT numpad plus
  39420. PRINT_SCREEN: 44,
  39421. INSERT: 45, // also NUM_INSERT
  39422. DELETE: 46, // also NUM_DELETE
  39423. ZERO: 48,
  39424. ONE: 49,
  39425. TWO: 50,
  39426. THREE: 51,
  39427. FOUR: 52,
  39428. FIVE: 53,
  39429. SIX: 54,
  39430. SEVEN: 55,
  39431. EIGHT: 56,
  39432. NINE: 57,
  39433. FF_SEMICOLON: 59, // Firefox (Gecko) fires this for semicolon instead of 186
  39434. FF_EQUALS: 61, // Firefox (Gecko) fires this for equals instead of 187
  39435. FF_DASH: 173, // Firefox (Gecko) fires this for dash instead of 189
  39436. QUESTION_MARK: 63, // needs localization
  39437. AT_SIGN: 64,
  39438. A: 65,
  39439. B: 66,
  39440. C: 67,
  39441. D: 68,
  39442. E: 69,
  39443. F: 70,
  39444. G: 71,
  39445. H: 72,
  39446. I: 73,
  39447. J: 74,
  39448. K: 75,
  39449. L: 76,
  39450. M: 77,
  39451. N: 78,
  39452. O: 79,
  39453. P: 80,
  39454. Q: 81,
  39455. R: 82,
  39456. S: 83,
  39457. T: 84,
  39458. U: 85,
  39459. V: 86,
  39460. W: 87,
  39461. X: 88,
  39462. Y: 89,
  39463. Z: 90,
  39464. META: 91, // WIN_KEY_LEFT
  39465. WIN_KEY_RIGHT: 92,
  39466. CONTEXT_MENU: 93,
  39467. NUM_ZERO: 96,
  39468. NUM_ONE: 97,
  39469. NUM_TWO: 98,
  39470. NUM_THREE: 99,
  39471. NUM_FOUR: 100,
  39472. NUM_FIVE: 101,
  39473. NUM_SIX: 102,
  39474. NUM_SEVEN: 103,
  39475. NUM_EIGHT: 104,
  39476. NUM_NINE: 105,
  39477. NUM_MULTIPLY: 106,
  39478. NUM_PLUS: 107,
  39479. NUM_MINUS: 109,
  39480. NUM_PERIOD: 110,
  39481. NUM_DIVISION: 111,
  39482. F1: 112,
  39483. F2: 113,
  39484. F3: 114,
  39485. F4: 115,
  39486. F5: 116,
  39487. F6: 117,
  39488. F7: 118,
  39489. F8: 119,
  39490. F9: 120,
  39491. F10: 121,
  39492. F11: 122,
  39493. F12: 123,
  39494. NUMLOCK: 144,
  39495. SCROLL_LOCK: 145,
  39496. // OS-specific media keys like volume controls and browser controls.
  39497. FIRST_MEDIA_KEY: 166,
  39498. LAST_MEDIA_KEY: 183,
  39499. SEMICOLON: 186, // needs localization
  39500. DASH: 189, // needs localization
  39501. EQUALS: 187, // needs localization
  39502. COMMA: 188, // needs localization
  39503. PERIOD: 190, // needs localization
  39504. SLASH: 191, // needs localization
  39505. APOSTROPHE: 192, // needs localization
  39506. TILDE: 192, // needs localization
  39507. SINGLE_QUOTE: 222, // needs localization
  39508. OPEN_SQUARE_BRACKET: 219, // needs localization
  39509. BACKSLASH: 220, // needs localization
  39510. CLOSE_SQUARE_BRACKET: 221, // needs localization
  39511. WIN_KEY: 224,
  39512. MAC_FF_META: 224, // Firefox (Gecko) fires this for the meta key instead of 91
  39513. MAC_WK_CMD_LEFT: 91, // WebKit Left Command key fired, same as META
  39514. MAC_WK_CMD_RIGHT: 93, // WebKit Right Command key fired, different from META
  39515. WIN_IME: 229,
  39516. // "Reserved for future use". Some programs (e.g. the SlingPlayer 2.4 ActiveX
  39517. // control) fire this as a hacky way to disable screensavers.
  39518. VK_NONAME: 252,
  39519. // We've seen users whose machines fire this keycode at regular one
  39520. // second intervals. The common thread among these users is that
  39521. // they're all using Dell Inspiron laptops, so we suspect that this
  39522. // indicates a hardware/bios problem.
  39523. // http://en.community.dell.com/support-forums/laptop/f/3518/p/19285957/19523128.aspx
  39524. PHANTOM: 255
  39525. };
  39526. /**
  39527. * Returns true if the event contains a text modifying key.
  39528. * @param {goog.events.BrowserEvent} e A key event.
  39529. * @return {boolean} Whether it's a text modifying key.
  39530. */
  39531. goog.events.KeyCodes.isTextModifyingKeyEvent = function(e) {
  39532. if (e.altKey && !e.ctrlKey ||
  39533. e.metaKey ||
  39534. // Function keys don't generate text
  39535. e.keyCode >= goog.events.KeyCodes.F1 &&
  39536. e.keyCode <= goog.events.KeyCodes.F12) {
  39537. return false;
  39538. }
  39539. // The following keys are quite harmless, even in combination with
  39540. // CTRL, ALT or SHIFT.
  39541. switch (e.keyCode) {
  39542. case goog.events.KeyCodes.ALT:
  39543. case goog.events.KeyCodes.CAPS_LOCK:
  39544. case goog.events.KeyCodes.CONTEXT_MENU:
  39545. case goog.events.KeyCodes.CTRL:
  39546. case goog.events.KeyCodes.DOWN:
  39547. case goog.events.KeyCodes.END:
  39548. case goog.events.KeyCodes.ESC:
  39549. case goog.events.KeyCodes.HOME:
  39550. case goog.events.KeyCodes.INSERT:
  39551. case goog.events.KeyCodes.LEFT:
  39552. case goog.events.KeyCodes.MAC_FF_META:
  39553. case goog.events.KeyCodes.META:
  39554. case goog.events.KeyCodes.NUMLOCK:
  39555. case goog.events.KeyCodes.NUM_CENTER:
  39556. case goog.events.KeyCodes.PAGE_DOWN:
  39557. case goog.events.KeyCodes.PAGE_UP:
  39558. case goog.events.KeyCodes.PAUSE:
  39559. case goog.events.KeyCodes.PHANTOM:
  39560. case goog.events.KeyCodes.PRINT_SCREEN:
  39561. case goog.events.KeyCodes.RIGHT:
  39562. case goog.events.KeyCodes.SCROLL_LOCK:
  39563. case goog.events.KeyCodes.SHIFT:
  39564. case goog.events.KeyCodes.UP:
  39565. case goog.events.KeyCodes.VK_NONAME:
  39566. case goog.events.KeyCodes.WIN_KEY:
  39567. case goog.events.KeyCodes.WIN_KEY_RIGHT:
  39568. return false;
  39569. case goog.events.KeyCodes.WIN_KEY_FF_LINUX:
  39570. return !goog.userAgent.GECKO;
  39571. default:
  39572. return e.keyCode < goog.events.KeyCodes.FIRST_MEDIA_KEY ||
  39573. e.keyCode > goog.events.KeyCodes.LAST_MEDIA_KEY;
  39574. }
  39575. };
  39576. /**
  39577. * Returns true if the key fires a keypress event in the current browser.
  39578. *
  39579. * Accoridng to MSDN [1] IE only fires keypress events for the following keys:
  39580. * - Letters: A - Z (uppercase and lowercase)
  39581. * - Numerals: 0 - 9
  39582. * - Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
  39583. * - System: ESC, SPACEBAR, ENTER
  39584. *
  39585. * That's not entirely correct though, for instance there's no distinction
  39586. * between upper and lower case letters.
  39587. *
  39588. * [1] http://msdn2.microsoft.com/en-us/library/ms536939(VS.85).aspx)
  39589. *
  39590. * Safari is similar to IE, but does not fire keypress for ESC.
  39591. *
  39592. * Additionally, IE6 does not fire keydown or keypress events for letters when
  39593. * the control or alt keys are held down and the shift key is not. IE7 does
  39594. * fire keydown in these cases, though, but not keypress.
  39595. *
  39596. * @param {number} keyCode A key code.
  39597. * @param {number=} opt_heldKeyCode Key code of a currently-held key.
  39598. * @param {boolean=} opt_shiftKey Whether the shift key is held down.
  39599. * @param {boolean=} opt_ctrlKey Whether the control key is held down.
  39600. * @param {boolean=} opt_altKey Whether the alt key is held down.
  39601. * @return {boolean} Whether it's a key that fires a keypress event.
  39602. */
  39603. goog.events.KeyCodes.firesKeyPressEvent = function(keyCode, opt_heldKeyCode,
  39604. opt_shiftKey, opt_ctrlKey, opt_altKey) {
  39605. if (!goog.userAgent.IE && !goog.userAgent.EDGE &&
  39606. !(goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('525'))) {
  39607. return true;
  39608. }
  39609. if (goog.userAgent.MAC && opt_altKey) {
  39610. return goog.events.KeyCodes.isCharacterKey(keyCode);
  39611. }
  39612. // Alt but not AltGr which is represented as Alt+Ctrl.
  39613. if (opt_altKey && !opt_ctrlKey) {
  39614. return false;
  39615. }
  39616. // Saves Ctrl or Alt + key for IE and WebKit 525+, which won't fire keypress.
  39617. // Non-IE browsers and WebKit prior to 525 won't get this far so no need to
  39618. // check the user agent.
  39619. if (goog.isNumber(opt_heldKeyCode)) {
  39620. opt_heldKeyCode = goog.events.KeyCodes.normalizeKeyCode(opt_heldKeyCode);
  39621. }
  39622. if (!opt_shiftKey &&
  39623. (opt_heldKeyCode == goog.events.KeyCodes.CTRL ||
  39624. opt_heldKeyCode == goog.events.KeyCodes.ALT ||
  39625. goog.userAgent.MAC &&
  39626. opt_heldKeyCode == goog.events.KeyCodes.META)) {
  39627. return false;
  39628. }
  39629. // Some keys with Ctrl/Shift do not issue keypress in WEBKIT.
  39630. if ((goog.userAgent.WEBKIT || goog.userAgent.EDGE) &&
  39631. opt_ctrlKey && opt_shiftKey) {
  39632. switch (keyCode) {
  39633. case goog.events.KeyCodes.BACKSLASH:
  39634. case goog.events.KeyCodes.OPEN_SQUARE_BRACKET:
  39635. case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET:
  39636. case goog.events.KeyCodes.TILDE:
  39637. case goog.events.KeyCodes.SEMICOLON:
  39638. case goog.events.KeyCodes.DASH:
  39639. case goog.events.KeyCodes.EQUALS:
  39640. case goog.events.KeyCodes.COMMA:
  39641. case goog.events.KeyCodes.PERIOD:
  39642. case goog.events.KeyCodes.SLASH:
  39643. case goog.events.KeyCodes.APOSTROPHE:
  39644. case goog.events.KeyCodes.SINGLE_QUOTE:
  39645. return false;
  39646. }
  39647. }
  39648. // When Ctrl+<somekey> is held in IE, it only fires a keypress once, but it
  39649. // continues to fire keydown events as the event repeats.
  39650. if (goog.userAgent.IE && opt_ctrlKey && opt_heldKeyCode == keyCode) {
  39651. return false;
  39652. }
  39653. switch (keyCode) {
  39654. case goog.events.KeyCodes.ENTER:
  39655. return true;
  39656. case goog.events.KeyCodes.ESC:
  39657. return !(goog.userAgent.WEBKIT || goog.userAgent.EDGE);
  39658. }
  39659. return goog.events.KeyCodes.isCharacterKey(keyCode);
  39660. };
  39661. /**
  39662. * Returns true if the key produces a character.
  39663. * This does not cover characters on non-US keyboards (Russian, Hebrew, etc.).
  39664. *
  39665. * @param {number} keyCode A key code.
  39666. * @return {boolean} Whether it's a character key.
  39667. */
  39668. goog.events.KeyCodes.isCharacterKey = function(keyCode) {
  39669. if (keyCode >= goog.events.KeyCodes.ZERO &&
  39670. keyCode <= goog.events.KeyCodes.NINE) {
  39671. return true;
  39672. }
  39673. if (keyCode >= goog.events.KeyCodes.NUM_ZERO &&
  39674. keyCode <= goog.events.KeyCodes.NUM_MULTIPLY) {
  39675. return true;
  39676. }
  39677. if (keyCode >= goog.events.KeyCodes.A &&
  39678. keyCode <= goog.events.KeyCodes.Z) {
  39679. return true;
  39680. }
  39681. // Safari sends zero key code for non-latin characters.
  39682. if ((goog.userAgent.WEBKIT || goog.userAgent.EDGE) && keyCode == 0) {
  39683. return true;
  39684. }
  39685. switch (keyCode) {
  39686. case goog.events.KeyCodes.SPACE:
  39687. case goog.events.KeyCodes.PLUS_SIGN:
  39688. case goog.events.KeyCodes.QUESTION_MARK:
  39689. case goog.events.KeyCodes.AT_SIGN:
  39690. case goog.events.KeyCodes.NUM_PLUS:
  39691. case goog.events.KeyCodes.NUM_MINUS:
  39692. case goog.events.KeyCodes.NUM_PERIOD:
  39693. case goog.events.KeyCodes.NUM_DIVISION:
  39694. case goog.events.KeyCodes.SEMICOLON:
  39695. case goog.events.KeyCodes.FF_SEMICOLON:
  39696. case goog.events.KeyCodes.DASH:
  39697. case goog.events.KeyCodes.EQUALS:
  39698. case goog.events.KeyCodes.FF_EQUALS:
  39699. case goog.events.KeyCodes.COMMA:
  39700. case goog.events.KeyCodes.PERIOD:
  39701. case goog.events.KeyCodes.SLASH:
  39702. case goog.events.KeyCodes.APOSTROPHE:
  39703. case goog.events.KeyCodes.SINGLE_QUOTE:
  39704. case goog.events.KeyCodes.OPEN_SQUARE_BRACKET:
  39705. case goog.events.KeyCodes.BACKSLASH:
  39706. case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET:
  39707. return true;
  39708. default:
  39709. return false;
  39710. }
  39711. };
  39712. /**
  39713. * Normalizes key codes from OS/Browser-specific value to the general one.
  39714. * @param {number} keyCode The native key code.
  39715. * @return {number} The normalized key code.
  39716. */
  39717. goog.events.KeyCodes.normalizeKeyCode = function(keyCode) {
  39718. if (goog.userAgent.GECKO) {
  39719. return goog.events.KeyCodes.normalizeGeckoKeyCode(keyCode);
  39720. } else if (goog.userAgent.MAC && goog.userAgent.WEBKIT) {
  39721. return goog.events.KeyCodes.normalizeMacWebKitKeyCode(keyCode);
  39722. } else {
  39723. return keyCode;
  39724. }
  39725. };
  39726. /**
  39727. * Normalizes key codes from their Gecko-specific value to the general one.
  39728. * @param {number} keyCode The native key code.
  39729. * @return {number} The normalized key code.
  39730. */
  39731. goog.events.KeyCodes.normalizeGeckoKeyCode = function(keyCode) {
  39732. switch (keyCode) {
  39733. case goog.events.KeyCodes.FF_EQUALS:
  39734. return goog.events.KeyCodes.EQUALS;
  39735. case goog.events.KeyCodes.FF_SEMICOLON:
  39736. return goog.events.KeyCodes.SEMICOLON;
  39737. case goog.events.KeyCodes.FF_DASH:
  39738. return goog.events.KeyCodes.DASH;
  39739. case goog.events.KeyCodes.MAC_FF_META:
  39740. return goog.events.KeyCodes.META;
  39741. case goog.events.KeyCodes.WIN_KEY_FF_LINUX:
  39742. return goog.events.KeyCodes.WIN_KEY;
  39743. default:
  39744. return keyCode;
  39745. }
  39746. };
  39747. /**
  39748. * Normalizes key codes from their Mac WebKit-specific value to the general one.
  39749. * @param {number} keyCode The native key code.
  39750. * @return {number} The normalized key code.
  39751. */
  39752. goog.events.KeyCodes.normalizeMacWebKitKeyCode = function(keyCode) {
  39753. switch (keyCode) {
  39754. case goog.events.KeyCodes.MAC_WK_CMD_RIGHT: // 93
  39755. return goog.events.KeyCodes.META; // 91
  39756. default:
  39757. return keyCode;
  39758. }
  39759. };
  39760. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  39761. //
  39762. // Licensed under the Apache License, Version 2.0 (the "License");
  39763. // you may not use this file except in compliance with the License.
  39764. // You may obtain a copy of the License at
  39765. //
  39766. // http://www.apache.org/licenses/LICENSE-2.0
  39767. //
  39768. // Unless required by applicable law or agreed to in writing, software
  39769. // distributed under the License is distributed on an "AS-IS" BASIS,
  39770. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39771. // See the License for the specific language governing permissions and
  39772. // limitations under the License.
  39773. /**
  39774. * @fileoverview This file contains a class for working with keyboard events
  39775. * that repeat consistently across browsers and platforms. It also unifies the
  39776. * key code so that it is the same in all browsers and platforms.
  39777. *
  39778. * Different web browsers have very different keyboard event handling. Most
  39779. * importantly is that only certain browsers repeat keydown events:
  39780. * IE, Opera, FF/Win32, and Safari 3 repeat keydown events.
  39781. * FF/Mac and Safari 2 do not.
  39782. *
  39783. * For the purposes of this code, "Safari 3" means WebKit 525+, when WebKit
  39784. * decided that they should try to match IE's key handling behavior.
  39785. * Safari 3.0.4, which shipped with Leopard (WebKit 523), has the
  39786. * Safari 2 behavior.
  39787. *
  39788. * Firefox, Safari, Opera prevent on keypress
  39789. *
  39790. * IE prevents on keydown
  39791. *
  39792. * Firefox does not fire keypress for shift, ctrl, alt
  39793. * Firefox does fire keydown for shift, ctrl, alt, meta
  39794. * Firefox does not repeat keydown for shift, ctrl, alt, meta
  39795. *
  39796. * Firefox does not fire keypress for up and down in an input
  39797. *
  39798. * Opera fires keypress for shift, ctrl, alt, meta
  39799. * Opera does not repeat keypress for shift, ctrl, alt, meta
  39800. *
  39801. * Safari 2 and 3 do not fire keypress for shift, ctrl, alt
  39802. * Safari 2 does not fire keydown for shift, ctrl, alt
  39803. * Safari 3 *does* fire keydown for shift, ctrl, alt
  39804. *
  39805. * IE provides the keycode for keyup/down events and the charcode (in the
  39806. * keycode field) for keypress.
  39807. *
  39808. * Mozilla provides the keycode for keyup/down and the charcode for keypress
  39809. * unless it's a non text modifying key in which case the keycode is provided.
  39810. *
  39811. * Safari 3 provides the keycode and charcode for all events.
  39812. *
  39813. * Opera provides the keycode for keyup/down event and either the charcode or
  39814. * the keycode (in the keycode field) for keypress events.
  39815. *
  39816. * Firefox x11 doesn't fire keydown events if a another key is already held down
  39817. * until the first key is released. This can cause a key event to be fired with
  39818. * a keyCode for the first key and a charCode for the second key.
  39819. *
  39820. * Safari in keypress
  39821. *
  39822. * charCode keyCode which
  39823. * ENTER: 13 13 13
  39824. * F1: 63236 63236 63236
  39825. * F8: 63243 63243 63243
  39826. * ...
  39827. * p: 112 112 112
  39828. * P: 80 80 80
  39829. *
  39830. * Firefox, keypress:
  39831. *
  39832. * charCode keyCode which
  39833. * ENTER: 0 13 13
  39834. * F1: 0 112 0
  39835. * F8: 0 119 0
  39836. * ...
  39837. * p: 112 0 112
  39838. * P: 80 0 80
  39839. *
  39840. * Opera, Mac+Win32, keypress:
  39841. *
  39842. * charCode keyCode which
  39843. * ENTER: undefined 13 13
  39844. * F1: undefined 112 0
  39845. * F8: undefined 119 0
  39846. * ...
  39847. * p: undefined 112 112
  39848. * P: undefined 80 80
  39849. *
  39850. * IE7, keydown
  39851. *
  39852. * charCode keyCode which
  39853. * ENTER: undefined 13 undefined
  39854. * F1: undefined 112 undefined
  39855. * F8: undefined 119 undefined
  39856. * ...
  39857. * p: undefined 80 undefined
  39858. * P: undefined 80 undefined
  39859. *
  39860. * @author arv@google.com (Erik Arvidsson)
  39861. * @author eae@google.com (Emil A Eklund)
  39862. * @see ../demos/keyhandler.html
  39863. */
  39864. goog.provide('goog.events.KeyEvent');
  39865. goog.provide('goog.events.KeyHandler');
  39866. goog.provide('goog.events.KeyHandler.EventType');
  39867. goog.require('goog.events');
  39868. goog.require('goog.events.BrowserEvent');
  39869. goog.require('goog.events.EventTarget');
  39870. goog.require('goog.events.EventType');
  39871. goog.require('goog.events.KeyCodes');
  39872. goog.require('goog.userAgent');
  39873. /**
  39874. * A wrapper around an element that you want to listen to keyboard events on.
  39875. * @param {Element|Document=} opt_element The element or document to listen on.
  39876. * @param {boolean=} opt_capture Whether to listen for browser events in
  39877. * capture phase (defaults to false).
  39878. * @constructor
  39879. * @extends {goog.events.EventTarget}
  39880. * @final
  39881. */
  39882. goog.events.KeyHandler = function(opt_element, opt_capture) {
  39883. goog.events.EventTarget.call(this);
  39884. if (opt_element) {
  39885. this.attach(opt_element, opt_capture);
  39886. }
  39887. };
  39888. goog.inherits(goog.events.KeyHandler, goog.events.EventTarget);
  39889. /**
  39890. * This is the element that we will listen to the real keyboard events on.
  39891. * @type {Element|Document|null}
  39892. * @private
  39893. */
  39894. goog.events.KeyHandler.prototype.element_ = null;
  39895. /**
  39896. * The key for the key press listener.
  39897. * @type {goog.events.Key}
  39898. * @private
  39899. */
  39900. goog.events.KeyHandler.prototype.keyPressKey_ = null;
  39901. /**
  39902. * The key for the key down listener.
  39903. * @type {goog.events.Key}
  39904. * @private
  39905. */
  39906. goog.events.KeyHandler.prototype.keyDownKey_ = null;
  39907. /**
  39908. * The key for the key up listener.
  39909. * @type {goog.events.Key}
  39910. * @private
  39911. */
  39912. goog.events.KeyHandler.prototype.keyUpKey_ = null;
  39913. /**
  39914. * Used to detect keyboard repeat events.
  39915. * @private
  39916. * @type {number}
  39917. */
  39918. goog.events.KeyHandler.prototype.lastKey_ = -1;
  39919. /**
  39920. * Keycode recorded for key down events. As most browsers don't report the
  39921. * keycode in the key press event we need to record it in the key down phase.
  39922. * @private
  39923. * @type {number}
  39924. */
  39925. goog.events.KeyHandler.prototype.keyCode_ = -1;
  39926. /**
  39927. * Alt key recorded for key down events. FF on Mac does not report the alt key
  39928. * flag in the key press event, we need to record it in the key down phase.
  39929. * @type {boolean}
  39930. * @private
  39931. */
  39932. goog.events.KeyHandler.prototype.altKey_ = false;
  39933. /**
  39934. * Enum type for the events fired by the key handler
  39935. * @enum {string}
  39936. */
  39937. goog.events.KeyHandler.EventType = {
  39938. KEY: 'key'
  39939. };
  39940. /**
  39941. * An enumeration of key codes that Safari 2 does incorrectly
  39942. * @type {Object}
  39943. * @private
  39944. */
  39945. goog.events.KeyHandler.safariKey_ = {
  39946. '3': goog.events.KeyCodes.ENTER, // 13
  39947. '12': goog.events.KeyCodes.NUMLOCK, // 144
  39948. '63232': goog.events.KeyCodes.UP, // 38
  39949. '63233': goog.events.KeyCodes.DOWN, // 40
  39950. '63234': goog.events.KeyCodes.LEFT, // 37
  39951. '63235': goog.events.KeyCodes.RIGHT, // 39
  39952. '63236': goog.events.KeyCodes.F1, // 112
  39953. '63237': goog.events.KeyCodes.F2, // 113
  39954. '63238': goog.events.KeyCodes.F3, // 114
  39955. '63239': goog.events.KeyCodes.F4, // 115
  39956. '63240': goog.events.KeyCodes.F5, // 116
  39957. '63241': goog.events.KeyCodes.F6, // 117
  39958. '63242': goog.events.KeyCodes.F7, // 118
  39959. '63243': goog.events.KeyCodes.F8, // 119
  39960. '63244': goog.events.KeyCodes.F9, // 120
  39961. '63245': goog.events.KeyCodes.F10, // 121
  39962. '63246': goog.events.KeyCodes.F11, // 122
  39963. '63247': goog.events.KeyCodes.F12, // 123
  39964. '63248': goog.events.KeyCodes.PRINT_SCREEN, // 44
  39965. '63272': goog.events.KeyCodes.DELETE, // 46
  39966. '63273': goog.events.KeyCodes.HOME, // 36
  39967. '63275': goog.events.KeyCodes.END, // 35
  39968. '63276': goog.events.KeyCodes.PAGE_UP, // 33
  39969. '63277': goog.events.KeyCodes.PAGE_DOWN, // 34
  39970. '63289': goog.events.KeyCodes.NUMLOCK, // 144
  39971. '63302': goog.events.KeyCodes.INSERT // 45
  39972. };
  39973. /**
  39974. * An enumeration of key identifiers currently part of the W3C draft for DOM3
  39975. * and their mappings to keyCodes.
  39976. * http://www.w3.org/TR/DOM-Level-3-Events/keyset.html#KeySet-Set
  39977. * This is currently supported in Safari and should be platform independent.
  39978. * @type {Object}
  39979. * @private
  39980. */
  39981. goog.events.KeyHandler.keyIdentifier_ = {
  39982. 'Up': goog.events.KeyCodes.UP, // 38
  39983. 'Down': goog.events.KeyCodes.DOWN, // 40
  39984. 'Left': goog.events.KeyCodes.LEFT, // 37
  39985. 'Right': goog.events.KeyCodes.RIGHT, // 39
  39986. 'Enter': goog.events.KeyCodes.ENTER, // 13
  39987. 'F1': goog.events.KeyCodes.F1, // 112
  39988. 'F2': goog.events.KeyCodes.F2, // 113
  39989. 'F3': goog.events.KeyCodes.F3, // 114
  39990. 'F4': goog.events.KeyCodes.F4, // 115
  39991. 'F5': goog.events.KeyCodes.F5, // 116
  39992. 'F6': goog.events.KeyCodes.F6, // 117
  39993. 'F7': goog.events.KeyCodes.F7, // 118
  39994. 'F8': goog.events.KeyCodes.F8, // 119
  39995. 'F9': goog.events.KeyCodes.F9, // 120
  39996. 'F10': goog.events.KeyCodes.F10, // 121
  39997. 'F11': goog.events.KeyCodes.F11, // 122
  39998. 'F12': goog.events.KeyCodes.F12, // 123
  39999. 'U+007F': goog.events.KeyCodes.DELETE, // 46
  40000. 'Home': goog.events.KeyCodes.HOME, // 36
  40001. 'End': goog.events.KeyCodes.END, // 35
  40002. 'PageUp': goog.events.KeyCodes.PAGE_UP, // 33
  40003. 'PageDown': goog.events.KeyCodes.PAGE_DOWN, // 34
  40004. 'Insert': goog.events.KeyCodes.INSERT // 45
  40005. };
  40006. /**
  40007. * If true, the KeyEvent fires on keydown. Otherwise, it fires on keypress.
  40008. *
  40009. * @type {boolean}
  40010. * @private
  40011. */
  40012. goog.events.KeyHandler.USES_KEYDOWN_ = goog.userAgent.IE ||
  40013. goog.userAgent.EDGE ||
  40014. goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('525');
  40015. /**
  40016. * If true, the alt key flag is saved during the key down and reused when
  40017. * handling the key press. FF on Mac does not set the alt flag in the key press
  40018. * event.
  40019. * @type {boolean}
  40020. * @private
  40021. */
  40022. goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_ = goog.userAgent.MAC &&
  40023. goog.userAgent.GECKO;
  40024. /**
  40025. * Records the keycode for browsers that only returns the keycode for key up/
  40026. * down events. For browser/key combinations that doesn't trigger a key pressed
  40027. * event it also fires the patched key event.
  40028. * @param {goog.events.BrowserEvent} e The key down event.
  40029. * @private
  40030. */
  40031. goog.events.KeyHandler.prototype.handleKeyDown_ = function(e) {
  40032. // Ctrl-Tab and Alt-Tab can cause the focus to be moved to another window
  40033. // before we've caught a key-up event. If the last-key was one of these we
  40034. // reset the state.
  40035. if (goog.userAgent.WEBKIT || goog.userAgent.EDGE) {
  40036. if (this.lastKey_ == goog.events.KeyCodes.CTRL && !e.ctrlKey ||
  40037. this.lastKey_ == goog.events.KeyCodes.ALT && !e.altKey ||
  40038. goog.userAgent.MAC &&
  40039. this.lastKey_ == goog.events.KeyCodes.META && !e.metaKey) {
  40040. this.resetState();
  40041. }
  40042. }
  40043. if (this.lastKey_ == -1) {
  40044. if (e.ctrlKey && e.keyCode != goog.events.KeyCodes.CTRL) {
  40045. this.lastKey_ = goog.events.KeyCodes.CTRL;
  40046. } else if (e.altKey && e.keyCode != goog.events.KeyCodes.ALT) {
  40047. this.lastKey_ = goog.events.KeyCodes.ALT;
  40048. } else if (e.metaKey && e.keyCode != goog.events.KeyCodes.META) {
  40049. this.lastKey_ = goog.events.KeyCodes.META;
  40050. }
  40051. }
  40052. if (goog.events.KeyHandler.USES_KEYDOWN_ &&
  40053. !goog.events.KeyCodes.firesKeyPressEvent(e.keyCode,
  40054. this.lastKey_, e.shiftKey, e.ctrlKey, e.altKey)) {
  40055. this.handleEvent(e);
  40056. } else {
  40057. this.keyCode_ = goog.events.KeyCodes.normalizeKeyCode(e.keyCode);
  40058. if (goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_) {
  40059. this.altKey_ = e.altKey;
  40060. }
  40061. }
  40062. };
  40063. /**
  40064. * Resets the stored previous values. Needed to be called for webkit which will
  40065. * not generate a key up for meta key operations. This should only be called
  40066. * when having finished with repeat key possiblities.
  40067. */
  40068. goog.events.KeyHandler.prototype.resetState = function() {
  40069. this.lastKey_ = -1;
  40070. this.keyCode_ = -1;
  40071. };
  40072. /**
  40073. * Clears the stored previous key value, resetting the key repeat status. Uses
  40074. * -1 because the Safari 3 Windows beta reports 0 for certain keys (like Home
  40075. * and End.)
  40076. * @param {goog.events.BrowserEvent} e The keyup event.
  40077. * @private
  40078. */
  40079. goog.events.KeyHandler.prototype.handleKeyup_ = function(e) {
  40080. this.resetState();
  40081. this.altKey_ = e.altKey;
  40082. };
  40083. /**
  40084. * Handles the events on the element.
  40085. * @param {goog.events.BrowserEvent} e The keyboard event sent from the
  40086. * browser.
  40087. */
  40088. goog.events.KeyHandler.prototype.handleEvent = function(e) {
  40089. var be = e.getBrowserEvent();
  40090. var keyCode, charCode;
  40091. var altKey = be.altKey;
  40092. // IE reports the character code in the keyCode field for keypress events.
  40093. // There are two exceptions however, Enter and Escape.
  40094. if (goog.userAgent.IE && e.type == goog.events.EventType.KEYPRESS) {
  40095. keyCode = this.keyCode_;
  40096. charCode = keyCode != goog.events.KeyCodes.ENTER &&
  40097. keyCode != goog.events.KeyCodes.ESC ?
  40098. be.keyCode : 0;
  40099. // Safari reports the character code in the keyCode field for keypress
  40100. // events but also has a charCode field.
  40101. } else if ((goog.userAgent.WEBKIT || goog.userAgent.EDGE) &&
  40102. e.type == goog.events.EventType.KEYPRESS) {
  40103. keyCode = this.keyCode_;
  40104. charCode = be.charCode >= 0 && be.charCode < 63232 &&
  40105. goog.events.KeyCodes.isCharacterKey(keyCode) ?
  40106. be.charCode : 0;
  40107. // Opera reports the keycode or the character code in the keyCode field.
  40108. } else if (goog.userAgent.OPERA && !goog.userAgent.WEBKIT) {
  40109. keyCode = this.keyCode_;
  40110. charCode = goog.events.KeyCodes.isCharacterKey(keyCode) ?
  40111. be.keyCode : 0;
  40112. // Mozilla reports the character code in the charCode field.
  40113. } else {
  40114. keyCode = be.keyCode || this.keyCode_;
  40115. charCode = be.charCode || 0;
  40116. if (goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_) {
  40117. altKey = this.altKey_;
  40118. }
  40119. // On the Mac, shift-/ triggers a question mark char code and no key code
  40120. // (normalized to WIN_KEY), so we synthesize the latter.
  40121. if (goog.userAgent.MAC &&
  40122. charCode == goog.events.KeyCodes.QUESTION_MARK &&
  40123. keyCode == goog.events.KeyCodes.WIN_KEY) {
  40124. keyCode = goog.events.KeyCodes.SLASH;
  40125. }
  40126. }
  40127. keyCode = goog.events.KeyCodes.normalizeKeyCode(keyCode);
  40128. var key = keyCode;
  40129. var keyIdentifier = be.keyIdentifier;
  40130. // Correct the key value for certain browser-specific quirks.
  40131. if (keyCode) {
  40132. if (keyCode >= 63232 && keyCode in goog.events.KeyHandler.safariKey_) {
  40133. // NOTE(nicksantos): Safari 3 has fixed this problem,
  40134. // this is only needed for Safari 2.
  40135. key = goog.events.KeyHandler.safariKey_[keyCode];
  40136. } else {
  40137. // Safari returns 25 for Shift+Tab instead of 9.
  40138. if (keyCode == 25 && e.shiftKey) {
  40139. key = 9;
  40140. }
  40141. }
  40142. } else if (keyIdentifier &&
  40143. keyIdentifier in goog.events.KeyHandler.keyIdentifier_) {
  40144. // This is needed for Safari Windows because it currently doesn't give a
  40145. // keyCode/which for non printable keys.
  40146. key = goog.events.KeyHandler.keyIdentifier_[keyIdentifier];
  40147. }
  40148. // If we get the same keycode as a keydown/keypress without having seen a
  40149. // keyup event, then this event was caused by key repeat.
  40150. var repeat = key == this.lastKey_;
  40151. this.lastKey_ = key;
  40152. var event = new goog.events.KeyEvent(key, charCode, repeat, be);
  40153. event.altKey = altKey;
  40154. this.dispatchEvent(event);
  40155. };
  40156. /**
  40157. * Returns the element listened on for the real keyboard events.
  40158. * @return {Element|Document|null} The element listened on for the real
  40159. * keyboard events.
  40160. */
  40161. goog.events.KeyHandler.prototype.getElement = function() {
  40162. return this.element_;
  40163. };
  40164. /**
  40165. * Adds the proper key event listeners to the element.
  40166. * @param {Element|Document} element The element to listen on.
  40167. * @param {boolean=} opt_capture Whether to listen for browser events in
  40168. * capture phase (defaults to false).
  40169. */
  40170. goog.events.KeyHandler.prototype.attach = function(element, opt_capture) {
  40171. if (this.keyUpKey_) {
  40172. this.detach();
  40173. }
  40174. this.element_ = element;
  40175. this.keyPressKey_ = goog.events.listen(this.element_,
  40176. goog.events.EventType.KEYPRESS,
  40177. this,
  40178. opt_capture);
  40179. // Most browsers (Safari 2 being the notable exception) doesn't include the
  40180. // keyCode in keypress events (IE has the char code in the keyCode field and
  40181. // Mozilla only included the keyCode if there's no charCode). Thus we have to
  40182. // listen for keydown to capture the keycode.
  40183. this.keyDownKey_ = goog.events.listen(this.element_,
  40184. goog.events.EventType.KEYDOWN,
  40185. this.handleKeyDown_,
  40186. opt_capture,
  40187. this);
  40188. this.keyUpKey_ = goog.events.listen(this.element_,
  40189. goog.events.EventType.KEYUP,
  40190. this.handleKeyup_,
  40191. opt_capture,
  40192. this);
  40193. };
  40194. /**
  40195. * Removes the listeners that may exist.
  40196. */
  40197. goog.events.KeyHandler.prototype.detach = function() {
  40198. if (this.keyPressKey_) {
  40199. goog.events.unlistenByKey(this.keyPressKey_);
  40200. goog.events.unlistenByKey(this.keyDownKey_);
  40201. goog.events.unlistenByKey(this.keyUpKey_);
  40202. this.keyPressKey_ = null;
  40203. this.keyDownKey_ = null;
  40204. this.keyUpKey_ = null;
  40205. }
  40206. this.element_ = null;
  40207. this.lastKey_ = -1;
  40208. this.keyCode_ = -1;
  40209. };
  40210. /** @override */
  40211. goog.events.KeyHandler.prototype.disposeInternal = function() {
  40212. goog.events.KeyHandler.superClass_.disposeInternal.call(this);
  40213. this.detach();
  40214. };
  40215. /**
  40216. * This class is used for the goog.events.KeyHandler.EventType.KEY event and
  40217. * it overrides the key code with the fixed key code.
  40218. * @param {number} keyCode The adjusted key code.
  40219. * @param {number} charCode The unicode character code.
  40220. * @param {boolean} repeat Whether this event was generated by keyboard repeat.
  40221. * @param {Event} browserEvent Browser event object.
  40222. * @constructor
  40223. * @extends {goog.events.BrowserEvent}
  40224. * @final
  40225. */
  40226. goog.events.KeyEvent = function(keyCode, charCode, repeat, browserEvent) {
  40227. goog.events.BrowserEvent.call(this, browserEvent);
  40228. this.type = goog.events.KeyHandler.EventType.KEY;
  40229. /**
  40230. * Keycode of key press.
  40231. * @type {number}
  40232. */
  40233. this.keyCode = keyCode;
  40234. /**
  40235. * Unicode character code.
  40236. * @type {number}
  40237. */
  40238. this.charCode = charCode;
  40239. /**
  40240. * True if this event was generated by keyboard auto-repeat (i.e., the user is
  40241. * holding the key down.)
  40242. * @type {boolean}
  40243. */
  40244. this.repeat = repeat;
  40245. };
  40246. goog.inherits(goog.events.KeyEvent, goog.events.BrowserEvent);
  40247. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  40248. //
  40249. // Licensed under the Apache License, Version 2.0 (the "License");
  40250. // you may not use this file except in compliance with the License.
  40251. // You may obtain a copy of the License at
  40252. //
  40253. // http://www.apache.org/licenses/LICENSE-2.0
  40254. //
  40255. // Unless required by applicable law or agreed to in writing, software
  40256. // distributed under the License is distributed on an "AS-IS" BASIS,
  40257. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40258. // See the License for the specific language governing permissions and
  40259. // limitations under the License.
  40260. /**
  40261. * @fileoverview This event wrapper will dispatch an event when the user uses
  40262. * the mouse wheel to scroll an element. You can get the direction by checking
  40263. * the deltaX and deltaY properties of the event.
  40264. *
  40265. * This class aims to smooth out inconsistencies between browser platforms with
  40266. * regards to mousewheel events, but we do not cover every possible
  40267. * software/hardware combination out there, some of which occasionally produce
  40268. * very large deltas in mousewheel events. If your application wants to guard
  40269. * against extremely large deltas, use the setMaxDeltaX and setMaxDeltaY APIs
  40270. * to set maximum values that make sense for your application.
  40271. *
  40272. * @author arv@google.com (Erik Arvidsson)
  40273. * @see ../demos/mousewheelhandler.html
  40274. */
  40275. goog.provide('goog.events.MouseWheelEvent');
  40276. goog.provide('goog.events.MouseWheelHandler');
  40277. goog.provide('goog.events.MouseWheelHandler.EventType');
  40278. goog.require('goog.dom');
  40279. goog.require('goog.events');
  40280. goog.require('goog.events.BrowserEvent');
  40281. goog.require('goog.events.EventTarget');
  40282. goog.require('goog.math');
  40283. goog.require('goog.style');
  40284. goog.require('goog.userAgent');
  40285. /**
  40286. * This event handler allows you to catch mouse wheel events in a consistent
  40287. * manner.
  40288. * @param {Element|Document} element The element to listen to the mouse wheel
  40289. * event on.
  40290. * @param {boolean=} opt_capture Whether to handle the mouse wheel event in
  40291. * capture phase.
  40292. * @constructor
  40293. * @extends {goog.events.EventTarget}
  40294. */
  40295. goog.events.MouseWheelHandler = function(element, opt_capture) {
  40296. goog.events.EventTarget.call(this);
  40297. /**
  40298. * This is the element that we will listen to the real mouse wheel events on.
  40299. * @type {Element|Document}
  40300. * @private
  40301. */
  40302. this.element_ = element;
  40303. var rtlElement = goog.dom.isElement(this.element_) ?
  40304. /** @type {Element} */ (this.element_) :
  40305. (this.element_ ? /** @type {Document} */ (this.element_).body : null);
  40306. /**
  40307. * True if the element exists and is RTL, false otherwise.
  40308. * @type {boolean}
  40309. * @private
  40310. */
  40311. this.isRtl_ = !!rtlElement && goog.style.isRightToLeft(rtlElement);
  40312. var type = goog.userAgent.GECKO ? 'DOMMouseScroll' : 'mousewheel';
  40313. /**
  40314. * The key returned from the goog.events.listen.
  40315. * @type {goog.events.Key}
  40316. * @private
  40317. */
  40318. this.listenKey_ = goog.events.listen(this.element_, type, this, opt_capture);
  40319. };
  40320. goog.inherits(goog.events.MouseWheelHandler, goog.events.EventTarget);
  40321. /**
  40322. * Enum type for the events fired by the mouse wheel handler.
  40323. * @enum {string}
  40324. */
  40325. goog.events.MouseWheelHandler.EventType = {
  40326. MOUSEWHEEL: 'mousewheel'
  40327. };
  40328. /**
  40329. * Optional maximum magnitude for x delta on each mousewheel event.
  40330. * @type {number|undefined}
  40331. * @private
  40332. */
  40333. goog.events.MouseWheelHandler.prototype.maxDeltaX_;
  40334. /**
  40335. * Optional maximum magnitude for y delta on each mousewheel event.
  40336. * @type {number|undefined}
  40337. * @private
  40338. */
  40339. goog.events.MouseWheelHandler.prototype.maxDeltaY_;
  40340. /**
  40341. * @param {number} maxDeltaX Maximum magnitude for x delta on each mousewheel
  40342. * event. Should be non-negative.
  40343. */
  40344. goog.events.MouseWheelHandler.prototype.setMaxDeltaX = function(maxDeltaX) {
  40345. this.maxDeltaX_ = maxDeltaX;
  40346. };
  40347. /**
  40348. * @param {number} maxDeltaY Maximum magnitude for y delta on each mousewheel
  40349. * event. Should be non-negative.
  40350. */
  40351. goog.events.MouseWheelHandler.prototype.setMaxDeltaY = function(maxDeltaY) {
  40352. this.maxDeltaY_ = maxDeltaY;
  40353. };
  40354. /**
  40355. * Handles the events on the element.
  40356. * @param {goog.events.BrowserEvent} e The underlying browser event.
  40357. */
  40358. goog.events.MouseWheelHandler.prototype.handleEvent = function(e) {
  40359. var deltaX = 0;
  40360. var deltaY = 0;
  40361. var detail = 0;
  40362. var be = e.getBrowserEvent();
  40363. if (be.type == 'mousewheel') {
  40364. var wheelDeltaScaleFactor = 1;
  40365. if (goog.userAgent.IE ||
  40366. goog.userAgent.WEBKIT &&
  40367. (goog.userAgent.WINDOWS || goog.userAgent.isVersionOrHigher('532.0'))) {
  40368. // In IE we get a multiple of 120; we adjust to a multiple of 3 to
  40369. // represent number of lines scrolled (like Gecko).
  40370. // Newer versions of Webkit match IE behavior, and WebKit on
  40371. // Windows also matches IE behavior.
  40372. // See bug https://bugs.webkit.org/show_bug.cgi?id=24368
  40373. wheelDeltaScaleFactor = 40;
  40374. }
  40375. detail = goog.events.MouseWheelHandler.smartScale_(
  40376. -be.wheelDelta, wheelDeltaScaleFactor);
  40377. if (goog.isDef(be.wheelDeltaX)) {
  40378. // Webkit has two properties to indicate directional scroll, and
  40379. // can scroll both directions at once.
  40380. deltaX = goog.events.MouseWheelHandler.smartScale_(
  40381. -be.wheelDeltaX, wheelDeltaScaleFactor);
  40382. deltaY = goog.events.MouseWheelHandler.smartScale_(
  40383. -be.wheelDeltaY, wheelDeltaScaleFactor);
  40384. } else {
  40385. deltaY = detail;
  40386. }
  40387. // Historical note: Opera (pre 9.5) used to negate the detail value.
  40388. } else { // Gecko
  40389. // Gecko returns multiple of 3 (representing the number of lines scrolled)
  40390. detail = be.detail;
  40391. // Gecko sometimes returns really big values if the user changes settings to
  40392. // scroll a whole page per scroll
  40393. if (detail > 100) {
  40394. detail = 3;
  40395. } else if (detail < -100) {
  40396. detail = -3;
  40397. }
  40398. // Firefox 3.1 adds an axis field to the event to indicate direction of
  40399. // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
  40400. if (goog.isDef(be.axis) && be.axis === be.HORIZONTAL_AXIS) {
  40401. deltaX = detail;
  40402. } else {
  40403. deltaY = detail;
  40404. }
  40405. }
  40406. if (goog.isNumber(this.maxDeltaX_)) {
  40407. deltaX = goog.math.clamp(deltaX, -this.maxDeltaX_, this.maxDeltaX_);
  40408. }
  40409. if (goog.isNumber(this.maxDeltaY_)) {
  40410. deltaY = goog.math.clamp(deltaY, -this.maxDeltaY_, this.maxDeltaY_);
  40411. }
  40412. // Don't clamp 'detail', since it could be ambiguous which axis it refers to
  40413. // and because it's informally deprecated anyways.
  40414. // For horizontal scrolling we need to flip the value for RTL grids.
  40415. if (this.isRtl_) {
  40416. deltaX = -deltaX;
  40417. }
  40418. var newEvent = new goog.events.MouseWheelEvent(detail, be, deltaX, deltaY);
  40419. this.dispatchEvent(newEvent);
  40420. };
  40421. /**
  40422. * Helper for scaling down a mousewheel delta by a scale factor, if appropriate.
  40423. * @param {number} mouseWheelDelta Delta from a mouse wheel event. Expected to
  40424. * be an integer.
  40425. * @param {number} scaleFactor Factor to scale the delta down by. Expected to
  40426. * be an integer.
  40427. * @return {number} Scaled-down delta value, or the original delta if the
  40428. * scaleFactor does not appear to be applicable.
  40429. * @private
  40430. */
  40431. goog.events.MouseWheelHandler.smartScale_ = function(mouseWheelDelta,
  40432. scaleFactor) {
  40433. // The basic problem here is that in Webkit on Mac and Linux, we can get two
  40434. // very different types of mousewheel events: from continuous devices
  40435. // (touchpads, Mighty Mouse) or non-continuous devices (normal wheel mice).
  40436. //
  40437. // Non-continuous devices in Webkit get their wheel deltas scaled up to
  40438. // behave like IE. Continuous devices return much smaller unscaled values
  40439. // (which most of the time will not be cleanly divisible by the IE scale
  40440. // factor), so we should not try to normalize them down.
  40441. //
  40442. // Detailed discussion:
  40443. // https://bugs.webkit.org/show_bug.cgi?id=29601
  40444. // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063
  40445. if (goog.userAgent.WEBKIT &&
  40446. (goog.userAgent.MAC || goog.userAgent.LINUX) &&
  40447. (mouseWheelDelta % scaleFactor) != 0) {
  40448. return mouseWheelDelta;
  40449. } else {
  40450. return mouseWheelDelta / scaleFactor;
  40451. }
  40452. };
  40453. /** @override */
  40454. goog.events.MouseWheelHandler.prototype.disposeInternal = function() {
  40455. goog.events.MouseWheelHandler.superClass_.disposeInternal.call(this);
  40456. goog.events.unlistenByKey(this.listenKey_);
  40457. this.listenKey_ = null;
  40458. };
  40459. /**
  40460. * A base class for mouse wheel events. This is used with the
  40461. * MouseWheelHandler.
  40462. *
  40463. * @param {number} detail The number of rows the user scrolled.
  40464. * @param {Event} browserEvent Browser event object.
  40465. * @param {number} deltaX The number of rows the user scrolled in the X
  40466. * direction.
  40467. * @param {number} deltaY The number of rows the user scrolled in the Y
  40468. * direction.
  40469. * @constructor
  40470. * @extends {goog.events.BrowserEvent}
  40471. * @final
  40472. */
  40473. goog.events.MouseWheelEvent = function(detail, browserEvent, deltaX, deltaY) {
  40474. goog.events.BrowserEvent.call(this, browserEvent);
  40475. this.type = goog.events.MouseWheelHandler.EventType.MOUSEWHEEL;
  40476. /**
  40477. * The number of lines the user scrolled
  40478. * @type {number}
  40479. * NOTE: Informally deprecated. Use deltaX and deltaY instead, they provide
  40480. * more information.
  40481. */
  40482. this.detail = detail;
  40483. /**
  40484. * The number of "lines" scrolled in the X direction.
  40485. *
  40486. * Note that not all browsers provide enough information to distinguish
  40487. * horizontal and vertical scroll events, so for these unsupported browsers,
  40488. * we will always have a deltaX of 0, even if the user scrolled their mouse
  40489. * wheel or trackpad sideways.
  40490. *
  40491. * Currently supported browsers are Webkit and Firefox 3.1 or later.
  40492. *
  40493. * @type {number}
  40494. */
  40495. this.deltaX = deltaX;
  40496. /**
  40497. * The number of lines scrolled in the Y direction.
  40498. * @type {number}
  40499. */
  40500. this.deltaY = deltaY;
  40501. };
  40502. goog.inherits(goog.events.MouseWheelEvent, goog.events.BrowserEvent);
  40503. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  40504. //
  40505. // Licensed under the Apache License, Version 2.0 (the "License");
  40506. // you may not use this file except in compliance with the License.
  40507. // You may obtain a copy of the License at
  40508. //
  40509. // http://www.apache.org/licenses/LICENSE-2.0
  40510. //
  40511. // Unless required by applicable law or agreed to in writing, software
  40512. // distributed under the License is distributed on an "AS-IS" BASIS,
  40513. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40514. // See the License for the specific language governing permissions and
  40515. // limitations under the License.
  40516. /**
  40517. * @fileoverview Basic strippable logging definitions.
  40518. * @see http://go/closurelogging
  40519. *
  40520. * @author johnlenz@google.com (John Lenz)
  40521. */
  40522. goog.provide('goog.log');
  40523. goog.provide('goog.log.Level');
  40524. goog.provide('goog.log.LogRecord');
  40525. goog.provide('goog.log.Logger');
  40526. goog.require('goog.debug');
  40527. goog.require('goog.debug.LogManager');
  40528. goog.require('goog.debug.LogRecord');
  40529. goog.require('goog.debug.Logger');
  40530. /** @define {boolean} Whether logging is enabled. */
  40531. goog.define('goog.log.ENABLED', goog.debug.LOGGING_ENABLED);
  40532. /** @const */
  40533. goog.log.ROOT_LOGGER_NAME = goog.debug.Logger.ROOT_LOGGER_NAME;
  40534. /**
  40535. * @constructor
  40536. * @final
  40537. */
  40538. goog.log.Logger = goog.debug.Logger;
  40539. /**
  40540. * @constructor
  40541. * @final
  40542. */
  40543. goog.log.Level = goog.debug.Logger.Level;
  40544. /**
  40545. * @constructor
  40546. * @final
  40547. */
  40548. goog.log.LogRecord = goog.debug.LogRecord;
  40549. /**
  40550. * Finds or creates a logger for a named subsystem. If a logger has already been
  40551. * created with the given name it is returned. Otherwise a new logger is
  40552. * created. If a new logger is created its log level will be configured based
  40553. * on the goog.debug.LogManager configuration and it will configured to also
  40554. * send logging output to its parent's handlers.
  40555. * @see goog.debug.LogManager
  40556. *
  40557. * @param {string} name A name for the logger. This should be a dot-separated
  40558. * name and should normally be based on the package name or class name of
  40559. * the subsystem, such as goog.net.BrowserChannel.
  40560. * @param {goog.log.Level=} opt_level If provided, override the
  40561. * default logging level with the provided level.
  40562. * @return {goog.log.Logger} The named logger or null if logging is disabled.
  40563. */
  40564. goog.log.getLogger = function(name, opt_level) {
  40565. if (goog.log.ENABLED) {
  40566. var logger = goog.debug.LogManager.getLogger(name);
  40567. if (opt_level && logger) {
  40568. logger.setLevel(opt_level);
  40569. }
  40570. return logger;
  40571. } else {
  40572. return null;
  40573. }
  40574. };
  40575. // TODO(johnlenz): try to tighten the types to these functions.
  40576. /**
  40577. * Adds a handler to the logger. This doesn't use the event system because
  40578. * we want to be able to add logging to the event system.
  40579. * @param {goog.log.Logger} logger
  40580. * @param {Function} handler Handler function to add.
  40581. */
  40582. goog.log.addHandler = function(logger, handler) {
  40583. if (goog.log.ENABLED && logger) {
  40584. logger.addHandler(handler);
  40585. }
  40586. };
  40587. /**
  40588. * Removes a handler from the logger. This doesn't use the event system because
  40589. * we want to be able to add logging to the event system.
  40590. * @param {goog.log.Logger} logger
  40591. * @param {Function} handler Handler function to remove.
  40592. * @return {boolean} Whether the handler was removed.
  40593. */
  40594. goog.log.removeHandler = function(logger, handler) {
  40595. if (goog.log.ENABLED && logger) {
  40596. return logger.removeHandler(handler);
  40597. } else {
  40598. return false;
  40599. }
  40600. };
  40601. /**
  40602. * Logs a message. If the logger is currently enabled for the
  40603. * given message level then the given message is forwarded to all the
  40604. * registered output Handler objects.
  40605. * @param {goog.log.Logger} logger
  40606. * @param {goog.log.Level} level One of the level identifiers.
  40607. * @param {goog.debug.Loggable} msg The message to log.
  40608. * @param {Error|Object=} opt_exception An exception associated with the
  40609. * message.
  40610. */
  40611. goog.log.log = function(logger, level, msg, opt_exception) {
  40612. if (goog.log.ENABLED && logger) {
  40613. logger.log(level, msg, opt_exception);
  40614. }
  40615. };
  40616. /**
  40617. * Logs a message at the Level.SEVERE level.
  40618. * If the logger is currently enabled for the given message level then the
  40619. * given message is forwarded to all the registered output Handler objects.
  40620. * @param {goog.log.Logger} logger
  40621. * @param {goog.debug.Loggable} msg The message to log.
  40622. * @param {Error=} opt_exception An exception associated with the message.
  40623. */
  40624. goog.log.error = function(logger, msg, opt_exception) {
  40625. if (goog.log.ENABLED && logger) {
  40626. logger.severe(msg, opt_exception);
  40627. }
  40628. };
  40629. /**
  40630. * Logs a message at the Level.WARNING level.
  40631. * If the logger is currently enabled for the given message level then the
  40632. * given message is forwarded to all the registered output Handler objects.
  40633. * @param {goog.log.Logger} logger
  40634. * @param {goog.debug.Loggable} msg The message to log.
  40635. * @param {Error=} opt_exception An exception associated with the message.
  40636. */
  40637. goog.log.warning = function(logger, msg, opt_exception) {
  40638. if (goog.log.ENABLED && logger) {
  40639. logger.warning(msg, opt_exception);
  40640. }
  40641. };
  40642. /**
  40643. * Logs a message at the Level.INFO level.
  40644. * If the logger is currently enabled for the given message level then the
  40645. * given message is forwarded to all the registered output Handler objects.
  40646. * @param {goog.log.Logger} logger
  40647. * @param {goog.debug.Loggable} msg The message to log.
  40648. * @param {Error=} opt_exception An exception associated with the message.
  40649. */
  40650. goog.log.info = function(logger, msg, opt_exception) {
  40651. if (goog.log.ENABLED && logger) {
  40652. logger.info(msg, opt_exception);
  40653. }
  40654. };
  40655. /**
  40656. * Logs a message at the Level.Fine level.
  40657. * If the logger is currently enabled for the given message level then the
  40658. * given message is forwarded to all the registered output Handler objects.
  40659. * @param {goog.log.Logger} logger
  40660. * @param {goog.debug.Loggable} msg The message to log.
  40661. * @param {Error=} opt_exception An exception associated with the message.
  40662. */
  40663. goog.log.fine = function(logger, msg, opt_exception) {
  40664. if (goog.log.ENABLED && logger) {
  40665. logger.fine(msg, opt_exception);
  40666. }
  40667. };
  40668. // Based on https://github.com/Polymer/PointerEvents
  40669. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  40670. //
  40671. // Redistribution and use in source and binary forms, with or without
  40672. // modification, are permitted provided that the following conditions are
  40673. // met:
  40674. //
  40675. // * Redistributions of source code must retain the above copyright
  40676. // notice, this list of conditions and the following disclaimer.
  40677. // * Redistributions in binary form must reproduce the above
  40678. // copyright notice, this list of conditions and the following disclaimer
  40679. // in the documentation and/or other materials provided with the
  40680. // distribution.
  40681. // * Neither the name of Google Inc. nor the names of its
  40682. // contributors may be used to endorse or promote products derived from
  40683. // this software without specific prior written permission.
  40684. //
  40685. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  40686. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  40687. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  40688. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  40689. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40690. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40691. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  40692. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  40693. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  40694. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  40695. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40696. goog.provide('ol.pointer.PointerEvent');
  40697. goog.require('goog.events');
  40698. goog.require('goog.events.Event');
  40699. /**
  40700. * A class for pointer events.
  40701. *
  40702. * This class is used as an abstraction for mouse events,
  40703. * touch events and even native pointer events.
  40704. *
  40705. * @constructor
  40706. * @extends {goog.events.Event}
  40707. * @param {string} type The type of the event to create.
  40708. * @param {goog.events.BrowserEvent} browserEvent
  40709. * @param {Object.<string, ?>=} opt_eventDict An optional dictionary of
  40710. * initial event properties.
  40711. */
  40712. ol.pointer.PointerEvent = function(type, browserEvent, opt_eventDict) {
  40713. goog.base(this, type);
  40714. /**
  40715. * @const
  40716. * @type {goog.events.BrowserEvent}
  40717. */
  40718. this.browserEvent = browserEvent;
  40719. var eventDict = opt_eventDict ? opt_eventDict : {};
  40720. /**
  40721. * @type {number}
  40722. */
  40723. this.buttons = this.getButtons_(eventDict);
  40724. /**
  40725. * @type {number}
  40726. */
  40727. this.pressure = this.getPressure_(eventDict, this.buttons);
  40728. // MouseEvent related properties
  40729. /**
  40730. * @type {boolean}
  40731. */
  40732. this.bubbles = 'bubbles' in eventDict ? eventDict['bubbles'] : false;
  40733. /**
  40734. * @type {boolean}
  40735. */
  40736. this.cancelable = 'cancelable' in eventDict ? eventDict['cancelable'] : false;
  40737. /**
  40738. * @type {Object}
  40739. */
  40740. this.view = 'view' in eventDict ? eventDict['view'] : null;
  40741. /**
  40742. * @type {number}
  40743. */
  40744. this.detail = 'detail' in eventDict ? eventDict['detail'] : null;
  40745. /**
  40746. * @type {number}
  40747. */
  40748. this.screenX = 'screenX' in eventDict ? eventDict['screenX'] : 0;
  40749. /**
  40750. * @type {number}
  40751. */
  40752. this.screenY = 'screenY' in eventDict ? eventDict['screenY'] : 0;
  40753. /**
  40754. * @type {number}
  40755. */
  40756. this.clientX = 'clientX' in eventDict ? eventDict['clientX'] : 0;
  40757. /**
  40758. * @type {number}
  40759. */
  40760. this.clientY = 'clientY' in eventDict ? eventDict['clientY'] : 0;
  40761. /**
  40762. * @type {boolean}
  40763. */
  40764. this.ctrlKey = 'ctrlKey' in eventDict ? eventDict['ctrlKey'] : false;
  40765. /**
  40766. * @type {boolean}
  40767. */
  40768. this.altKey = 'altKey' in eventDict ? eventDict['altKey'] : false;
  40769. /**
  40770. * @type {boolean}
  40771. */
  40772. this.shiftKey = 'shiftKey' in eventDict ? eventDict['shiftKey'] : false;
  40773. /**
  40774. * @type {boolean}
  40775. */
  40776. this.metaKey = 'metaKey' in eventDict ? eventDict['metaKey'] : false;
  40777. /**
  40778. * @type {number}
  40779. */
  40780. this.button = 'button' in eventDict ? eventDict['button'] : 0;
  40781. /**
  40782. * @type {Node}
  40783. */
  40784. this.relatedTarget = 'relatedTarget' in eventDict ?
  40785. eventDict['relatedTarget'] : null;
  40786. // PointerEvent related properties
  40787. /**
  40788. * @const
  40789. * @type {number}
  40790. */
  40791. this.pointerId = 'pointerId' in eventDict ? eventDict['pointerId'] : 0;
  40792. /**
  40793. * @type {number}
  40794. */
  40795. this.width = 'width' in eventDict ? eventDict['width'] : 0;
  40796. /**
  40797. * @type {number}
  40798. */
  40799. this.height = 'height' in eventDict ? eventDict['height'] : 0;
  40800. /**
  40801. * @type {number}
  40802. */
  40803. this.tiltX = 'tiltX' in eventDict ? eventDict['tiltX'] : 0;
  40804. /**
  40805. * @type {number}
  40806. */
  40807. this.tiltY = 'tiltY' in eventDict ? eventDict['tiltY'] : 0;
  40808. /**
  40809. * @type {string}
  40810. */
  40811. this.pointerType = 'pointerType' in eventDict ? eventDict['pointerType'] : '';
  40812. /**
  40813. * @type {number}
  40814. */
  40815. this.hwTimestamp = 'hwTimestamp' in eventDict ? eventDict['hwTimestamp'] : 0;
  40816. /**
  40817. * @type {boolean}
  40818. */
  40819. this.isPrimary = 'isPrimary' in eventDict ? eventDict['isPrimary'] : false;
  40820. // keep the semantics of preventDefault
  40821. if (browserEvent.preventDefault) {
  40822. this.preventDefault = function() {
  40823. browserEvent.preventDefault();
  40824. };
  40825. }
  40826. };
  40827. goog.inherits(ol.pointer.PointerEvent, goog.events.Event);
  40828. /**
  40829. * @private
  40830. * @param {Object.<string, ?>} eventDict
  40831. * @return {number}
  40832. */
  40833. ol.pointer.PointerEvent.prototype.getButtons_ = function(eventDict) {
  40834. // According to the w3c spec,
  40835. // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-button
  40836. // MouseEvent.button == 0 can mean either no mouse button depressed, or the
  40837. // left mouse button depressed.
  40838. //
  40839. // As of now, the only way to distinguish between the two states of
  40840. // MouseEvent.button is by using the deprecated MouseEvent.which property, as
  40841. // this maps mouse buttons to positive integers > 0, and uses 0 to mean that
  40842. // no mouse button is held.
  40843. //
  40844. // MouseEvent.which is derived from MouseEvent.button at MouseEvent creation,
  40845. // but initMouseEvent does not expose an argument with which to set
  40846. // MouseEvent.which. Calling initMouseEvent with a buttonArg of 0 will set
  40847. // MouseEvent.button == 0 and MouseEvent.which == 1, breaking the expectations
  40848. // of app developers.
  40849. //
  40850. // The only way to propagate the correct state of MouseEvent.which and
  40851. // MouseEvent.button to a new MouseEvent.button == 0 and MouseEvent.which == 0
  40852. // is to call initMouseEvent with a buttonArg value of -1.
  40853. //
  40854. // This is fixed with DOM Level 4's use of buttons
  40855. var buttons;
  40856. if (eventDict.buttons || ol.pointer.PointerEvent.HAS_BUTTONS) {
  40857. buttons = eventDict.buttons;
  40858. } else {
  40859. switch (eventDict.which) {
  40860. case 1: buttons = 1; break;
  40861. case 2: buttons = 4; break;
  40862. case 3: buttons = 2; break;
  40863. default: buttons = 0;
  40864. }
  40865. }
  40866. return buttons;
  40867. };
  40868. /**
  40869. * @private
  40870. * @param {Object.<string, ?>} eventDict
  40871. * @param {number} buttons
  40872. * @return {number}
  40873. */
  40874. ol.pointer.PointerEvent.prototype.getPressure_ = function(eventDict, buttons) {
  40875. // Spec requires that pointers without pressure specified use 0.5 for down
  40876. // state and 0 for up state.
  40877. var pressure = 0;
  40878. if (eventDict.pressure) {
  40879. pressure = eventDict.pressure;
  40880. } else {
  40881. pressure = buttons ? 0.5 : 0;
  40882. }
  40883. return pressure;
  40884. };
  40885. /**
  40886. * Is the `buttons` property supported?
  40887. * @type {boolean}
  40888. */
  40889. ol.pointer.PointerEvent.HAS_BUTTONS = false;
  40890. /**
  40891. * Checks if the `buttons` property is supported.
  40892. */
  40893. (function() {
  40894. try {
  40895. var ev = new MouseEvent('click', {buttons: 1});
  40896. ol.pointer.PointerEvent.HAS_BUTTONS = ev.buttons === 1;
  40897. } catch (e) {
  40898. }
  40899. })();
  40900. // FIXME add tests for browser features (Modernizr?)
  40901. goog.provide('ol.dom');
  40902. goog.provide('ol.dom.BrowserFeature');
  40903. goog.require('goog.asserts');
  40904. goog.require('goog.dom');
  40905. goog.require('goog.dom.TagName');
  40906. goog.require('goog.userAgent');
  40907. goog.require('goog.vec.Mat4');
  40908. goog.require('ol');
  40909. /**
  40910. * Create an html canvas element and returns its 2d context.
  40911. * @param {number=} opt_width Canvas width.
  40912. * @param {number=} opt_height Canvas height.
  40913. * @return {CanvasRenderingContext2D}
  40914. */
  40915. ol.dom.createCanvasContext2D = function(opt_width, opt_height) {
  40916. var canvas = goog.dom.createElement(goog.dom.TagName.CANVAS);
  40917. if (opt_width) {
  40918. canvas.width = opt_width;
  40919. }
  40920. if (opt_height) {
  40921. canvas.height = opt_height;
  40922. }
  40923. return canvas.getContext('2d');
  40924. };
  40925. /**
  40926. * Detect 2d transform.
  40927. * Adapted from http://stackoverflow.com/q/5661671/130442
  40928. * http://caniuse.com/#feat=transforms2d
  40929. * @return {boolean}
  40930. */
  40931. ol.dom.canUseCssTransform = (function() {
  40932. var canUseCssTransform;
  40933. return function() {
  40934. if (canUseCssTransform === undefined) {
  40935. goog.asserts.assert(document.body,
  40936. 'document.body should not be null');
  40937. if (!goog.global.getComputedStyle) {
  40938. // this browser is ancient
  40939. canUseCssTransform = false;
  40940. } else {
  40941. var el = goog.dom.createElement(goog.dom.TagName.P),
  40942. has2d,
  40943. transforms = {
  40944. 'webkitTransform': '-webkit-transform',
  40945. 'OTransform': '-o-transform',
  40946. 'msTransform': '-ms-transform',
  40947. 'MozTransform': '-moz-transform',
  40948. 'transform': 'transform'
  40949. };
  40950. document.body.appendChild(el);
  40951. for (var t in transforms) {
  40952. if (t in el.style) {
  40953. el.style[t] = 'translate(1px,1px)';
  40954. has2d = goog.global.getComputedStyle(el).getPropertyValue(
  40955. transforms[t]);
  40956. }
  40957. }
  40958. goog.dom.removeNode(el);
  40959. canUseCssTransform = (has2d && has2d !== 'none');
  40960. }
  40961. }
  40962. return canUseCssTransform;
  40963. };
  40964. }());
  40965. /**
  40966. * Detect 3d transform.
  40967. * Adapted from http://stackoverflow.com/q/5661671/130442
  40968. * http://caniuse.com/#feat=transforms3d
  40969. * @return {boolean}
  40970. */
  40971. ol.dom.canUseCssTransform3D = (function() {
  40972. var canUseCssTransform3D;
  40973. return function() {
  40974. if (canUseCssTransform3D === undefined) {
  40975. goog.asserts.assert(document.body,
  40976. 'document.body should not be null');
  40977. if (!goog.global.getComputedStyle) {
  40978. // this browser is ancient
  40979. canUseCssTransform3D = false;
  40980. } else {
  40981. var el = goog.dom.createElement(goog.dom.TagName.P),
  40982. has3d,
  40983. transforms = {
  40984. 'webkitTransform': '-webkit-transform',
  40985. 'OTransform': '-o-transform',
  40986. 'msTransform': '-ms-transform',
  40987. 'MozTransform': '-moz-transform',
  40988. 'transform': 'transform'
  40989. };
  40990. document.body.appendChild(el);
  40991. for (var t in transforms) {
  40992. if (t in el.style) {
  40993. el.style[t] = 'translate3d(1px,1px,1px)';
  40994. has3d = goog.global.getComputedStyle(el).getPropertyValue(
  40995. transforms[t]);
  40996. }
  40997. }
  40998. goog.dom.removeNode(el);
  40999. canUseCssTransform3D = (has3d && has3d !== 'none');
  41000. }
  41001. }
  41002. return canUseCssTransform3D;
  41003. };
  41004. }());
  41005. /**
  41006. * @param {Element} element Element.
  41007. * @param {string} value Value.
  41008. */
  41009. ol.dom.setTransform = function(element, value) {
  41010. var style = element.style;
  41011. style.WebkitTransform = value;
  41012. style.MozTransform = value;
  41013. style.OTransform = value;
  41014. style.msTransform = value;
  41015. style.transform = value;
  41016. // IE 9+ seems to assume transform-origin: 100% 100%; for some unknown reason
  41017. if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9.0')) {
  41018. element.style.transformOrigin = '0 0';
  41019. }
  41020. };
  41021. /**
  41022. * @param {!Element} element Element.
  41023. * @param {goog.vec.Mat4.Number} transform Matrix.
  41024. * @param {number=} opt_precision Precision.
  41025. */
  41026. ol.dom.transformElement2D = function(element, transform, opt_precision) {
  41027. // using matrix() causes gaps in Chrome and Firefox on Mac OS X, so prefer
  41028. // matrix3d()
  41029. var i;
  41030. if (ol.dom.canUseCssTransform3D()) {
  41031. var value3D;
  41032. if (opt_precision !== undefined) {
  41033. /** @type {Array.<string>} */
  41034. var strings3D = new Array(16);
  41035. for (i = 0; i < 16; ++i) {
  41036. strings3D[i] = transform[i].toFixed(opt_precision);
  41037. }
  41038. value3D = strings3D.join(',');
  41039. } else {
  41040. value3D = transform.join(',');
  41041. }
  41042. ol.dom.setTransform(element, 'matrix3d(' + value3D + ')');
  41043. } else if (ol.dom.canUseCssTransform()) {
  41044. /** @type {Array.<number>} */
  41045. var transform2D = [
  41046. goog.vec.Mat4.getElement(transform, 0, 0),
  41047. goog.vec.Mat4.getElement(transform, 1, 0),
  41048. goog.vec.Mat4.getElement(transform, 0, 1),
  41049. goog.vec.Mat4.getElement(transform, 1, 1),
  41050. goog.vec.Mat4.getElement(transform, 0, 3),
  41051. goog.vec.Mat4.getElement(transform, 1, 3)
  41052. ];
  41053. var value2D;
  41054. if (opt_precision !== undefined) {
  41055. /** @type {Array.<string>} */
  41056. var strings2D = new Array(6);
  41057. for (i = 0; i < 6; ++i) {
  41058. strings2D[i] = transform2D[i].toFixed(opt_precision);
  41059. }
  41060. value2D = strings2D.join(',');
  41061. } else {
  41062. value2D = transform2D.join(',');
  41063. }
  41064. ol.dom.setTransform(element, 'matrix(' + value2D + ')');
  41065. } else {
  41066. element.style.left =
  41067. Math.round(goog.vec.Mat4.getElement(transform, 0, 3)) + 'px';
  41068. element.style.top =
  41069. Math.round(goog.vec.Mat4.getElement(transform, 1, 3)) + 'px';
  41070. // TODO: Add scaling here. This isn't quite as simple as multiplying
  41071. // width/height, because that only changes the container size, not the
  41072. // content size.
  41073. }
  41074. };
  41075. /**
  41076. * Get the current computed width for the given element including margin,
  41077. * padding and border.
  41078. * Equivalent to jQuery's `$(el).outerWidth(true)`.
  41079. * @param {!Element} element Element.
  41080. * @return {number}
  41081. */
  41082. ol.dom.outerWidth = function(element) {
  41083. var width = element.offsetWidth;
  41084. var style = element.currentStyle || window.getComputedStyle(element);
  41085. width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10);
  41086. return width;
  41087. };
  41088. /**
  41089. * Get the current computed height for the given element including margin,
  41090. * padding and border.
  41091. * Equivalent to jQuery's `$(el).outerHeight(true)`.
  41092. * @param {!Element} element Element.
  41093. * @return {number}
  41094. */
  41095. ol.dom.outerHeight = function(element) {
  41096. var height = element.offsetHeight;
  41097. var style = element.currentStyle || window.getComputedStyle(element);
  41098. height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10);
  41099. return height;
  41100. };
  41101. goog.provide('ol.webgl');
  41102. goog.provide('ol.webgl.WebGLContextEventType');
  41103. /**
  41104. * @const
  41105. * @private
  41106. * @type {Array.<string>}
  41107. */
  41108. ol.webgl.CONTEXT_IDS_ = [
  41109. 'experimental-webgl',
  41110. 'webgl',
  41111. 'webkit-3d',
  41112. 'moz-webgl'
  41113. ];
  41114. /**
  41115. * @enum {string}
  41116. */
  41117. ol.webgl.WebGLContextEventType = {
  41118. LOST: 'webglcontextlost',
  41119. RESTORED: 'webglcontextrestored'
  41120. };
  41121. /**
  41122. * @param {HTMLCanvasElement} canvas Canvas.
  41123. * @param {Object=} opt_attributes Attributes.
  41124. * @return {WebGLRenderingContext} WebGL rendering context.
  41125. */
  41126. ol.webgl.getContext = function(canvas, opt_attributes) {
  41127. var context, i, ii = ol.webgl.CONTEXT_IDS_.length;
  41128. for (i = 0; i < ii; ++i) {
  41129. try {
  41130. context = canvas.getContext(ol.webgl.CONTEXT_IDS_[i], opt_attributes);
  41131. if (context) {
  41132. return /** @type {!WebGLRenderingContext} */ (context);
  41133. }
  41134. } catch (e) {
  41135. }
  41136. }
  41137. return null;
  41138. };
  41139. goog.provide('ol.has');
  41140. goog.require('goog.dom');
  41141. goog.require('goog.dom.TagName');
  41142. goog.require('ol');
  41143. goog.require('ol.dom');
  41144. goog.require('ol.webgl');
  41145. /**
  41146. * The ratio between physical pixels and device-independent pixels
  41147. * (dips) on the device (`window.devicePixelRatio`).
  41148. * @const
  41149. * @type {number}
  41150. * @api stable
  41151. */
  41152. ol.has.DEVICE_PIXEL_RATIO = goog.global.devicePixelRatio || 1;
  41153. /**
  41154. * True if the browser's Canvas implementation implements {get,set}LineDash.
  41155. * @type {boolean}
  41156. */
  41157. ol.has.CANVAS_LINE_DASH = false;
  41158. /**
  41159. * True if both the library and browser support Canvas. Always `false`
  41160. * if `ol.ENABLE_CANVAS` is set to `false` at compile time.
  41161. * @const
  41162. * @type {boolean}
  41163. * @api stable
  41164. */
  41165. ol.has.CANVAS = ol.ENABLE_CANVAS && (
  41166. /**
  41167. * @return {boolean} Canvas supported.
  41168. */
  41169. function() {
  41170. if (!('HTMLCanvasElement' in goog.global)) {
  41171. return false;
  41172. }
  41173. try {
  41174. var context = ol.dom.createCanvasContext2D();
  41175. if (!context) {
  41176. return false;
  41177. } else {
  41178. if (context.setLineDash !== undefined) {
  41179. ol.has.CANVAS_LINE_DASH = true;
  41180. }
  41181. return true;
  41182. }
  41183. } catch (e) {
  41184. return false;
  41185. }
  41186. })();
  41187. /**
  41188. * Indicates if DeviceOrientation is supported in the user's browser.
  41189. * @const
  41190. * @type {boolean}
  41191. * @api stable
  41192. */
  41193. ol.has.DEVICE_ORIENTATION = 'DeviceOrientationEvent' in goog.global;
  41194. /**
  41195. * True if `ol.ENABLE_DOM` is set to `true` at compile time.
  41196. * @const
  41197. * @type {boolean}
  41198. */
  41199. ol.has.DOM = ol.ENABLE_DOM;
  41200. /**
  41201. * Is HTML5 geolocation supported in the current browser?
  41202. * @const
  41203. * @type {boolean}
  41204. * @api stable
  41205. */
  41206. ol.has.GEOLOCATION = 'geolocation' in goog.global.navigator;
  41207. /**
  41208. * True if browser supports touch events.
  41209. * @const
  41210. * @type {boolean}
  41211. * @api stable
  41212. */
  41213. ol.has.TOUCH = ol.ASSUME_TOUCH || 'ontouchstart' in goog.global;
  41214. /**
  41215. * True if browser supports pointer events.
  41216. * @const
  41217. * @type {boolean}
  41218. */
  41219. ol.has.POINTER = 'PointerEvent' in goog.global;
  41220. /**
  41221. * True if browser supports ms pointer events (IE 10).
  41222. * @const
  41223. * @type {boolean}
  41224. */
  41225. ol.has.MSPOINTER = !!(goog.global.navigator.msPointerEnabled);
  41226. /**
  41227. * True if both OpenLayers and browser support WebGL. Always `false`
  41228. * if `ol.ENABLE_WEBGL` is set to `false` at compile time.
  41229. * @const
  41230. * @type {boolean}
  41231. * @api stable
  41232. */
  41233. ol.has.WEBGL;
  41234. (function() {
  41235. if (ol.ENABLE_WEBGL) {
  41236. var hasWebGL = false;
  41237. var textureSize;
  41238. var /** @type {Array.<string>} */ extensions = [];
  41239. if ('WebGLRenderingContext' in goog.global) {
  41240. try {
  41241. var canvas = /** @type {HTMLCanvasElement} */
  41242. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  41243. var gl = ol.webgl.getContext(canvas, {
  41244. failIfMajorPerformanceCaveat: true
  41245. });
  41246. if (gl) {
  41247. hasWebGL = true;
  41248. textureSize = /** @type {number} */
  41249. (gl.getParameter(gl.MAX_TEXTURE_SIZE));
  41250. extensions = gl.getSupportedExtensions();
  41251. }
  41252. } catch (e) {}
  41253. }
  41254. ol.has.WEBGL = hasWebGL;
  41255. ol.WEBGL_EXTENSIONS = extensions;
  41256. ol.WEBGL_MAX_TEXTURE_SIZE = textureSize;
  41257. }
  41258. })();
  41259. goog.provide('ol.pointer.EventSource');
  41260. goog.require('goog.events.BrowserEvent');
  41261. /**
  41262. * @param {ol.pointer.PointerEventHandler} dispatcher
  41263. * @param {!Object.<string, function(goog.events.BrowserEvent)>} mapping
  41264. * @constructor
  41265. */
  41266. ol.pointer.EventSource = function(dispatcher, mapping) {
  41267. /**
  41268. * @type {ol.pointer.PointerEventHandler}
  41269. */
  41270. this.dispatcher = dispatcher;
  41271. /**
  41272. * @private
  41273. * @const
  41274. * @type {!Object.<string, function(goog.events.BrowserEvent)>}
  41275. */
  41276. this.mapping_ = mapping;
  41277. };
  41278. /**
  41279. * List of events supported by this source.
  41280. * @return {Array.<string>} Event names
  41281. */
  41282. ol.pointer.EventSource.prototype.getEvents = function() {
  41283. return Object.keys(this.mapping_);
  41284. };
  41285. /**
  41286. * Returns a mapping between the supported event types and
  41287. * the handlers that should handle an event.
  41288. * @return {Object.<string, function(goog.events.BrowserEvent)>}
  41289. * Event/Handler mapping
  41290. */
  41291. ol.pointer.EventSource.prototype.getMapping = function() {
  41292. return this.mapping_;
  41293. };
  41294. /**
  41295. * Returns the handler that should handle a given event type.
  41296. * @param {string} eventType
  41297. * @return {function(goog.events.BrowserEvent)} Handler
  41298. */
  41299. ol.pointer.EventSource.prototype.getHandlerForEvent = function(eventType) {
  41300. return this.mapping_[eventType];
  41301. };
  41302. // Based on https://github.com/Polymer/PointerEvents
  41303. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  41304. //
  41305. // Redistribution and use in source and binary forms, with or without
  41306. // modification, are permitted provided that the following conditions are
  41307. // met:
  41308. //
  41309. // * Redistributions of source code must retain the above copyright
  41310. // notice, this list of conditions and the following disclaimer.
  41311. // * Redistributions in binary form must reproduce the above
  41312. // copyright notice, this list of conditions and the following disclaimer
  41313. // in the documentation and/or other materials provided with the
  41314. // distribution.
  41315. // * Neither the name of Google Inc. nor the names of its
  41316. // contributors may be used to endorse or promote products derived from
  41317. // this software without specific prior written permission.
  41318. //
  41319. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  41320. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  41321. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41322. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  41323. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41324. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41325. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41326. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41327. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41328. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41329. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41330. goog.provide('ol.pointer.MouseSource');
  41331. goog.require('ol.pointer.EventSource');
  41332. /**
  41333. * @param {ol.pointer.PointerEventHandler} dispatcher
  41334. * @constructor
  41335. * @extends {ol.pointer.EventSource}
  41336. */
  41337. ol.pointer.MouseSource = function(dispatcher) {
  41338. var mapping = {
  41339. 'mousedown': this.mousedown,
  41340. 'mousemove': this.mousemove,
  41341. 'mouseup': this.mouseup,
  41342. 'mouseover': this.mouseover,
  41343. 'mouseout': this.mouseout
  41344. };
  41345. goog.base(this, dispatcher, mapping);
  41346. /**
  41347. * @const
  41348. * @type {Object.<string, goog.events.BrowserEvent|Object>}
  41349. */
  41350. this.pointerMap = dispatcher.pointerMap;
  41351. /**
  41352. * @const
  41353. * @type {Array.<ol.Pixel>}
  41354. */
  41355. this.lastTouches = [];
  41356. };
  41357. goog.inherits(ol.pointer.MouseSource, ol.pointer.EventSource);
  41358. /**
  41359. * @const
  41360. * @type {number}
  41361. */
  41362. ol.pointer.MouseSource.POINTER_ID = 1;
  41363. /**
  41364. * @const
  41365. * @type {string}
  41366. */
  41367. ol.pointer.MouseSource.POINTER_TYPE = 'mouse';
  41368. /**
  41369. * Radius around touchend that swallows mouse events.
  41370. *
  41371. * @const
  41372. * @type {number}
  41373. */
  41374. ol.pointer.MouseSource.DEDUP_DIST = 25;
  41375. /**
  41376. * Detect if a mouse event was simulated from a touch by
  41377. * checking if previously there was a touch event at the
  41378. * same position.
  41379. *
  41380. * FIXME - Known problem with the native Android browser on
  41381. * Samsung GT-I9100 (Android 4.1.2):
  41382. * In case the page is scrolled, this function does not work
  41383. * correctly when a canvas is used (WebGL or canvas renderer).
  41384. * Mouse listeners on canvas elements (for this browser), create
  41385. * two mouse events: One 'good' and one 'bad' one (on other browsers or
  41386. * when a div is used, there is only one event). For the 'bad' one,
  41387. * clientX/clientY and also pageX/pageY are wrong when the page
  41388. * is scrolled. Because of that, this function can not detect if
  41389. * the events were simulated from a touch event. As result, a
  41390. * pointer event at a wrong position is dispatched, which confuses
  41391. * the map interactions.
  41392. * It is unclear, how one can get the correct position for the event
  41393. * or detect that the positions are invalid.
  41394. *
  41395. * @private
  41396. * @param {goog.events.BrowserEvent} inEvent
  41397. * @return {boolean} True, if the event was generated by a touch.
  41398. */
  41399. ol.pointer.MouseSource.prototype.isEventSimulatedFromTouch_ =
  41400. function(inEvent) {
  41401. var lts = this.lastTouches;
  41402. var x = inEvent.clientX, y = inEvent.clientY;
  41403. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  41404. // simulated mouse events will be swallowed near a primary touchend
  41405. var dx = Math.abs(x - t[0]), dy = Math.abs(y - t[1]);
  41406. if (dx <= ol.pointer.MouseSource.DEDUP_DIST &&
  41407. dy <= ol.pointer.MouseSource.DEDUP_DIST) {
  41408. return true;
  41409. }
  41410. }
  41411. return false;
  41412. };
  41413. /**
  41414. * Creates a copy of the original event that will be used
  41415. * for the fake pointer event.
  41416. *
  41417. * @param {goog.events.BrowserEvent} inEvent
  41418. * @param {ol.pointer.PointerEventHandler} dispatcher
  41419. * @return {Object}
  41420. */
  41421. ol.pointer.MouseSource.prepareEvent = function(inEvent, dispatcher) {
  41422. var e = dispatcher.cloneEvent(inEvent, inEvent.getBrowserEvent());
  41423. // forward mouse preventDefault
  41424. var pd = e.preventDefault;
  41425. e.preventDefault = function() {
  41426. inEvent.preventDefault();
  41427. pd();
  41428. };
  41429. e.pointerId = ol.pointer.MouseSource.POINTER_ID;
  41430. e.isPrimary = true;
  41431. e.pointerType = ol.pointer.MouseSource.POINTER_TYPE;
  41432. return e;
  41433. };
  41434. /**
  41435. * Handler for `mousedown`.
  41436. *
  41437. * @param {goog.events.BrowserEvent} inEvent
  41438. */
  41439. ol.pointer.MouseSource.prototype.mousedown = function(inEvent) {
  41440. if (!this.isEventSimulatedFromTouch_(inEvent)) {
  41441. // TODO(dfreedman) workaround for some elements not sending mouseup
  41442. // http://crbug/149091
  41443. if (ol.pointer.MouseSource.POINTER_ID.toString() in this.pointerMap) {
  41444. this.cancel(inEvent);
  41445. }
  41446. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41447. this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()] = inEvent;
  41448. this.dispatcher.down(e, inEvent);
  41449. }
  41450. };
  41451. /**
  41452. * Handler for `mousemove`.
  41453. *
  41454. * @param {goog.events.BrowserEvent} inEvent
  41455. */
  41456. ol.pointer.MouseSource.prototype.mousemove = function(inEvent) {
  41457. if (!this.isEventSimulatedFromTouch_(inEvent)) {
  41458. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41459. this.dispatcher.move(e, inEvent);
  41460. }
  41461. };
  41462. /**
  41463. * Handler for `mouseup`.
  41464. *
  41465. * @param {goog.events.BrowserEvent} inEvent
  41466. */
  41467. ol.pointer.MouseSource.prototype.mouseup = function(inEvent) {
  41468. if (!this.isEventSimulatedFromTouch_(inEvent)) {
  41469. var p = this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()];
  41470. if (p && p.button === inEvent.button) {
  41471. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41472. this.dispatcher.up(e, inEvent);
  41473. this.cleanupMouse();
  41474. }
  41475. }
  41476. };
  41477. /**
  41478. * Handler for `mouseover`.
  41479. *
  41480. * @param {goog.events.BrowserEvent} inEvent
  41481. */
  41482. ol.pointer.MouseSource.prototype.mouseover = function(inEvent) {
  41483. if (!this.isEventSimulatedFromTouch_(inEvent)) {
  41484. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41485. this.dispatcher.enterOver(e, inEvent);
  41486. }
  41487. };
  41488. /**
  41489. * Handler for `mouseout`.
  41490. *
  41491. * @param {goog.events.BrowserEvent} inEvent
  41492. */
  41493. ol.pointer.MouseSource.prototype.mouseout = function(inEvent) {
  41494. if (!this.isEventSimulatedFromTouch_(inEvent)) {
  41495. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41496. this.dispatcher.leaveOut(e, inEvent);
  41497. }
  41498. };
  41499. /**
  41500. * Dispatches a `pointercancel` event.
  41501. *
  41502. * @param {goog.events.BrowserEvent} inEvent
  41503. */
  41504. ol.pointer.MouseSource.prototype.cancel = function(inEvent) {
  41505. var e = ol.pointer.MouseSource.prepareEvent(inEvent, this.dispatcher);
  41506. this.dispatcher.cancel(e, inEvent);
  41507. this.cleanupMouse();
  41508. };
  41509. /**
  41510. * Remove the mouse from the list of active pointers.
  41511. */
  41512. ol.pointer.MouseSource.prototype.cleanupMouse = function() {
  41513. delete this.pointerMap[ol.pointer.MouseSource.POINTER_ID.toString()];
  41514. };
  41515. // Based on https://github.com/Polymer/PointerEvents
  41516. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  41517. //
  41518. // Redistribution and use in source and binary forms, with or without
  41519. // modification, are permitted provided that the following conditions are
  41520. // met:
  41521. //
  41522. // * Redistributions of source code must retain the above copyright
  41523. // notice, this list of conditions and the following disclaimer.
  41524. // * Redistributions in binary form must reproduce the above
  41525. // copyright notice, this list of conditions and the following disclaimer
  41526. // in the documentation and/or other materials provided with the
  41527. // distribution.
  41528. // * Neither the name of Google Inc. nor the names of its
  41529. // contributors may be used to endorse or promote products derived from
  41530. // this software without specific prior written permission.
  41531. //
  41532. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  41533. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  41534. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41535. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  41536. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41537. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41538. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41539. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41540. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41541. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41542. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41543. goog.provide('ol.pointer.MsSource');
  41544. goog.require('ol.pointer.EventSource');
  41545. /**
  41546. * @param {ol.pointer.PointerEventHandler} dispatcher
  41547. * @constructor
  41548. * @extends {ol.pointer.EventSource}
  41549. */
  41550. ol.pointer.MsSource = function(dispatcher) {
  41551. var mapping = {
  41552. 'MSPointerDown': this.msPointerDown,
  41553. 'MSPointerMove': this.msPointerMove,
  41554. 'MSPointerUp': this.msPointerUp,
  41555. 'MSPointerOut': this.msPointerOut,
  41556. 'MSPointerOver': this.msPointerOver,
  41557. 'MSPointerCancel': this.msPointerCancel,
  41558. 'MSGotPointerCapture': this.msGotPointerCapture,
  41559. 'MSLostPointerCapture': this.msLostPointerCapture
  41560. };
  41561. goog.base(this, dispatcher, mapping);
  41562. /**
  41563. * @const
  41564. * @type {Object.<string, goog.events.BrowserEvent|Object>}
  41565. */
  41566. this.pointerMap = dispatcher.pointerMap;
  41567. /**
  41568. * @const
  41569. * @type {Array.<string>}
  41570. */
  41571. this.POINTER_TYPES = [
  41572. '',
  41573. 'unavailable',
  41574. 'touch',
  41575. 'pen',
  41576. 'mouse'
  41577. ];
  41578. };
  41579. goog.inherits(ol.pointer.MsSource, ol.pointer.EventSource);
  41580. /**
  41581. * Creates a copy of the original event that will be used
  41582. * for the fake pointer event.
  41583. *
  41584. * @private
  41585. * @param {goog.events.BrowserEvent} inEvent
  41586. * @return {Object}
  41587. */
  41588. ol.pointer.MsSource.prototype.prepareEvent_ = function(inEvent) {
  41589. var e = inEvent;
  41590. if (goog.isNumber(inEvent.getBrowserEvent().pointerType)) {
  41591. e = this.dispatcher.cloneEvent(inEvent, inEvent.getBrowserEvent());
  41592. e.pointerType = this.POINTER_TYPES[inEvent.getBrowserEvent().pointerType];
  41593. }
  41594. return e;
  41595. };
  41596. /**
  41597. * Remove this pointer from the list of active pointers.
  41598. * @param {number} pointerId
  41599. */
  41600. ol.pointer.MsSource.prototype.cleanup = function(pointerId) {
  41601. delete this.pointerMap[pointerId.toString()];
  41602. };
  41603. /**
  41604. * Handler for `msPointerDown`.
  41605. *
  41606. * @param {goog.events.BrowserEvent} inEvent
  41607. */
  41608. ol.pointer.MsSource.prototype.msPointerDown = function(inEvent) {
  41609. this.pointerMap[inEvent.getBrowserEvent().pointerId.toString()] = inEvent;
  41610. var e = this.prepareEvent_(inEvent);
  41611. this.dispatcher.down(e, inEvent);
  41612. };
  41613. /**
  41614. * Handler for `msPointerMove`.
  41615. *
  41616. * @param {goog.events.BrowserEvent} inEvent
  41617. */
  41618. ol.pointer.MsSource.prototype.msPointerMove = function(inEvent) {
  41619. var e = this.prepareEvent_(inEvent);
  41620. this.dispatcher.move(e, inEvent);
  41621. };
  41622. /**
  41623. * Handler for `msPointerUp`.
  41624. *
  41625. * @param {goog.events.BrowserEvent} inEvent
  41626. */
  41627. ol.pointer.MsSource.prototype.msPointerUp = function(inEvent) {
  41628. var e = this.prepareEvent_(inEvent);
  41629. this.dispatcher.up(e, inEvent);
  41630. this.cleanup(inEvent.getBrowserEvent().pointerId);
  41631. };
  41632. /**
  41633. * Handler for `msPointerOut`.
  41634. *
  41635. * @param {goog.events.BrowserEvent} inEvent
  41636. */
  41637. ol.pointer.MsSource.prototype.msPointerOut = function(inEvent) {
  41638. var e = this.prepareEvent_(inEvent);
  41639. this.dispatcher.leaveOut(e, inEvent);
  41640. };
  41641. /**
  41642. * Handler for `msPointerOver`.
  41643. *
  41644. * @param {goog.events.BrowserEvent} inEvent
  41645. */
  41646. ol.pointer.MsSource.prototype.msPointerOver = function(inEvent) {
  41647. var e = this.prepareEvent_(inEvent);
  41648. this.dispatcher.enterOver(e, inEvent);
  41649. };
  41650. /**
  41651. * Handler for `msPointerCancel`.
  41652. *
  41653. * @param {goog.events.BrowserEvent} inEvent
  41654. */
  41655. ol.pointer.MsSource.prototype.msPointerCancel = function(inEvent) {
  41656. var e = this.prepareEvent_(inEvent);
  41657. this.dispatcher.cancel(e, inEvent);
  41658. this.cleanup(inEvent.getBrowserEvent().pointerId);
  41659. };
  41660. /**
  41661. * Handler for `msLostPointerCapture`.
  41662. *
  41663. * @param {goog.events.BrowserEvent} inEvent
  41664. */
  41665. ol.pointer.MsSource.prototype.msLostPointerCapture = function(inEvent) {
  41666. var e = this.dispatcher.makeEvent('lostpointercapture',
  41667. inEvent.getBrowserEvent(), inEvent);
  41668. this.dispatcher.dispatchEvent(e);
  41669. };
  41670. /**
  41671. * Handler for `msGotPointerCapture`.
  41672. *
  41673. * @param {goog.events.BrowserEvent} inEvent
  41674. */
  41675. ol.pointer.MsSource.prototype.msGotPointerCapture = function(inEvent) {
  41676. var e = this.dispatcher.makeEvent('gotpointercapture',
  41677. inEvent.getBrowserEvent(), inEvent);
  41678. this.dispatcher.dispatchEvent(e);
  41679. };
  41680. // Based on https://github.com/Polymer/PointerEvents
  41681. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  41682. //
  41683. // Redistribution and use in source and binary forms, with or without
  41684. // modification, are permitted provided that the following conditions are
  41685. // met:
  41686. //
  41687. // * Redistributions of source code must retain the above copyright
  41688. // notice, this list of conditions and the following disclaimer.
  41689. // * Redistributions in binary form must reproduce the above
  41690. // copyright notice, this list of conditions and the following disclaimer
  41691. // in the documentation and/or other materials provided with the
  41692. // distribution.
  41693. // * Neither the name of Google Inc. nor the names of its
  41694. // contributors may be used to endorse or promote products derived from
  41695. // this software without specific prior written permission.
  41696. //
  41697. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  41698. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  41699. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41700. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  41701. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41702. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41703. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41704. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41705. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41706. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41707. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41708. goog.provide('ol.pointer.NativeSource');
  41709. goog.require('ol.pointer.EventSource');
  41710. /**
  41711. * @param {ol.pointer.PointerEventHandler} dispatcher
  41712. * @constructor
  41713. * @extends {ol.pointer.EventSource}
  41714. */
  41715. ol.pointer.NativeSource = function(dispatcher) {
  41716. var mapping = {
  41717. 'pointerdown': this.pointerDown,
  41718. 'pointermove': this.pointerMove,
  41719. 'pointerup': this.pointerUp,
  41720. 'pointerout': this.pointerOut,
  41721. 'pointerover': this.pointerOver,
  41722. 'pointercancel': this.pointerCancel,
  41723. 'gotpointercapture': this.gotPointerCapture,
  41724. 'lostpointercapture': this.lostPointerCapture
  41725. };
  41726. goog.base(this, dispatcher, mapping);
  41727. };
  41728. goog.inherits(ol.pointer.NativeSource, ol.pointer.EventSource);
  41729. /**
  41730. * Handler for `pointerdown`.
  41731. *
  41732. * @param {goog.events.BrowserEvent} inEvent
  41733. */
  41734. ol.pointer.NativeSource.prototype.pointerDown = function(inEvent) {
  41735. this.dispatcher.fireNativeEvent(inEvent);
  41736. };
  41737. /**
  41738. * Handler for `pointermove`.
  41739. *
  41740. * @param {goog.events.BrowserEvent} inEvent
  41741. */
  41742. ol.pointer.NativeSource.prototype.pointerMove = function(inEvent) {
  41743. this.dispatcher.fireNativeEvent(inEvent);
  41744. };
  41745. /**
  41746. * Handler for `pointerup`.
  41747. *
  41748. * @param {goog.events.BrowserEvent} inEvent
  41749. */
  41750. ol.pointer.NativeSource.prototype.pointerUp = function(inEvent) {
  41751. this.dispatcher.fireNativeEvent(inEvent);
  41752. };
  41753. /**
  41754. * Handler for `pointerout`.
  41755. *
  41756. * @param {goog.events.BrowserEvent} inEvent
  41757. */
  41758. ol.pointer.NativeSource.prototype.pointerOut = function(inEvent) {
  41759. this.dispatcher.fireNativeEvent(inEvent);
  41760. };
  41761. /**
  41762. * Handler for `pointerover`.
  41763. *
  41764. * @param {goog.events.BrowserEvent} inEvent
  41765. */
  41766. ol.pointer.NativeSource.prototype.pointerOver = function(inEvent) {
  41767. this.dispatcher.fireNativeEvent(inEvent);
  41768. };
  41769. /**
  41770. * Handler for `pointercancel`.
  41771. *
  41772. * @param {goog.events.BrowserEvent} inEvent
  41773. */
  41774. ol.pointer.NativeSource.prototype.pointerCancel = function(inEvent) {
  41775. this.dispatcher.fireNativeEvent(inEvent);
  41776. };
  41777. /**
  41778. * Handler for `lostpointercapture`.
  41779. *
  41780. * @param {goog.events.BrowserEvent} inEvent
  41781. */
  41782. ol.pointer.NativeSource.prototype.lostPointerCapture = function(inEvent) {
  41783. this.dispatcher.fireNativeEvent(inEvent);
  41784. };
  41785. /**
  41786. * Handler for `gotpointercapture`.
  41787. *
  41788. * @param {goog.events.BrowserEvent} inEvent
  41789. */
  41790. ol.pointer.NativeSource.prototype.gotPointerCapture = function(inEvent) {
  41791. this.dispatcher.fireNativeEvent(inEvent);
  41792. };
  41793. // Based on https://github.com/Polymer/PointerEvents
  41794. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  41795. //
  41796. // Redistribution and use in source and binary forms, with or without
  41797. // modification, are permitted provided that the following conditions are
  41798. // met:
  41799. //
  41800. // * Redistributions of source code must retain the above copyright
  41801. // notice, this list of conditions and the following disclaimer.
  41802. // * Redistributions in binary form must reproduce the above
  41803. // copyright notice, this list of conditions and the following disclaimer
  41804. // in the documentation and/or other materials provided with the
  41805. // distribution.
  41806. // * Neither the name of Google Inc. nor the names of its
  41807. // contributors may be used to endorse or promote products derived from
  41808. // this software without specific prior written permission.
  41809. //
  41810. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  41811. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  41812. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41813. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  41814. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41815. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41816. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41817. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41818. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41819. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41820. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41821. goog.provide('ol.pointer.TouchSource');
  41822. goog.require('goog.array');
  41823. goog.require('goog.object');
  41824. goog.require('ol');
  41825. goog.require('ol.pointer.EventSource');
  41826. goog.require('ol.pointer.MouseSource');
  41827. /**
  41828. * @constructor
  41829. * @param {ol.pointer.PointerEventHandler} dispatcher
  41830. * @param {ol.pointer.MouseSource} mouseSource
  41831. * @extends {ol.pointer.EventSource}
  41832. */
  41833. ol.pointer.TouchSource = function(dispatcher, mouseSource) {
  41834. var mapping = {
  41835. 'touchstart': this.touchstart,
  41836. 'touchmove': this.touchmove,
  41837. 'touchend': this.touchend,
  41838. 'touchcancel': this.touchcancel
  41839. };
  41840. goog.base(this, dispatcher, mapping);
  41841. /**
  41842. * @const
  41843. * @type {Object.<string, goog.events.BrowserEvent|Object>}
  41844. */
  41845. this.pointerMap = dispatcher.pointerMap;
  41846. /**
  41847. * @const
  41848. * @type {ol.pointer.MouseSource}
  41849. */
  41850. this.mouseSource = mouseSource;
  41851. /**
  41852. * @private
  41853. * @type {number|undefined}
  41854. */
  41855. this.firstTouchId_ = undefined;
  41856. /**
  41857. * @private
  41858. * @type {number}
  41859. */
  41860. this.clickCount_ = 0;
  41861. /**
  41862. * @private
  41863. * @type {number|undefined}
  41864. */
  41865. this.resetId_ = undefined;
  41866. };
  41867. goog.inherits(ol.pointer.TouchSource, ol.pointer.EventSource);
  41868. /**
  41869. * Mouse event timeout: This should be long enough to
  41870. * ignore compat mouse events made by touch.
  41871. * @const
  41872. * @type {number}
  41873. */
  41874. ol.pointer.TouchSource.DEDUP_TIMEOUT = 2500;
  41875. /**
  41876. * @const
  41877. * @type {number}
  41878. */
  41879. ol.pointer.TouchSource.CLICK_COUNT_TIMEOUT = 200;
  41880. /**
  41881. * @const
  41882. * @type {string}
  41883. */
  41884. ol.pointer.TouchSource.POINTER_TYPE = 'touch';
  41885. /**
  41886. * @private
  41887. * @param {Touch} inTouch
  41888. * @return {boolean} True, if this is the primary touch.
  41889. */
  41890. ol.pointer.TouchSource.prototype.isPrimaryTouch_ = function(inTouch) {
  41891. return this.firstTouchId_ === inTouch.identifier;
  41892. };
  41893. /**
  41894. * Set primary touch if there are no pointers, or the only pointer is the mouse.
  41895. * @param {Touch} inTouch
  41896. * @private
  41897. */
  41898. ol.pointer.TouchSource.prototype.setPrimaryTouch_ = function(inTouch) {
  41899. var count = goog.object.getCount(this.pointerMap);
  41900. if (count === 0 || (count === 1 && goog.object.containsKey(this.pointerMap,
  41901. ol.pointer.MouseSource.POINTER_ID.toString()))) {
  41902. this.firstTouchId_ = inTouch.identifier;
  41903. this.cancelResetClickCount_();
  41904. }
  41905. };
  41906. /**
  41907. * @private
  41908. * @param {Object} inPointer
  41909. */
  41910. ol.pointer.TouchSource.prototype.removePrimaryPointer_ = function(inPointer) {
  41911. if (inPointer.isPrimary) {
  41912. this.firstTouchId_ = undefined;
  41913. this.resetClickCount_();
  41914. }
  41915. };
  41916. /**
  41917. * @private
  41918. */
  41919. ol.pointer.TouchSource.prototype.resetClickCount_ = function() {
  41920. this.resetId_ = goog.global.setTimeout(
  41921. goog.bind(this.resetClickCountHandler_, this),
  41922. ol.pointer.TouchSource.CLICK_COUNT_TIMEOUT);
  41923. };
  41924. /**
  41925. * @private
  41926. */
  41927. ol.pointer.TouchSource.prototype.resetClickCountHandler_ = function() {
  41928. this.clickCount_ = 0;
  41929. this.resetId_ = undefined;
  41930. };
  41931. /**
  41932. * @private
  41933. */
  41934. ol.pointer.TouchSource.prototype.cancelResetClickCount_ = function() {
  41935. if (this.resetId_ !== undefined) {
  41936. goog.global.clearTimeout(this.resetId_);
  41937. }
  41938. };
  41939. /**
  41940. * @private
  41941. * @param {goog.events.BrowserEvent} browserEvent Browser event
  41942. * @param {Touch} inTouch Touch event
  41943. * @return {Object}
  41944. */
  41945. ol.pointer.TouchSource.prototype.touchToPointer_ =
  41946. function(browserEvent, inTouch) {
  41947. var e = this.dispatcher.cloneEvent(browserEvent, inTouch);
  41948. // Spec specifies that pointerId 1 is reserved for Mouse.
  41949. // Touch identifiers can start at 0.
  41950. // Add 2 to the touch identifier for compatibility.
  41951. e.pointerId = inTouch.identifier + 2;
  41952. // TODO: check if this is necessary?
  41953. //e.target = findTarget(e);
  41954. e.bubbles = true;
  41955. e.cancelable = true;
  41956. e.detail = this.clickCount_;
  41957. e.button = 0;
  41958. e.buttons = 1;
  41959. e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0;
  41960. e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0;
  41961. e.pressure = inTouch.webkitForce || inTouch.force || 0.5;
  41962. e.isPrimary = this.isPrimaryTouch_(inTouch);
  41963. e.pointerType = ol.pointer.TouchSource.POINTER_TYPE;
  41964. // make sure that the properties that are different for
  41965. // each `Touch` object are not copied from the BrowserEvent object
  41966. e.clientX = inTouch.clientX;
  41967. e.clientY = inTouch.clientY;
  41968. e.screenX = inTouch.screenX;
  41969. e.screenY = inTouch.screenY;
  41970. return e;
  41971. };
  41972. /**
  41973. * @private
  41974. * @param {goog.events.BrowserEvent} inEvent Touch event
  41975. * @param {function(goog.events.BrowserEvent, Object)} inFunction
  41976. */
  41977. ol.pointer.TouchSource.prototype.processTouches_ =
  41978. function(inEvent, inFunction) {
  41979. var touches = Array.prototype.slice.call(
  41980. inEvent.getBrowserEvent().changedTouches);
  41981. var count = touches.length;
  41982. function preventDefault() {
  41983. inEvent.preventDefault();
  41984. }
  41985. var i, pointer;
  41986. for (i = 0; i < count; ++i) {
  41987. pointer = this.touchToPointer_(inEvent, touches[i]);
  41988. // forward touch preventDefaults
  41989. pointer.preventDefault = preventDefault;
  41990. inFunction.call(this, inEvent, pointer);
  41991. }
  41992. };
  41993. /**
  41994. * @private
  41995. * @param {TouchList} touchList
  41996. * @param {number} searchId
  41997. * @return {boolean} True, if the `Touch` with the given id is in the list.
  41998. */
  41999. ol.pointer.TouchSource.prototype.findTouch_ = function(touchList, searchId) {
  42000. var l = touchList.length;
  42001. var touch;
  42002. for (var i = 0; i < l; i++) {
  42003. touch = touchList[i];
  42004. if (touch.identifier === searchId) {
  42005. return true;
  42006. }
  42007. }
  42008. return false;
  42009. };
  42010. /**
  42011. * In some instances, a touchstart can happen without a touchend. This
  42012. * leaves the pointermap in a broken state.
  42013. * Therefore, on every touchstart, we remove the touches that did not fire a
  42014. * touchend event.
  42015. * To keep state globally consistent, we fire a pointercancel for
  42016. * this "abandoned" touch
  42017. *
  42018. * @private
  42019. * @param {goog.events.BrowserEvent} inEvent
  42020. */
  42021. ol.pointer.TouchSource.prototype.vacuumTouches_ = function(inEvent) {
  42022. var touchList = inEvent.getBrowserEvent().touches;
  42023. // pointerMap.getCount() should be < touchList.length here,
  42024. // as the touchstart has not been processed yet.
  42025. var keys = goog.object.getKeys(this.pointerMap);
  42026. var count = keys.length;
  42027. if (count >= touchList.length) {
  42028. var d = [];
  42029. var i, key, value;
  42030. for (i = 0; i < count; ++i) {
  42031. key = keys[i];
  42032. value = this.pointerMap[key];
  42033. // Never remove pointerId == 1, which is mouse.
  42034. // Touch identifiers are 2 smaller than their pointerId, which is the
  42035. // index in pointermap.
  42036. if (key != ol.pointer.MouseSource.POINTER_ID &&
  42037. !this.findTouch_(touchList, key - 2)) {
  42038. d.push(value.out);
  42039. }
  42040. }
  42041. for (i = 0; i < d.length; ++i) {
  42042. this.cancelOut_(inEvent, d[i]);
  42043. }
  42044. }
  42045. };
  42046. /**
  42047. * Handler for `touchstart`, triggers `pointerover`,
  42048. * `pointerenter` and `pointerdown` events.
  42049. *
  42050. * @param {goog.events.BrowserEvent} inEvent
  42051. */
  42052. ol.pointer.TouchSource.prototype.touchstart = function(inEvent) {
  42053. this.vacuumTouches_(inEvent);
  42054. this.setPrimaryTouch_(inEvent.getBrowserEvent().changedTouches[0]);
  42055. this.dedupSynthMouse_(inEvent);
  42056. this.clickCount_++;
  42057. this.processTouches_(inEvent, this.overDown_);
  42058. };
  42059. /**
  42060. * @private
  42061. * @param {goog.events.BrowserEvent} browserEvent
  42062. * @param {Object} inPointer
  42063. */
  42064. ol.pointer.TouchSource.prototype.overDown_ = function(browserEvent, inPointer) {
  42065. this.pointerMap[inPointer.pointerId] = {
  42066. target: inPointer.target,
  42067. out: inPointer,
  42068. outTarget: inPointer.target
  42069. };
  42070. this.dispatcher.over(inPointer, browserEvent);
  42071. this.dispatcher.enter(inPointer, browserEvent);
  42072. this.dispatcher.down(inPointer, browserEvent);
  42073. };
  42074. /**
  42075. * Handler for `touchmove`.
  42076. *
  42077. * @param {goog.events.BrowserEvent} inEvent
  42078. */
  42079. ol.pointer.TouchSource.prototype.touchmove = function(inEvent) {
  42080. inEvent.preventDefault();
  42081. this.processTouches_(inEvent, this.moveOverOut_);
  42082. };
  42083. /**
  42084. * @private
  42085. * @param {goog.events.BrowserEvent} browserEvent
  42086. * @param {Object} inPointer
  42087. */
  42088. ol.pointer.TouchSource.prototype.moveOverOut_ =
  42089. function(browserEvent, inPointer) {
  42090. var event = inPointer;
  42091. var pointer = this.pointerMap[event.pointerId];
  42092. // a finger drifted off the screen, ignore it
  42093. if (!pointer) {
  42094. return;
  42095. }
  42096. var outEvent = pointer.out;
  42097. var outTarget = pointer.outTarget;
  42098. this.dispatcher.move(event, browserEvent);
  42099. if (outEvent && outTarget !== event.target) {
  42100. outEvent.relatedTarget = event.target;
  42101. event.relatedTarget = outTarget;
  42102. // recover from retargeting by shadow
  42103. outEvent.target = outTarget;
  42104. if (event.target) {
  42105. this.dispatcher.leaveOut(outEvent, browserEvent);
  42106. this.dispatcher.enterOver(event, browserEvent);
  42107. } else {
  42108. // clean up case when finger leaves the screen
  42109. event.target = outTarget;
  42110. event.relatedTarget = null;
  42111. this.cancelOut_(browserEvent, event);
  42112. }
  42113. }
  42114. pointer.out = event;
  42115. pointer.outTarget = event.target;
  42116. };
  42117. /**
  42118. * Handler for `touchend`, triggers `pointerup`,
  42119. * `pointerout` and `pointerleave` events.
  42120. *
  42121. * @param {goog.events.BrowserEvent} inEvent
  42122. */
  42123. ol.pointer.TouchSource.prototype.touchend = function(inEvent) {
  42124. this.dedupSynthMouse_(inEvent);
  42125. this.processTouches_(inEvent, this.upOut_);
  42126. };
  42127. /**
  42128. * @private
  42129. * @param {goog.events.BrowserEvent} browserEvent
  42130. * @param {Object} inPointer
  42131. */
  42132. ol.pointer.TouchSource.prototype.upOut_ = function(browserEvent, inPointer) {
  42133. this.dispatcher.up(inPointer, browserEvent);
  42134. this.dispatcher.out(inPointer, browserEvent);
  42135. this.dispatcher.leave(inPointer, browserEvent);
  42136. this.cleanUpPointer_(inPointer);
  42137. };
  42138. /**
  42139. * Handler for `touchcancel`, triggers `pointercancel`,
  42140. * `pointerout` and `pointerleave` events.
  42141. *
  42142. * @param {goog.events.BrowserEvent} inEvent
  42143. */
  42144. ol.pointer.TouchSource.prototype.touchcancel = function(inEvent) {
  42145. this.processTouches_(inEvent, this.cancelOut_);
  42146. };
  42147. /**
  42148. * @private
  42149. * @param {goog.events.BrowserEvent} browserEvent
  42150. * @param {Object} inPointer
  42151. */
  42152. ol.pointer.TouchSource.prototype.cancelOut_ =
  42153. function(browserEvent, inPointer) {
  42154. this.dispatcher.cancel(inPointer, browserEvent);
  42155. this.dispatcher.out(inPointer, browserEvent);
  42156. this.dispatcher.leave(inPointer, browserEvent);
  42157. this.cleanUpPointer_(inPointer);
  42158. };
  42159. /**
  42160. * @private
  42161. * @param {Object} inPointer
  42162. */
  42163. ol.pointer.TouchSource.prototype.cleanUpPointer_ = function(inPointer) {
  42164. delete this.pointerMap[inPointer.pointerId];
  42165. this.removePrimaryPointer_(inPointer);
  42166. };
  42167. /**
  42168. * Prevent synth mouse events from creating pointer events.
  42169. *
  42170. * @private
  42171. * @param {goog.events.BrowserEvent} inEvent
  42172. */
  42173. ol.pointer.TouchSource.prototype.dedupSynthMouse_ = function(inEvent) {
  42174. var lts = this.mouseSource.lastTouches;
  42175. var t = inEvent.getBrowserEvent().changedTouches[0];
  42176. // only the primary finger will synth mouse events
  42177. if (this.isPrimaryTouch_(t)) {
  42178. // remember x/y of last touch
  42179. var lt = /** @type {ol.Pixel} */ ([t.clientX, t.clientY]);
  42180. lts.push(lt);
  42181. goog.global.setTimeout(function() {
  42182. // remove touch after timeout
  42183. goog.array.remove(lts, lt);
  42184. }, ol.pointer.TouchSource.DEDUP_TIMEOUT);
  42185. }
  42186. };
  42187. // Based on https://github.com/Polymer/PointerEvents
  42188. // Copyright (c) 2013 The Polymer Authors. All rights reserved.
  42189. //
  42190. // Redistribution and use in source and binary forms, with or without
  42191. // modification, are permitted provided that the following conditions are
  42192. // met:
  42193. //
  42194. // * Redistributions of source code must retain the above copyright
  42195. // notice, this list of conditions and the following disclaimer.
  42196. // * Redistributions in binary form must reproduce the above
  42197. // copyright notice, this list of conditions and the following disclaimer
  42198. // in the documentation and/or other materials provided with the
  42199. // distribution.
  42200. // * Neither the name of Google Inc. nor the names of its
  42201. // contributors may be used to endorse or promote products derived from
  42202. // this software without specific prior written permission.
  42203. //
  42204. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  42205. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  42206. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  42207. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  42208. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  42209. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42210. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  42211. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  42212. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  42213. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  42214. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42215. goog.provide('ol.pointer.PointerEventHandler');
  42216. goog.require('goog.dom');
  42217. goog.require('goog.events');
  42218. goog.require('goog.events.BrowserEvent');
  42219. goog.require('goog.events.EventTarget');
  42220. goog.require('ol.has');
  42221. goog.require('ol.pointer.MouseSource');
  42222. goog.require('ol.pointer.MsSource');
  42223. goog.require('ol.pointer.NativeSource');
  42224. goog.require('ol.pointer.PointerEvent');
  42225. goog.require('ol.pointer.TouchSource');
  42226. /**
  42227. * @constructor
  42228. * @extends {goog.events.EventTarget}
  42229. * @param {Element|HTMLDocument} element Viewport element.
  42230. */
  42231. ol.pointer.PointerEventHandler = function(element) {
  42232. goog.base(this);
  42233. /**
  42234. * @const
  42235. * @private
  42236. * @type {Element|HTMLDocument}
  42237. */
  42238. this.element_ = element;
  42239. /**
  42240. * @const
  42241. * @type {Object.<string, goog.events.BrowserEvent|Object>}
  42242. */
  42243. this.pointerMap = {};
  42244. /**
  42245. * @type {Object.<string, function(goog.events.BrowserEvent)>}
  42246. * @private
  42247. */
  42248. this.eventMap_ = {};
  42249. /**
  42250. * @type {Array.<ol.pointer.EventSource>}
  42251. * @private
  42252. */
  42253. this.eventSourceList_ = [];
  42254. this.registerSources();
  42255. };
  42256. goog.inherits(ol.pointer.PointerEventHandler, goog.events.EventTarget);
  42257. /**
  42258. * Set up the event sources (mouse, touch and native pointers)
  42259. * that generate pointer events.
  42260. */
  42261. ol.pointer.PointerEventHandler.prototype.registerSources = function() {
  42262. if (ol.has.POINTER) {
  42263. this.registerSource('native', new ol.pointer.NativeSource(this));
  42264. } else if (ol.has.MSPOINTER) {
  42265. this.registerSource('ms', new ol.pointer.MsSource(this));
  42266. } else {
  42267. var mouseSource = new ol.pointer.MouseSource(this);
  42268. this.registerSource('mouse', mouseSource);
  42269. if (ol.has.TOUCH) {
  42270. this.registerSource('touch',
  42271. new ol.pointer.TouchSource(this, mouseSource));
  42272. }
  42273. }
  42274. // register events on the viewport element
  42275. this.register_();
  42276. };
  42277. /**
  42278. * Add a new event source that will generate pointer events.
  42279. *
  42280. * @param {string} name A name for the event source
  42281. * @param {ol.pointer.EventSource} source
  42282. */
  42283. ol.pointer.PointerEventHandler.prototype.registerSource =
  42284. function(name, source) {
  42285. var s = source;
  42286. var newEvents = s.getEvents();
  42287. if (newEvents) {
  42288. newEvents.forEach(function(e) {
  42289. var handler = s.getHandlerForEvent(e);
  42290. if (handler) {
  42291. this.eventMap_[e] = goog.bind(handler, s);
  42292. }
  42293. }, this);
  42294. this.eventSourceList_.push(s);
  42295. }
  42296. };
  42297. /**
  42298. * Set up the events for all registered event sources.
  42299. * @private
  42300. */
  42301. ol.pointer.PointerEventHandler.prototype.register_ = function() {
  42302. var l = this.eventSourceList_.length;
  42303. var eventSource;
  42304. for (var i = 0; i < l; i++) {
  42305. eventSource = this.eventSourceList_[i];
  42306. this.addEvents_(eventSource.getEvents());
  42307. }
  42308. };
  42309. /**
  42310. * Remove all registered events.
  42311. * @private
  42312. */
  42313. ol.pointer.PointerEventHandler.prototype.unregister_ = function() {
  42314. var l = this.eventSourceList_.length;
  42315. var eventSource;
  42316. for (var i = 0; i < l; i++) {
  42317. eventSource = this.eventSourceList_[i];
  42318. this.removeEvents_(eventSource.getEvents());
  42319. }
  42320. };
  42321. /**
  42322. * Calls the right handler for a new event.
  42323. * @private
  42324. * @param {goog.events.BrowserEvent} inEvent Browser event.
  42325. */
  42326. ol.pointer.PointerEventHandler.prototype.eventHandler_ = function(inEvent) {
  42327. var type = inEvent.type;
  42328. var handler = this.eventMap_[type];
  42329. if (handler) {
  42330. handler(inEvent);
  42331. }
  42332. };
  42333. /**
  42334. * Setup listeners for the given events.
  42335. * @private
  42336. * @param {Array.<string>} events List of events.
  42337. */
  42338. ol.pointer.PointerEventHandler.prototype.addEvents_ = function(events) {
  42339. events.forEach(function(eventName) {
  42340. goog.events.listen(this.element_, eventName,
  42341. this.eventHandler_, false, this);
  42342. }, this);
  42343. };
  42344. /**
  42345. * Unregister listeners for the given events.
  42346. * @private
  42347. * @param {Array.<string>} events List of events.
  42348. */
  42349. ol.pointer.PointerEventHandler.prototype.removeEvents_ = function(events) {
  42350. events.forEach(function(e) {
  42351. goog.events.unlisten(this.element_, e,
  42352. this.eventHandler_, false, this);
  42353. }, this);
  42354. };
  42355. /**
  42356. * Returns a snapshot of inEvent, with writable properties.
  42357. *
  42358. * @param {goog.events.BrowserEvent} browserEvent Browser event.
  42359. * @param {Event|Touch} inEvent An event that contains
  42360. * properties to copy.
  42361. * @return {Object} An object containing shallow copies of
  42362. * `inEvent`'s properties.
  42363. */
  42364. ol.pointer.PointerEventHandler.prototype.cloneEvent =
  42365. function(browserEvent, inEvent) {
  42366. var eventCopy = {}, p;
  42367. for (var i = 0, ii = ol.pointer.CLONE_PROPS.length; i < ii; i++) {
  42368. p = ol.pointer.CLONE_PROPS[i][0];
  42369. eventCopy[p] =
  42370. browserEvent[p] ||
  42371. inEvent[p] ||
  42372. ol.pointer.CLONE_PROPS[i][1];
  42373. }
  42374. return eventCopy;
  42375. };
  42376. // EVENTS
  42377. /**
  42378. * Triggers a 'pointerdown' event.
  42379. * @param {Object} pointerEventData
  42380. * @param {goog.events.BrowserEvent } browserEvent
  42381. */
  42382. ol.pointer.PointerEventHandler.prototype.down =
  42383. function(pointerEventData, browserEvent) {
  42384. this.fireEvent(ol.pointer.EventType.POINTERDOWN,
  42385. pointerEventData, browserEvent);
  42386. };
  42387. /**
  42388. * Triggers a 'pointermove' event.
  42389. * @param {Object} pointerEventData
  42390. * @param {goog.events.BrowserEvent } browserEvent
  42391. */
  42392. ol.pointer.PointerEventHandler.prototype.move =
  42393. function(pointerEventData, browserEvent) {
  42394. this.fireEvent(ol.pointer.EventType.POINTERMOVE,
  42395. pointerEventData, browserEvent);
  42396. };
  42397. /**
  42398. * Triggers a 'pointerup' event.
  42399. * @param {Object} pointerEventData
  42400. * @param {goog.events.BrowserEvent } browserEvent
  42401. */
  42402. ol.pointer.PointerEventHandler.prototype.up =
  42403. function(pointerEventData, browserEvent) {
  42404. this.fireEvent(ol.pointer.EventType.POINTERUP,
  42405. pointerEventData, browserEvent);
  42406. };
  42407. /**
  42408. * Triggers a 'pointerenter' event.
  42409. * @param {Object} pointerEventData
  42410. * @param {goog.events.BrowserEvent } browserEvent
  42411. */
  42412. ol.pointer.PointerEventHandler.prototype.enter =
  42413. function(pointerEventData, browserEvent) {
  42414. pointerEventData.bubbles = false;
  42415. this.fireEvent(ol.pointer.EventType.POINTERENTER,
  42416. pointerEventData, browserEvent);
  42417. };
  42418. /**
  42419. * Triggers a 'pointerleave' event.
  42420. * @param {Object} pointerEventData
  42421. * @param {goog.events.BrowserEvent } browserEvent
  42422. */
  42423. ol.pointer.PointerEventHandler.prototype.leave =
  42424. function(pointerEventData, browserEvent) {
  42425. pointerEventData.bubbles = false;
  42426. this.fireEvent(ol.pointer.EventType.POINTERLEAVE,
  42427. pointerEventData, browserEvent);
  42428. };
  42429. /**
  42430. * Triggers a 'pointerover' event.
  42431. * @param {Object} pointerEventData
  42432. * @param {goog.events.BrowserEvent } browserEvent
  42433. */
  42434. ol.pointer.PointerEventHandler.prototype.over =
  42435. function(pointerEventData, browserEvent) {
  42436. pointerEventData.bubbles = true;
  42437. this.fireEvent(ol.pointer.EventType.POINTEROVER,
  42438. pointerEventData, browserEvent);
  42439. };
  42440. /**
  42441. * Triggers a 'pointerout' event.
  42442. * @param {Object} pointerEventData
  42443. * @param {goog.events.BrowserEvent } browserEvent
  42444. */
  42445. ol.pointer.PointerEventHandler.prototype.out =
  42446. function(pointerEventData, browserEvent) {
  42447. pointerEventData.bubbles = true;
  42448. this.fireEvent(ol.pointer.EventType.POINTEROUT,
  42449. pointerEventData, browserEvent);
  42450. };
  42451. /**
  42452. * Triggers a 'pointercancel' event.
  42453. * @param {Object} pointerEventData
  42454. * @param {goog.events.BrowserEvent } browserEvent
  42455. */
  42456. ol.pointer.PointerEventHandler.prototype.cancel =
  42457. function(pointerEventData, browserEvent) {
  42458. this.fireEvent(ol.pointer.EventType.POINTERCANCEL,
  42459. pointerEventData, browserEvent);
  42460. };
  42461. /**
  42462. * Triggers a combination of 'pointerout' and 'pointerleave' events.
  42463. * @param {Object} pointerEventData
  42464. * @param {goog.events.BrowserEvent } browserEvent
  42465. */
  42466. ol.pointer.PointerEventHandler.prototype.leaveOut =
  42467. function(pointerEventData, browserEvent) {
  42468. this.out(pointerEventData, browserEvent);
  42469. if (!this.contains_(
  42470. pointerEventData.target,
  42471. pointerEventData.relatedTarget)) {
  42472. this.leave(pointerEventData, browserEvent);
  42473. }
  42474. };
  42475. /**
  42476. * Triggers a combination of 'pointerover' and 'pointerevents' events.
  42477. * @param {Object} pointerEventData
  42478. * @param {goog.events.BrowserEvent } browserEvent
  42479. */
  42480. ol.pointer.PointerEventHandler.prototype.enterOver =
  42481. function(pointerEventData, browserEvent) {
  42482. this.over(pointerEventData, browserEvent);
  42483. if (!this.contains_(
  42484. pointerEventData.target,
  42485. pointerEventData.relatedTarget)) {
  42486. this.enter(pointerEventData, browserEvent);
  42487. }
  42488. };
  42489. /**
  42490. * @private
  42491. * @param {Element} container
  42492. * @param {Element} contained
  42493. * @return {boolean} Returns true if the container element
  42494. * contains the other element.
  42495. */
  42496. ol.pointer.PointerEventHandler.prototype.contains_ =
  42497. function(container, contained) {
  42498. if (!contained) {
  42499. return false;
  42500. }
  42501. return goog.dom.contains(container, contained);
  42502. };
  42503. // EVENT CREATION AND TRACKING
  42504. /**
  42505. * Creates a new Event of type `inType`, based on the information in
  42506. * `pointerEventData`.
  42507. *
  42508. * @param {string} inType A string representing the type of event to create.
  42509. * @param {Object} pointerEventData
  42510. * @param {goog.events.BrowserEvent } browserEvent
  42511. * @return {ol.pointer.PointerEvent} A PointerEvent of type `inType`.
  42512. */
  42513. ol.pointer.PointerEventHandler.prototype.makeEvent =
  42514. function(inType, pointerEventData, browserEvent) {
  42515. return new ol.pointer.PointerEvent(inType, browserEvent, pointerEventData);
  42516. };
  42517. /**
  42518. * Make and dispatch an event in one call.
  42519. * @param {string} inType A string representing the type of event.
  42520. * @param {Object} pointerEventData
  42521. * @param {goog.events.BrowserEvent } browserEvent
  42522. */
  42523. ol.pointer.PointerEventHandler.prototype.fireEvent =
  42524. function(inType, pointerEventData, browserEvent) {
  42525. var e = this.makeEvent(inType, pointerEventData, browserEvent);
  42526. this.dispatchEvent(e);
  42527. };
  42528. /**
  42529. * Creates a pointer event from a native pointer event
  42530. * and dispatches this event.
  42531. * @param {goog.events.BrowserEvent} nativeEvent A platform event with a target.
  42532. */
  42533. ol.pointer.PointerEventHandler.prototype.fireNativeEvent =
  42534. function(nativeEvent) {
  42535. var e = this.makeEvent(nativeEvent.type, nativeEvent.getBrowserEvent(),
  42536. nativeEvent);
  42537. this.dispatchEvent(e);
  42538. };
  42539. /**
  42540. * Wrap a native mouse event into a pointer event.
  42541. * This proxy method is required for the legacy IE support.
  42542. * @param {string} eventType The pointer event type.
  42543. * @param {goog.events.BrowserEvent} browserEvent
  42544. * @return {ol.pointer.PointerEvent}
  42545. */
  42546. ol.pointer.PointerEventHandler.prototype.wrapMouseEvent =
  42547. function(eventType, browserEvent) {
  42548. var pointerEvent = this.makeEvent(
  42549. eventType,
  42550. ol.pointer.MouseSource.prepareEvent(browserEvent, this),
  42551. browserEvent
  42552. );
  42553. return pointerEvent;
  42554. };
  42555. /**
  42556. * @inheritDoc
  42557. */
  42558. ol.pointer.PointerEventHandler.prototype.disposeInternal = function() {
  42559. this.unregister_();
  42560. goog.base(this, 'disposeInternal');
  42561. };
  42562. /**
  42563. * Constants for event names.
  42564. * @enum {string}
  42565. */
  42566. ol.pointer.EventType = {
  42567. POINTERMOVE: 'pointermove',
  42568. POINTERDOWN: 'pointerdown',
  42569. POINTERUP: 'pointerup',
  42570. POINTEROVER: 'pointerover',
  42571. POINTEROUT: 'pointerout',
  42572. POINTERENTER: 'pointerenter',
  42573. POINTERLEAVE: 'pointerleave',
  42574. POINTERCANCEL: 'pointercancel'
  42575. };
  42576. /**
  42577. * Properties to copy when cloning an event, with default values.
  42578. * @type {Array.<Array>}
  42579. */
  42580. ol.pointer.CLONE_PROPS = [
  42581. // MouseEvent
  42582. ['bubbles', false],
  42583. ['cancelable', false],
  42584. ['view', null],
  42585. ['detail', null],
  42586. ['screenX', 0],
  42587. ['screenY', 0],
  42588. ['clientX', 0],
  42589. ['clientY', 0],
  42590. ['ctrlKey', false],
  42591. ['altKey', false],
  42592. ['shiftKey', false],
  42593. ['metaKey', false],
  42594. ['button', 0],
  42595. ['relatedTarget', null],
  42596. // DOM Level 3
  42597. ['buttons', 0],
  42598. // PointerEvent
  42599. ['pointerId', 0],
  42600. ['width', 0],
  42601. ['height', 0],
  42602. ['pressure', 0],
  42603. ['tiltX', 0],
  42604. ['tiltY', 0],
  42605. ['pointerType', ''],
  42606. ['hwTimestamp', 0],
  42607. ['isPrimary', false],
  42608. // event instance
  42609. ['type', ''],
  42610. ['target', null],
  42611. ['currentTarget', null],
  42612. ['which', 0]
  42613. ];
  42614. goog.provide('ol.MapBrowserEvent');
  42615. goog.provide('ol.MapBrowserEvent.EventType');
  42616. goog.provide('ol.MapBrowserEventHandler');
  42617. goog.provide('ol.MapBrowserPointerEvent');
  42618. goog.require('goog.asserts');
  42619. goog.require('goog.events');
  42620. goog.require('goog.events.BrowserEvent');
  42621. goog.require('goog.events.EventTarget');
  42622. goog.require('goog.events.EventType');
  42623. goog.require('goog.object');
  42624. goog.require('ol');
  42625. goog.require('ol.Coordinate');
  42626. goog.require('ol.MapEvent');
  42627. goog.require('ol.Pixel');
  42628. goog.require('ol.pointer.PointerEvent');
  42629. goog.require('ol.pointer.PointerEventHandler');
  42630. /**
  42631. * @classdesc
  42632. * Events emitted as map browser events are instances of this type.
  42633. * See {@link ol.Map} for which events trigger a map browser event.
  42634. *
  42635. * @constructor
  42636. * @extends {ol.MapEvent}
  42637. * @implements {oli.MapBrowserEvent}
  42638. * @param {string} type Event type.
  42639. * @param {ol.Map} map Map.
  42640. * @param {goog.events.BrowserEvent} browserEvent Browser event.
  42641. * @param {boolean=} opt_dragging Is the map currently being dragged?
  42642. * @param {?olx.FrameState=} opt_frameState Frame state.
  42643. */
  42644. ol.MapBrowserEvent = function(type, map, browserEvent, opt_dragging,
  42645. opt_frameState) {
  42646. goog.base(this, type, map, opt_frameState);
  42647. /**
  42648. * @const
  42649. * @type {goog.events.BrowserEvent}
  42650. */
  42651. this.browserEvent = browserEvent;
  42652. /**
  42653. * The original browser event.
  42654. * @const
  42655. * @type {Event}
  42656. * @api stable
  42657. */
  42658. this.originalEvent = browserEvent.getBrowserEvent();
  42659. /**
  42660. * The pixel of the original browser event.
  42661. * @type {ol.Pixel}
  42662. * @api stable
  42663. */
  42664. this.pixel = map.getEventPixel(this.originalEvent);
  42665. /**
  42666. * The coordinate of the original browser event.
  42667. * @type {ol.Coordinate}
  42668. * @api stable
  42669. */
  42670. this.coordinate = map.getCoordinateFromPixel(this.pixel);
  42671. /**
  42672. * Indicates if the map is currently being dragged. Only set for
  42673. * `POINTERDRAG` and `POINTERMOVE` events. Default is `false`.
  42674. *
  42675. * @type {boolean}
  42676. * @api stable
  42677. */
  42678. this.dragging = opt_dragging !== undefined ? opt_dragging : false;
  42679. };
  42680. goog.inherits(ol.MapBrowserEvent, ol.MapEvent);
  42681. /**
  42682. * Prevents the default browser action.
  42683. * @see https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
  42684. * @override
  42685. * @api stable
  42686. */
  42687. ol.MapBrowserEvent.prototype.preventDefault = function() {
  42688. goog.base(this, 'preventDefault');
  42689. this.browserEvent.preventDefault();
  42690. };
  42691. /**
  42692. * Prevents further propagation of the current event.
  42693. * @see https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
  42694. * @override
  42695. * @api stable
  42696. */
  42697. ol.MapBrowserEvent.prototype.stopPropagation = function() {
  42698. goog.base(this, 'stopPropagation');
  42699. this.browserEvent.stopPropagation();
  42700. };
  42701. /**
  42702. * @constructor
  42703. * @extends {ol.MapBrowserEvent}
  42704. * @param {string} type Event type.
  42705. * @param {ol.Map} map Map.
  42706. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42707. * @param {boolean=} opt_dragging Is the map currently being dragged?
  42708. * @param {?olx.FrameState=} opt_frameState Frame state.
  42709. */
  42710. ol.MapBrowserPointerEvent = function(type, map, pointerEvent, opt_dragging,
  42711. opt_frameState) {
  42712. goog.base(this, type, map, pointerEvent.browserEvent, opt_dragging,
  42713. opt_frameState);
  42714. /**
  42715. * @const
  42716. * @type {ol.pointer.PointerEvent}
  42717. */
  42718. this.pointerEvent = pointerEvent;
  42719. };
  42720. goog.inherits(ol.MapBrowserPointerEvent, ol.MapBrowserEvent);
  42721. /**
  42722. * @param {ol.Map} map The map with the viewport to listen to events on.
  42723. * @constructor
  42724. * @extends {goog.events.EventTarget}
  42725. */
  42726. ol.MapBrowserEventHandler = function(map) {
  42727. goog.base(this);
  42728. /**
  42729. * This is the element that we will listen to the real events on.
  42730. * @type {ol.Map}
  42731. * @private
  42732. */
  42733. this.map_ = map;
  42734. /**
  42735. * @type {number}
  42736. * @private
  42737. */
  42738. this.clickTimeoutId_ = 0;
  42739. /**
  42740. * @type {boolean}
  42741. * @private
  42742. */
  42743. this.dragging_ = false;
  42744. /**
  42745. * @type {Array.<goog.events.Key>}
  42746. * @private
  42747. */
  42748. this.dragListenerKeys_ = null;
  42749. /**
  42750. * @type {goog.events.Key}
  42751. * @private
  42752. */
  42753. this.pointerdownListenerKey_ = null;
  42754. /**
  42755. * The most recent "down" type event (or null if none have occurred).
  42756. * Set on pointerdown.
  42757. * @type {ol.pointer.PointerEvent}
  42758. * @private
  42759. */
  42760. this.down_ = null;
  42761. var element = this.map_.getViewport();
  42762. /**
  42763. * @type {number}
  42764. * @private
  42765. */
  42766. this.activePointers_ = 0;
  42767. /**
  42768. * @type {Object.<number, boolean>}
  42769. * @private
  42770. */
  42771. this.trackedTouches_ = {};
  42772. /**
  42773. * Event handler which generates pointer events for
  42774. * the viewport element.
  42775. *
  42776. * @type {ol.pointer.PointerEventHandler}
  42777. * @private
  42778. */
  42779. this.pointerEventHandler_ = new ol.pointer.PointerEventHandler(element);
  42780. /**
  42781. * Event handler which generates pointer events for
  42782. * the document (used when dragging).
  42783. *
  42784. * @type {ol.pointer.PointerEventHandler}
  42785. * @private
  42786. */
  42787. this.documentPointerEventHandler_ = null;
  42788. this.pointerdownListenerKey_ = goog.events.listen(this.pointerEventHandler_,
  42789. ol.pointer.EventType.POINTERDOWN,
  42790. this.handlePointerDown_, false, this);
  42791. this.relayedListenerKey_ = goog.events.listen(this.pointerEventHandler_,
  42792. ol.pointer.EventType.POINTERMOVE,
  42793. this.relayEvent_, false, this);
  42794. };
  42795. goog.inherits(ol.MapBrowserEventHandler, goog.events.EventTarget);
  42796. /**
  42797. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42798. * @private
  42799. */
  42800. ol.MapBrowserEventHandler.prototype.emulateClick_ = function(pointerEvent) {
  42801. var newEvent;
  42802. newEvent = new ol.MapBrowserPointerEvent(
  42803. ol.MapBrowserEvent.EventType.CLICK, this.map_, pointerEvent);
  42804. this.dispatchEvent(newEvent);
  42805. if (this.clickTimeoutId_ !== 0) {
  42806. // double-click
  42807. goog.global.clearTimeout(this.clickTimeoutId_);
  42808. this.clickTimeoutId_ = 0;
  42809. newEvent = new ol.MapBrowserPointerEvent(
  42810. ol.MapBrowserEvent.EventType.DBLCLICK, this.map_, pointerEvent);
  42811. this.dispatchEvent(newEvent);
  42812. } else {
  42813. // click
  42814. this.clickTimeoutId_ = goog.global.setTimeout(goog.bind(function() {
  42815. this.clickTimeoutId_ = 0;
  42816. var newEvent = new ol.MapBrowserPointerEvent(
  42817. ol.MapBrowserEvent.EventType.SINGLECLICK, this.map_, pointerEvent);
  42818. this.dispatchEvent(newEvent);
  42819. }, this), 250);
  42820. }
  42821. };
  42822. /**
  42823. * Keeps track on how many pointers are currently active.
  42824. *
  42825. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42826. * @private
  42827. */
  42828. ol.MapBrowserEventHandler.prototype.updateActivePointers_ =
  42829. function(pointerEvent) {
  42830. var event = pointerEvent;
  42831. if (event.type == ol.MapBrowserEvent.EventType.POINTERUP ||
  42832. event.type == ol.MapBrowserEvent.EventType.POINTERCANCEL) {
  42833. delete this.trackedTouches_[event.pointerId];
  42834. } else if (event.type == ol.MapBrowserEvent.EventType.POINTERDOWN) {
  42835. this.trackedTouches_[event.pointerId] = true;
  42836. }
  42837. this.activePointers_ = goog.object.getCount(this.trackedTouches_);
  42838. };
  42839. /**
  42840. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42841. * @private
  42842. */
  42843. ol.MapBrowserEventHandler.prototype.handlePointerUp_ = function(pointerEvent) {
  42844. this.updateActivePointers_(pointerEvent);
  42845. var newEvent = new ol.MapBrowserPointerEvent(
  42846. ol.MapBrowserEvent.EventType.POINTERUP, this.map_, pointerEvent);
  42847. this.dispatchEvent(newEvent);
  42848. // We emulate click events on left mouse button click, touch contact, and pen
  42849. // contact. isMouseActionButton returns true in these cases (evt.button is set
  42850. // to 0).
  42851. // See http://www.w3.org/TR/pointerevents/#button-states
  42852. if (!this.dragging_ && this.isMouseActionButton_(pointerEvent)) {
  42853. goog.asserts.assert(this.down_, 'this.down_ must be truthy');
  42854. this.emulateClick_(this.down_);
  42855. }
  42856. goog.asserts.assert(this.activePointers_ >= 0,
  42857. 'this.activePointers_ should be equal to or larger than 0');
  42858. if (this.activePointers_ === 0) {
  42859. this.dragListenerKeys_.forEach(goog.events.unlistenByKey);
  42860. this.dragListenerKeys_ = null;
  42861. this.dragging_ = false;
  42862. this.down_ = null;
  42863. goog.dispose(this.documentPointerEventHandler_);
  42864. this.documentPointerEventHandler_ = null;
  42865. }
  42866. };
  42867. /**
  42868. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42869. * @return {boolean} If the left mouse button was pressed.
  42870. * @private
  42871. */
  42872. ol.MapBrowserEventHandler.prototype.isMouseActionButton_ =
  42873. function(pointerEvent) {
  42874. return pointerEvent.button === 0;
  42875. };
  42876. /**
  42877. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42878. * @private
  42879. */
  42880. ol.MapBrowserEventHandler.prototype.handlePointerDown_ =
  42881. function(pointerEvent) {
  42882. this.updateActivePointers_(pointerEvent);
  42883. var newEvent = new ol.MapBrowserPointerEvent(
  42884. ol.MapBrowserEvent.EventType.POINTERDOWN, this.map_, pointerEvent);
  42885. this.dispatchEvent(newEvent);
  42886. this.down_ = pointerEvent;
  42887. if (!this.dragListenerKeys_) {
  42888. /* Set up a pointer event handler on the `document`,
  42889. * which is required when the pointer is moved outside
  42890. * the viewport when dragging.
  42891. */
  42892. this.documentPointerEventHandler_ =
  42893. new ol.pointer.PointerEventHandler(document);
  42894. this.dragListenerKeys_ = [
  42895. goog.events.listen(this.documentPointerEventHandler_,
  42896. ol.MapBrowserEvent.EventType.POINTERMOVE,
  42897. this.handlePointerMove_, false, this),
  42898. goog.events.listen(this.documentPointerEventHandler_,
  42899. ol.MapBrowserEvent.EventType.POINTERUP,
  42900. this.handlePointerUp_, false, this),
  42901. /* Note that the listener for `pointercancel is set up on
  42902. * `pointerEventHandler_` and not `documentPointerEventHandler_` like
  42903. * the `pointerup` and `pointermove` listeners.
  42904. *
  42905. * The reason for this is the following: `TouchSource.vacuumTouches_()`
  42906. * issues `pointercancel` events, when there was no `touchend` for a
  42907. * `touchstart`. Now, let's say a first `touchstart` is registered on
  42908. * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up.
  42909. * But `documentPointerEventHandler_` doesn't know about the first
  42910. * `touchstart`. If there is no `touchend` for the `touchstart`, we can
  42911. * only receive a `touchcancel` from `pointerEventHandler_`, because it is
  42912. * only registered there.
  42913. */
  42914. goog.events.listen(this.pointerEventHandler_,
  42915. ol.MapBrowserEvent.EventType.POINTERCANCEL,
  42916. this.handlePointerUp_, false, this)
  42917. ];
  42918. }
  42919. };
  42920. /**
  42921. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42922. * @private
  42923. */
  42924. ol.MapBrowserEventHandler.prototype.handlePointerMove_ =
  42925. function(pointerEvent) {
  42926. // Fix IE10 on windows Surface : When you tap the tablet, it triggers
  42927. // multiple pointermove events between pointerdown and pointerup with
  42928. // the exact same coordinates of the pointerdown event. To avoid a
  42929. // 'false' touchmove event to be dispatched , we test if the pointer
  42930. // effectively moved.
  42931. if (this.isMoving_(pointerEvent)) {
  42932. this.dragging_ = true;
  42933. var newEvent = new ol.MapBrowserPointerEvent(
  42934. ol.MapBrowserEvent.EventType.POINTERDRAG, this.map_, pointerEvent,
  42935. this.dragging_);
  42936. this.dispatchEvent(newEvent);
  42937. }
  42938. // Some native android browser triggers mousemove events during small period
  42939. // of time. See: https://code.google.com/p/android/issues/detail?id=5491 or
  42940. // https://code.google.com/p/android/issues/detail?id=19827
  42941. // ex: Galaxy Tab P3110 + Android 4.1.1
  42942. pointerEvent.preventDefault();
  42943. };
  42944. /**
  42945. * Wrap and relay a pointer event. Note that this requires that the type
  42946. * string for the MapBrowserPointerEvent matches the PointerEvent type.
  42947. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42948. * @private
  42949. */
  42950. ol.MapBrowserEventHandler.prototype.relayEvent_ = function(pointerEvent) {
  42951. var dragging = !!(this.down_ && this.isMoving_(pointerEvent));
  42952. this.dispatchEvent(new ol.MapBrowserPointerEvent(
  42953. pointerEvent.type, this.map_, pointerEvent, dragging));
  42954. };
  42955. /**
  42956. * @param {ol.pointer.PointerEvent} pointerEvent Pointer event.
  42957. * @return {boolean}
  42958. * @private
  42959. */
  42960. ol.MapBrowserEventHandler.prototype.isMoving_ = function(pointerEvent) {
  42961. return pointerEvent.clientX != this.down_.clientX ||
  42962. pointerEvent.clientY != this.down_.clientY;
  42963. };
  42964. /**
  42965. * @inheritDoc
  42966. */
  42967. ol.MapBrowserEventHandler.prototype.disposeInternal = function() {
  42968. if (this.relayedListenerKey_) {
  42969. goog.events.unlistenByKey(this.relayedListenerKey_);
  42970. this.relayedListenerKey_ = null;
  42971. }
  42972. if (this.pointerdownListenerKey_) {
  42973. goog.events.unlistenByKey(this.pointerdownListenerKey_);
  42974. this.pointerdownListenerKey_ = null;
  42975. }
  42976. if (this.dragListenerKeys_) {
  42977. this.dragListenerKeys_.forEach(goog.events.unlistenByKey);
  42978. this.dragListenerKeys_ = null;
  42979. }
  42980. if (this.documentPointerEventHandler_) {
  42981. goog.dispose(this.documentPointerEventHandler_);
  42982. this.documentPointerEventHandler_ = null;
  42983. }
  42984. if (this.pointerEventHandler_) {
  42985. goog.dispose(this.pointerEventHandler_);
  42986. this.pointerEventHandler_ = null;
  42987. }
  42988. goog.base(this, 'disposeInternal');
  42989. };
  42990. /**
  42991. * Constants for event names.
  42992. * @enum {string}
  42993. */
  42994. ol.MapBrowserEvent.EventType = {
  42995. /**
  42996. * A true single click with no dragging and no double click. Note that this
  42997. * event is delayed by 250 ms to ensure that it is not a double click.
  42998. * @event ol.MapBrowserEvent#singleclick
  42999. * @api stable
  43000. */
  43001. SINGLECLICK: 'singleclick',
  43002. /**
  43003. * A click with no dragging. A double click will fire two of this.
  43004. * @event ol.MapBrowserEvent#click
  43005. * @api stable
  43006. */
  43007. CLICK: goog.events.EventType.CLICK,
  43008. /**
  43009. * A true double click, with no dragging.
  43010. * @event ol.MapBrowserEvent#dblclick
  43011. * @api stable
  43012. */
  43013. DBLCLICK: goog.events.EventType.DBLCLICK,
  43014. /**
  43015. * Triggered when a pointer is dragged.
  43016. * @event ol.MapBrowserEvent#pointerdrag
  43017. * @api
  43018. */
  43019. POINTERDRAG: 'pointerdrag',
  43020. /**
  43021. * Triggered when a pointer is moved. Note that on touch devices this is
  43022. * triggered when the map is panned, so is not the same as mousemove.
  43023. * @event ol.MapBrowserEvent#pointermove
  43024. * @api stable
  43025. */
  43026. POINTERMOVE: 'pointermove',
  43027. POINTERDOWN: 'pointerdown',
  43028. POINTERUP: 'pointerup',
  43029. POINTEROVER: 'pointerover',
  43030. POINTEROUT: 'pointerout',
  43031. POINTERENTER: 'pointerenter',
  43032. POINTERLEAVE: 'pointerleave',
  43033. POINTERCANCEL: 'pointercancel'
  43034. };
  43035. goog.provide('ol.layer.Base');
  43036. goog.provide('ol.layer.LayerProperty');
  43037. goog.provide('ol.layer.LayerState');
  43038. goog.require('goog.object');
  43039. goog.require('ol');
  43040. goog.require('ol.Object');
  43041. goog.require('ol.math');
  43042. goog.require('ol.source.State');
  43043. /**
  43044. * @enum {string}
  43045. */
  43046. ol.layer.LayerProperty = {
  43047. OPACITY: 'opacity',
  43048. VISIBLE: 'visible',
  43049. EXTENT: 'extent',
  43050. Z_INDEX: 'zIndex',
  43051. MAX_RESOLUTION: 'maxResolution',
  43052. MIN_RESOLUTION: 'minResolution',
  43053. SOURCE: 'source'
  43054. };
  43055. /**
  43056. * @typedef {{layer: ol.layer.Layer,
  43057. * opacity: number,
  43058. * sourceState: ol.source.State,
  43059. * visible: boolean,
  43060. * managed: boolean,
  43061. * extent: (ol.Extent|undefined),
  43062. * zIndex: number,
  43063. * maxResolution: number,
  43064. * minResolution: number}}
  43065. */
  43066. ol.layer.LayerState;
  43067. /**
  43068. * @classdesc
  43069. * Abstract base class; normally only used for creating subclasses and not
  43070. * instantiated in apps.
  43071. * Note that with `ol.layer.Base` and all its subclasses, any property set in
  43072. * the options is set as a {@link ol.Object} property on the layer object, so
  43073. * is observable, and has get/set accessors.
  43074. *
  43075. * @constructor
  43076. * @extends {ol.Object}
  43077. * @param {olx.layer.BaseOptions} options Layer options.
  43078. * @api stable
  43079. */
  43080. ol.layer.Base = function(options) {
  43081. goog.base(this);
  43082. /**
  43083. * @type {Object.<string, *>}
  43084. */
  43085. var properties = goog.object.clone(options);
  43086. properties[ol.layer.LayerProperty.OPACITY] =
  43087. options.opacity !== undefined ? options.opacity : 1;
  43088. properties[ol.layer.LayerProperty.VISIBLE] =
  43089. options.visible !== undefined ? options.visible : true;
  43090. properties[ol.layer.LayerProperty.Z_INDEX] =
  43091. options.zIndex !== undefined ? options.zIndex : 0;
  43092. properties[ol.layer.LayerProperty.MAX_RESOLUTION] =
  43093. options.maxResolution !== undefined ? options.maxResolution : Infinity;
  43094. properties[ol.layer.LayerProperty.MIN_RESOLUTION] =
  43095. options.minResolution !== undefined ? options.minResolution : 0;
  43096. this.setProperties(properties);
  43097. };
  43098. goog.inherits(ol.layer.Base, ol.Object);
  43099. /**
  43100. * @return {ol.layer.LayerState} Layer state.
  43101. */
  43102. ol.layer.Base.prototype.getLayerState = function() {
  43103. var opacity = this.getOpacity();
  43104. var sourceState = this.getSourceState();
  43105. var visible = this.getVisible();
  43106. var extent = this.getExtent();
  43107. var zIndex = this.getZIndex();
  43108. var maxResolution = this.getMaxResolution();
  43109. var minResolution = this.getMinResolution();
  43110. return {
  43111. layer: /** @type {ol.layer.Layer} */ (this),
  43112. opacity: ol.math.clamp(opacity, 0, 1),
  43113. sourceState: sourceState,
  43114. visible: visible,
  43115. managed: true,
  43116. extent: extent,
  43117. zIndex: zIndex,
  43118. maxResolution: maxResolution,
  43119. minResolution: Math.max(minResolution, 0)
  43120. };
  43121. };
  43122. /**
  43123. * @param {Array.<ol.layer.Layer>=} opt_array Array of layers (to be
  43124. * modified in place).
  43125. * @return {Array.<ol.layer.Layer>} Array of layers.
  43126. */
  43127. ol.layer.Base.prototype.getLayersArray = goog.abstractMethod;
  43128. /**
  43129. * @param {Array.<ol.layer.LayerState>=} opt_states Optional list of layer
  43130. * states (to be modified in place).
  43131. * @return {Array.<ol.layer.LayerState>} List of layer states.
  43132. */
  43133. ol.layer.Base.prototype.getLayerStatesArray = goog.abstractMethod;
  43134. /**
  43135. * Return the {@link ol.Extent extent} of the layer or `undefined` if it
  43136. * will be visible regardless of extent.
  43137. * @return {ol.Extent|undefined} The layer extent.
  43138. * @observable
  43139. * @api stable
  43140. */
  43141. ol.layer.Base.prototype.getExtent = function() {
  43142. return /** @type {ol.Extent|undefined} */ (
  43143. this.get(ol.layer.LayerProperty.EXTENT));
  43144. };
  43145. /**
  43146. * Return the maximum resolution of the layer.
  43147. * @return {number} The maximum resolution of the layer.
  43148. * @observable
  43149. * @api stable
  43150. */
  43151. ol.layer.Base.prototype.getMaxResolution = function() {
  43152. return /** @type {number} */ (
  43153. this.get(ol.layer.LayerProperty.MAX_RESOLUTION));
  43154. };
  43155. /**
  43156. * Return the minimum resolution of the layer.
  43157. * @return {number} The minimum resolution of the layer.
  43158. * @observable
  43159. * @api stable
  43160. */
  43161. ol.layer.Base.prototype.getMinResolution = function() {
  43162. return /** @type {number} */ (
  43163. this.get(ol.layer.LayerProperty.MIN_RESOLUTION));
  43164. };
  43165. /**
  43166. * Return the opacity of the layer (between 0 and 1).
  43167. * @return {number} The opacity of the layer.
  43168. * @observable
  43169. * @api stable
  43170. */
  43171. ol.layer.Base.prototype.getOpacity = function() {
  43172. return /** @type {number} */ (this.get(ol.layer.LayerProperty.OPACITY));
  43173. };
  43174. /**
  43175. * @return {ol.source.State} Source state.
  43176. */
  43177. ol.layer.Base.prototype.getSourceState = goog.abstractMethod;
  43178. /**
  43179. * Return the visibility of the layer (`true` or `false`).
  43180. * @return {boolean} The visibility of the layer.
  43181. * @observable
  43182. * @api stable
  43183. */
  43184. ol.layer.Base.prototype.getVisible = function() {
  43185. return /** @type {boolean} */ (this.get(ol.layer.LayerProperty.VISIBLE));
  43186. };
  43187. /**
  43188. * Return the Z-index of the layer, which is used to order layers before
  43189. * rendering. The default Z-index is 0.
  43190. * @return {number} The Z-index of the layer.
  43191. * @observable
  43192. * @api
  43193. */
  43194. ol.layer.Base.prototype.getZIndex = function() {
  43195. return /** @type {number} */ (this.get(ol.layer.LayerProperty.Z_INDEX));
  43196. };
  43197. /**
  43198. * Set the extent at which the layer is visible. If `undefined`, the layer
  43199. * will be visible at all extents.
  43200. * @param {ol.Extent|undefined} extent The extent of the layer.
  43201. * @observable
  43202. * @api stable
  43203. */
  43204. ol.layer.Base.prototype.setExtent = function(extent) {
  43205. this.set(ol.layer.LayerProperty.EXTENT, extent);
  43206. };
  43207. /**
  43208. * Set the maximum resolution at which the layer is visible.
  43209. * @param {number} maxResolution The maximum resolution of the layer.
  43210. * @observable
  43211. * @api stable
  43212. */
  43213. ol.layer.Base.prototype.setMaxResolution = function(maxResolution) {
  43214. this.set(ol.layer.LayerProperty.MAX_RESOLUTION, maxResolution);
  43215. };
  43216. /**
  43217. * Set the minimum resolution at which the layer is visible.
  43218. * @param {number} minResolution The minimum resolution of the layer.
  43219. * @observable
  43220. * @api stable
  43221. */
  43222. ol.layer.Base.prototype.setMinResolution = function(minResolution) {
  43223. this.set(ol.layer.LayerProperty.MIN_RESOLUTION, minResolution);
  43224. };
  43225. /**
  43226. * Set the opacity of the layer, allowed values range from 0 to 1.
  43227. * @param {number} opacity The opacity of the layer.
  43228. * @observable
  43229. * @api stable
  43230. */
  43231. ol.layer.Base.prototype.setOpacity = function(opacity) {
  43232. this.set(ol.layer.LayerProperty.OPACITY, opacity);
  43233. };
  43234. /**
  43235. * Set the visibility of the layer (`true` or `false`).
  43236. * @param {boolean} visible The visibility of the layer.
  43237. * @observable
  43238. * @api stable
  43239. */
  43240. ol.layer.Base.prototype.setVisible = function(visible) {
  43241. this.set(ol.layer.LayerProperty.VISIBLE, visible);
  43242. };
  43243. /**
  43244. * Set Z-index of the layer, which is used to order layers before rendering.
  43245. * The default Z-index is 0.
  43246. * @param {number} zindex The z-index of the layer.
  43247. * @observable
  43248. * @api
  43249. */
  43250. ol.layer.Base.prototype.setZIndex = function(zindex) {
  43251. this.set(ol.layer.LayerProperty.Z_INDEX, zindex);
  43252. };
  43253. goog.provide('ol.render.VectorContext');
  43254. /**
  43255. * Context for drawing geometries. A vector context is available on render
  43256. * events and does not need to be constructed directly.
  43257. * @constructor
  43258. * @struct
  43259. * @api
  43260. */
  43261. ol.render.VectorContext = function() {
  43262. };
  43263. /**
  43264. * @param {number} zIndex Z index.
  43265. * @param {function(ol.render.VectorContext)} callback Callback.
  43266. */
  43267. ol.render.VectorContext.prototype.drawAsync = goog.abstractMethod;
  43268. /**
  43269. * @param {ol.geom.Circle} circleGeometry Circle geometry.
  43270. * @param {ol.Feature} feature Feature,
  43271. */
  43272. ol.render.VectorContext.prototype.drawCircleGeometry = goog.abstractMethod;
  43273. /**
  43274. * @param {ol.Feature} feature Feature.
  43275. * @param {ol.style.Style} style Style.
  43276. */
  43277. ol.render.VectorContext.prototype.drawFeature = goog.abstractMethod;
  43278. /**
  43279. * @param {ol.geom.GeometryCollection} geometryCollectionGeometry Geometry
  43280. * collection.
  43281. * @param {ol.Feature} feature Feature.
  43282. */
  43283. ol.render.VectorContext.prototype.drawGeometryCollectionGeometry =
  43284. goog.abstractMethod;
  43285. /**
  43286. * @param {ol.geom.LineString} lineStringGeometry Line string geometry.
  43287. * @param {ol.Feature} feature Feature.
  43288. */
  43289. ol.render.VectorContext.prototype.drawLineStringGeometry =
  43290. goog.abstractMethod;
  43291. /**
  43292. * @param {ol.geom.MultiLineString} multiLineStringGeometry
  43293. * MultiLineString geometry.
  43294. * @param {ol.Feature} feature Feature.
  43295. */
  43296. ol.render.VectorContext.prototype.drawMultiLineStringGeometry =
  43297. goog.abstractMethod;
  43298. /**
  43299. * @param {ol.geom.MultiPoint} multiPointGeometry MultiPoint geometry.
  43300. * @param {ol.Feature} feature Feature.
  43301. */
  43302. ol.render.VectorContext.prototype.drawMultiPointGeometry = goog.abstractMethod;
  43303. /**
  43304. * @param {ol.geom.MultiPolygon} multiPolygonGeometry MultiPolygon geometry.
  43305. * @param {ol.Feature} feature Feature.
  43306. */
  43307. ol.render.VectorContext.prototype.drawMultiPolygonGeometry =
  43308. goog.abstractMethod;
  43309. /**
  43310. * @param {ol.geom.Point} pointGeometry Point geometry.
  43311. * @param {ol.Feature} feature Feature.
  43312. */
  43313. ol.render.VectorContext.prototype.drawPointGeometry = goog.abstractMethod;
  43314. /**
  43315. * @param {ol.geom.Polygon} polygonGeometry Polygon geometry.
  43316. * @param {ol.Feature} feature Feature.
  43317. */
  43318. ol.render.VectorContext.prototype.drawPolygonGeometry = goog.abstractMethod;
  43319. /**
  43320. * @param {Array.<number>} flatCoordinates Flat coordinates.
  43321. * @param {number} offset Offset.
  43322. * @param {number} end End.
  43323. * @param {number} stride Stride.
  43324. * @param {ol.geom.Geometry} geometry Geometry.
  43325. * @param {ol.Feature} feature Feature.
  43326. */
  43327. ol.render.VectorContext.prototype.drawText = goog.abstractMethod;
  43328. /**
  43329. * @param {ol.style.Fill} fillStyle Fill style.
  43330. * @param {ol.style.Stroke} strokeStyle Stroke style.
  43331. */
  43332. ol.render.VectorContext.prototype.setFillStrokeStyle = goog.abstractMethod;
  43333. /**
  43334. * @param {ol.style.Image} imageStyle Image style.
  43335. */
  43336. ol.render.VectorContext.prototype.setImageStyle = goog.abstractMethod;
  43337. /**
  43338. * @param {ol.style.Text} textStyle Text style.
  43339. */
  43340. ol.render.VectorContext.prototype.setTextStyle = goog.abstractMethod;
  43341. goog.provide('ol.render.Event');
  43342. goog.provide('ol.render.EventType');
  43343. goog.require('goog.events.Event');
  43344. goog.require('ol.render.VectorContext');
  43345. /**
  43346. * @enum {string}
  43347. */
  43348. ol.render.EventType = {
  43349. /**
  43350. * @event ol.render.Event#postcompose
  43351. * @api
  43352. */
  43353. POSTCOMPOSE: 'postcompose',
  43354. /**
  43355. * @event ol.render.Event#precompose
  43356. * @api
  43357. */
  43358. PRECOMPOSE: 'precompose',
  43359. /**
  43360. * @event ol.render.Event#render
  43361. * @api
  43362. */
  43363. RENDER: 'render'
  43364. };
  43365. /**
  43366. * @constructor
  43367. * @extends {goog.events.Event}
  43368. * @implements {oli.render.Event}
  43369. * @param {ol.render.EventType} type Type.
  43370. * @param {Object=} opt_target Target.
  43371. * @param {ol.render.VectorContext=} opt_vectorContext Vector context.
  43372. * @param {olx.FrameState=} opt_frameState Frame state.
  43373. * @param {?CanvasRenderingContext2D=} opt_context Context.
  43374. * @param {?ol.webgl.Context=} opt_glContext WebGL Context.
  43375. */
  43376. ol.render.Event = function(
  43377. type, opt_target, opt_vectorContext, opt_frameState, opt_context,
  43378. opt_glContext) {
  43379. goog.base(this, type, opt_target);
  43380. /**
  43381. * For canvas, this is an instance of {@link ol.render.canvas.Immediate}.
  43382. * @type {ol.render.VectorContext|undefined}
  43383. * @api
  43384. */
  43385. this.vectorContext = opt_vectorContext;
  43386. /**
  43387. * An object representing the current render frame state.
  43388. * @type {olx.FrameState|undefined}
  43389. * @api
  43390. */
  43391. this.frameState = opt_frameState;
  43392. /**
  43393. * Canvas context. Only available when a Canvas renderer is used, null
  43394. * otherwise.
  43395. * @type {CanvasRenderingContext2D|null|undefined}
  43396. * @api
  43397. */
  43398. this.context = opt_context;
  43399. /**
  43400. * WebGL context. Only available when a WebGL renderer is used, null
  43401. * otherwise.
  43402. * @type {ol.webgl.Context|null|undefined}
  43403. * @api
  43404. */
  43405. this.glContext = opt_glContext;
  43406. };
  43407. goog.inherits(ol.render.Event, goog.events.Event);
  43408. goog.provide('ol.layer.Layer');
  43409. goog.require('goog.events');
  43410. goog.require('goog.events.EventType');
  43411. goog.require('goog.object');
  43412. goog.require('ol');
  43413. goog.require('ol.Object');
  43414. goog.require('ol.layer.Base');
  43415. goog.require('ol.layer.LayerProperty');
  43416. goog.require('ol.render.EventType');
  43417. goog.require('ol.source.State');
  43418. /**
  43419. * @classdesc
  43420. * Abstract base class; normally only used for creating subclasses and not
  43421. * instantiated in apps.
  43422. * A visual representation of raster or vector map data.
  43423. * Layers group together those properties that pertain to how the data is to be
  43424. * displayed, irrespective of the source of that data.
  43425. *
  43426. * A generic `change` event is fired when the state of the source changes.
  43427. *
  43428. * @constructor
  43429. * @extends {ol.layer.Base}
  43430. * @fires ol.render.Event
  43431. * @param {olx.layer.LayerOptions} options Layer options.
  43432. * @api stable
  43433. */
  43434. ol.layer.Layer = function(options) {
  43435. var baseOptions = goog.object.clone(options);
  43436. delete baseOptions.source;
  43437. goog.base(this, /** @type {olx.layer.LayerOptions} */ (baseOptions));
  43438. /**
  43439. * @private
  43440. * @type {goog.events.Key}
  43441. */
  43442. this.mapPrecomposeKey_ = null;
  43443. /**
  43444. * @private
  43445. * @type {goog.events.Key}
  43446. */
  43447. this.mapRenderKey_ = null;
  43448. /**
  43449. * @private
  43450. * @type {goog.events.Key}
  43451. */
  43452. this.sourceChangeKey_ = null;
  43453. if (options.map) {
  43454. this.setMap(options.map);
  43455. }
  43456. goog.events.listen(this,
  43457. ol.Object.getChangeEventType(ol.layer.LayerProperty.SOURCE),
  43458. this.handleSourcePropertyChange_, false, this);
  43459. var source = options.source ? options.source : null;
  43460. this.setSource(source);
  43461. };
  43462. goog.inherits(ol.layer.Layer, ol.layer.Base);
  43463. /**
  43464. * Return `true` if the layer is visible, and if the passed resolution is
  43465. * between the layer's minResolution and maxResolution. The comparison is
  43466. * inclusive for `minResolution` and exclusive for `maxResolution`.
  43467. * @param {ol.layer.LayerState} layerState Layer state.
  43468. * @param {number} resolution Resolution.
  43469. * @return {boolean} The layer is visible at the given resolution.
  43470. */
  43471. ol.layer.Layer.visibleAtResolution = function(layerState, resolution) {
  43472. return layerState.visible && resolution >= layerState.minResolution &&
  43473. resolution < layerState.maxResolution;
  43474. };
  43475. /**
  43476. * @inheritDoc
  43477. */
  43478. ol.layer.Layer.prototype.getLayersArray = function(opt_array) {
  43479. var array = opt_array ? opt_array : [];
  43480. array.push(this);
  43481. return array;
  43482. };
  43483. /**
  43484. * @inheritDoc
  43485. */
  43486. ol.layer.Layer.prototype.getLayerStatesArray = function(opt_states) {
  43487. var states = opt_states ? opt_states : [];
  43488. states.push(this.getLayerState());
  43489. return states;
  43490. };
  43491. /**
  43492. * Get the layer source.
  43493. * @return {ol.source.Source} The layer source (or `null` if not yet set).
  43494. * @observable
  43495. * @api stable
  43496. */
  43497. ol.layer.Layer.prototype.getSource = function() {
  43498. var source = this.get(ol.layer.LayerProperty.SOURCE);
  43499. return /** @type {ol.source.Source} */ (source) || null;
  43500. };
  43501. /**
  43502. * @inheritDoc
  43503. */
  43504. ol.layer.Layer.prototype.getSourceState = function() {
  43505. var source = this.getSource();
  43506. return !source ? ol.source.State.UNDEFINED : source.getState();
  43507. };
  43508. /**
  43509. * @private
  43510. */
  43511. ol.layer.Layer.prototype.handleSourceChange_ = function() {
  43512. this.changed();
  43513. };
  43514. /**
  43515. * @private
  43516. */
  43517. ol.layer.Layer.prototype.handleSourcePropertyChange_ = function() {
  43518. if (this.sourceChangeKey_) {
  43519. goog.events.unlistenByKey(this.sourceChangeKey_);
  43520. this.sourceChangeKey_ = null;
  43521. }
  43522. var source = this.getSource();
  43523. if (source) {
  43524. this.sourceChangeKey_ = goog.events.listen(source,
  43525. goog.events.EventType.CHANGE, this.handleSourceChange_, false, this);
  43526. }
  43527. this.changed();
  43528. };
  43529. /**
  43530. * Sets the layer to be rendered on a map. The map will not manage this layer in
  43531. * its layers collection, layer filters in {@link ol.Map#forEachLayerAtPixel}
  43532. * will not filter the layer, and it will be rendered on top. This is useful for
  43533. * temporary layers. To remove an unmanaged layer from the map, use
  43534. * `#setMap(null)`.
  43535. *
  43536. * To add the layer to a map and have it managed by the map, use
  43537. * {@link ol.Map#addLayer} instead.
  43538. * @param {ol.Map} map Map.
  43539. * @api
  43540. */
  43541. ol.layer.Layer.prototype.setMap = function(map) {
  43542. goog.events.unlistenByKey(this.mapPrecomposeKey_);
  43543. this.mapPrecomposeKey_ = null;
  43544. if (!map) {
  43545. this.changed();
  43546. }
  43547. goog.events.unlistenByKey(this.mapRenderKey_);
  43548. this.mapRenderKey_ = null;
  43549. if (map) {
  43550. this.mapPrecomposeKey_ = goog.events.listen(
  43551. map, ol.render.EventType.PRECOMPOSE, function(evt) {
  43552. var layerState = this.getLayerState();
  43553. layerState.managed = false;
  43554. layerState.zIndex = Infinity;
  43555. evt.frameState.layerStatesArray.push(layerState);
  43556. evt.frameState.layerStates[goog.getUid(this)] = layerState;
  43557. }, false, this);
  43558. this.mapRenderKey_ = goog.events.listen(
  43559. this, goog.events.EventType.CHANGE, map.render, false, map);
  43560. this.changed();
  43561. }
  43562. };
  43563. /**
  43564. * Set the layer source.
  43565. * @param {ol.source.Source} source The layer source.
  43566. * @observable
  43567. * @api stable
  43568. */
  43569. ol.layer.Layer.prototype.setSource = function(source) {
  43570. this.set(ol.layer.LayerProperty.SOURCE, source);
  43571. };
  43572. goog.provide('ol.ImageBase');
  43573. goog.provide('ol.ImageState');
  43574. goog.require('goog.asserts');
  43575. goog.require('goog.events.EventTarget');
  43576. goog.require('goog.events.EventType');
  43577. goog.require('ol.Attribution');
  43578. goog.require('ol.Extent');
  43579. /**
  43580. * @enum {number}
  43581. */
  43582. ol.ImageState = {
  43583. IDLE: 0,
  43584. LOADING: 1,
  43585. LOADED: 2,
  43586. ERROR: 3
  43587. };
  43588. /**
  43589. * @constructor
  43590. * @extends {goog.events.EventTarget}
  43591. * @param {ol.Extent} extent Extent.
  43592. * @param {number|undefined} resolution Resolution.
  43593. * @param {number} pixelRatio Pixel ratio.
  43594. * @param {ol.ImageState} state State.
  43595. * @param {Array.<ol.Attribution>} attributions Attributions.
  43596. */
  43597. ol.ImageBase = function(extent, resolution, pixelRatio, state, attributions) {
  43598. goog.base(this);
  43599. /**
  43600. * @private
  43601. * @type {Array.<ol.Attribution>}
  43602. */
  43603. this.attributions_ = attributions;
  43604. /**
  43605. * @protected
  43606. * @type {ol.Extent}
  43607. */
  43608. this.extent = extent;
  43609. /**
  43610. * @private
  43611. * @type {number}
  43612. */
  43613. this.pixelRatio_ = pixelRatio;
  43614. /**
  43615. * @protected
  43616. * @type {number|undefined}
  43617. */
  43618. this.resolution = resolution;
  43619. /**
  43620. * @protected
  43621. * @type {ol.ImageState}
  43622. */
  43623. this.state = state;
  43624. };
  43625. goog.inherits(ol.ImageBase, goog.events.EventTarget);
  43626. /**
  43627. * @protected
  43628. */
  43629. ol.ImageBase.prototype.changed = function() {
  43630. this.dispatchEvent(goog.events.EventType.CHANGE);
  43631. };
  43632. /**
  43633. * @return {Array.<ol.Attribution>} Attributions.
  43634. */
  43635. ol.ImageBase.prototype.getAttributions = function() {
  43636. return this.attributions_;
  43637. };
  43638. /**
  43639. * @return {ol.Extent} Extent.
  43640. */
  43641. ol.ImageBase.prototype.getExtent = function() {
  43642. return this.extent;
  43643. };
  43644. /**
  43645. * @param {Object=} opt_context Object.
  43646. * @return {HTMLCanvasElement|Image|HTMLVideoElement} Image.
  43647. */
  43648. ol.ImageBase.prototype.getImage = goog.abstractMethod;
  43649. /**
  43650. * @return {number} PixelRatio.
  43651. */
  43652. ol.ImageBase.prototype.getPixelRatio = function() {
  43653. return this.pixelRatio_;
  43654. };
  43655. /**
  43656. * @return {number} Resolution.
  43657. */
  43658. ol.ImageBase.prototype.getResolution = function() {
  43659. goog.asserts.assert(this.resolution !== undefined, 'resolution not yet set');
  43660. return this.resolution;
  43661. };
  43662. /**
  43663. * @return {ol.ImageState} State.
  43664. */
  43665. ol.ImageBase.prototype.getState = function() {
  43666. return this.state;
  43667. };
  43668. /**
  43669. * Load not yet loaded URI.
  43670. */
  43671. ol.ImageBase.prototype.load = goog.abstractMethod;
  43672. goog.provide('ol.vec.Mat4');
  43673. goog.provide('ol.vec.Mat4.Number');
  43674. goog.require('goog.vec.Mat4');
  43675. /**
  43676. * A alias for the goog.vec.Number type.
  43677. * @typedef {goog.vec.Number}
  43678. */
  43679. ol.vec.Mat4.Number;
  43680. /**
  43681. * @param {!goog.vec.Mat4.Number} mat Matrix.
  43682. * @param {number} translateX1 Translate X1.
  43683. * @param {number} translateY1 Translate Y1.
  43684. * @param {number} scaleX Scale X.
  43685. * @param {number} scaleY Scale Y.
  43686. * @param {number} rotation Rotation.
  43687. * @param {number} translateX2 Translate X2.
  43688. * @param {number} translateY2 Translate Y2.
  43689. * @return {!goog.vec.Mat4.Number} Matrix.
  43690. */
  43691. ol.vec.Mat4.makeTransform2D = function(mat, translateX1, translateY1,
  43692. scaleX, scaleY, rotation, translateX2, translateY2) {
  43693. goog.vec.Mat4.makeIdentity(mat);
  43694. if (translateX1 !== 0 || translateY1 !== 0) {
  43695. goog.vec.Mat4.translate(mat, translateX1, translateY1, 0);
  43696. }
  43697. if (scaleX != 1 || scaleY != 1) {
  43698. goog.vec.Mat4.scale(mat, scaleX, scaleY, 1);
  43699. }
  43700. if (rotation !== 0) {
  43701. goog.vec.Mat4.rotateZ(mat, rotation);
  43702. }
  43703. if (translateX2 !== 0 || translateY2 !== 0) {
  43704. goog.vec.Mat4.translate(mat, translateX2, translateY2, 0);
  43705. }
  43706. return mat;
  43707. };
  43708. /**
  43709. * Returns true if mat1 and mat2 represent the same 2D transformation.
  43710. * @param {goog.vec.Mat4.Number} mat1 Matrix 1.
  43711. * @param {goog.vec.Mat4.Number} mat2 Matrix 2.
  43712. * @return {boolean} Equal 2D.
  43713. */
  43714. ol.vec.Mat4.equals2D = function(mat1, mat2) {
  43715. return (
  43716. goog.vec.Mat4.getElement(mat1, 0, 0) ==
  43717. goog.vec.Mat4.getElement(mat2, 0, 0) &&
  43718. goog.vec.Mat4.getElement(mat1, 1, 0) ==
  43719. goog.vec.Mat4.getElement(mat2, 1, 0) &&
  43720. goog.vec.Mat4.getElement(mat1, 0, 1) ==
  43721. goog.vec.Mat4.getElement(mat2, 0, 1) &&
  43722. goog.vec.Mat4.getElement(mat1, 1, 1) ==
  43723. goog.vec.Mat4.getElement(mat2, 1, 1) &&
  43724. goog.vec.Mat4.getElement(mat1, 0, 3) ==
  43725. goog.vec.Mat4.getElement(mat2, 0, 3) &&
  43726. goog.vec.Mat4.getElement(mat1, 1, 3) ==
  43727. goog.vec.Mat4.getElement(mat2, 1, 3));
  43728. };
  43729. /**
  43730. * Transforms the given vector with the given matrix storing the resulting,
  43731. * transformed vector into resultVec. The input vector is multiplied against the
  43732. * upper 2x4 matrix omitting the projective component.
  43733. *
  43734. * @param {goog.vec.Mat4.Number} mat The matrix supplying the transformation.
  43735. * @param {Array.<number>} vec The 3 element vector to transform.
  43736. * @param {Array.<number>} resultVec The 3 element vector to receive the results
  43737. * (may be vec).
  43738. * @return {Array.<number>} return resultVec so that operations can be
  43739. * chained together.
  43740. */
  43741. ol.vec.Mat4.multVec2 = function(mat, vec, resultVec) {
  43742. var m00 = goog.vec.Mat4.getElement(mat, 0, 0);
  43743. var m10 = goog.vec.Mat4.getElement(mat, 1, 0);
  43744. var m01 = goog.vec.Mat4.getElement(mat, 0, 1);
  43745. var m11 = goog.vec.Mat4.getElement(mat, 1, 1);
  43746. var m03 = goog.vec.Mat4.getElement(mat, 0, 3);
  43747. var m13 = goog.vec.Mat4.getElement(mat, 1, 3);
  43748. var x = vec[0], y = vec[1];
  43749. resultVec[0] = m00 * x + m01 * y + m03;
  43750. resultVec[1] = m10 * x + m11 * y + m13;
  43751. return resultVec;
  43752. };
  43753. goog.provide('ol.renderer.Layer');
  43754. goog.require('goog.asserts');
  43755. goog.require('goog.events');
  43756. goog.require('goog.events.EventType');
  43757. goog.require('goog.functions');
  43758. goog.require('ol');
  43759. goog.require('ol.ImageState');
  43760. goog.require('ol.Observable');
  43761. goog.require('ol.TileRange');
  43762. goog.require('ol.TileState');
  43763. goog.require('ol.layer.Layer');
  43764. goog.require('ol.source.Source');
  43765. goog.require('ol.source.State');
  43766. goog.require('ol.source.Tile');
  43767. goog.require('ol.tilecoord');
  43768. goog.require('ol.vec.Mat4');
  43769. /**
  43770. * @constructor
  43771. * @extends {ol.Observable}
  43772. * @param {ol.layer.Layer} layer Layer.
  43773. * @struct
  43774. */
  43775. ol.renderer.Layer = function(layer) {
  43776. goog.base(this);
  43777. /**
  43778. * @private
  43779. * @type {ol.layer.Layer}
  43780. */
  43781. this.layer_ = layer;
  43782. };
  43783. goog.inherits(ol.renderer.Layer, ol.Observable);
  43784. /**
  43785. * @param {ol.Coordinate} coordinate Coordinate.
  43786. * @param {olx.FrameState} frameState Frame state.
  43787. * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
  43788. * callback.
  43789. * @param {S} thisArg Value to use as `this` when executing `callback`.
  43790. * @return {T|undefined} Callback result.
  43791. * @template S,T
  43792. */
  43793. ol.renderer.Layer.prototype.forEachFeatureAtCoordinate = ol.nullFunction;
  43794. /**
  43795. * @param {ol.Pixel} pixel Pixel.
  43796. * @param {olx.FrameState} frameState Frame state.
  43797. * @param {function(this: S, ol.layer.Layer): T} callback Layer callback.
  43798. * @param {S} thisArg Value to use as `this` when executing `callback`.
  43799. * @return {T|undefined} Callback result.
  43800. * @template S,T
  43801. */
  43802. ol.renderer.Layer.prototype.forEachLayerAtPixel =
  43803. function(pixel, frameState, callback, thisArg) {
  43804. var coordinate = pixel.slice();
  43805. ol.vec.Mat4.multVec2(
  43806. frameState.pixelToCoordinateMatrix, coordinate, coordinate);
  43807. var hasFeature = this.forEachFeatureAtCoordinate(
  43808. coordinate, frameState, goog.functions.TRUE, this);
  43809. if (hasFeature) {
  43810. return callback.call(thisArg, this.layer_);
  43811. } else {
  43812. return undefined;
  43813. }
  43814. };
  43815. /**
  43816. * @param {ol.Coordinate} coordinate Coordinate.
  43817. * @param {olx.FrameState} frameState Frame state.
  43818. * @return {boolean} Is there a feature at the given coordinate?
  43819. */
  43820. ol.renderer.Layer.prototype.hasFeatureAtCoordinate = goog.functions.FALSE;
  43821. /**
  43822. * Create a function that adds loaded tiles to the tile lookup.
  43823. * @param {ol.source.Tile} source Tile source.
  43824. * @param {Object.<number, Object.<string, ol.Tile>>} tiles Lookup of loaded
  43825. * tiles by zoom level.
  43826. * @return {function(number, ol.TileRange):boolean} A function that can be
  43827. * called with a zoom level and a tile range to add loaded tiles to the
  43828. * lookup.
  43829. * @protected
  43830. */
  43831. ol.renderer.Layer.prototype.createLoadedTileFinder = function(source, tiles) {
  43832. return (
  43833. /**
  43834. * @param {number} zoom Zoom level.
  43835. * @param {ol.TileRange} tileRange Tile range.
  43836. * @return {boolean} The tile range is fully loaded.
  43837. */
  43838. function(zoom, tileRange) {
  43839. return source.forEachLoadedTile(zoom, tileRange, function(tile) {
  43840. if (!tiles[zoom]) {
  43841. tiles[zoom] = {};
  43842. }
  43843. tiles[zoom][tile.tileCoord.toString()] = tile;
  43844. });
  43845. });
  43846. };
  43847. /**
  43848. * @return {ol.layer.Layer} Layer.
  43849. */
  43850. ol.renderer.Layer.prototype.getLayer = function() {
  43851. return this.layer_;
  43852. };
  43853. /**
  43854. * Handle changes in image state.
  43855. * @param {goog.events.Event} event Image change event.
  43856. * @private
  43857. */
  43858. ol.renderer.Layer.prototype.handleImageChange_ = function(event) {
  43859. var image = /** @type {ol.Image} */ (event.target);
  43860. if (image.getState() === ol.ImageState.LOADED) {
  43861. this.renderIfReadyAndVisible();
  43862. }
  43863. };
  43864. /**
  43865. * Load the image if not already loaded, and register the image change
  43866. * listener if needed.
  43867. * @param {ol.ImageBase} image Image.
  43868. * @return {boolean} `true` if the image is already loaded, `false`
  43869. * otherwise.
  43870. * @protected
  43871. */
  43872. ol.renderer.Layer.prototype.loadImage = function(image) {
  43873. var imageState = image.getState();
  43874. if (imageState != ol.ImageState.LOADED &&
  43875. imageState != ol.ImageState.ERROR) {
  43876. // the image is either "idle" or "loading", register the change
  43877. // listener (a noop if the listener was already registered)
  43878. goog.asserts.assert(imageState == ol.ImageState.IDLE ||
  43879. imageState == ol.ImageState.LOADING,
  43880. 'imageState is "idle" or "loading"');
  43881. goog.events.listen(image, goog.events.EventType.CHANGE,
  43882. this.handleImageChange_, false, this);
  43883. }
  43884. if (imageState == ol.ImageState.IDLE) {
  43885. image.load();
  43886. imageState = image.getState();
  43887. goog.asserts.assert(imageState == ol.ImageState.LOADING,
  43888. 'imageState is "loading"');
  43889. }
  43890. return imageState == ol.ImageState.LOADED;
  43891. };
  43892. /**
  43893. * @protected
  43894. */
  43895. ol.renderer.Layer.prototype.renderIfReadyAndVisible = function() {
  43896. var layer = this.getLayer();
  43897. if (layer.getVisible() && layer.getSourceState() == ol.source.State.READY) {
  43898. this.changed();
  43899. }
  43900. };
  43901. /**
  43902. * @param {olx.FrameState} frameState Frame state.
  43903. * @param {ol.source.Tile} tileSource Tile source.
  43904. * @protected
  43905. */
  43906. ol.renderer.Layer.prototype.scheduleExpireCache =
  43907. function(frameState, tileSource) {
  43908. if (tileSource.canExpireCache()) {
  43909. frameState.postRenderFunctions.push(
  43910. goog.partial(
  43911. /**
  43912. * @param {ol.source.Tile} tileSource Tile source.
  43913. * @param {ol.Map} map Map.
  43914. * @param {olx.FrameState} frameState Frame state.
  43915. */
  43916. function(tileSource, map, frameState) {
  43917. var tileSourceKey = goog.getUid(tileSource).toString();
  43918. tileSource.expireCache(frameState.usedTiles[tileSourceKey]);
  43919. }, tileSource));
  43920. }
  43921. };
  43922. /**
  43923. * @param {Object.<string, ol.Attribution>} attributionsSet Attributions
  43924. * set (target).
  43925. * @param {Array.<ol.Attribution>} attributions Attributions (source).
  43926. * @protected
  43927. */
  43928. ol.renderer.Layer.prototype.updateAttributions =
  43929. function(attributionsSet, attributions) {
  43930. if (attributions) {
  43931. var attribution, i, ii;
  43932. for (i = 0, ii = attributions.length; i < ii; ++i) {
  43933. attribution = attributions[i];
  43934. attributionsSet[goog.getUid(attribution).toString()] = attribution;
  43935. }
  43936. }
  43937. };
  43938. /**
  43939. * @param {olx.FrameState} frameState Frame state.
  43940. * @param {ol.source.Source} source Source.
  43941. * @protected
  43942. */
  43943. ol.renderer.Layer.prototype.updateLogos = function(frameState, source) {
  43944. var logo = source.getLogo();
  43945. if (logo !== undefined) {
  43946. if (goog.isString(logo)) {
  43947. frameState.logos[logo] = '';
  43948. } else if (goog.isObject(logo)) {
  43949. goog.asserts.assertString(logo.href, 'logo.href is a string');
  43950. goog.asserts.assertString(logo.src, 'logo.src is a string');
  43951. frameState.logos[logo.src] = logo.href;
  43952. }
  43953. }
  43954. };
  43955. /**
  43956. * @param {Object.<string, Object.<string, ol.TileRange>>} usedTiles Used tiles.
  43957. * @param {ol.source.Tile} tileSource Tile source.
  43958. * @param {number} z Z.
  43959. * @param {ol.TileRange} tileRange Tile range.
  43960. * @protected
  43961. */
  43962. ol.renderer.Layer.prototype.updateUsedTiles =
  43963. function(usedTiles, tileSource, z, tileRange) {
  43964. // FIXME should we use tilesToDrawByZ instead?
  43965. var tileSourceKey = goog.getUid(tileSource).toString();
  43966. var zKey = z.toString();
  43967. if (tileSourceKey in usedTiles) {
  43968. if (zKey in usedTiles[tileSourceKey]) {
  43969. usedTiles[tileSourceKey][zKey].extend(tileRange);
  43970. } else {
  43971. usedTiles[tileSourceKey][zKey] = tileRange;
  43972. }
  43973. } else {
  43974. usedTiles[tileSourceKey] = {};
  43975. usedTiles[tileSourceKey][zKey] = tileRange;
  43976. }
  43977. };
  43978. /**
  43979. * @param {ol.Coordinate} center Center.
  43980. * @param {number} resolution Resolution.
  43981. * @param {ol.Size} size Size.
  43982. * @protected
  43983. * @return {ol.Coordinate} Snapped center.
  43984. */
  43985. ol.renderer.Layer.prototype.snapCenterToPixel =
  43986. function(center, resolution, size) {
  43987. return [
  43988. resolution * (Math.round(center[0] / resolution) + (size[0] % 2) / 2),
  43989. resolution * (Math.round(center[1] / resolution) + (size[1] % 2) / 2)
  43990. ];
  43991. };
  43992. /**
  43993. * Manage tile pyramid.
  43994. * This function performs a number of functions related to the tiles at the
  43995. * current zoom and lower zoom levels:
  43996. * - registers idle tiles in frameState.wantedTiles so that they are not
  43997. * discarded by the tile queue
  43998. * - enqueues missing tiles
  43999. * @param {olx.FrameState} frameState Frame state.
  44000. * @param {ol.source.Tile} tileSource Tile source.
  44001. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  44002. * @param {number} pixelRatio Pixel ratio.
  44003. * @param {ol.proj.Projection} projection Projection.
  44004. * @param {ol.Extent} extent Extent.
  44005. * @param {number} currentZ Current Z.
  44006. * @param {number} preload Load low resolution tiles up to 'preload' levels.
  44007. * @param {function(this: T, ol.Tile)=} opt_tileCallback Tile callback.
  44008. * @param {T=} opt_this Object to use as `this` in `opt_tileCallback`.
  44009. * @protected
  44010. * @template T
  44011. */
  44012. ol.renderer.Layer.prototype.manageTilePyramid = function(
  44013. frameState, tileSource, tileGrid, pixelRatio, projection, extent,
  44014. currentZ, preload, opt_tileCallback, opt_this) {
  44015. var tileSourceKey = goog.getUid(tileSource).toString();
  44016. if (!(tileSourceKey in frameState.wantedTiles)) {
  44017. frameState.wantedTiles[tileSourceKey] = {};
  44018. }
  44019. var wantedTiles = frameState.wantedTiles[tileSourceKey];
  44020. var tileQueue = frameState.tileQueue;
  44021. var minZoom = tileGrid.getMinZoom();
  44022. var tile, tileRange, tileResolution, x, y, z;
  44023. for (z = currentZ; z >= minZoom; --z) {
  44024. tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange);
  44025. tileResolution = tileGrid.getResolution(z);
  44026. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  44027. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  44028. if (currentZ - z <= preload) {
  44029. tile = tileSource.getTile(z, x, y, pixelRatio, projection);
  44030. if (tile.getState() == ol.TileState.IDLE) {
  44031. wantedTiles[ol.tilecoord.toString(tile.tileCoord)] = true;
  44032. if (!tileQueue.isKeyQueued(tile.getKey())) {
  44033. tileQueue.enqueue([tile, tileSourceKey,
  44034. tileGrid.getTileCoordCenter(tile.tileCoord), tileResolution]);
  44035. }
  44036. }
  44037. if (opt_tileCallback !== undefined) {
  44038. opt_tileCallback.call(opt_this, tile);
  44039. }
  44040. } else {
  44041. tileSource.useTile(z, x, y);
  44042. }
  44043. }
  44044. }
  44045. }
  44046. };
  44047. goog.provide('ol.style.Image');
  44048. goog.provide('ol.style.ImageState');
  44049. /**
  44050. * @enum {number}
  44051. */
  44052. ol.style.ImageState = {
  44053. IDLE: 0,
  44054. LOADING: 1,
  44055. LOADED: 2,
  44056. ERROR: 3
  44057. };
  44058. /**
  44059. * @typedef {{opacity: number,
  44060. * rotateWithView: boolean,
  44061. * rotation: number,
  44062. * scale: number,
  44063. * snapToPixel: boolean}}
  44064. */
  44065. ol.style.ImageOptions;
  44066. /**
  44067. * @classdesc
  44068. * A base class used for creating subclasses and not instantiated in
  44069. * apps. Base class for {@link ol.style.Icon} and {@link ol.style.Circle}.
  44070. *
  44071. * @constructor
  44072. * @param {ol.style.ImageOptions} options Options.
  44073. * @api
  44074. */
  44075. ol.style.Image = function(options) {
  44076. /**
  44077. * @private
  44078. * @type {number}
  44079. */
  44080. this.opacity_ = options.opacity;
  44081. /**
  44082. * @private
  44083. * @type {boolean}
  44084. */
  44085. this.rotateWithView_ = options.rotateWithView;
  44086. /**
  44087. * @private
  44088. * @type {number}
  44089. */
  44090. this.rotation_ = options.rotation;
  44091. /**
  44092. * @private
  44093. * @type {number}
  44094. */
  44095. this.scale_ = options.scale;
  44096. /**
  44097. * @private
  44098. * @type {boolean}
  44099. */
  44100. this.snapToPixel_ = options.snapToPixel;
  44101. };
  44102. /**
  44103. * Get the symbolizer opacity.
  44104. * @return {number} Opacity.
  44105. * @api
  44106. */
  44107. ol.style.Image.prototype.getOpacity = function() {
  44108. return this.opacity_;
  44109. };
  44110. /**
  44111. * Determine whether the symbolizer rotates with the map.
  44112. * @return {boolean} Rotate with map.
  44113. * @api
  44114. */
  44115. ol.style.Image.prototype.getRotateWithView = function() {
  44116. return this.rotateWithView_;
  44117. };
  44118. /**
  44119. * Get the symoblizer rotation.
  44120. * @return {number} Rotation.
  44121. * @api
  44122. */
  44123. ol.style.Image.prototype.getRotation = function() {
  44124. return this.rotation_;
  44125. };
  44126. /**
  44127. * Get the symbolizer scale.
  44128. * @return {number} Scale.
  44129. * @api
  44130. */
  44131. ol.style.Image.prototype.getScale = function() {
  44132. return this.scale_;
  44133. };
  44134. /**
  44135. * Determine whether the symbolizer should be snapped to a pixel.
  44136. * @return {boolean} The symbolizer should snap to a pixel.
  44137. * @api
  44138. */
  44139. ol.style.Image.prototype.getSnapToPixel = function() {
  44140. return this.snapToPixel_;
  44141. };
  44142. /**
  44143. * Get the anchor point. The anchor determines the center point for the
  44144. * symbolizer. Its units are determined by `anchorXUnits` and `anchorYUnits`.
  44145. * @function
  44146. * @return {Array.<number>} Anchor.
  44147. */
  44148. ol.style.Image.prototype.getAnchor = goog.abstractMethod;
  44149. /**
  44150. * Get the image element for the symbolizer.
  44151. * @function
  44152. * @param {number} pixelRatio Pixel ratio.
  44153. * @return {HTMLCanvasElement|HTMLVideoElement|Image} Image element.
  44154. */
  44155. ol.style.Image.prototype.getImage = goog.abstractMethod;
  44156. /**
  44157. * @param {number} pixelRatio Pixel ratio.
  44158. * @return {HTMLCanvasElement|HTMLVideoElement|Image} Image element.
  44159. */
  44160. ol.style.Image.prototype.getHitDetectionImage = goog.abstractMethod;
  44161. /**
  44162. * @return {ol.style.ImageState} Image state.
  44163. */
  44164. ol.style.Image.prototype.getImageState = goog.abstractMethod;
  44165. /**
  44166. * @return {ol.Size} Image size.
  44167. */
  44168. ol.style.Image.prototype.getImageSize = goog.abstractMethod;
  44169. /**
  44170. * @return {ol.Size} Size of the hit-detection image.
  44171. */
  44172. ol.style.Image.prototype.getHitDetectionImageSize = goog.abstractMethod;
  44173. /**
  44174. * Get the origin of the symbolizer.
  44175. * @function
  44176. * @return {Array.<number>} Origin.
  44177. */
  44178. ol.style.Image.prototype.getOrigin = goog.abstractMethod;
  44179. /**
  44180. * Get the size of the symbolizer (in pixels).
  44181. * @function
  44182. * @return {ol.Size} Size.
  44183. */
  44184. ol.style.Image.prototype.getSize = goog.abstractMethod;
  44185. /**
  44186. * Set the opacity.
  44187. *
  44188. * @param {number} opacity Opacity.
  44189. * @api
  44190. */
  44191. ol.style.Image.prototype.setOpacity = function(opacity) {
  44192. this.opacity_ = opacity;
  44193. };
  44194. /**
  44195. * Set whether to rotate the style with the view.
  44196. *
  44197. * @param {boolean} rotateWithView Rotate with map.
  44198. */
  44199. ol.style.Image.prototype.setRotateWithView = function(rotateWithView) {
  44200. this.rotateWithView_ = rotateWithView;
  44201. };
  44202. /**
  44203. * Set the rotation.
  44204. *
  44205. * @param {number} rotation Rotation.
  44206. * @api
  44207. */
  44208. ol.style.Image.prototype.setRotation = function(rotation) {
  44209. this.rotation_ = rotation;
  44210. };
  44211. /**
  44212. * Set the scale.
  44213. *
  44214. * @param {number} scale Scale.
  44215. * @api
  44216. */
  44217. ol.style.Image.prototype.setScale = function(scale) {
  44218. this.scale_ = scale;
  44219. };
  44220. /**
  44221. * Set whether to snap the image to the closest pixel.
  44222. *
  44223. * @param {boolean} snapToPixel Snap to pixel?
  44224. */
  44225. ol.style.Image.prototype.setSnapToPixel = function(snapToPixel) {
  44226. this.snapToPixel_ = snapToPixel;
  44227. };
  44228. /**
  44229. * @param {function(this: T, goog.events.Event)} listener Listener function.
  44230. * @param {T} thisArg Value to use as `this` when executing `listener`.
  44231. * @return {goog.events.Key|undefined} Listener key.
  44232. * @template T
  44233. */
  44234. ol.style.Image.prototype.listenImageChange = goog.abstractMethod;
  44235. /**
  44236. * Load not yet loaded URI.
  44237. */
  44238. ol.style.Image.prototype.load = goog.abstractMethod;
  44239. /**
  44240. * @param {function(this: T, goog.events.Event)} listener Listener function.
  44241. * @param {T} thisArg Value to use as `this` when executing `listener`.
  44242. * @template T
  44243. */
  44244. ol.style.Image.prototype.unlistenImageChange = goog.abstractMethod;
  44245. goog.provide('ol.style.Icon');
  44246. goog.provide('ol.style.IconAnchorUnits');
  44247. goog.provide('ol.style.IconImageCache');
  44248. goog.provide('ol.style.IconOrigin');
  44249. goog.require('goog.asserts');
  44250. goog.require('goog.events');
  44251. goog.require('goog.events.EventTarget');
  44252. goog.require('goog.events.EventType');
  44253. goog.require('ol.dom');
  44254. goog.require('ol.style.Image');
  44255. goog.require('ol.style.ImageState');
  44256. /**
  44257. * Icon anchor units. One of 'fraction', 'pixels'.
  44258. * @enum {string}
  44259. * @api
  44260. */
  44261. ol.style.IconAnchorUnits = {
  44262. FRACTION: 'fraction',
  44263. PIXELS: 'pixels'
  44264. };
  44265. /**
  44266. * Icon origin. One of 'bottom-left', 'bottom-right', 'top-left', 'top-right'.
  44267. * @enum {string}
  44268. * @api
  44269. */
  44270. ol.style.IconOrigin = {
  44271. BOTTOM_LEFT: 'bottom-left',
  44272. BOTTOM_RIGHT: 'bottom-right',
  44273. TOP_LEFT: 'top-left',
  44274. TOP_RIGHT: 'top-right'
  44275. };
  44276. /**
  44277. * @classdesc
  44278. * Set icon style for vector features.
  44279. *
  44280. * @constructor
  44281. * @param {olx.style.IconOptions=} opt_options Options.
  44282. * @extends {ol.style.Image}
  44283. * @api
  44284. */
  44285. ol.style.Icon = function(opt_options) {
  44286. var options = opt_options || {};
  44287. /**
  44288. * @private
  44289. * @type {Array.<number>}
  44290. */
  44291. this.anchor_ = options.anchor !== undefined ? options.anchor : [0.5, 0.5];
  44292. /**
  44293. * @private
  44294. * @type {Array.<number>}
  44295. */
  44296. this.normalizedAnchor_ = null;
  44297. /**
  44298. * @private
  44299. * @type {ol.style.IconOrigin}
  44300. */
  44301. this.anchorOrigin_ = options.anchorOrigin !== undefined ?
  44302. options.anchorOrigin : ol.style.IconOrigin.TOP_LEFT;
  44303. /**
  44304. * @private
  44305. * @type {ol.style.IconAnchorUnits}
  44306. */
  44307. this.anchorXUnits_ = options.anchorXUnits !== undefined ?
  44308. options.anchorXUnits : ol.style.IconAnchorUnits.FRACTION;
  44309. /**
  44310. * @private
  44311. * @type {ol.style.IconAnchorUnits}
  44312. */
  44313. this.anchorYUnits_ = options.anchorYUnits !== undefined ?
  44314. options.anchorYUnits : ol.style.IconAnchorUnits.FRACTION;
  44315. /**
  44316. * @type {?string}
  44317. */
  44318. var crossOrigin =
  44319. options.crossOrigin !== undefined ? options.crossOrigin : null;
  44320. /**
  44321. * @type {Image}
  44322. */
  44323. var image = options.img !== undefined ? options.img : null;
  44324. /**
  44325. * @type {ol.Size}
  44326. */
  44327. var imgSize = options.imgSize !== undefined ? options.imgSize : null;
  44328. /**
  44329. * @type {string|undefined}
  44330. */
  44331. var src = options.src;
  44332. goog.asserts.assert(!(src !== undefined && image),
  44333. 'image and src can not provided at the same time');
  44334. goog.asserts.assert(
  44335. src === undefined || (src !== undefined && !imgSize),
  44336. 'imgSize should not be set when src is provided');
  44337. goog.asserts.assert(
  44338. !image || (image && imgSize),
  44339. 'imgSize must be set when image is provided');
  44340. if ((src === undefined || src.length === 0) && image) {
  44341. src = image.src;
  44342. }
  44343. goog.asserts.assert(src !== undefined && src.length > 0,
  44344. 'must provide a defined and non-empty src or image');
  44345. /**
  44346. * @type {ol.style.ImageState}
  44347. */
  44348. var imageState = options.src !== undefined ?
  44349. ol.style.ImageState.IDLE : ol.style.ImageState.LOADED;
  44350. /**
  44351. * @private
  44352. * @type {ol.style.IconImage_}
  44353. */
  44354. this.iconImage_ = ol.style.IconImage_.get(
  44355. image, src, imgSize, crossOrigin, imageState);
  44356. /**
  44357. * @private
  44358. * @type {Array.<number>}
  44359. */
  44360. this.offset_ = options.offset !== undefined ? options.offset : [0, 0];
  44361. /**
  44362. * @private
  44363. * @type {ol.style.IconOrigin}
  44364. */
  44365. this.offsetOrigin_ = options.offsetOrigin !== undefined ?
  44366. options.offsetOrigin : ol.style.IconOrigin.TOP_LEFT;
  44367. /**
  44368. * @private
  44369. * @type {Array.<number>}
  44370. */
  44371. this.origin_ = null;
  44372. /**
  44373. * @private
  44374. * @type {ol.Size}
  44375. */
  44376. this.size_ = options.size !== undefined ? options.size : null;
  44377. /**
  44378. * @type {number}
  44379. */
  44380. var opacity = options.opacity !== undefined ? options.opacity : 1;
  44381. /**
  44382. * @type {boolean}
  44383. */
  44384. var rotateWithView = options.rotateWithView !== undefined ?
  44385. options.rotateWithView : false;
  44386. /**
  44387. * @type {number}
  44388. */
  44389. var rotation = options.rotation !== undefined ? options.rotation : 0;
  44390. /**
  44391. * @type {number}
  44392. */
  44393. var scale = options.scale !== undefined ? options.scale : 1;
  44394. /**
  44395. * @type {boolean}
  44396. */
  44397. var snapToPixel = options.snapToPixel !== undefined ?
  44398. options.snapToPixel : true;
  44399. goog.base(this, {
  44400. opacity: opacity,
  44401. rotation: rotation,
  44402. scale: scale,
  44403. snapToPixel: snapToPixel,
  44404. rotateWithView: rotateWithView
  44405. });
  44406. };
  44407. goog.inherits(ol.style.Icon, ol.style.Image);
  44408. /**
  44409. * @inheritDoc
  44410. * @api
  44411. */
  44412. ol.style.Icon.prototype.getAnchor = function() {
  44413. if (this.normalizedAnchor_) {
  44414. return this.normalizedAnchor_;
  44415. }
  44416. var anchor = this.anchor_;
  44417. var size = this.getSize();
  44418. if (this.anchorXUnits_ == ol.style.IconAnchorUnits.FRACTION ||
  44419. this.anchorYUnits_ == ol.style.IconAnchorUnits.FRACTION) {
  44420. if (!size) {
  44421. return null;
  44422. }
  44423. anchor = this.anchor_.slice();
  44424. if (this.anchorXUnits_ == ol.style.IconAnchorUnits.FRACTION) {
  44425. anchor[0] *= size[0];
  44426. }
  44427. if (this.anchorYUnits_ == ol.style.IconAnchorUnits.FRACTION) {
  44428. anchor[1] *= size[1];
  44429. }
  44430. }
  44431. if (this.anchorOrigin_ != ol.style.IconOrigin.TOP_LEFT) {
  44432. if (!size) {
  44433. return null;
  44434. }
  44435. if (anchor === this.anchor_) {
  44436. anchor = this.anchor_.slice();
  44437. }
  44438. if (this.anchorOrigin_ == ol.style.IconOrigin.TOP_RIGHT ||
  44439. this.anchorOrigin_ == ol.style.IconOrigin.BOTTOM_RIGHT) {
  44440. anchor[0] = -anchor[0] + size[0];
  44441. }
  44442. if (this.anchorOrigin_ == ol.style.IconOrigin.BOTTOM_LEFT ||
  44443. this.anchorOrigin_ == ol.style.IconOrigin.BOTTOM_RIGHT) {
  44444. anchor[1] = -anchor[1] + size[1];
  44445. }
  44446. }
  44447. this.normalizedAnchor_ = anchor;
  44448. return this.normalizedAnchor_;
  44449. };
  44450. /**
  44451. * Get the image icon.
  44452. * @param {number} pixelRatio Pixel ratio.
  44453. * @return {Image} Image element.
  44454. * @api
  44455. */
  44456. ol.style.Icon.prototype.getImage = function(pixelRatio) {
  44457. return this.iconImage_.getImage(pixelRatio);
  44458. };
  44459. /**
  44460. * Real Image size used.
  44461. * @return {ol.Size} Size.
  44462. */
  44463. ol.style.Icon.prototype.getImageSize = function() {
  44464. return this.iconImage_.getSize();
  44465. };
  44466. /**
  44467. * @inheritDoc
  44468. */
  44469. ol.style.Icon.prototype.getHitDetectionImageSize = function() {
  44470. return this.getImageSize();
  44471. };
  44472. /**
  44473. * @inheritDoc
  44474. */
  44475. ol.style.Icon.prototype.getImageState = function() {
  44476. return this.iconImage_.getImageState();
  44477. };
  44478. /**
  44479. * @inheritDoc
  44480. */
  44481. ol.style.Icon.prototype.getHitDetectionImage = function(pixelRatio) {
  44482. return this.iconImage_.getHitDetectionImage(pixelRatio);
  44483. };
  44484. /**
  44485. * @inheritDoc
  44486. * @api
  44487. */
  44488. ol.style.Icon.prototype.getOrigin = function() {
  44489. if (this.origin_) {
  44490. return this.origin_;
  44491. }
  44492. var offset = this.offset_;
  44493. if (this.offsetOrigin_ != ol.style.IconOrigin.TOP_LEFT) {
  44494. var size = this.getSize();
  44495. var iconImageSize = this.iconImage_.getSize();
  44496. if (!size || !iconImageSize) {
  44497. return null;
  44498. }
  44499. offset = offset.slice();
  44500. if (this.offsetOrigin_ == ol.style.IconOrigin.TOP_RIGHT ||
  44501. this.offsetOrigin_ == ol.style.IconOrigin.BOTTOM_RIGHT) {
  44502. offset[0] = iconImageSize[0] - size[0] - offset[0];
  44503. }
  44504. if (this.offsetOrigin_ == ol.style.IconOrigin.BOTTOM_LEFT ||
  44505. this.offsetOrigin_ == ol.style.IconOrigin.BOTTOM_RIGHT) {
  44506. offset[1] = iconImageSize[1] - size[1] - offset[1];
  44507. }
  44508. }
  44509. this.origin_ = offset;
  44510. return this.origin_;
  44511. };
  44512. /**
  44513. * Get the image URL.
  44514. * @return {string|undefined} Image src.
  44515. * @api
  44516. */
  44517. ol.style.Icon.prototype.getSrc = function() {
  44518. return this.iconImage_.getSrc();
  44519. };
  44520. /**
  44521. * @inheritDoc
  44522. * @api
  44523. */
  44524. ol.style.Icon.prototype.getSize = function() {
  44525. return !this.size_ ? this.iconImage_.getSize() : this.size_;
  44526. };
  44527. /**
  44528. * @inheritDoc
  44529. */
  44530. ol.style.Icon.prototype.listenImageChange = function(listener, thisArg) {
  44531. return goog.events.listen(this.iconImage_, goog.events.EventType.CHANGE,
  44532. listener, false, thisArg);
  44533. };
  44534. /**
  44535. * Load not yet loaded URI.
  44536. * When rendering a feature with an icon style, the vector renderer will
  44537. * automatically call this method. However, you might want to call this
  44538. * method yourself for preloading or other purposes.
  44539. * @api
  44540. */
  44541. ol.style.Icon.prototype.load = function() {
  44542. this.iconImage_.load();
  44543. };
  44544. /**
  44545. * @inheritDoc
  44546. */
  44547. ol.style.Icon.prototype.unlistenImageChange = function(listener, thisArg) {
  44548. goog.events.unlisten(this.iconImage_, goog.events.EventType.CHANGE,
  44549. listener, false, thisArg);
  44550. };
  44551. /**
  44552. * @constructor
  44553. * @param {Image} image Image.
  44554. * @param {string|undefined} src Src.
  44555. * @param {ol.Size} size Size.
  44556. * @param {?string} crossOrigin Cross origin.
  44557. * @param {ol.style.ImageState} imageState Image state.
  44558. * @extends {goog.events.EventTarget}
  44559. * @private
  44560. */
  44561. ol.style.IconImage_ = function(image, src, size, crossOrigin, imageState) {
  44562. goog.base(this);
  44563. /**
  44564. * @private
  44565. * @type {Image|HTMLCanvasElement}
  44566. */
  44567. this.hitDetectionImage_ = null;
  44568. /**
  44569. * @private
  44570. * @type {Image}
  44571. */
  44572. this.image_ = !image ? new Image() : image;
  44573. if (crossOrigin) {
  44574. this.image_.crossOrigin = crossOrigin;
  44575. }
  44576. /**
  44577. * @private
  44578. * @type {Array.<goog.events.Key>}
  44579. */
  44580. this.imageListenerKeys_ = null;
  44581. /**
  44582. * @private
  44583. * @type {ol.style.ImageState}
  44584. */
  44585. this.imageState_ = imageState;
  44586. /**
  44587. * @private
  44588. * @type {ol.Size}
  44589. */
  44590. this.size_ = size;
  44591. /**
  44592. * @private
  44593. * @type {string|undefined}
  44594. */
  44595. this.src_ = src;
  44596. /**
  44597. * @private
  44598. * @type {boolean}
  44599. */
  44600. this.tainting_ = false;
  44601. if (this.imageState_ == ol.style.ImageState.LOADED) {
  44602. this.determineTainting_();
  44603. }
  44604. };
  44605. goog.inherits(ol.style.IconImage_, goog.events.EventTarget);
  44606. /**
  44607. * @param {Image} image Image.
  44608. * @param {string} src Src.
  44609. * @param {ol.Size} size Size.
  44610. * @param {?string} crossOrigin Cross origin.
  44611. * @param {ol.style.ImageState} imageState Image state.
  44612. * @return {ol.style.IconImage_} Icon image.
  44613. */
  44614. ol.style.IconImage_.get = function(image, src, size, crossOrigin, imageState) {
  44615. var iconImageCache = ol.style.IconImageCache.getInstance();
  44616. var iconImage = iconImageCache.get(src, crossOrigin);
  44617. if (!iconImage) {
  44618. iconImage = new ol.style.IconImage_(
  44619. image, src, size, crossOrigin, imageState);
  44620. iconImageCache.set(src, crossOrigin, iconImage);
  44621. }
  44622. return iconImage;
  44623. };
  44624. /**
  44625. * @private
  44626. */
  44627. ol.style.IconImage_.prototype.determineTainting_ = function() {
  44628. var context = ol.dom.createCanvasContext2D(1, 1);
  44629. try {
  44630. context.drawImage(this.image_, 0, 0);
  44631. context.getImageData(0, 0, 1, 1);
  44632. } catch (e) {
  44633. this.tainting_ = true;
  44634. }
  44635. };
  44636. /**
  44637. * @private
  44638. */
  44639. ol.style.IconImage_.prototype.dispatchChangeEvent_ = function() {
  44640. this.dispatchEvent(goog.events.EventType.CHANGE);
  44641. };
  44642. /**
  44643. * @private
  44644. */
  44645. ol.style.IconImage_.prototype.handleImageError_ = function() {
  44646. this.imageState_ = ol.style.ImageState.ERROR;
  44647. this.unlistenImage_();
  44648. this.dispatchChangeEvent_();
  44649. };
  44650. /**
  44651. * @private
  44652. */
  44653. ol.style.IconImage_.prototype.handleImageLoad_ = function() {
  44654. this.imageState_ = ol.style.ImageState.LOADED;
  44655. this.size_ = [this.image_.width, this.image_.height];
  44656. this.unlistenImage_();
  44657. this.determineTainting_();
  44658. this.dispatchChangeEvent_();
  44659. };
  44660. /**
  44661. * @param {number} pixelRatio Pixel ratio.
  44662. * @return {Image} Image element.
  44663. */
  44664. ol.style.IconImage_.prototype.getImage = function(pixelRatio) {
  44665. return this.image_;
  44666. };
  44667. /**
  44668. * @return {ol.style.ImageState} Image state.
  44669. */
  44670. ol.style.IconImage_.prototype.getImageState = function() {
  44671. return this.imageState_;
  44672. };
  44673. /**
  44674. * @param {number} pixelRatio Pixel ratio.
  44675. * @return {Image|HTMLCanvasElement} Image element.
  44676. */
  44677. ol.style.IconImage_.prototype.getHitDetectionImage = function(pixelRatio) {
  44678. if (!this.hitDetectionImage_) {
  44679. if (this.tainting_) {
  44680. var width = this.size_[0];
  44681. var height = this.size_[1];
  44682. var context = ol.dom.createCanvasContext2D(width, height);
  44683. context.fillRect(0, 0, width, height);
  44684. this.hitDetectionImage_ = context.canvas;
  44685. } else {
  44686. this.hitDetectionImage_ = this.image_;
  44687. }
  44688. }
  44689. return this.hitDetectionImage_;
  44690. };
  44691. /**
  44692. * @return {ol.Size} Image size.
  44693. */
  44694. ol.style.IconImage_.prototype.getSize = function() {
  44695. return this.size_;
  44696. };
  44697. /**
  44698. * @return {string|undefined} Image src.
  44699. */
  44700. ol.style.IconImage_.prototype.getSrc = function() {
  44701. return this.src_;
  44702. };
  44703. /**
  44704. * Load not yet loaded URI.
  44705. */
  44706. ol.style.IconImage_.prototype.load = function() {
  44707. if (this.imageState_ == ol.style.ImageState.IDLE) {
  44708. goog.asserts.assert(this.src_ !== undefined,
  44709. 'this.src_ must not be undefined');
  44710. goog.asserts.assert(!this.imageListenerKeys_,
  44711. 'no listener keys existing');
  44712. this.imageState_ = ol.style.ImageState.LOADING;
  44713. this.imageListenerKeys_ = [
  44714. goog.events.listenOnce(this.image_, goog.events.EventType.ERROR,
  44715. this.handleImageError_, false, this),
  44716. goog.events.listenOnce(this.image_, goog.events.EventType.LOAD,
  44717. this.handleImageLoad_, false, this)
  44718. ];
  44719. try {
  44720. this.image_.src = this.src_;
  44721. } catch (e) {
  44722. this.handleImageError_();
  44723. }
  44724. }
  44725. };
  44726. /**
  44727. * Discards event handlers which listen for load completion or errors.
  44728. *
  44729. * @private
  44730. */
  44731. ol.style.IconImage_.prototype.unlistenImage_ = function() {
  44732. goog.asserts.assert(this.imageListenerKeys_,
  44733. 'we must have listeners registered');
  44734. this.imageListenerKeys_.forEach(goog.events.unlistenByKey);
  44735. this.imageListenerKeys_ = null;
  44736. };
  44737. /**
  44738. * @constructor
  44739. */
  44740. ol.style.IconImageCache = function() {
  44741. /**
  44742. * @type {Object.<string, ol.style.IconImage_>}
  44743. * @private
  44744. */
  44745. this.cache_ = {};
  44746. /**
  44747. * @type {number}
  44748. * @private
  44749. */
  44750. this.cacheSize_ = 0;
  44751. /**
  44752. * @const
  44753. * @type {number}
  44754. * @private
  44755. */
  44756. this.maxCacheSize_ = 32;
  44757. };
  44758. goog.addSingletonGetter(ol.style.IconImageCache);
  44759. /**
  44760. * @param {string} src Src.
  44761. * @param {?string} crossOrigin Cross origin.
  44762. * @return {string} Cache key.
  44763. */
  44764. ol.style.IconImageCache.getKey = function(src, crossOrigin) {
  44765. goog.asserts.assert(crossOrigin !== undefined,
  44766. 'argument crossOrigin must be defined');
  44767. return crossOrigin + ':' + src;
  44768. };
  44769. /**
  44770. * FIXME empty description for jsdoc
  44771. */
  44772. ol.style.IconImageCache.prototype.clear = function() {
  44773. this.cache_ = {};
  44774. this.cacheSize_ = 0;
  44775. };
  44776. /**
  44777. * FIXME empty description for jsdoc
  44778. */
  44779. ol.style.IconImageCache.prototype.expire = function() {
  44780. if (this.cacheSize_ > this.maxCacheSize_) {
  44781. var i = 0;
  44782. var key, iconImage;
  44783. for (key in this.cache_) {
  44784. iconImage = this.cache_[key];
  44785. if ((i++ & 3) === 0 && !goog.events.hasListener(iconImage)) {
  44786. delete this.cache_[key];
  44787. --this.cacheSize_;
  44788. }
  44789. }
  44790. }
  44791. };
  44792. /**
  44793. * @param {string} src Src.
  44794. * @param {?string} crossOrigin Cross origin.
  44795. * @return {ol.style.IconImage_} Icon image.
  44796. */
  44797. ol.style.IconImageCache.prototype.get = function(src, crossOrigin) {
  44798. var key = ol.style.IconImageCache.getKey(src, crossOrigin);
  44799. return key in this.cache_ ? this.cache_[key] : null;
  44800. };
  44801. /**
  44802. * @param {string} src Src.
  44803. * @param {?string} crossOrigin Cross origin.
  44804. * @param {ol.style.IconImage_} iconImage Icon image.
  44805. */
  44806. ol.style.IconImageCache.prototype.set = function(src, crossOrigin, iconImage) {
  44807. var key = ol.style.IconImageCache.getKey(src, crossOrigin);
  44808. this.cache_[key] = iconImage;
  44809. ++this.cacheSize_;
  44810. };
  44811. goog.provide('ol.RendererType');
  44812. goog.provide('ol.renderer.Map');
  44813. goog.require('goog.Disposable');
  44814. goog.require('goog.asserts');
  44815. goog.require('goog.dispose');
  44816. goog.require('goog.events');
  44817. goog.require('goog.events.EventType');
  44818. goog.require('goog.functions');
  44819. goog.require('goog.object');
  44820. goog.require('goog.vec.Mat4');
  44821. goog.require('ol');
  44822. goog.require('ol.extent');
  44823. goog.require('ol.layer.Layer');
  44824. goog.require('ol.renderer.Layer');
  44825. goog.require('ol.style.IconImageCache');
  44826. goog.require('ol.vec.Mat4');
  44827. /**
  44828. * Available renderers: `'canvas'`, `'dom'` or `'webgl'`.
  44829. * @enum {string}
  44830. * @api stable
  44831. */
  44832. ol.RendererType = {
  44833. CANVAS: 'canvas',
  44834. DOM: 'dom',
  44835. WEBGL: 'webgl'
  44836. };
  44837. /**
  44838. * @constructor
  44839. * @extends {goog.Disposable}
  44840. * @param {Element} container Container.
  44841. * @param {ol.Map} map Map.
  44842. * @struct
  44843. */
  44844. ol.renderer.Map = function(container, map) {
  44845. goog.base(this);
  44846. /**
  44847. * @private
  44848. * @type {ol.Map}
  44849. */
  44850. this.map_ = map;
  44851. /**
  44852. * @private
  44853. * @type {Object.<string, ol.renderer.Layer>}
  44854. */
  44855. this.layerRenderers_ = {};
  44856. /**
  44857. * @private
  44858. * @type {Object.<string, goog.events.Key>}
  44859. */
  44860. this.layerRendererListeners_ = {};
  44861. };
  44862. goog.inherits(ol.renderer.Map, goog.Disposable);
  44863. /**
  44864. * @param {olx.FrameState} frameState FrameState.
  44865. * @protected
  44866. */
  44867. ol.renderer.Map.prototype.calculateMatrices2D = function(frameState) {
  44868. var viewState = frameState.viewState;
  44869. var coordinateToPixelMatrix = frameState.coordinateToPixelMatrix;
  44870. goog.asserts.assert(coordinateToPixelMatrix,
  44871. 'frameState has a coordinateToPixelMatrix');
  44872. ol.vec.Mat4.makeTransform2D(coordinateToPixelMatrix,
  44873. frameState.size[0] / 2, frameState.size[1] / 2,
  44874. 1 / viewState.resolution, -1 / viewState.resolution,
  44875. -viewState.rotation,
  44876. -viewState.center[0], -viewState.center[1]);
  44877. var inverted = goog.vec.Mat4.invert(
  44878. coordinateToPixelMatrix, frameState.pixelToCoordinateMatrix);
  44879. goog.asserts.assert(inverted, 'matrix could be inverted');
  44880. };
  44881. /**
  44882. * @param {ol.layer.Layer} layer Layer.
  44883. * @protected
  44884. * @return {ol.renderer.Layer} layerRenderer Layer renderer.
  44885. */
  44886. ol.renderer.Map.prototype.createLayerRenderer = goog.abstractMethod;
  44887. /**
  44888. * @inheritDoc
  44889. */
  44890. ol.renderer.Map.prototype.disposeInternal = function() {
  44891. goog.object.forEach(this.layerRenderers_, goog.dispose);
  44892. goog.base(this, 'disposeInternal');
  44893. };
  44894. /**
  44895. * @param {ol.Map} map Map.
  44896. * @param {olx.FrameState} frameState Frame state.
  44897. * @private
  44898. */
  44899. ol.renderer.Map.expireIconCache_ = function(map, frameState) {
  44900. ol.style.IconImageCache.getInstance().expire();
  44901. };
  44902. /**
  44903. * @param {ol.Coordinate} coordinate Coordinate.
  44904. * @param {olx.FrameState} frameState FrameState.
  44905. * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
  44906. * callback.
  44907. * @param {S} thisArg Value to use as `this` when executing `callback`.
  44908. * @param {function(this: U, ol.layer.Layer): boolean} layerFilter Layer filter
  44909. * function, only layers which are visible and for which this function
  44910. * returns `true` will be tested for features. By default, all visible
  44911. * layers will be tested.
  44912. * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.
  44913. * @return {T|undefined} Callback result.
  44914. * @template S,T,U
  44915. */
  44916. ol.renderer.Map.prototype.forEachFeatureAtCoordinate =
  44917. function(coordinate, frameState, callback, thisArg,
  44918. layerFilter, thisArg2) {
  44919. var result;
  44920. var viewState = frameState.viewState;
  44921. var viewResolution = viewState.resolution;
  44922. /** @type {Object.<string, boolean>} */
  44923. var features = {};
  44924. /**
  44925. * @param {ol.Feature} feature Feature.
  44926. * @return {?} Callback result.
  44927. */
  44928. function forEachFeatureAtCoordinate(feature) {
  44929. goog.asserts.assert(feature !== undefined, 'received a feature');
  44930. var key = goog.getUid(feature).toString();
  44931. if (!(key in features)) {
  44932. features[key] = true;
  44933. return callback.call(thisArg, feature, null);
  44934. }
  44935. }
  44936. var projection = viewState.projection;
  44937. var translatedCoordinate = coordinate;
  44938. if (projection.canWrapX()) {
  44939. var projectionExtent = projection.getExtent();
  44940. var worldWidth = ol.extent.getWidth(projectionExtent);
  44941. var x = coordinate[0];
  44942. if (x < projectionExtent[0] || x > projectionExtent[2]) {
  44943. var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
  44944. translatedCoordinate = [x + worldWidth * worldsAway, coordinate[1]];
  44945. }
  44946. }
  44947. var layerStates = frameState.layerStatesArray;
  44948. var numLayers = layerStates.length;
  44949. var i;
  44950. for (i = numLayers - 1; i >= 0; --i) {
  44951. var layerState = layerStates[i];
  44952. var layer = layerState.layer;
  44953. if (!layerState.managed ||
  44954. (ol.layer.Layer.visibleAtResolution(layerState, viewResolution) &&
  44955. layerFilter.call(thisArg2, layer))) {
  44956. var layerRenderer = this.getLayerRenderer(layer);
  44957. if (layer.getSource()) {
  44958. result = layerRenderer.forEachFeatureAtCoordinate(
  44959. layer.getSource().getWrapX() ? translatedCoordinate : coordinate,
  44960. frameState, callback, thisArg);
  44961. }
  44962. if (result) {
  44963. return result;
  44964. }
  44965. }
  44966. }
  44967. return undefined;
  44968. };
  44969. /**
  44970. * @param {ol.Pixel} pixel Pixel.
  44971. * @param {olx.FrameState} frameState FrameState.
  44972. * @param {function(this: S, ol.layer.Layer): T} callback Layer
  44973. * callback.
  44974. * @param {S} thisArg Value to use as `this` when executing `callback`.
  44975. * @param {function(this: U, ol.layer.Layer): boolean} layerFilter Layer filter
  44976. * function, only layers which are visible and for which this function
  44977. * returns `true` will be tested for features. By default, all visible
  44978. * layers will be tested.
  44979. * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.
  44980. * @return {T|undefined} Callback result.
  44981. * @template S,T,U
  44982. */
  44983. ol.renderer.Map.prototype.forEachLayerAtPixel =
  44984. function(pixel, frameState, callback, thisArg,
  44985. layerFilter, thisArg2) {
  44986. var result;
  44987. var viewState = frameState.viewState;
  44988. var viewResolution = viewState.resolution;
  44989. var layerStates = frameState.layerStatesArray;
  44990. var numLayers = layerStates.length;
  44991. var i;
  44992. for (i = numLayers - 1; i >= 0; --i) {
  44993. var layerState = layerStates[i];
  44994. var layer = layerState.layer;
  44995. if (ol.layer.Layer.visibleAtResolution(layerState, viewResolution) &&
  44996. layerFilter.call(thisArg2, layer)) {
  44997. var layerRenderer = this.getLayerRenderer(layer);
  44998. result = layerRenderer.forEachLayerAtPixel(
  44999. pixel, frameState, callback, thisArg);
  45000. if (result) {
  45001. return result;
  45002. }
  45003. }
  45004. }
  45005. return undefined;
  45006. };
  45007. /**
  45008. * @param {ol.Coordinate} coordinate Coordinate.
  45009. * @param {olx.FrameState} frameState FrameState.
  45010. * @param {function(this: U, ol.layer.Layer): boolean} layerFilter Layer filter
  45011. * function, only layers which are visible and for which this function
  45012. * returns `true` will be tested for features. By default, all visible
  45013. * layers will be tested.
  45014. * @param {U} thisArg Value to use as `this` when executing `layerFilter`.
  45015. * @return {boolean} Is there a feature at the given coordinate?
  45016. * @template U
  45017. */
  45018. ol.renderer.Map.prototype.hasFeatureAtCoordinate =
  45019. function(coordinate, frameState, layerFilter, thisArg) {
  45020. var hasFeature = this.forEachFeatureAtCoordinate(
  45021. coordinate, frameState, goog.functions.TRUE, this, layerFilter, thisArg);
  45022. return hasFeature !== undefined;
  45023. };
  45024. /**
  45025. * @param {ol.layer.Layer} layer Layer.
  45026. * @protected
  45027. * @return {ol.renderer.Layer} Layer renderer.
  45028. */
  45029. ol.renderer.Map.prototype.getLayerRenderer = function(layer) {
  45030. var layerKey = goog.getUid(layer).toString();
  45031. if (layerKey in this.layerRenderers_) {
  45032. return this.layerRenderers_[layerKey];
  45033. } else {
  45034. var layerRenderer = this.createLayerRenderer(layer);
  45035. this.layerRenderers_[layerKey] = layerRenderer;
  45036. this.layerRendererListeners_[layerKey] = goog.events.listen(layerRenderer,
  45037. goog.events.EventType.CHANGE, this.handleLayerRendererChange_,
  45038. false, this);
  45039. return layerRenderer;
  45040. }
  45041. };
  45042. /**
  45043. * @param {string} layerKey Layer key.
  45044. * @protected
  45045. * @return {ol.renderer.Layer} Layer renderer.
  45046. */
  45047. ol.renderer.Map.prototype.getLayerRendererByKey = function(layerKey) {
  45048. goog.asserts.assert(layerKey in this.layerRenderers_,
  45049. 'given layerKey (%s) exists in layerRenderers', layerKey);
  45050. return this.layerRenderers_[layerKey];
  45051. };
  45052. /**
  45053. * @protected
  45054. * @return {Object.<number, ol.renderer.Layer>} Layer renderers.
  45055. */
  45056. ol.renderer.Map.prototype.getLayerRenderers = function() {
  45057. return this.layerRenderers_;
  45058. };
  45059. /**
  45060. * @return {ol.Map} Map.
  45061. */
  45062. ol.renderer.Map.prototype.getMap = function() {
  45063. return this.map_;
  45064. };
  45065. /**
  45066. * @return {string} Type
  45067. */
  45068. ol.renderer.Map.prototype.getType = goog.abstractMethod;
  45069. /**
  45070. * Handle changes in a layer renderer.
  45071. * @private
  45072. */
  45073. ol.renderer.Map.prototype.handleLayerRendererChange_ = function() {
  45074. this.map_.render();
  45075. };
  45076. /**
  45077. * @param {string} layerKey Layer key.
  45078. * @return {ol.renderer.Layer} Layer renderer.
  45079. * @private
  45080. */
  45081. ol.renderer.Map.prototype.removeLayerRendererByKey_ = function(layerKey) {
  45082. goog.asserts.assert(layerKey in this.layerRenderers_,
  45083. 'given layerKey (%s) exists in layerRenderers', layerKey);
  45084. var layerRenderer = this.layerRenderers_[layerKey];
  45085. delete this.layerRenderers_[layerKey];
  45086. goog.asserts.assert(layerKey in this.layerRendererListeners_,
  45087. 'given layerKey (%s) exists in layerRendererListeners', layerKey);
  45088. goog.events.unlistenByKey(this.layerRendererListeners_[layerKey]);
  45089. delete this.layerRendererListeners_[layerKey];
  45090. return layerRenderer;
  45091. };
  45092. /**
  45093. * Render.
  45094. * @param {?olx.FrameState} frameState Frame state.
  45095. */
  45096. ol.renderer.Map.prototype.renderFrame = ol.nullFunction;
  45097. /**
  45098. * @param {ol.Map} map Map.
  45099. * @param {olx.FrameState} frameState Frame state.
  45100. * @private
  45101. */
  45102. ol.renderer.Map.prototype.removeUnusedLayerRenderers_ =
  45103. function(map, frameState) {
  45104. var layerKey;
  45105. for (layerKey in this.layerRenderers_) {
  45106. if (!frameState || !(layerKey in frameState.layerStates)) {
  45107. goog.dispose(this.removeLayerRendererByKey_(layerKey));
  45108. }
  45109. }
  45110. };
  45111. /**
  45112. * @param {olx.FrameState} frameState Frame state.
  45113. * @protected
  45114. */
  45115. ol.renderer.Map.prototype.scheduleExpireIconCache = function(frameState) {
  45116. frameState.postRenderFunctions.push(ol.renderer.Map.expireIconCache_);
  45117. };
  45118. /**
  45119. * @param {!olx.FrameState} frameState Frame state.
  45120. * @protected
  45121. */
  45122. ol.renderer.Map.prototype.scheduleRemoveUnusedLayerRenderers =
  45123. function(frameState) {
  45124. var layerKey;
  45125. for (layerKey in this.layerRenderers_) {
  45126. if (!(layerKey in frameState.layerStates)) {
  45127. frameState.postRenderFunctions.push(
  45128. goog.bind(this.removeUnusedLayerRenderers_, this));
  45129. return;
  45130. }
  45131. }
  45132. };
  45133. /**
  45134. * @param {ol.layer.LayerState} state1
  45135. * @param {ol.layer.LayerState} state2
  45136. * @return {number}
  45137. */
  45138. ol.renderer.Map.sortByZIndex = function(state1, state2) {
  45139. return state1.zIndex - state2.zIndex;
  45140. };
  45141. goog.provide('ol.structs.PriorityQueue');
  45142. goog.require('goog.asserts');
  45143. goog.require('goog.object');
  45144. /**
  45145. * Priority queue.
  45146. *
  45147. * The implementation is inspired from the Closure Library's Heap class and
  45148. * Python's heapq module.
  45149. *
  45150. * @see http://closure-library.googlecode.com/svn/docs/closure_goog_structs_heap.js.source.html
  45151. * @see http://hg.python.org/cpython/file/2.7/Lib/heapq.py
  45152. *
  45153. * @constructor
  45154. * @param {function(T): number} priorityFunction Priority function.
  45155. * @param {function(T): string} keyFunction Key function.
  45156. * @struct
  45157. * @template T
  45158. */
  45159. ol.structs.PriorityQueue = function(priorityFunction, keyFunction) {
  45160. /**
  45161. * @type {function(T): number}
  45162. * @private
  45163. */
  45164. this.priorityFunction_ = priorityFunction;
  45165. /**
  45166. * @type {function(T): string}
  45167. * @private
  45168. */
  45169. this.keyFunction_ = keyFunction;
  45170. /**
  45171. * @type {Array.<T>}
  45172. * @private
  45173. */
  45174. this.elements_ = [];
  45175. /**
  45176. * @type {Array.<number>}
  45177. * @private
  45178. */
  45179. this.priorities_ = [];
  45180. /**
  45181. * @type {Object.<string, boolean>}
  45182. * @private
  45183. */
  45184. this.queuedElements_ = {};
  45185. };
  45186. /**
  45187. * @const
  45188. * @type {number}
  45189. */
  45190. ol.structs.PriorityQueue.DROP = Infinity;
  45191. /**
  45192. * FIXME empty description for jsdoc
  45193. */
  45194. ol.structs.PriorityQueue.prototype.assertValid = function() {
  45195. var elements = this.elements_;
  45196. var priorities = this.priorities_;
  45197. var n = elements.length;
  45198. goog.asserts.assert(priorities.length == n);
  45199. var i, priority;
  45200. for (i = 0; i < (n >> 1) - 1; ++i) {
  45201. priority = priorities[i];
  45202. goog.asserts.assert(priority <= priorities[this.getLeftChildIndex_(i)],
  45203. 'priority smaller than or equal to priority of left child (%s <= %s)',
  45204. priority, priorities[this.getLeftChildIndex_(i)]);
  45205. goog.asserts.assert(priority <= priorities[this.getRightChildIndex_(i)],
  45206. 'priority smaller than or equal to priority of right child (%s <= %s)',
  45207. priority, priorities[this.getRightChildIndex_(i)]);
  45208. }
  45209. };
  45210. /**
  45211. * FIXME empty description for jsdoc
  45212. */
  45213. ol.structs.PriorityQueue.prototype.clear = function() {
  45214. this.elements_.length = 0;
  45215. this.priorities_.length = 0;
  45216. goog.object.clear(this.queuedElements_);
  45217. };
  45218. /**
  45219. * Remove and return the highest-priority element. O(log N).
  45220. * @return {T} Element.
  45221. */
  45222. ol.structs.PriorityQueue.prototype.dequeue = function() {
  45223. var elements = this.elements_;
  45224. goog.asserts.assert(elements.length > 0,
  45225. 'must have elements in order to be able to dequeue');
  45226. var priorities = this.priorities_;
  45227. var element = elements[0];
  45228. if (elements.length == 1) {
  45229. elements.length = 0;
  45230. priorities.length = 0;
  45231. } else {
  45232. elements[0] = elements.pop();
  45233. priorities[0] = priorities.pop();
  45234. this.siftUp_(0);
  45235. }
  45236. var elementKey = this.keyFunction_(element);
  45237. goog.asserts.assert(elementKey in this.queuedElements_,
  45238. 'key %s is not listed as queued', elementKey);
  45239. delete this.queuedElements_[elementKey];
  45240. return element;
  45241. };
  45242. /**
  45243. * Enqueue an element. O(log N).
  45244. * @param {T} element Element.
  45245. */
  45246. ol.structs.PriorityQueue.prototype.enqueue = function(element) {
  45247. goog.asserts.assert(!(this.keyFunction_(element) in this.queuedElements_),
  45248. 'key %s is already listed as queued', this.keyFunction_(element));
  45249. var priority = this.priorityFunction_(element);
  45250. if (priority != ol.structs.PriorityQueue.DROP) {
  45251. this.elements_.push(element);
  45252. this.priorities_.push(priority);
  45253. this.queuedElements_[this.keyFunction_(element)] = true;
  45254. this.siftDown_(0, this.elements_.length - 1);
  45255. }
  45256. };
  45257. /**
  45258. * @return {number} Count.
  45259. */
  45260. ol.structs.PriorityQueue.prototype.getCount = function() {
  45261. return this.elements_.length;
  45262. };
  45263. /**
  45264. * Gets the index of the left child of the node at the given index.
  45265. * @param {number} index The index of the node to get the left child for.
  45266. * @return {number} The index of the left child.
  45267. * @private
  45268. */
  45269. ol.structs.PriorityQueue.prototype.getLeftChildIndex_ = function(index) {
  45270. return index * 2 + 1;
  45271. };
  45272. /**
  45273. * Gets the index of the right child of the node at the given index.
  45274. * @param {number} index The index of the node to get the right child for.
  45275. * @return {number} The index of the right child.
  45276. * @private
  45277. */
  45278. ol.structs.PriorityQueue.prototype.getRightChildIndex_ = function(index) {
  45279. return index * 2 + 2;
  45280. };
  45281. /**
  45282. * Gets the index of the parent of the node at the given index.
  45283. * @param {number} index The index of the node to get the parent for.
  45284. * @return {number} The index of the parent.
  45285. * @private
  45286. */
  45287. ol.structs.PriorityQueue.prototype.getParentIndex_ = function(index) {
  45288. return (index - 1) >> 1;
  45289. };
  45290. /**
  45291. * Make this a heap. O(N).
  45292. * @private
  45293. */
  45294. ol.structs.PriorityQueue.prototype.heapify_ = function() {
  45295. var i;
  45296. for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) {
  45297. this.siftUp_(i);
  45298. }
  45299. };
  45300. /**
  45301. * @return {boolean} Is empty.
  45302. */
  45303. ol.structs.PriorityQueue.prototype.isEmpty = function() {
  45304. return this.elements_.length === 0;
  45305. };
  45306. /**
  45307. * @param {string} key Key.
  45308. * @return {boolean} Is key queued.
  45309. */
  45310. ol.structs.PriorityQueue.prototype.isKeyQueued = function(key) {
  45311. return key in this.queuedElements_;
  45312. };
  45313. /**
  45314. * @param {T} element Element.
  45315. * @return {boolean} Is queued.
  45316. */
  45317. ol.structs.PriorityQueue.prototype.isQueued = function(element) {
  45318. return this.isKeyQueued(this.keyFunction_(element));
  45319. };
  45320. /**
  45321. * @param {number} index The index of the node to move down.
  45322. * @private
  45323. */
  45324. ol.structs.PriorityQueue.prototype.siftUp_ = function(index) {
  45325. var elements = this.elements_;
  45326. var priorities = this.priorities_;
  45327. var count = elements.length;
  45328. var element = elements[index];
  45329. var priority = priorities[index];
  45330. var startIndex = index;
  45331. while (index < (count >> 1)) {
  45332. var lIndex = this.getLeftChildIndex_(index);
  45333. var rIndex = this.getRightChildIndex_(index);
  45334. var smallerChildIndex = rIndex < count &&
  45335. priorities[rIndex] < priorities[lIndex] ?
  45336. rIndex : lIndex;
  45337. elements[index] = elements[smallerChildIndex];
  45338. priorities[index] = priorities[smallerChildIndex];
  45339. index = smallerChildIndex;
  45340. }
  45341. elements[index] = element;
  45342. priorities[index] = priority;
  45343. this.siftDown_(startIndex, index);
  45344. };
  45345. /**
  45346. * @param {number} startIndex The index of the root.
  45347. * @param {number} index The index of the node to move up.
  45348. * @private
  45349. */
  45350. ol.structs.PriorityQueue.prototype.siftDown_ = function(startIndex, index) {
  45351. var elements = this.elements_;
  45352. var priorities = this.priorities_;
  45353. var element = elements[index];
  45354. var priority = priorities[index];
  45355. while (index > startIndex) {
  45356. var parentIndex = this.getParentIndex_(index);
  45357. if (priorities[parentIndex] > priority) {
  45358. elements[index] = elements[parentIndex];
  45359. priorities[index] = priorities[parentIndex];
  45360. index = parentIndex;
  45361. } else {
  45362. break;
  45363. }
  45364. }
  45365. elements[index] = element;
  45366. priorities[index] = priority;
  45367. };
  45368. /**
  45369. * FIXME empty description for jsdoc
  45370. */
  45371. ol.structs.PriorityQueue.prototype.reprioritize = function() {
  45372. var priorityFunction = this.priorityFunction_;
  45373. var elements = this.elements_;
  45374. var priorities = this.priorities_;
  45375. var index = 0;
  45376. var n = elements.length;
  45377. var element, i, priority;
  45378. for (i = 0; i < n; ++i) {
  45379. element = elements[i];
  45380. priority = priorityFunction(element);
  45381. if (priority == ol.structs.PriorityQueue.DROP) {
  45382. delete this.queuedElements_[this.keyFunction_(element)];
  45383. } else {
  45384. priorities[index] = priority;
  45385. elements[index++] = element;
  45386. }
  45387. }
  45388. elements.length = index;
  45389. priorities.length = index;
  45390. this.heapify_();
  45391. };
  45392. goog.provide('ol.TilePriorityFunction');
  45393. goog.provide('ol.TileQueue');
  45394. goog.require('goog.events');
  45395. goog.require('goog.events.EventType');
  45396. goog.require('ol.Coordinate');
  45397. goog.require('ol.TileState');
  45398. goog.require('ol.structs.PriorityQueue');
  45399. /**
  45400. * @typedef {function(ol.Tile, string, ol.Coordinate, number): number}
  45401. */
  45402. ol.TilePriorityFunction;
  45403. /**
  45404. * @constructor
  45405. * @extends {ol.structs.PriorityQueue.<Array>}
  45406. * @param {ol.TilePriorityFunction} tilePriorityFunction
  45407. * Tile priority function.
  45408. * @param {function(): ?} tileChangeCallback
  45409. * Function called on each tile change event.
  45410. * @struct
  45411. */
  45412. ol.TileQueue = function(tilePriorityFunction, tileChangeCallback) {
  45413. goog.base(
  45414. this,
  45415. /**
  45416. * @param {Array} element Element.
  45417. * @return {number} Priority.
  45418. */
  45419. function(element) {
  45420. return tilePriorityFunction.apply(null, element);
  45421. },
  45422. /**
  45423. * @param {Array} element Element.
  45424. * @return {string} Key.
  45425. */
  45426. function(element) {
  45427. return /** @type {ol.Tile} */ (element[0]).getKey();
  45428. });
  45429. /**
  45430. * @private
  45431. * @type {function(): ?}
  45432. */
  45433. this.tileChangeCallback_ = tileChangeCallback;
  45434. /**
  45435. * @private
  45436. * @type {number}
  45437. */
  45438. this.tilesLoading_ = 0;
  45439. };
  45440. goog.inherits(ol.TileQueue, ol.structs.PriorityQueue);
  45441. /**
  45442. * @return {number} Number of tiles loading.
  45443. */
  45444. ol.TileQueue.prototype.getTilesLoading = function() {
  45445. return this.tilesLoading_;
  45446. };
  45447. /**
  45448. * @param {goog.events.Event} event Event.
  45449. * @protected
  45450. */
  45451. ol.TileQueue.prototype.handleTileChange = function(event) {
  45452. var tile = /** @type {ol.Tile} */ (event.target);
  45453. var state = tile.getState();
  45454. if (state === ol.TileState.LOADED || state === ol.TileState.ERROR ||
  45455. state === ol.TileState.EMPTY) {
  45456. goog.events.unlisten(tile, goog.events.EventType.CHANGE,
  45457. this.handleTileChange, false, this);
  45458. --this.tilesLoading_;
  45459. this.tileChangeCallback_();
  45460. }
  45461. };
  45462. /**
  45463. * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.
  45464. * @param {number} maxNewLoads Maximum number of new tiles to load.
  45465. */
  45466. ol.TileQueue.prototype.loadMoreTiles = function(maxTotalLoading, maxNewLoads) {
  45467. var newLoads = 0;
  45468. var tile;
  45469. while (this.tilesLoading_ < maxTotalLoading && newLoads < maxNewLoads &&
  45470. this.getCount() > 0) {
  45471. tile = /** @type {ol.Tile} */ (this.dequeue()[0]);
  45472. if (tile.getState() === ol.TileState.IDLE) {
  45473. goog.events.listen(tile, goog.events.EventType.CHANGE,
  45474. this.handleTileChange, false, this);
  45475. tile.load();
  45476. ++this.tilesLoading_;
  45477. ++newLoads;
  45478. }
  45479. }
  45480. };
  45481. goog.provide('ol.Kinetic');
  45482. goog.require('ol.Coordinate');
  45483. goog.require('ol.PreRenderFunction');
  45484. goog.require('ol.animation');
  45485. /**
  45486. * @classdesc
  45487. * Implementation of inertial deceleration for map movement.
  45488. *
  45489. * @constructor
  45490. * @param {number} decay Rate of decay (must be negative).
  45491. * @param {number} minVelocity Minimum velocity (pixels/millisecond).
  45492. * @param {number} delay Delay to consider to calculate the kinetic
  45493. * initial values (milliseconds).
  45494. * @struct
  45495. * @api
  45496. */
  45497. ol.Kinetic = function(decay, minVelocity, delay) {
  45498. /**
  45499. * @private
  45500. * @type {number}
  45501. */
  45502. this.decay_ = decay;
  45503. /**
  45504. * @private
  45505. * @type {number}
  45506. */
  45507. this.minVelocity_ = minVelocity;
  45508. /**
  45509. * @private
  45510. * @type {number}
  45511. */
  45512. this.delay_ = delay;
  45513. /**
  45514. * @private
  45515. * @type {Array.<number>}
  45516. */
  45517. this.points_ = [];
  45518. /**
  45519. * @private
  45520. * @type {number}
  45521. */
  45522. this.angle_ = 0;
  45523. /**
  45524. * @private
  45525. * @type {number}
  45526. */
  45527. this.initialVelocity_ = 0;
  45528. };
  45529. /**
  45530. * FIXME empty description for jsdoc
  45531. */
  45532. ol.Kinetic.prototype.begin = function() {
  45533. this.points_.length = 0;
  45534. this.angle_ = 0;
  45535. this.initialVelocity_ = 0;
  45536. };
  45537. /**
  45538. * @param {number} x X.
  45539. * @param {number} y Y.
  45540. */
  45541. ol.Kinetic.prototype.update = function(x, y) {
  45542. this.points_.push(x, y, Date.now());
  45543. };
  45544. /**
  45545. * @return {boolean} Whether we should do kinetic animation.
  45546. */
  45547. ol.Kinetic.prototype.end = function() {
  45548. if (this.points_.length < 6) {
  45549. // at least 2 points are required (i.e. there must be at least 6 elements
  45550. // in the array)
  45551. return false;
  45552. }
  45553. var delay = Date.now() - this.delay_;
  45554. var lastIndex = this.points_.length - 3;
  45555. if (this.points_[lastIndex + 2] < delay) {
  45556. // the last tracked point is too old, which means that the user stopped
  45557. // panning before releasing the map
  45558. return false;
  45559. }
  45560. // get the first point which still falls into the delay time
  45561. var firstIndex = lastIndex - 3;
  45562. while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) {
  45563. firstIndex -= 3;
  45564. }
  45565. var duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2];
  45566. var dx = this.points_[lastIndex] - this.points_[firstIndex];
  45567. var dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1];
  45568. this.angle_ = Math.atan2(dy, dx);
  45569. this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration;
  45570. return this.initialVelocity_ > this.minVelocity_;
  45571. };
  45572. /**
  45573. * @param {ol.Coordinate} source Source coordinate for the animation.
  45574. * @return {ol.PreRenderFunction} Pre-render function for kinetic animation.
  45575. */
  45576. ol.Kinetic.prototype.pan = function(source) {
  45577. var decay = this.decay_;
  45578. var initialVelocity = this.initialVelocity_;
  45579. var velocity = this.minVelocity_ - initialVelocity;
  45580. var duration = this.getDuration_();
  45581. var easingFunction = (
  45582. /**
  45583. * @param {number} t T.
  45584. * @return {number} Easing.
  45585. */
  45586. function(t) {
  45587. return initialVelocity * (Math.exp((decay * t) * duration) - 1) /
  45588. velocity;
  45589. });
  45590. return ol.animation.pan({
  45591. source: source,
  45592. duration: duration,
  45593. easing: easingFunction
  45594. });
  45595. };
  45596. /**
  45597. * @private
  45598. * @return {number} Duration of animation (milliseconds).
  45599. */
  45600. ol.Kinetic.prototype.getDuration_ = function() {
  45601. return Math.log(this.minVelocity_ / this.initialVelocity_) / this.decay_;
  45602. };
  45603. /**
  45604. * @return {number} Total distance travelled (pixels).
  45605. */
  45606. ol.Kinetic.prototype.getDistance = function() {
  45607. return (this.minVelocity_ - this.initialVelocity_) / this.decay_;
  45608. };
  45609. /**
  45610. * @return {number} Angle of the kinetic panning animation (radians).
  45611. */
  45612. ol.Kinetic.prototype.getAngle = function() {
  45613. return this.angle_;
  45614. };
  45615. // FIXME factor out key precondition (shift et. al)
  45616. goog.provide('ol.interaction.Interaction');
  45617. goog.provide('ol.interaction.InteractionProperty');
  45618. goog.require('ol');
  45619. goog.require('ol.MapBrowserEvent');
  45620. goog.require('ol.Object');
  45621. goog.require('ol.animation');
  45622. goog.require('ol.easing');
  45623. /**
  45624. * @enum {string}
  45625. */
  45626. ol.interaction.InteractionProperty = {
  45627. ACTIVE: 'active'
  45628. };
  45629. /**
  45630. * @classdesc
  45631. * Abstract base class; normally only used for creating subclasses and not
  45632. * instantiated in apps.
  45633. * User actions that change the state of the map. Some are similar to controls,
  45634. * but are not associated with a DOM element.
  45635. * For example, {@link ol.interaction.KeyboardZoom} is functionally the same as
  45636. * {@link ol.control.Zoom}, but triggered by a keyboard event not a button
  45637. * element event.
  45638. * Although interactions do not have a DOM element, some of them do render
  45639. * vectors and so are visible on the screen.
  45640. *
  45641. * @constructor
  45642. * @param {olx.interaction.InteractionOptions} options Options.
  45643. * @extends {ol.Object}
  45644. * @api
  45645. */
  45646. ol.interaction.Interaction = function(options) {
  45647. goog.base(this);
  45648. /**
  45649. * @private
  45650. * @type {ol.Map}
  45651. */
  45652. this.map_ = null;
  45653. this.setActive(true);
  45654. /**
  45655. * @type {function(ol.MapBrowserEvent):boolean}
  45656. */
  45657. this.handleEvent = options.handleEvent;
  45658. };
  45659. goog.inherits(ol.interaction.Interaction, ol.Object);
  45660. /**
  45661. * Return whether the interaction is currently active.
  45662. * @return {boolean} `true` if the interaction is active, `false` otherwise.
  45663. * @observable
  45664. * @api
  45665. */
  45666. ol.interaction.Interaction.prototype.getActive = function() {
  45667. return /** @type {boolean} */ (
  45668. this.get(ol.interaction.InteractionProperty.ACTIVE));
  45669. };
  45670. /**
  45671. * Get the map associated with this interaction.
  45672. * @return {ol.Map} Map.
  45673. */
  45674. ol.interaction.Interaction.prototype.getMap = function() {
  45675. return this.map_;
  45676. };
  45677. /**
  45678. * Activate or deactivate the interaction.
  45679. * @param {boolean} active Active.
  45680. * @observable
  45681. * @api
  45682. */
  45683. ol.interaction.Interaction.prototype.setActive = function(active) {
  45684. this.set(ol.interaction.InteractionProperty.ACTIVE, active);
  45685. };
  45686. /**
  45687. * Remove the interaction from its current map and attach it to the new map.
  45688. * Subclasses may set up event handlers to get notified about changes to
  45689. * the map here.
  45690. * @param {ol.Map} map Map.
  45691. */
  45692. ol.interaction.Interaction.prototype.setMap = function(map) {
  45693. this.map_ = map;
  45694. };
  45695. /**
  45696. * @param {ol.Map} map Map.
  45697. * @param {ol.View} view View.
  45698. * @param {ol.Coordinate} delta Delta.
  45699. * @param {number=} opt_duration Duration.
  45700. */
  45701. ol.interaction.Interaction.pan = function(map, view, delta, opt_duration) {
  45702. var currentCenter = view.getCenter();
  45703. if (currentCenter) {
  45704. if (opt_duration && opt_duration > 0) {
  45705. map.beforeRender(ol.animation.pan({
  45706. source: currentCenter,
  45707. duration: opt_duration,
  45708. easing: ol.easing.linear
  45709. }));
  45710. }
  45711. var center = view.constrainCenter(
  45712. [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]);
  45713. view.setCenter(center);
  45714. }
  45715. };
  45716. /**
  45717. * @param {ol.Map} map Map.
  45718. * @param {ol.View} view View.
  45719. * @param {number|undefined} rotation Rotation.
  45720. * @param {ol.Coordinate=} opt_anchor Anchor coordinate.
  45721. * @param {number=} opt_duration Duration.
  45722. */
  45723. ol.interaction.Interaction.rotate =
  45724. function(map, view, rotation, opt_anchor, opt_duration) {
  45725. rotation = view.constrainRotation(rotation, 0);
  45726. ol.interaction.Interaction.rotateWithoutConstraints(
  45727. map, view, rotation, opt_anchor, opt_duration);
  45728. };
  45729. /**
  45730. * @param {ol.Map} map Map.
  45731. * @param {ol.View} view View.
  45732. * @param {number|undefined} rotation Rotation.
  45733. * @param {ol.Coordinate=} opt_anchor Anchor coordinate.
  45734. * @param {number=} opt_duration Duration.
  45735. */
  45736. ol.interaction.Interaction.rotateWithoutConstraints =
  45737. function(map, view, rotation, opt_anchor, opt_duration) {
  45738. if (rotation !== undefined) {
  45739. var currentRotation = view.getRotation();
  45740. var currentCenter = view.getCenter();
  45741. if (currentRotation !== undefined && currentCenter &&
  45742. opt_duration && opt_duration > 0) {
  45743. map.beforeRender(ol.animation.rotate({
  45744. rotation: currentRotation,
  45745. duration: opt_duration,
  45746. easing: ol.easing.easeOut
  45747. }));
  45748. if (opt_anchor) {
  45749. map.beforeRender(ol.animation.pan({
  45750. source: currentCenter,
  45751. duration: opt_duration,
  45752. easing: ol.easing.easeOut
  45753. }));
  45754. }
  45755. }
  45756. view.rotate(rotation, opt_anchor);
  45757. }
  45758. };
  45759. /**
  45760. * @param {ol.Map} map Map.
  45761. * @param {ol.View} view View.
  45762. * @param {number|undefined} resolution Resolution to go to.
  45763. * @param {ol.Coordinate=} opt_anchor Anchor coordinate.
  45764. * @param {number=} opt_duration Duration.
  45765. * @param {number=} opt_direction Zooming direction; > 0 indicates
  45766. * zooming out, in which case the constraints system will select
  45767. * the largest nearest resolution; < 0 indicates zooming in, in
  45768. * which case the constraints system will select the smallest
  45769. * nearest resolution; == 0 indicates that the zooming direction
  45770. * is unknown/not relevant, in which case the constraints system
  45771. * will select the nearest resolution. If not defined 0 is
  45772. * assumed.
  45773. */
  45774. ol.interaction.Interaction.zoom =
  45775. function(map, view, resolution, opt_anchor, opt_duration, opt_direction) {
  45776. resolution = view.constrainResolution(resolution, 0, opt_direction);
  45777. ol.interaction.Interaction.zoomWithoutConstraints(
  45778. map, view, resolution, opt_anchor, opt_duration);
  45779. };
  45780. /**
  45781. * @param {ol.Map} map Map.
  45782. * @param {ol.View} view View.
  45783. * @param {number} delta Delta from previous zoom level.
  45784. * @param {ol.Coordinate=} opt_anchor Anchor coordinate.
  45785. * @param {number=} opt_duration Duration.
  45786. */
  45787. ol.interaction.Interaction.zoomByDelta =
  45788. function(map, view, delta, opt_anchor, opt_duration) {
  45789. var currentResolution = view.getResolution();
  45790. var resolution = view.constrainResolution(currentResolution, delta, 0);
  45791. ol.interaction.Interaction.zoomWithoutConstraints(
  45792. map, view, resolution, opt_anchor, opt_duration);
  45793. };
  45794. /**
  45795. * @param {ol.Map} map Map.
  45796. * @param {ol.View} view View.
  45797. * @param {number|undefined} resolution Resolution to go to.
  45798. * @param {ol.Coordinate=} opt_anchor Anchor coordinate.
  45799. * @param {number=} opt_duration Duration.
  45800. */
  45801. ol.interaction.Interaction.zoomWithoutConstraints =
  45802. function(map, view, resolution, opt_anchor, opt_duration) {
  45803. if (resolution) {
  45804. var currentResolution = view.getResolution();
  45805. var currentCenter = view.getCenter();
  45806. if (currentResolution !== undefined && currentCenter &&
  45807. resolution !== currentResolution &&
  45808. opt_duration && opt_duration > 0) {
  45809. map.beforeRender(ol.animation.zoom({
  45810. resolution: currentResolution,
  45811. duration: opt_duration,
  45812. easing: ol.easing.easeOut
  45813. }));
  45814. if (opt_anchor) {
  45815. map.beforeRender(ol.animation.pan({
  45816. source: currentCenter,
  45817. duration: opt_duration,
  45818. easing: ol.easing.easeOut
  45819. }));
  45820. }
  45821. }
  45822. if (opt_anchor) {
  45823. var center = view.calculateCenterZoom(resolution, opt_anchor);
  45824. view.setCenter(center);
  45825. }
  45826. view.setResolution(resolution);
  45827. }
  45828. };
  45829. goog.provide('ol.interaction.DoubleClickZoom');
  45830. goog.require('goog.asserts');
  45831. goog.require('ol.MapBrowserEvent');
  45832. goog.require('ol.MapBrowserEvent.EventType');
  45833. goog.require('ol.interaction.Interaction');
  45834. /**
  45835. * @classdesc
  45836. * Allows the user to zoom by double-clicking on the map.
  45837. *
  45838. * @constructor
  45839. * @extends {ol.interaction.Interaction}
  45840. * @param {olx.interaction.DoubleClickZoomOptions=} opt_options Options.
  45841. * @api stable
  45842. */
  45843. ol.interaction.DoubleClickZoom = function(opt_options) {
  45844. var options = opt_options ? opt_options : {};
  45845. /**
  45846. * @private
  45847. * @type {number}
  45848. */
  45849. this.delta_ = options.delta ? options.delta : 1;
  45850. goog.base(this, {
  45851. handleEvent: ol.interaction.DoubleClickZoom.handleEvent
  45852. });
  45853. /**
  45854. * @private
  45855. * @type {number}
  45856. */
  45857. this.duration_ = options.duration ? options.duration : 250;
  45858. };
  45859. goog.inherits(ol.interaction.DoubleClickZoom, ol.interaction.Interaction);
  45860. /**
  45861. * Handles the {@link ol.MapBrowserEvent map browser event} (if it was a
  45862. * doubleclick) and eventually zooms the map.
  45863. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45864. * @return {boolean} `false` to stop event propagation.
  45865. * @this {ol.interaction.DoubleClickZoom}
  45866. * @api
  45867. */
  45868. ol.interaction.DoubleClickZoom.handleEvent = function(mapBrowserEvent) {
  45869. var stopEvent = false;
  45870. var browserEvent = mapBrowserEvent.browserEvent;
  45871. if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.DBLCLICK) {
  45872. var map = mapBrowserEvent.map;
  45873. var anchor = mapBrowserEvent.coordinate;
  45874. var delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;
  45875. var view = map.getView();
  45876. goog.asserts.assert(view, 'map must have a view');
  45877. ol.interaction.Interaction.zoomByDelta(
  45878. map, view, delta, anchor, this.duration_);
  45879. mapBrowserEvent.preventDefault();
  45880. stopEvent = true;
  45881. }
  45882. return !stopEvent;
  45883. };
  45884. goog.provide('ol.events.ConditionType');
  45885. goog.provide('ol.events.condition');
  45886. goog.require('goog.asserts');
  45887. goog.require('goog.dom.TagName');
  45888. goog.require('goog.functions');
  45889. goog.require('ol.MapBrowserEvent.EventType');
  45890. goog.require('ol.MapBrowserPointerEvent');
  45891. /**
  45892. * A function that takes an {@link ol.MapBrowserEvent} and returns a
  45893. * `{boolean}`. If the condition is met, true should be returned.
  45894. *
  45895. * @typedef {function(ol.MapBrowserEvent): boolean}
  45896. * @api stable
  45897. */
  45898. ol.events.ConditionType;
  45899. /**
  45900. * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when
  45901. * additionally the shift-key is pressed).
  45902. *
  45903. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45904. * @return {boolean} True if only the alt key is pressed.
  45905. * @api stable
  45906. */
  45907. ol.events.condition.altKeyOnly = function(mapBrowserEvent) {
  45908. var browserEvent = mapBrowserEvent.browserEvent;
  45909. return (
  45910. browserEvent.altKey &&
  45911. !browserEvent.platformModifierKey &&
  45912. !browserEvent.shiftKey);
  45913. };
  45914. /**
  45915. * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise
  45916. * (e.g. when additionally the platform-modifier-key is pressed).
  45917. *
  45918. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45919. * @return {boolean} True if only the alt and shift keys are pressed.
  45920. * @api stable
  45921. */
  45922. ol.events.condition.altShiftKeysOnly = function(mapBrowserEvent) {
  45923. var browserEvent = mapBrowserEvent.browserEvent;
  45924. return (
  45925. browserEvent.altKey &&
  45926. !browserEvent.platformModifierKey &&
  45927. browserEvent.shiftKey);
  45928. };
  45929. /**
  45930. * Return always true.
  45931. *
  45932. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45933. * @return {boolean} True.
  45934. * @function
  45935. * @api stable
  45936. */
  45937. ol.events.condition.always = goog.functions.TRUE;
  45938. /**
  45939. * Return `true` if the event is a `click` event, `false` otherwise.
  45940. *
  45941. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45942. * @return {boolean} True if the event is a map `click` event.
  45943. * @api stable
  45944. */
  45945. ol.events.condition.click = function(mapBrowserEvent) {
  45946. return mapBrowserEvent.type == ol.MapBrowserEvent.EventType.CLICK;
  45947. };
  45948. /**
  45949. * Return always false.
  45950. *
  45951. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45952. * @return {boolean} False.
  45953. * @function
  45954. * @api stable
  45955. */
  45956. ol.events.condition.never = goog.functions.FALSE;
  45957. /**
  45958. * Return `true` if the browser event is a `pointermove` event, `false`
  45959. * otherwise.
  45960. *
  45961. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45962. * @return {boolean} True if the browser event is a `pointermove` event.
  45963. * @api
  45964. */
  45965. ol.events.condition.pointerMove = function(mapBrowserEvent) {
  45966. return mapBrowserEvent.type == 'pointermove';
  45967. };
  45968. /**
  45969. * Return `true` if the event is a map `singleclick` event, `false` otherwise.
  45970. *
  45971. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45972. * @return {boolean} True if the event is a map `singleclick` event.
  45973. * @api stable
  45974. */
  45975. ol.events.condition.singleClick = function(mapBrowserEvent) {
  45976. return mapBrowserEvent.type == ol.MapBrowserEvent.EventType.SINGLECLICK;
  45977. };
  45978. /**
  45979. * Return `true` if the event is a map `dblclick` event, `false` otherwise.
  45980. *
  45981. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45982. * @return {boolean} True if the event is a map `dblclick` event.
  45983. * @api stable
  45984. */
  45985. ol.events.condition.doubleClick = function(mapBrowserEvent) {
  45986. return mapBrowserEvent.type == ol.MapBrowserEvent.EventType.DBLCLICK;
  45987. };
  45988. /**
  45989. * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is
  45990. * pressed.
  45991. *
  45992. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  45993. * @return {boolean} True only if there no modifier keys are pressed.
  45994. * @api stable
  45995. */
  45996. ol.events.condition.noModifierKeys = function(mapBrowserEvent) {
  45997. var browserEvent = mapBrowserEvent.browserEvent;
  45998. return (
  45999. !browserEvent.altKey &&
  46000. !browserEvent.platformModifierKey &&
  46001. !browserEvent.shiftKey);
  46002. };
  46003. /**
  46004. * Return `true` if only the platform-modifier-key (e.g. the windows-key) is
  46005. * pressed, `false` otherwise (e.g. when additionally the shift-key is pressed).
  46006. *
  46007. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46008. * @return {boolean} True if only the platform modifier key is pressed.
  46009. * @api stable
  46010. */
  46011. ol.events.condition.platformModifierKeyOnly = function(mapBrowserEvent) {
  46012. var browserEvent = mapBrowserEvent.browserEvent;
  46013. return (
  46014. !browserEvent.altKey &&
  46015. browserEvent.platformModifierKey &&
  46016. !browserEvent.shiftKey);
  46017. };
  46018. /**
  46019. * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when
  46020. * additionally the alt-key is pressed).
  46021. *
  46022. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46023. * @return {boolean} True if only the shift key is pressed.
  46024. * @api stable
  46025. */
  46026. ol.events.condition.shiftKeyOnly = function(mapBrowserEvent) {
  46027. var browserEvent = mapBrowserEvent.browserEvent;
  46028. return (
  46029. !browserEvent.altKey &&
  46030. !browserEvent.platformModifierKey &&
  46031. browserEvent.shiftKey);
  46032. };
  46033. /**
  46034. * Return `true` if the target element is not editable, i.e. not a `<input>`-,
  46035. * `<select>`- or `<textarea>`-element, `false` otherwise.
  46036. *
  46037. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46038. * @return {boolean} True only if the target element is not editable.
  46039. * @api
  46040. */
  46041. ol.events.condition.targetNotEditable = function(mapBrowserEvent) {
  46042. var target = mapBrowserEvent.browserEvent.target;
  46043. goog.asserts.assertInstanceof(target, Element,
  46044. 'target should be an Element');
  46045. var tagName = target.tagName;
  46046. return (
  46047. tagName !== goog.dom.TagName.INPUT &&
  46048. tagName !== goog.dom.TagName.SELECT &&
  46049. tagName !== goog.dom.TagName.TEXTAREA);
  46050. };
  46051. /**
  46052. * Return `true` if the event originates from a mouse device.
  46053. *
  46054. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46055. * @return {boolean} True if the event originates from a mouse device.
  46056. * @api stable
  46057. */
  46058. ol.events.condition.mouseOnly = function(mapBrowserEvent) {
  46059. goog.asserts.assertInstanceof(mapBrowserEvent, ol.MapBrowserPointerEvent,
  46060. 'mapBrowserEvent should be an instance of ol.MapBrowserPointerEvent');
  46061. /* pointerId must be 1 for mouse devices,
  46062. * see: http://www.w3.org/Submission/pointer-events/#pointerevent-interface
  46063. */
  46064. return mapBrowserEvent.pointerEvent.pointerId == 1;
  46065. };
  46066. goog.provide('ol.interaction.Pointer');
  46067. goog.require('goog.functions');
  46068. goog.require('goog.object');
  46069. goog.require('ol');
  46070. goog.require('ol.MapBrowserEvent.EventType');
  46071. goog.require('ol.MapBrowserPointerEvent');
  46072. goog.require('ol.Pixel');
  46073. goog.require('ol.interaction.Interaction');
  46074. /**
  46075. * @classdesc
  46076. * Base class that calls user-defined functions on `down`, `move` and `up`
  46077. * events. This class also manages "drag sequences".
  46078. *
  46079. * When the `handleDownEvent` user function returns `true` a drag sequence is
  46080. * started. During a drag sequence the `handleDragEvent` user function is
  46081. * called on `move` events. The drag sequence ends when the `handleUpEvent`
  46082. * user function is called and returns `false`.
  46083. *
  46084. * @constructor
  46085. * @param {olx.interaction.PointerOptions=} opt_options Options.
  46086. * @extends {ol.interaction.Interaction}
  46087. * @api
  46088. */
  46089. ol.interaction.Pointer = function(opt_options) {
  46090. var options = opt_options ? opt_options : {};
  46091. var handleEvent = options.handleEvent ?
  46092. options.handleEvent : ol.interaction.Pointer.handleEvent;
  46093. goog.base(this, {
  46094. handleEvent: handleEvent
  46095. });
  46096. /**
  46097. * @type {function(ol.MapBrowserPointerEvent):boolean}
  46098. * @private
  46099. */
  46100. this.handleDownEvent_ = options.handleDownEvent ?
  46101. options.handleDownEvent : ol.interaction.Pointer.handleDownEvent;
  46102. /**
  46103. * @type {function(ol.MapBrowserPointerEvent)}
  46104. * @private
  46105. */
  46106. this.handleDragEvent_ = options.handleDragEvent ?
  46107. options.handleDragEvent : ol.interaction.Pointer.handleDragEvent;
  46108. /**
  46109. * @type {function(ol.MapBrowserPointerEvent)}
  46110. * @private
  46111. */
  46112. this.handleMoveEvent_ = options.handleMoveEvent ?
  46113. options.handleMoveEvent : ol.interaction.Pointer.handleMoveEvent;
  46114. /**
  46115. * @type {function(ol.MapBrowserPointerEvent):boolean}
  46116. * @private
  46117. */
  46118. this.handleUpEvent_ = options.handleUpEvent ?
  46119. options.handleUpEvent : ol.interaction.Pointer.handleUpEvent;
  46120. /**
  46121. * @type {boolean}
  46122. * @protected
  46123. */
  46124. this.handlingDownUpSequence = false;
  46125. /**
  46126. * @type {Object.<number, ol.pointer.PointerEvent>}
  46127. * @private
  46128. */
  46129. this.trackedPointers_ = {};
  46130. /**
  46131. * @type {Array.<ol.pointer.PointerEvent>}
  46132. * @protected
  46133. */
  46134. this.targetPointers = [];
  46135. };
  46136. goog.inherits(ol.interaction.Pointer, ol.interaction.Interaction);
  46137. /**
  46138. * @param {Array.<ol.pointer.PointerEvent>} pointerEvents
  46139. * @return {ol.Pixel} Centroid pixel.
  46140. */
  46141. ol.interaction.Pointer.centroid = function(pointerEvents) {
  46142. var length = pointerEvents.length;
  46143. var clientX = 0;
  46144. var clientY = 0;
  46145. for (var i = 0; i < length; i++) {
  46146. clientX += pointerEvents[i].clientX;
  46147. clientY += pointerEvents[i].clientY;
  46148. }
  46149. return [clientX / length, clientY / length];
  46150. };
  46151. /**
  46152. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46153. * @return {boolean} Whether the event is a pointerdown, pointerdrag
  46154. * or pointerup event.
  46155. * @private
  46156. */
  46157. ol.interaction.Pointer.prototype.isPointerDraggingEvent_ =
  46158. function(mapBrowserEvent) {
  46159. var type = mapBrowserEvent.type;
  46160. return (
  46161. type === ol.MapBrowserEvent.EventType.POINTERDOWN ||
  46162. type === ol.MapBrowserEvent.EventType.POINTERDRAG ||
  46163. type === ol.MapBrowserEvent.EventType.POINTERUP);
  46164. };
  46165. /**
  46166. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46167. * @private
  46168. */
  46169. ol.interaction.Pointer.prototype.updateTrackedPointers_ =
  46170. function(mapBrowserEvent) {
  46171. if (this.isPointerDraggingEvent_(mapBrowserEvent)) {
  46172. var event = mapBrowserEvent.pointerEvent;
  46173. if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERUP) {
  46174. delete this.trackedPointers_[event.pointerId];
  46175. } else if (mapBrowserEvent.type ==
  46176. ol.MapBrowserEvent.EventType.POINTERDOWN) {
  46177. this.trackedPointers_[event.pointerId] = event;
  46178. } else if (event.pointerId in this.trackedPointers_) {
  46179. // update only when there was a pointerdown event for this pointer
  46180. this.trackedPointers_[event.pointerId] = event;
  46181. }
  46182. this.targetPointers = goog.object.getValues(this.trackedPointers_);
  46183. }
  46184. };
  46185. /**
  46186. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46187. * @this {ol.interaction.Pointer}
  46188. */
  46189. ol.interaction.Pointer.handleDragEvent = ol.nullFunction;
  46190. /**
  46191. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46192. * @return {boolean} Capture dragging.
  46193. * @this {ol.interaction.Pointer}
  46194. */
  46195. ol.interaction.Pointer.handleUpEvent = goog.functions.FALSE;
  46196. /**
  46197. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46198. * @return {boolean} Capture dragging.
  46199. * @this {ol.interaction.Pointer}
  46200. */
  46201. ol.interaction.Pointer.handleDownEvent = goog.functions.FALSE;
  46202. /**
  46203. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46204. * @this {ol.interaction.Pointer}
  46205. */
  46206. ol.interaction.Pointer.handleMoveEvent = ol.nullFunction;
  46207. /**
  46208. * Handles the {@link ol.MapBrowserEvent map browser event} and may call into
  46209. * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are
  46210. * detected.
  46211. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46212. * @return {boolean} `false` to stop event propagation.
  46213. * @this {ol.interaction.Pointer}
  46214. * @api
  46215. */
  46216. ol.interaction.Pointer.handleEvent = function(mapBrowserEvent) {
  46217. if (!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent)) {
  46218. return true;
  46219. }
  46220. var stopEvent = false;
  46221. this.updateTrackedPointers_(mapBrowserEvent);
  46222. if (this.handlingDownUpSequence) {
  46223. if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERDRAG) {
  46224. this.handleDragEvent_(mapBrowserEvent);
  46225. } else if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERUP) {
  46226. this.handlingDownUpSequence = this.handleUpEvent_(mapBrowserEvent);
  46227. }
  46228. }
  46229. if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERDOWN) {
  46230. var handled = this.handleDownEvent_(mapBrowserEvent);
  46231. this.handlingDownUpSequence = handled;
  46232. stopEvent = this.shouldStopEvent(handled);
  46233. } else if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERMOVE) {
  46234. this.handleMoveEvent_(mapBrowserEvent);
  46235. }
  46236. return !stopEvent;
  46237. };
  46238. /**
  46239. * This method is used to determine if "down" events should be propagated to
  46240. * other interactions or should be stopped.
  46241. *
  46242. * The method receives the return code of the "handleDownEvent" function.
  46243. *
  46244. * By default this function is the "identity" function. It's overidden in
  46245. * child classes.
  46246. *
  46247. * @param {boolean} handled Was the event handled by the interaction?
  46248. * @return {boolean} Should the event be stopped?
  46249. * @protected
  46250. */
  46251. ol.interaction.Pointer.prototype.shouldStopEvent = goog.functions.identity;
  46252. goog.provide('ol.interaction.DragPan');
  46253. goog.require('goog.asserts');
  46254. goog.require('ol.Kinetic');
  46255. goog.require('ol.Pixel');
  46256. goog.require('ol.PreRenderFunction');
  46257. goog.require('ol.ViewHint');
  46258. goog.require('ol.coordinate');
  46259. goog.require('ol.events.condition');
  46260. goog.require('ol.interaction.Pointer');
  46261. /**
  46262. * @classdesc
  46263. * Allows the user to pan the map by dragging the map.
  46264. *
  46265. * @constructor
  46266. * @extends {ol.interaction.Pointer}
  46267. * @param {olx.interaction.DragPanOptions=} opt_options Options.
  46268. * @api stable
  46269. */
  46270. ol.interaction.DragPan = function(opt_options) {
  46271. goog.base(this, {
  46272. handleDownEvent: ol.interaction.DragPan.handleDownEvent_,
  46273. handleDragEvent: ol.interaction.DragPan.handleDragEvent_,
  46274. handleUpEvent: ol.interaction.DragPan.handleUpEvent_
  46275. });
  46276. var options = opt_options ? opt_options : {};
  46277. /**
  46278. * @private
  46279. * @type {ol.Kinetic|undefined}
  46280. */
  46281. this.kinetic_ = options.kinetic;
  46282. /**
  46283. * @private
  46284. * @type {?ol.PreRenderFunction}
  46285. */
  46286. this.kineticPreRenderFn_ = null;
  46287. /**
  46288. * @type {ol.Pixel}
  46289. */
  46290. this.lastCentroid = null;
  46291. /**
  46292. * @private
  46293. * @type {ol.events.ConditionType}
  46294. */
  46295. this.condition_ = options.condition ?
  46296. options.condition : ol.events.condition.noModifierKeys;
  46297. /**
  46298. * @private
  46299. * @type {boolean}
  46300. */
  46301. this.noKinetic_ = false;
  46302. };
  46303. goog.inherits(ol.interaction.DragPan, ol.interaction.Pointer);
  46304. /**
  46305. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46306. * @this {ol.interaction.DragPan}
  46307. * @private
  46308. */
  46309. ol.interaction.DragPan.handleDragEvent_ = function(mapBrowserEvent) {
  46310. goog.asserts.assert(this.targetPointers.length >= 1,
  46311. 'the length of this.targetPointers should be more than 1');
  46312. var centroid =
  46313. ol.interaction.Pointer.centroid(this.targetPointers);
  46314. if (this.kinetic_) {
  46315. this.kinetic_.update(centroid[0], centroid[1]);
  46316. }
  46317. if (this.lastCentroid) {
  46318. var deltaX = this.lastCentroid[0] - centroid[0];
  46319. var deltaY = centroid[1] - this.lastCentroid[1];
  46320. var map = mapBrowserEvent.map;
  46321. var view = map.getView();
  46322. var viewState = view.getState();
  46323. var center = [deltaX, deltaY];
  46324. ol.coordinate.scale(center, viewState.resolution);
  46325. ol.coordinate.rotate(center, viewState.rotation);
  46326. ol.coordinate.add(center, viewState.center);
  46327. center = view.constrainCenter(center);
  46328. map.render();
  46329. view.setCenter(center);
  46330. }
  46331. this.lastCentroid = centroid;
  46332. };
  46333. /**
  46334. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46335. * @return {boolean} Stop drag sequence?
  46336. * @this {ol.interaction.DragPan}
  46337. * @private
  46338. */
  46339. ol.interaction.DragPan.handleUpEvent_ = function(mapBrowserEvent) {
  46340. var map = mapBrowserEvent.map;
  46341. var view = map.getView();
  46342. if (this.targetPointers.length === 0) {
  46343. if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) {
  46344. var distance = this.kinetic_.getDistance();
  46345. var angle = this.kinetic_.getAngle();
  46346. var center = view.getCenter();
  46347. goog.asserts.assert(center !== undefined, 'center should be defined');
  46348. this.kineticPreRenderFn_ = this.kinetic_.pan(center);
  46349. map.beforeRender(this.kineticPreRenderFn_);
  46350. var centerpx = map.getPixelFromCoordinate(center);
  46351. var dest = map.getCoordinateFromPixel([
  46352. centerpx[0] - distance * Math.cos(angle),
  46353. centerpx[1] - distance * Math.sin(angle)
  46354. ]);
  46355. dest = view.constrainCenter(dest);
  46356. view.setCenter(dest);
  46357. }
  46358. view.setHint(ol.ViewHint.INTERACTING, -1);
  46359. map.render();
  46360. return false;
  46361. } else {
  46362. this.lastCentroid = null;
  46363. return true;
  46364. }
  46365. };
  46366. /**
  46367. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46368. * @return {boolean} Start drag sequence?
  46369. * @this {ol.interaction.DragPan}
  46370. * @private
  46371. */
  46372. ol.interaction.DragPan.handleDownEvent_ = function(mapBrowserEvent) {
  46373. if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) {
  46374. var map = mapBrowserEvent.map;
  46375. var view = map.getView();
  46376. this.lastCentroid = null;
  46377. if (!this.handlingDownUpSequence) {
  46378. view.setHint(ol.ViewHint.INTERACTING, 1);
  46379. }
  46380. map.render();
  46381. if (this.kineticPreRenderFn_ &&
  46382. map.removePreRenderFunction(this.kineticPreRenderFn_)) {
  46383. view.setCenter(mapBrowserEvent.frameState.viewState.center);
  46384. this.kineticPreRenderFn_ = null;
  46385. }
  46386. if (this.kinetic_) {
  46387. this.kinetic_.begin();
  46388. }
  46389. // No kinetic as soon as more than one pointer on the screen is
  46390. // detected. This is to prevent nasty pans after pinch.
  46391. this.noKinetic_ = this.targetPointers.length > 1;
  46392. return true;
  46393. } else {
  46394. return false;
  46395. }
  46396. };
  46397. /**
  46398. * @inheritDoc
  46399. */
  46400. ol.interaction.DragPan.prototype.shouldStopEvent = goog.functions.FALSE;
  46401. goog.provide('ol.interaction.DragRotate');
  46402. goog.require('ol');
  46403. goog.require('ol.ViewHint');
  46404. goog.require('ol.events.ConditionType');
  46405. goog.require('ol.events.condition');
  46406. goog.require('ol.interaction.Interaction');
  46407. goog.require('ol.interaction.Pointer');
  46408. /**
  46409. * @classdesc
  46410. * Allows the user to rotate the map by clicking and dragging on the map,
  46411. * normally combined with an {@link ol.events.condition} that limits
  46412. * it to when the alt and shift keys are held down.
  46413. *
  46414. * This interaction is only supported for mouse devices.
  46415. *
  46416. * @constructor
  46417. * @extends {ol.interaction.Pointer}
  46418. * @param {olx.interaction.DragRotateOptions=} opt_options Options.
  46419. * @api stable
  46420. */
  46421. ol.interaction.DragRotate = function(opt_options) {
  46422. var options = opt_options ? opt_options : {};
  46423. goog.base(this, {
  46424. handleDownEvent: ol.interaction.DragRotate.handleDownEvent_,
  46425. handleDragEvent: ol.interaction.DragRotate.handleDragEvent_,
  46426. handleUpEvent: ol.interaction.DragRotate.handleUpEvent_
  46427. });
  46428. /**
  46429. * @private
  46430. * @type {ol.events.ConditionType}
  46431. */
  46432. this.condition_ = options.condition ?
  46433. options.condition : ol.events.condition.altShiftKeysOnly;
  46434. /**
  46435. * @private
  46436. * @type {number|undefined}
  46437. */
  46438. this.lastAngle_ = undefined;
  46439. /**
  46440. * @private
  46441. * @type {number}
  46442. */
  46443. this.duration_ = options.duration ? options.duration : 250;
  46444. };
  46445. goog.inherits(ol.interaction.DragRotate, ol.interaction.Pointer);
  46446. /**
  46447. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46448. * @this {ol.interaction.DragRotate}
  46449. * @private
  46450. */
  46451. ol.interaction.DragRotate.handleDragEvent_ = function(mapBrowserEvent) {
  46452. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46453. return;
  46454. }
  46455. var map = mapBrowserEvent.map;
  46456. var size = map.getSize();
  46457. var offset = mapBrowserEvent.pixel;
  46458. var theta =
  46459. Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2);
  46460. if (this.lastAngle_ !== undefined) {
  46461. var delta = theta - this.lastAngle_;
  46462. var view = map.getView();
  46463. var rotation = view.getRotation();
  46464. map.render();
  46465. ol.interaction.Interaction.rotateWithoutConstraints(
  46466. map, view, rotation - delta);
  46467. }
  46468. this.lastAngle_ = theta;
  46469. };
  46470. /**
  46471. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46472. * @return {boolean} Stop drag sequence?
  46473. * @this {ol.interaction.DragRotate}
  46474. * @private
  46475. */
  46476. ol.interaction.DragRotate.handleUpEvent_ = function(mapBrowserEvent) {
  46477. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46478. return true;
  46479. }
  46480. var map = mapBrowserEvent.map;
  46481. var view = map.getView();
  46482. view.setHint(ol.ViewHint.INTERACTING, -1);
  46483. var rotation = view.getRotation();
  46484. ol.interaction.Interaction.rotate(map, view, rotation,
  46485. undefined, this.duration_);
  46486. return false;
  46487. };
  46488. /**
  46489. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46490. * @return {boolean} Start drag sequence?
  46491. * @this {ol.interaction.DragRotate}
  46492. * @private
  46493. */
  46494. ol.interaction.DragRotate.handleDownEvent_ = function(mapBrowserEvent) {
  46495. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46496. return false;
  46497. }
  46498. var browserEvent = mapBrowserEvent.browserEvent;
  46499. if (browserEvent.isMouseActionButton() && this.condition_(mapBrowserEvent)) {
  46500. var map = mapBrowserEvent.map;
  46501. map.getView().setHint(ol.ViewHint.INTERACTING, 1);
  46502. map.render();
  46503. this.lastAngle_ = undefined;
  46504. return true;
  46505. } else {
  46506. return false;
  46507. }
  46508. };
  46509. /**
  46510. * @inheritDoc
  46511. */
  46512. ol.interaction.DragRotate.prototype.shouldStopEvent = goog.functions.FALSE;
  46513. // FIXME add rotation
  46514. goog.provide('ol.render.Box');
  46515. goog.require('goog.Disposable');
  46516. goog.require('goog.asserts');
  46517. goog.require('goog.events');
  46518. goog.require('ol.geom.Polygon');
  46519. goog.require('ol.render.EventType');
  46520. /**
  46521. * @constructor
  46522. * @extends {goog.Disposable}
  46523. * @param {ol.style.Style} style Style.
  46524. */
  46525. ol.render.Box = function(style) {
  46526. /**
  46527. * @private
  46528. * @type {ol.Map}
  46529. */
  46530. this.map_ = null;
  46531. /**
  46532. * @private
  46533. * @type {goog.events.Key}
  46534. */
  46535. this.postComposeListenerKey_ = null;
  46536. /**
  46537. * @private
  46538. * @type {ol.Pixel}
  46539. */
  46540. this.startPixel_ = null;
  46541. /**
  46542. * @private
  46543. * @type {ol.Pixel}
  46544. */
  46545. this.endPixel_ = null;
  46546. /**
  46547. * @private
  46548. * @type {ol.geom.Polygon}
  46549. */
  46550. this.geometry_ = null;
  46551. /**
  46552. * @private
  46553. * @type {ol.style.Style}
  46554. */
  46555. this.style_ = style;
  46556. };
  46557. goog.inherits(ol.render.Box, goog.Disposable);
  46558. /**
  46559. * @private
  46560. * @return {ol.geom.Polygon} Geometry.
  46561. */
  46562. ol.render.Box.prototype.createGeometry_ = function() {
  46563. goog.asserts.assert(this.startPixel_,
  46564. 'this.startPixel_ must be truthy');
  46565. goog.asserts.assert(this.endPixel_,
  46566. 'this.endPixel_ must be truthy');
  46567. goog.asserts.assert(this.map_, 'this.map_ must be truthy');
  46568. var startPixel = this.startPixel_;
  46569. var endPixel = this.endPixel_;
  46570. var pixels = [
  46571. startPixel,
  46572. [startPixel[0], endPixel[1]],
  46573. endPixel,
  46574. [endPixel[0], startPixel[1]]
  46575. ];
  46576. var coordinates = pixels.map(this.map_.getCoordinateFromPixel, this.map_);
  46577. // close the polygon
  46578. coordinates[4] = coordinates[0].slice();
  46579. return new ol.geom.Polygon([coordinates]);
  46580. };
  46581. /**
  46582. * @inheritDoc
  46583. */
  46584. ol.render.Box.prototype.disposeInternal = function() {
  46585. this.setMap(null);
  46586. };
  46587. /**
  46588. * @param {ol.render.Event} event Event.
  46589. * @private
  46590. */
  46591. ol.render.Box.prototype.handleMapPostCompose_ = function(event) {
  46592. var geometry = this.geometry_;
  46593. goog.asserts.assert(geometry, 'geometry should be defined');
  46594. var style = this.style_;
  46595. goog.asserts.assert(style, 'style must be truthy');
  46596. // use drawAsync(Infinity) to draw above everything
  46597. event.vectorContext.drawAsync(Infinity, function(render) {
  46598. render.setFillStrokeStyle(style.getFill(), style.getStroke());
  46599. render.setTextStyle(style.getText());
  46600. render.drawPolygonGeometry(geometry, null);
  46601. });
  46602. };
  46603. /**
  46604. * @return {ol.geom.Polygon} Geometry.
  46605. */
  46606. ol.render.Box.prototype.getGeometry = function() {
  46607. return this.geometry_;
  46608. };
  46609. /**
  46610. * @private
  46611. */
  46612. ol.render.Box.prototype.requestMapRenderFrame_ = function() {
  46613. if (this.map_ && this.startPixel_ && this.endPixel_) {
  46614. this.map_.render();
  46615. }
  46616. };
  46617. /**
  46618. * @param {ol.Map} map Map.
  46619. */
  46620. ol.render.Box.prototype.setMap = function(map) {
  46621. if (this.postComposeListenerKey_) {
  46622. goog.events.unlistenByKey(this.postComposeListenerKey_);
  46623. this.postComposeListenerKey_ = null;
  46624. this.map_.render();
  46625. this.map_ = null;
  46626. }
  46627. this.map_ = map;
  46628. if (this.map_) {
  46629. this.postComposeListenerKey_ = goog.events.listen(
  46630. map, ol.render.EventType.POSTCOMPOSE, this.handleMapPostCompose_, false,
  46631. this);
  46632. this.requestMapRenderFrame_();
  46633. }
  46634. };
  46635. /**
  46636. * @param {ol.Pixel} startPixel Start pixel.
  46637. * @param {ol.Pixel} endPixel End pixel.
  46638. */
  46639. ol.render.Box.prototype.setPixels = function(startPixel, endPixel) {
  46640. this.startPixel_ = startPixel;
  46641. this.endPixel_ = endPixel;
  46642. this.geometry_ = this.createGeometry_();
  46643. this.requestMapRenderFrame_();
  46644. };
  46645. // FIXME draw drag box
  46646. goog.provide('ol.DragBoxEvent');
  46647. goog.provide('ol.interaction.DragBox');
  46648. goog.require('goog.events.Event');
  46649. goog.require('ol');
  46650. goog.require('ol.events.ConditionType');
  46651. goog.require('ol.events.condition');
  46652. goog.require('ol.interaction.Pointer');
  46653. goog.require('ol.render.Box');
  46654. /**
  46655. * @const
  46656. * @type {number}
  46657. */
  46658. ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED =
  46659. ol.DRAG_BOX_HYSTERESIS_PIXELS *
  46660. ol.DRAG_BOX_HYSTERESIS_PIXELS;
  46661. /**
  46662. * @enum {string}
  46663. */
  46664. ol.DragBoxEventType = {
  46665. /**
  46666. * Triggered upon drag box start.
  46667. * @event ol.DragBoxEvent#boxstart
  46668. * @api stable
  46669. */
  46670. BOXSTART: 'boxstart',
  46671. /**
  46672. * Triggered upon drag box end.
  46673. * @event ol.DragBoxEvent#boxend
  46674. * @api stable
  46675. */
  46676. BOXEND: 'boxend'
  46677. };
  46678. /**
  46679. * @classdesc
  46680. * Events emitted by {@link ol.interaction.DragBox} instances are instances of
  46681. * this type.
  46682. *
  46683. * @param {string} type The event type.
  46684. * @param {ol.Coordinate} coordinate The event coordinate.
  46685. * @extends {goog.events.Event}
  46686. * @constructor
  46687. * @implements {oli.DragBoxEvent}
  46688. */
  46689. ol.DragBoxEvent = function(type, coordinate) {
  46690. goog.base(this, type);
  46691. /**
  46692. * The coordinate of the drag event.
  46693. * @const
  46694. * @type {ol.Coordinate}
  46695. * @api stable
  46696. */
  46697. this.coordinate = coordinate;
  46698. };
  46699. goog.inherits(ol.DragBoxEvent, goog.events.Event);
  46700. /**
  46701. * @classdesc
  46702. * Allows the user to draw a vector box by clicking and dragging on the map,
  46703. * normally combined with an {@link ol.events.condition} that limits
  46704. * it to when the shift or other key is held down. This is used, for example,
  46705. * for zooming to a specific area of the map
  46706. * (see {@link ol.interaction.DragZoom} and
  46707. * {@link ol.interaction.DragRotateAndZoom}).
  46708. *
  46709. * This interaction is only supported for mouse devices.
  46710. *
  46711. * @constructor
  46712. * @extends {ol.interaction.Pointer}
  46713. * @fires ol.DragBoxEvent
  46714. * @param {olx.interaction.DragBoxOptions=} opt_options Options.
  46715. * @api stable
  46716. */
  46717. ol.interaction.DragBox = function(opt_options) {
  46718. goog.base(this, {
  46719. handleDownEvent: ol.interaction.DragBox.handleDownEvent_,
  46720. handleDragEvent: ol.interaction.DragBox.handleDragEvent_,
  46721. handleUpEvent: ol.interaction.DragBox.handleUpEvent_
  46722. });
  46723. var options = opt_options ? opt_options : {};
  46724. /**
  46725. * @private
  46726. * @type {ol.style.Style}
  46727. */
  46728. var style = options.style ? options.style : null;
  46729. /**
  46730. * @type {ol.render.Box}
  46731. * @private
  46732. */
  46733. this.box_ = new ol.render.Box(style);
  46734. /**
  46735. * @type {ol.Pixel}
  46736. * @private
  46737. */
  46738. this.startPixel_ = null;
  46739. /**
  46740. * @private
  46741. * @type {ol.events.ConditionType}
  46742. */
  46743. this.condition_ = options.condition ?
  46744. options.condition : ol.events.condition.always;
  46745. };
  46746. goog.inherits(ol.interaction.DragBox, ol.interaction.Pointer);
  46747. /**
  46748. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46749. * @this {ol.interaction.DragBox}
  46750. * @private
  46751. */
  46752. ol.interaction.DragBox.handleDragEvent_ = function(mapBrowserEvent) {
  46753. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46754. return;
  46755. }
  46756. this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);
  46757. };
  46758. /**
  46759. * Returns geometry of last drawn box.
  46760. * @return {ol.geom.Polygon} Geometry.
  46761. * @api stable
  46762. */
  46763. ol.interaction.DragBox.prototype.getGeometry = function() {
  46764. return this.box_.getGeometry();
  46765. };
  46766. /**
  46767. * To be overriden by child classes.
  46768. * FIXME: use constructor option instead of relying on overridding.
  46769. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  46770. * @protected
  46771. */
  46772. ol.interaction.DragBox.prototype.onBoxEnd = ol.nullFunction;
  46773. /**
  46774. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46775. * @return {boolean} Stop drag sequence?
  46776. * @this {ol.interaction.DragBox}
  46777. * @private
  46778. */
  46779. ol.interaction.DragBox.handleUpEvent_ = function(mapBrowserEvent) {
  46780. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46781. return true;
  46782. }
  46783. this.box_.setMap(null);
  46784. var deltaX = mapBrowserEvent.pixel[0] - this.startPixel_[0];
  46785. var deltaY = mapBrowserEvent.pixel[1] - this.startPixel_[1];
  46786. if (deltaX * deltaX + deltaY * deltaY >=
  46787. ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED) {
  46788. this.onBoxEnd(mapBrowserEvent);
  46789. this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXEND,
  46790. mapBrowserEvent.coordinate));
  46791. }
  46792. return false;
  46793. };
  46794. /**
  46795. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  46796. * @return {boolean} Start drag sequence?
  46797. * @this {ol.interaction.DragBox}
  46798. * @private
  46799. */
  46800. ol.interaction.DragBox.handleDownEvent_ = function(mapBrowserEvent) {
  46801. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  46802. return false;
  46803. }
  46804. var browserEvent = mapBrowserEvent.browserEvent;
  46805. if (browserEvent.isMouseActionButton() && this.condition_(mapBrowserEvent)) {
  46806. this.startPixel_ = mapBrowserEvent.pixel;
  46807. this.box_.setMap(mapBrowserEvent.map);
  46808. this.box_.setPixels(this.startPixel_, this.startPixel_);
  46809. this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXSTART,
  46810. mapBrowserEvent.coordinate));
  46811. return true;
  46812. } else {
  46813. return false;
  46814. }
  46815. };
  46816. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  46817. //
  46818. // Licensed under the Apache License, Version 2.0 (the "License");
  46819. // you may not use this file except in compliance with the License.
  46820. // You may obtain a copy of the License at
  46821. //
  46822. // http://www.apache.org/licenses/LICENSE-2.0
  46823. //
  46824. // Unless required by applicable law or agreed to in writing, software
  46825. // distributed under the License is distributed on an "AS-IS" BASIS,
  46826. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  46827. // See the License for the specific language governing permissions and
  46828. // limitations under the License.
  46829. /**
  46830. * @fileoverview Namespace with crypto related helper functions.
  46831. */
  46832. goog.provide('goog.crypt');
  46833. goog.require('goog.array');
  46834. goog.require('goog.asserts');
  46835. /**
  46836. * Turns a string into an array of bytes; a "byte" being a JS number in the
  46837. * range 0-255.
  46838. * @param {string} str String value to arrify.
  46839. * @return {!Array<number>} Array of numbers corresponding to the
  46840. * UCS character codes of each character in str.
  46841. */
  46842. goog.crypt.stringToByteArray = function(str) {
  46843. var output = [], p = 0;
  46844. for (var i = 0; i < str.length; i++) {
  46845. var c = str.charCodeAt(i);
  46846. while (c > 0xff) {
  46847. output[p++] = c & 0xff;
  46848. c >>= 8;
  46849. }
  46850. output[p++] = c;
  46851. }
  46852. return output;
  46853. };
  46854. /**
  46855. * Turns an array of numbers into the string given by the concatenation of the
  46856. * characters to which the numbers correspond.
  46857. * @param {Array<number>} bytes Array of numbers representing characters.
  46858. * @return {string} Stringification of the array.
  46859. */
  46860. goog.crypt.byteArrayToString = function(bytes) {
  46861. var CHUNK_SIZE = 8192;
  46862. // Special-case the simple case for speed's sake.
  46863. if (bytes.length <= CHUNK_SIZE) {
  46864. return String.fromCharCode.apply(null, bytes);
  46865. }
  46866. // The remaining logic splits conversion by chunks since
  46867. // Function#apply() has a maximum parameter count.
  46868. // See discussion: http://goo.gl/LrWmZ9
  46869. var str = '';
  46870. for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {
  46871. var chunk = goog.array.slice(bytes, i, i + CHUNK_SIZE);
  46872. str += String.fromCharCode.apply(null, chunk);
  46873. }
  46874. return str;
  46875. };
  46876. /**
  46877. * Turns an array of numbers into the hex string given by the concatenation of
  46878. * the hex values to which the numbers correspond.
  46879. * @param {Uint8Array|Array<number>} array Array of numbers representing
  46880. * characters.
  46881. * @return {string} Hex string.
  46882. */
  46883. goog.crypt.byteArrayToHex = function(array) {
  46884. return goog.array.map(array, function(numByte) {
  46885. var hexByte = numByte.toString(16);
  46886. return hexByte.length > 1 ? hexByte : '0' + hexByte;
  46887. }).join('');
  46888. };
  46889. /**
  46890. * Converts a hex string into an integer array.
  46891. * @param {string} hexString Hex string of 16-bit integers (two characters
  46892. * per integer).
  46893. * @return {!Array<number>} Array of {0,255} integers for the given string.
  46894. */
  46895. goog.crypt.hexToByteArray = function(hexString) {
  46896. goog.asserts.assert(hexString.length % 2 == 0,
  46897. 'Key string length must be multiple of 2');
  46898. var arr = [];
  46899. for (var i = 0; i < hexString.length; i += 2) {
  46900. arr.push(parseInt(hexString.substring(i, i + 2), 16));
  46901. }
  46902. return arr;
  46903. };
  46904. /**
  46905. * Converts a JS string to a UTF-8 "byte" array.
  46906. * @param {string} str 16-bit unicode string.
  46907. * @return {!Array<number>} UTF-8 byte array.
  46908. */
  46909. goog.crypt.stringToUtf8ByteArray = function(str) {
  46910. // TODO(user): Use native implementations if/when available
  46911. var out = [], p = 0;
  46912. for (var i = 0; i < str.length; i++) {
  46913. var c = str.charCodeAt(i);
  46914. if (c < 128) {
  46915. out[p++] = c;
  46916. } else if (c < 2048) {
  46917. out[p++] = (c >> 6) | 192;
  46918. out[p++] = (c & 63) | 128;
  46919. } else {
  46920. out[p++] = (c >> 12) | 224;
  46921. out[p++] = ((c >> 6) & 63) | 128;
  46922. out[p++] = (c & 63) | 128;
  46923. }
  46924. }
  46925. return out;
  46926. };
  46927. /**
  46928. * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode.
  46929. * @param {Uint8Array|Array<number>} bytes UTF-8 byte array.
  46930. * @return {string} 16-bit Unicode string.
  46931. */
  46932. goog.crypt.utf8ByteArrayToString = function(bytes) {
  46933. // TODO(user): Use native implementations if/when available
  46934. var out = [], pos = 0, c = 0;
  46935. while (pos < bytes.length) {
  46936. var c1 = bytes[pos++];
  46937. if (c1 < 128) {
  46938. out[c++] = String.fromCharCode(c1);
  46939. } else if (c1 > 191 && c1 < 224) {
  46940. var c2 = bytes[pos++];
  46941. out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
  46942. } else {
  46943. var c2 = bytes[pos++];
  46944. var c3 = bytes[pos++];
  46945. out[c++] = String.fromCharCode(
  46946. (c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
  46947. }
  46948. }
  46949. return out.join('');
  46950. };
  46951. /**
  46952. * XOR two byte arrays.
  46953. * @param {!ArrayBufferView|!Array<number>} bytes1 Byte array 1.
  46954. * @param {!ArrayBufferView|!Array<number>} bytes2 Byte array 2.
  46955. * @return {!Array<number>} Resulting XOR of the two byte arrays.
  46956. */
  46957. goog.crypt.xorByteArray = function(bytes1, bytes2) {
  46958. goog.asserts.assert(
  46959. bytes1.length == bytes2.length,
  46960. 'XOR array lengths must match');
  46961. var result = [];
  46962. for (var i = 0; i < bytes1.length; i++) {
  46963. result.push(bytes1[i] ^ bytes2[i]);
  46964. }
  46965. return result;
  46966. };
  46967. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  46968. //
  46969. // Licensed under the Apache License, Version 2.0 (the "License");
  46970. // you may not use this file except in compliance with the License.
  46971. // You may obtain a copy of the License at
  46972. //
  46973. // http://www.apache.org/licenses/LICENSE-2.0
  46974. //
  46975. // Unless required by applicable law or agreed to in writing, software
  46976. // distributed under the License is distributed on an "AS-IS" BASIS,
  46977. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  46978. // See the License for the specific language governing permissions and
  46979. // limitations under the License.
  46980. /**
  46981. * @fileoverview Abstract cryptographic hash interface.
  46982. *
  46983. * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.
  46984. *
  46985. */
  46986. goog.provide('goog.crypt.Hash');
  46987. /**
  46988. * Create a cryptographic hash instance.
  46989. *
  46990. * @constructor
  46991. * @struct
  46992. */
  46993. goog.crypt.Hash = function() {
  46994. /**
  46995. * The block size for the hasher.
  46996. * @type {number}
  46997. */
  46998. this.blockSize = -1;
  46999. };
  47000. /**
  47001. * Resets the internal accumulator.
  47002. */
  47003. goog.crypt.Hash.prototype.reset = goog.abstractMethod;
  47004. /**
  47005. * Adds a byte array (array with values in [0-255] range) or a string (might
  47006. * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator.
  47007. *
  47008. * Many hash functions operate on blocks of data and implement optimizations
  47009. * when a full chunk of data is readily available. Hence it is often preferable
  47010. * to provide large chunks of data (a kilobyte or more) than to repeatedly
  47011. * call the update method with few tens of bytes. If this is not possible, or
  47012. * not feasible, it might be good to provide data in multiplies of hash block
  47013. * size (often 64 bytes). Please see the implementation and performance tests
  47014. * of your favourite hash.
  47015. *
  47016. * @param {Array<number>|Uint8Array|string} bytes Data used for the update.
  47017. * @param {number=} opt_length Number of bytes to use.
  47018. */
  47019. goog.crypt.Hash.prototype.update = goog.abstractMethod;
  47020. /**
  47021. * @return {!Array<number>} The finalized hash computed
  47022. * from the internal accumulator.
  47023. */
  47024. goog.crypt.Hash.prototype.digest = goog.abstractMethod;
  47025. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  47026. //
  47027. // Licensed under the Apache License, Version 2.0 (the "License");
  47028. // you may not use this file except in compliance with the License.
  47029. // You may obtain a copy of the License at
  47030. //
  47031. // http://www.apache.org/licenses/LICENSE-2.0
  47032. //
  47033. // Unless required by applicable law or agreed to in writing, software
  47034. // distributed under the License is distributed on an "AS-IS" BASIS,
  47035. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  47036. // See the License for the specific language governing permissions and
  47037. // limitations under the License.
  47038. /**
  47039. * @fileoverview MD5 cryptographic hash.
  47040. * Implementation of http://tools.ietf.org/html/rfc1321 with common
  47041. * optimizations and tweaks (see http://en.wikipedia.org/wiki/MD5).
  47042. *
  47043. * Usage:
  47044. * var md5 = new goog.crypt.Md5();
  47045. * md5.update(bytes);
  47046. * var hash = md5.digest();
  47047. *
  47048. * Performance:
  47049. * Chrome 23 ~680 Mbit/s
  47050. * Chrome 13 (in a VM) ~250 Mbit/s
  47051. * Firefox 6.0 (in a VM) ~100 Mbit/s
  47052. * IE9 (in a VM) ~27 Mbit/s
  47053. * Firefox 3.6 ~15 Mbit/s
  47054. * IE8 (in a VM) ~13 Mbit/s
  47055. *
  47056. */
  47057. goog.provide('goog.crypt.Md5');
  47058. goog.require('goog.crypt.Hash');
  47059. /**
  47060. * MD5 cryptographic hash constructor.
  47061. * @constructor
  47062. * @extends {goog.crypt.Hash}
  47063. * @final
  47064. * @struct
  47065. */
  47066. goog.crypt.Md5 = function() {
  47067. goog.crypt.Md5.base(this, 'constructor');
  47068. this.blockSize = 512 / 8;
  47069. /**
  47070. * Holds the current values of accumulated A-D variables (MD buffer).
  47071. * @type {!Array<number>}
  47072. * @private
  47073. */
  47074. this.chain_ = new Array(4);
  47075. /**
  47076. * A buffer holding the data until the whole block can be processed.
  47077. * @type {!Array<number>}
  47078. * @private
  47079. */
  47080. this.block_ = new Array(this.blockSize);
  47081. /**
  47082. * The length of yet-unprocessed data as collected in the block.
  47083. * @type {number}
  47084. * @private
  47085. */
  47086. this.blockLength_ = 0;
  47087. /**
  47088. * The total length of the message so far.
  47089. * @type {number}
  47090. * @private
  47091. */
  47092. this.totalLength_ = 0;
  47093. this.reset();
  47094. };
  47095. goog.inherits(goog.crypt.Md5, goog.crypt.Hash);
  47096. /**
  47097. * Integer rotation constants used by the abbreviated implementation.
  47098. * They are hardcoded in the unrolled implementation, so it is left
  47099. * here commented out.
  47100. * @type {Array<number>}
  47101. * @private
  47102. *
  47103. goog.crypt.Md5.S_ = [
  47104. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  47105. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  47106. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  47107. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
  47108. ];
  47109. */
  47110. /**
  47111. * Sine function constants used by the abbreviated implementation.
  47112. * They are hardcoded in the unrolled implementation, so it is left
  47113. * here commented out.
  47114. * @type {Array<number>}
  47115. * @private
  47116. *
  47117. goog.crypt.Md5.T_ = [
  47118. 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
  47119. 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
  47120. 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
  47121. 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
  47122. 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
  47123. 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
  47124. 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
  47125. 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
  47126. 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
  47127. 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
  47128. 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
  47129. 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
  47130. 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
  47131. 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
  47132. 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
  47133. 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
  47134. ];
  47135. */
  47136. /** @override */
  47137. goog.crypt.Md5.prototype.reset = function() {
  47138. this.chain_[0] = 0x67452301;
  47139. this.chain_[1] = 0xefcdab89;
  47140. this.chain_[2] = 0x98badcfe;
  47141. this.chain_[3] = 0x10325476;
  47142. this.blockLength_ = 0;
  47143. this.totalLength_ = 0;
  47144. };
  47145. /**
  47146. * Internal compress helper function. It takes a block of data (64 bytes)
  47147. * and updates the accumulator.
  47148. * @param {Array<number>|Uint8Array|string} buf The block to compress.
  47149. * @param {number=} opt_offset Offset of the block in the buffer.
  47150. * @private
  47151. */
  47152. goog.crypt.Md5.prototype.compress_ = function(buf, opt_offset) {
  47153. if (!opt_offset) {
  47154. opt_offset = 0;
  47155. }
  47156. // We allocate the array every time, but it's cheap in practice.
  47157. var X = new Array(16);
  47158. // Get 16 little endian words. It is not worth unrolling this for Chrome 11.
  47159. if (goog.isString(buf)) {
  47160. for (var i = 0; i < 16; ++i) {
  47161. X[i] = (buf.charCodeAt(opt_offset++)) |
  47162. (buf.charCodeAt(opt_offset++) << 8) |
  47163. (buf.charCodeAt(opt_offset++) << 16) |
  47164. (buf.charCodeAt(opt_offset++) << 24);
  47165. }
  47166. } else {
  47167. for (var i = 0; i < 16; ++i) {
  47168. X[i] = (buf[opt_offset++]) |
  47169. (buf[opt_offset++] << 8) |
  47170. (buf[opt_offset++] << 16) |
  47171. (buf[opt_offset++] << 24);
  47172. }
  47173. }
  47174. var A = this.chain_[0];
  47175. var B = this.chain_[1];
  47176. var C = this.chain_[2];
  47177. var D = this.chain_[3];
  47178. var sum = 0;
  47179. /*
  47180. * This is an abbreviated implementation, it is left here commented out for
  47181. * reference purposes. See below for an unrolled version in use.
  47182. *
  47183. var f, n, tmp;
  47184. for (var i = 0; i < 64; ++i) {
  47185. if (i < 16) {
  47186. f = (D ^ (B & (C ^ D)));
  47187. n = i;
  47188. } else if (i < 32) {
  47189. f = (C ^ (D & (B ^ C)));
  47190. n = (5 * i + 1) % 16;
  47191. } else if (i < 48) {
  47192. f = (B ^ C ^ D);
  47193. n = (3 * i + 5) % 16;
  47194. } else {
  47195. f = (C ^ (B | (~D)));
  47196. n = (7 * i) % 16;
  47197. }
  47198. tmp = D;
  47199. D = C;
  47200. C = B;
  47201. sum = (A + f + goog.crypt.Md5.T_[i] + X[n]) & 0xffffffff;
  47202. B += ((sum << goog.crypt.Md5.S_[i]) & 0xffffffff) |
  47203. (sum >>> (32 - goog.crypt.Md5.S_[i]));
  47204. A = tmp;
  47205. }
  47206. */
  47207. /*
  47208. * This is an unrolled MD5 implementation, which gives ~30% speedup compared
  47209. * to the abbreviated implementation above, as measured on Chrome 11. It is
  47210. * important to keep 32-bit croppings to minimum and inline the integer
  47211. * rotation.
  47212. */
  47213. sum = (A + (D ^ (B & (C ^ D))) + X[0] + 0xd76aa478) & 0xffffffff;
  47214. A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));
  47215. sum = (D + (C ^ (A & (B ^ C))) + X[1] + 0xe8c7b756) & 0xffffffff;
  47216. D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));
  47217. sum = (C + (B ^ (D & (A ^ B))) + X[2] + 0x242070db) & 0xffffffff;
  47218. C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));
  47219. sum = (B + (A ^ (C & (D ^ A))) + X[3] + 0xc1bdceee) & 0xffffffff;
  47220. B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));
  47221. sum = (A + (D ^ (B & (C ^ D))) + X[4] + 0xf57c0faf) & 0xffffffff;
  47222. A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));
  47223. sum = (D + (C ^ (A & (B ^ C))) + X[5] + 0x4787c62a) & 0xffffffff;
  47224. D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));
  47225. sum = (C + (B ^ (D & (A ^ B))) + X[6] + 0xa8304613) & 0xffffffff;
  47226. C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));
  47227. sum = (B + (A ^ (C & (D ^ A))) + X[7] + 0xfd469501) & 0xffffffff;
  47228. B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));
  47229. sum = (A + (D ^ (B & (C ^ D))) + X[8] + 0x698098d8) & 0xffffffff;
  47230. A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));
  47231. sum = (D + (C ^ (A & (B ^ C))) + X[9] + 0x8b44f7af) & 0xffffffff;
  47232. D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));
  47233. sum = (C + (B ^ (D & (A ^ B))) + X[10] + 0xffff5bb1) & 0xffffffff;
  47234. C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));
  47235. sum = (B + (A ^ (C & (D ^ A))) + X[11] + 0x895cd7be) & 0xffffffff;
  47236. B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));
  47237. sum = (A + (D ^ (B & (C ^ D))) + X[12] + 0x6b901122) & 0xffffffff;
  47238. A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));
  47239. sum = (D + (C ^ (A & (B ^ C))) + X[13] + 0xfd987193) & 0xffffffff;
  47240. D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));
  47241. sum = (C + (B ^ (D & (A ^ B))) + X[14] + 0xa679438e) & 0xffffffff;
  47242. C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));
  47243. sum = (B + (A ^ (C & (D ^ A))) + X[15] + 0x49b40821) & 0xffffffff;
  47244. B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));
  47245. sum = (A + (C ^ (D & (B ^ C))) + X[1] + 0xf61e2562) & 0xffffffff;
  47246. A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));
  47247. sum = (D + (B ^ (C & (A ^ B))) + X[6] + 0xc040b340) & 0xffffffff;
  47248. D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));
  47249. sum = (C + (A ^ (B & (D ^ A))) + X[11] + 0x265e5a51) & 0xffffffff;
  47250. C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));
  47251. sum = (B + (D ^ (A & (C ^ D))) + X[0] + 0xe9b6c7aa) & 0xffffffff;
  47252. B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));
  47253. sum = (A + (C ^ (D & (B ^ C))) + X[5] + 0xd62f105d) & 0xffffffff;
  47254. A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));
  47255. sum = (D + (B ^ (C & (A ^ B))) + X[10] + 0x02441453) & 0xffffffff;
  47256. D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));
  47257. sum = (C + (A ^ (B & (D ^ A))) + X[15] + 0xd8a1e681) & 0xffffffff;
  47258. C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));
  47259. sum = (B + (D ^ (A & (C ^ D))) + X[4] + 0xe7d3fbc8) & 0xffffffff;
  47260. B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));
  47261. sum = (A + (C ^ (D & (B ^ C))) + X[9] + 0x21e1cde6) & 0xffffffff;
  47262. A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));
  47263. sum = (D + (B ^ (C & (A ^ B))) + X[14] + 0xc33707d6) & 0xffffffff;
  47264. D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));
  47265. sum = (C + (A ^ (B & (D ^ A))) + X[3] + 0xf4d50d87) & 0xffffffff;
  47266. C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));
  47267. sum = (B + (D ^ (A & (C ^ D))) + X[8] + 0x455a14ed) & 0xffffffff;
  47268. B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));
  47269. sum = (A + (C ^ (D & (B ^ C))) + X[13] + 0xa9e3e905) & 0xffffffff;
  47270. A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));
  47271. sum = (D + (B ^ (C & (A ^ B))) + X[2] + 0xfcefa3f8) & 0xffffffff;
  47272. D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));
  47273. sum = (C + (A ^ (B & (D ^ A))) + X[7] + 0x676f02d9) & 0xffffffff;
  47274. C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));
  47275. sum = (B + (D ^ (A & (C ^ D))) + X[12] + 0x8d2a4c8a) & 0xffffffff;
  47276. B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));
  47277. sum = (A + (B ^ C ^ D) + X[5] + 0xfffa3942) & 0xffffffff;
  47278. A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));
  47279. sum = (D + (A ^ B ^ C) + X[8] + 0x8771f681) & 0xffffffff;
  47280. D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));
  47281. sum = (C + (D ^ A ^ B) + X[11] + 0x6d9d6122) & 0xffffffff;
  47282. C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));
  47283. sum = (B + (C ^ D ^ A) + X[14] + 0xfde5380c) & 0xffffffff;
  47284. B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));
  47285. sum = (A + (B ^ C ^ D) + X[1] + 0xa4beea44) & 0xffffffff;
  47286. A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));
  47287. sum = (D + (A ^ B ^ C) + X[4] + 0x4bdecfa9) & 0xffffffff;
  47288. D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));
  47289. sum = (C + (D ^ A ^ B) + X[7] + 0xf6bb4b60) & 0xffffffff;
  47290. C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));
  47291. sum = (B + (C ^ D ^ A) + X[10] + 0xbebfbc70) & 0xffffffff;
  47292. B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));
  47293. sum = (A + (B ^ C ^ D) + X[13] + 0x289b7ec6) & 0xffffffff;
  47294. A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));
  47295. sum = (D + (A ^ B ^ C) + X[0] + 0xeaa127fa) & 0xffffffff;
  47296. D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));
  47297. sum = (C + (D ^ A ^ B) + X[3] + 0xd4ef3085) & 0xffffffff;
  47298. C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));
  47299. sum = (B + (C ^ D ^ A) + X[6] + 0x04881d05) & 0xffffffff;
  47300. B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));
  47301. sum = (A + (B ^ C ^ D) + X[9] + 0xd9d4d039) & 0xffffffff;
  47302. A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));
  47303. sum = (D + (A ^ B ^ C) + X[12] + 0xe6db99e5) & 0xffffffff;
  47304. D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));
  47305. sum = (C + (D ^ A ^ B) + X[15] + 0x1fa27cf8) & 0xffffffff;
  47306. C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));
  47307. sum = (B + (C ^ D ^ A) + X[2] + 0xc4ac5665) & 0xffffffff;
  47308. B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));
  47309. sum = (A + (C ^ (B | (~D))) + X[0] + 0xf4292244) & 0xffffffff;
  47310. A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));
  47311. sum = (D + (B ^ (A | (~C))) + X[7] + 0x432aff97) & 0xffffffff;
  47312. D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));
  47313. sum = (C + (A ^ (D | (~B))) + X[14] + 0xab9423a7) & 0xffffffff;
  47314. C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));
  47315. sum = (B + (D ^ (C | (~A))) + X[5] + 0xfc93a039) & 0xffffffff;
  47316. B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));
  47317. sum = (A + (C ^ (B | (~D))) + X[12] + 0x655b59c3) & 0xffffffff;
  47318. A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));
  47319. sum = (D + (B ^ (A | (~C))) + X[3] + 0x8f0ccc92) & 0xffffffff;
  47320. D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));
  47321. sum = (C + (A ^ (D | (~B))) + X[10] + 0xffeff47d) & 0xffffffff;
  47322. C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));
  47323. sum = (B + (D ^ (C | (~A))) + X[1] + 0x85845dd1) & 0xffffffff;
  47324. B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));
  47325. sum = (A + (C ^ (B | (~D))) + X[8] + 0x6fa87e4f) & 0xffffffff;
  47326. A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));
  47327. sum = (D + (B ^ (A | (~C))) + X[15] + 0xfe2ce6e0) & 0xffffffff;
  47328. D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));
  47329. sum = (C + (A ^ (D | (~B))) + X[6] + 0xa3014314) & 0xffffffff;
  47330. C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));
  47331. sum = (B + (D ^ (C | (~A))) + X[13] + 0x4e0811a1) & 0xffffffff;
  47332. B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));
  47333. sum = (A + (C ^ (B | (~D))) + X[4] + 0xf7537e82) & 0xffffffff;
  47334. A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));
  47335. sum = (D + (B ^ (A | (~C))) + X[11] + 0xbd3af235) & 0xffffffff;
  47336. D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));
  47337. sum = (C + (A ^ (D | (~B))) + X[2] + 0x2ad7d2bb) & 0xffffffff;
  47338. C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));
  47339. sum = (B + (D ^ (C | (~A))) + X[9] + 0xeb86d391) & 0xffffffff;
  47340. B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));
  47341. this.chain_[0] = (this.chain_[0] + A) & 0xffffffff;
  47342. this.chain_[1] = (this.chain_[1] + B) & 0xffffffff;
  47343. this.chain_[2] = (this.chain_[2] + C) & 0xffffffff;
  47344. this.chain_[3] = (this.chain_[3] + D) & 0xffffffff;
  47345. };
  47346. /** @override */
  47347. goog.crypt.Md5.prototype.update = function(bytes, opt_length) {
  47348. if (!goog.isDef(opt_length)) {
  47349. opt_length = bytes.length;
  47350. }
  47351. var lengthMinusBlock = opt_length - this.blockSize;
  47352. // Copy some object properties to local variables in order to save on access
  47353. // time from inside the loop (~10% speedup was observed on Chrome 11).
  47354. var block = this.block_;
  47355. var blockLength = this.blockLength_;
  47356. var i = 0;
  47357. // The outer while loop should execute at most twice.
  47358. while (i < opt_length) {
  47359. // When we have no data in the block to top up, we can directly process the
  47360. // input buffer (assuming it contains sufficient data). This gives ~30%
  47361. // speedup on Chrome 14 and ~70% speedup on Firefox 6.0, but requires that
  47362. // the data is provided in large chunks (or in multiples of 64 bytes).
  47363. if (blockLength == 0) {
  47364. while (i <= lengthMinusBlock) {
  47365. this.compress_(bytes, i);
  47366. i += this.blockSize;
  47367. }
  47368. }
  47369. if (goog.isString(bytes)) {
  47370. while (i < opt_length) {
  47371. block[blockLength++] = bytes.charCodeAt(i++);
  47372. if (blockLength == this.blockSize) {
  47373. this.compress_(block);
  47374. blockLength = 0;
  47375. // Jump to the outer loop so we use the full-block optimization.
  47376. break;
  47377. }
  47378. }
  47379. } else {
  47380. while (i < opt_length) {
  47381. block[blockLength++] = bytes[i++];
  47382. if (blockLength == this.blockSize) {
  47383. this.compress_(block);
  47384. blockLength = 0;
  47385. // Jump to the outer loop so we use the full-block optimization.
  47386. break;
  47387. }
  47388. }
  47389. }
  47390. }
  47391. this.blockLength_ = blockLength;
  47392. this.totalLength_ += opt_length;
  47393. };
  47394. /** @override */
  47395. goog.crypt.Md5.prototype.digest = function() {
  47396. // This must accommodate at least 1 padding byte (0x80), 8 bytes of
  47397. // total bitlength, and must end at a 64-byte boundary.
  47398. var pad = new Array((this.blockLength_ < 56 ?
  47399. this.blockSize :
  47400. this.blockSize * 2) - this.blockLength_);
  47401. // Add padding: 0x80 0x00*
  47402. pad[0] = 0x80;
  47403. for (var i = 1; i < pad.length - 8; ++i) {
  47404. pad[i] = 0;
  47405. }
  47406. // Add the total number of bits, little endian 64-bit integer.
  47407. var totalBits = this.totalLength_ * 8;
  47408. for (var i = pad.length - 8; i < pad.length; ++i) {
  47409. pad[i] = totalBits & 0xff;
  47410. totalBits /= 0x100; // Don't use bit-shifting here!
  47411. }
  47412. this.update(pad);
  47413. var digest = new Array(16);
  47414. var n = 0;
  47415. for (var i = 0; i < 4; ++i) {
  47416. for (var j = 0; j < 32; j += 8) {
  47417. digest[n++] = (this.chain_[i] >>> j) & 0xff;
  47418. }
  47419. }
  47420. return digest;
  47421. };
  47422. goog.provide('ol.structs.IHasChecksum');
  47423. /**
  47424. * @interface
  47425. */
  47426. ol.structs.IHasChecksum = function() {
  47427. };
  47428. /**
  47429. * @return {string} The checksum.
  47430. */
  47431. ol.structs.IHasChecksum.prototype.getChecksum = function() {
  47432. };
  47433. goog.provide('ol.style.Stroke');
  47434. goog.require('goog.crypt');
  47435. goog.require('goog.crypt.Md5');
  47436. goog.require('ol.color');
  47437. goog.require('ol.structs.IHasChecksum');
  47438. /**
  47439. * @classdesc
  47440. * Set stroke style for vector features.
  47441. * Note that the defaults given are the Canvas defaults, which will be used if
  47442. * option is not defined. The `get` functions return whatever was entered in
  47443. * the options; they will not return the default.
  47444. *
  47445. * @constructor
  47446. * @param {olx.style.StrokeOptions=} opt_options Options.
  47447. * @implements {ol.structs.IHasChecksum}
  47448. * @api
  47449. */
  47450. ol.style.Stroke = function(opt_options) {
  47451. var options = opt_options || {};
  47452. /**
  47453. * @private
  47454. * @type {ol.Color|string}
  47455. */
  47456. this.color_ = options.color !== undefined ? options.color : null;
  47457. /**
  47458. * @private
  47459. * @type {string|undefined}
  47460. */
  47461. this.lineCap_ = options.lineCap;
  47462. /**
  47463. * @private
  47464. * @type {Array.<number>}
  47465. */
  47466. this.lineDash_ = options.lineDash !== undefined ? options.lineDash : null;
  47467. /**
  47468. * @private
  47469. * @type {string|undefined}
  47470. */
  47471. this.lineJoin_ = options.lineJoin;
  47472. /**
  47473. * @private
  47474. * @type {number|undefined}
  47475. */
  47476. this.miterLimit_ = options.miterLimit;
  47477. /**
  47478. * @private
  47479. * @type {number|undefined}
  47480. */
  47481. this.width_ = options.width;
  47482. /**
  47483. * @private
  47484. * @type {string|undefined}
  47485. */
  47486. this.checksum_ = undefined;
  47487. };
  47488. /**
  47489. * Get the stroke color.
  47490. * @return {ol.Color|string} Color.
  47491. * @api
  47492. */
  47493. ol.style.Stroke.prototype.getColor = function() {
  47494. return this.color_;
  47495. };
  47496. /**
  47497. * Get the line cap type for the stroke.
  47498. * @return {string|undefined} Line cap.
  47499. * @api
  47500. */
  47501. ol.style.Stroke.prototype.getLineCap = function() {
  47502. return this.lineCap_;
  47503. };
  47504. /**
  47505. * Get the line dash style for the stroke.
  47506. * @return {Array.<number>} Line dash.
  47507. * @api
  47508. */
  47509. ol.style.Stroke.prototype.getLineDash = function() {
  47510. return this.lineDash_;
  47511. };
  47512. /**
  47513. * Get the line join type for the stroke.
  47514. * @return {string|undefined} Line join.
  47515. * @api
  47516. */
  47517. ol.style.Stroke.prototype.getLineJoin = function() {
  47518. return this.lineJoin_;
  47519. };
  47520. /**
  47521. * Get the miter limit for the stroke.
  47522. * @return {number|undefined} Miter limit.
  47523. * @api
  47524. */
  47525. ol.style.Stroke.prototype.getMiterLimit = function() {
  47526. return this.miterLimit_;
  47527. };
  47528. /**
  47529. * Get the stroke width.
  47530. * @return {number|undefined} Width.
  47531. * @api
  47532. */
  47533. ol.style.Stroke.prototype.getWidth = function() {
  47534. return this.width_;
  47535. };
  47536. /**
  47537. * Set the color.
  47538. *
  47539. * @param {ol.Color|string} color Color.
  47540. * @api
  47541. */
  47542. ol.style.Stroke.prototype.setColor = function(color) {
  47543. this.color_ = color;
  47544. this.checksum_ = undefined;
  47545. };
  47546. /**
  47547. * Set the line cap.
  47548. *
  47549. * @param {string|undefined} lineCap Line cap.
  47550. * @api
  47551. */
  47552. ol.style.Stroke.prototype.setLineCap = function(lineCap) {
  47553. this.lineCap_ = lineCap;
  47554. this.checksum_ = undefined;
  47555. };
  47556. /**
  47557. * Set the line dash.
  47558. *
  47559. * @param {Array.<number>} lineDash Line dash.
  47560. * @api
  47561. */
  47562. ol.style.Stroke.prototype.setLineDash = function(lineDash) {
  47563. this.lineDash_ = lineDash;
  47564. this.checksum_ = undefined;
  47565. };
  47566. /**
  47567. * Set the line join.
  47568. *
  47569. * @param {string|undefined} lineJoin Line join.
  47570. * @api
  47571. */
  47572. ol.style.Stroke.prototype.setLineJoin = function(lineJoin) {
  47573. this.lineJoin_ = lineJoin;
  47574. this.checksum_ = undefined;
  47575. };
  47576. /**
  47577. * Set the miter limit.
  47578. *
  47579. * @param {number|undefined} miterLimit Miter limit.
  47580. * @api
  47581. */
  47582. ol.style.Stroke.prototype.setMiterLimit = function(miterLimit) {
  47583. this.miterLimit_ = miterLimit;
  47584. this.checksum_ = undefined;
  47585. };
  47586. /**
  47587. * Set the width.
  47588. *
  47589. * @param {number|undefined} width Width.
  47590. * @api
  47591. */
  47592. ol.style.Stroke.prototype.setWidth = function(width) {
  47593. this.width_ = width;
  47594. this.checksum_ = undefined;
  47595. };
  47596. /**
  47597. * @inheritDoc
  47598. */
  47599. ol.style.Stroke.prototype.getChecksum = function() {
  47600. if (this.checksum_ === undefined) {
  47601. var raw = 's' +
  47602. (this.color_ ?
  47603. ol.color.asString(this.color_) : '-') + ',' +
  47604. (this.lineCap_ !== undefined ?
  47605. this.lineCap_.toString() : '-') + ',' +
  47606. (this.lineDash_ ?
  47607. this.lineDash_.toString() : '-') + ',' +
  47608. (this.lineJoin_ !== undefined ?
  47609. this.lineJoin_ : '-') + ',' +
  47610. (this.miterLimit_ !== undefined ?
  47611. this.miterLimit_.toString() : '-') + ',' +
  47612. (this.width_ !== undefined ?
  47613. this.width_.toString() : '-');
  47614. var md5 = new goog.crypt.Md5();
  47615. md5.update(raw);
  47616. this.checksum_ = goog.crypt.byteArrayToString(md5.digest());
  47617. }
  47618. return this.checksum_;
  47619. };
  47620. goog.provide('ol.render.canvas');
  47621. /**
  47622. * @typedef {{fillStyle: string}}
  47623. */
  47624. ol.render.canvas.FillState;
  47625. /**
  47626. * @typedef {{lineCap: string,
  47627. * lineDash: Array.<number>,
  47628. * lineJoin: string,
  47629. * lineWidth: number,
  47630. * miterLimit: number,
  47631. * strokeStyle: string}}
  47632. */
  47633. ol.render.canvas.StrokeState;
  47634. /**
  47635. * @typedef {{font: string,
  47636. * textAlign: string,
  47637. * textBaseline: string}}
  47638. */
  47639. ol.render.canvas.TextState;
  47640. /**
  47641. * @const
  47642. * @type {string}
  47643. */
  47644. ol.render.canvas.defaultFont = '10px sans-serif';
  47645. /**
  47646. * @const
  47647. * @type {ol.Color}
  47648. */
  47649. ol.render.canvas.defaultFillStyle = [0, 0, 0, 1];
  47650. /**
  47651. * @const
  47652. * @type {string}
  47653. */
  47654. ol.render.canvas.defaultLineCap = 'round';
  47655. /**
  47656. * @const
  47657. * @type {Array.<number>}
  47658. */
  47659. ol.render.canvas.defaultLineDash = [];
  47660. /**
  47661. * @const
  47662. * @type {string}
  47663. */
  47664. ol.render.canvas.defaultLineJoin = 'round';
  47665. /**
  47666. * @const
  47667. * @type {number}
  47668. */
  47669. ol.render.canvas.defaultMiterLimit = 10;
  47670. /**
  47671. * @const
  47672. * @type {ol.Color}
  47673. */
  47674. ol.render.canvas.defaultStrokeStyle = [0, 0, 0, 1];
  47675. /**
  47676. * @const
  47677. * @type {string}
  47678. */
  47679. ol.render.canvas.defaultTextAlign = 'center';
  47680. /**
  47681. * @const
  47682. * @type {string}
  47683. */
  47684. ol.render.canvas.defaultTextBaseline = 'middle';
  47685. /**
  47686. * @const
  47687. * @type {number}
  47688. */
  47689. ol.render.canvas.defaultLineWidth = 1;
  47690. goog.provide('ol.style.Fill');
  47691. goog.require('ol.color');
  47692. goog.require('ol.structs.IHasChecksum');
  47693. /**
  47694. * @classdesc
  47695. * Set fill style for vector features.
  47696. *
  47697. * @constructor
  47698. * @param {olx.style.FillOptions=} opt_options Options.
  47699. * @implements {ol.structs.IHasChecksum}
  47700. * @api
  47701. */
  47702. ol.style.Fill = function(opt_options) {
  47703. var options = opt_options || {};
  47704. /**
  47705. * @private
  47706. * @type {ol.Color|string}
  47707. */
  47708. this.color_ = options.color !== undefined ? options.color : null;
  47709. /**
  47710. * @private
  47711. * @type {string|undefined}
  47712. */
  47713. this.checksum_ = undefined;
  47714. };
  47715. /**
  47716. * Get the fill color.
  47717. * @return {ol.Color|string} Color.
  47718. * @api
  47719. */
  47720. ol.style.Fill.prototype.getColor = function() {
  47721. return this.color_;
  47722. };
  47723. /**
  47724. * Set the color.
  47725. *
  47726. * @param {ol.Color|string} color Color.
  47727. * @api
  47728. */
  47729. ol.style.Fill.prototype.setColor = function(color) {
  47730. this.color_ = color;
  47731. this.checksum_ = undefined;
  47732. };
  47733. /**
  47734. * @inheritDoc
  47735. */
  47736. ol.style.Fill.prototype.getChecksum = function() {
  47737. if (this.checksum_ === undefined) {
  47738. this.checksum_ = 'f' + (this.color_ ?
  47739. ol.color.asString(this.color_) : '-');
  47740. }
  47741. return this.checksum_;
  47742. };
  47743. goog.provide('ol.style.Circle');
  47744. goog.require('goog.asserts');
  47745. goog.require('goog.dom');
  47746. goog.require('goog.dom.TagName');
  47747. goog.require('ol');
  47748. goog.require('ol.color');
  47749. goog.require('ol.has');
  47750. goog.require('ol.render.canvas');
  47751. goog.require('ol.structs.IHasChecksum');
  47752. goog.require('ol.style.Fill');
  47753. goog.require('ol.style.Image');
  47754. goog.require('ol.style.ImageState');
  47755. goog.require('ol.style.Stroke');
  47756. /**
  47757. * @classdesc
  47758. * Set circle style for vector features.
  47759. *
  47760. * @constructor
  47761. * @param {olx.style.CircleOptions=} opt_options Options.
  47762. * @extends {ol.style.Image}
  47763. * @implements {ol.structs.IHasChecksum}
  47764. * @api
  47765. */
  47766. ol.style.Circle = function(opt_options) {
  47767. var options = opt_options || {};
  47768. /**
  47769. * @private
  47770. * @type {Array.<string>}
  47771. */
  47772. this.checksums_ = null;
  47773. /**
  47774. * @private
  47775. * @type {HTMLCanvasElement}
  47776. */
  47777. this.canvas_ = null;
  47778. /**
  47779. * @private
  47780. * @type {HTMLCanvasElement}
  47781. */
  47782. this.hitDetectionCanvas_ = null;
  47783. /**
  47784. * @private
  47785. * @type {ol.style.Fill}
  47786. */
  47787. this.fill_ = options.fill !== undefined ? options.fill : null;
  47788. /**
  47789. * @private
  47790. * @type {ol.style.Stroke}
  47791. */
  47792. this.stroke_ = options.stroke !== undefined ? options.stroke : null;
  47793. /**
  47794. * @private
  47795. * @type {number}
  47796. */
  47797. this.radius_ = options.radius;
  47798. /**
  47799. * @private
  47800. * @type {Array.<number>}
  47801. */
  47802. this.origin_ = [0, 0];
  47803. /**
  47804. * @private
  47805. * @type {Array.<number>}
  47806. */
  47807. this.anchor_ = null;
  47808. /**
  47809. * @private
  47810. * @type {ol.Size}
  47811. */
  47812. this.size_ = null;
  47813. /**
  47814. * @private
  47815. * @type {ol.Size}
  47816. */
  47817. this.imageSize_ = null;
  47818. /**
  47819. * @private
  47820. * @type {ol.Size}
  47821. */
  47822. this.hitDetectionImageSize_ = null;
  47823. this.render_(options.atlasManager);
  47824. /**
  47825. * @type {boolean}
  47826. */
  47827. var snapToPixel = options.snapToPixel !== undefined ?
  47828. options.snapToPixel : true;
  47829. goog.base(this, {
  47830. opacity: 1,
  47831. rotateWithView: false,
  47832. rotation: 0,
  47833. scale: 1,
  47834. snapToPixel: snapToPixel
  47835. });
  47836. };
  47837. goog.inherits(ol.style.Circle, ol.style.Image);
  47838. /**
  47839. * @inheritDoc
  47840. */
  47841. ol.style.Circle.prototype.getAnchor = function() {
  47842. return this.anchor_;
  47843. };
  47844. /**
  47845. * Get the fill style for the circle.
  47846. * @return {ol.style.Fill} Fill style.
  47847. * @api
  47848. */
  47849. ol.style.Circle.prototype.getFill = function() {
  47850. return this.fill_;
  47851. };
  47852. /**
  47853. * @inheritDoc
  47854. */
  47855. ol.style.Circle.prototype.getHitDetectionImage = function(pixelRatio) {
  47856. return this.hitDetectionCanvas_;
  47857. };
  47858. /**
  47859. * Get the image used to render the circle.
  47860. * @param {number} pixelRatio Pixel ratio.
  47861. * @return {HTMLCanvasElement} Canvas element.
  47862. * @api
  47863. */
  47864. ol.style.Circle.prototype.getImage = function(pixelRatio) {
  47865. return this.canvas_;
  47866. };
  47867. /**
  47868. * @inheritDoc
  47869. */
  47870. ol.style.Circle.prototype.getImageState = function() {
  47871. return ol.style.ImageState.LOADED;
  47872. };
  47873. /**
  47874. * @inheritDoc
  47875. */
  47876. ol.style.Circle.prototype.getImageSize = function() {
  47877. return this.imageSize_;
  47878. };
  47879. /**
  47880. * @inheritDoc
  47881. */
  47882. ol.style.Circle.prototype.getHitDetectionImageSize = function() {
  47883. return this.hitDetectionImageSize_;
  47884. };
  47885. /**
  47886. * @inheritDoc
  47887. */
  47888. ol.style.Circle.prototype.getOrigin = function() {
  47889. return this.origin_;
  47890. };
  47891. /**
  47892. * Get the circle radius.
  47893. * @return {number} Radius.
  47894. * @api
  47895. */
  47896. ol.style.Circle.prototype.getRadius = function() {
  47897. return this.radius_;
  47898. };
  47899. /**
  47900. * @inheritDoc
  47901. */
  47902. ol.style.Circle.prototype.getSize = function() {
  47903. return this.size_;
  47904. };
  47905. /**
  47906. * Get the stroke style for the circle.
  47907. * @return {ol.style.Stroke} Stroke style.
  47908. * @api
  47909. */
  47910. ol.style.Circle.prototype.getStroke = function() {
  47911. return this.stroke_;
  47912. };
  47913. /**
  47914. * @inheritDoc
  47915. */
  47916. ol.style.Circle.prototype.listenImageChange = ol.nullFunction;
  47917. /**
  47918. * @inheritDoc
  47919. */
  47920. ol.style.Circle.prototype.load = ol.nullFunction;
  47921. /**
  47922. * @inheritDoc
  47923. */
  47924. ol.style.Circle.prototype.unlistenImageChange = ol.nullFunction;
  47925. /**
  47926. * @typedef {{strokeStyle: (string|undefined), strokeWidth: number,
  47927. * size: number, lineDash: Array.<number>}}
  47928. */
  47929. ol.style.Circle.RenderOptions;
  47930. /**
  47931. * @private
  47932. * @param {ol.style.AtlasManager|undefined} atlasManager
  47933. */
  47934. ol.style.Circle.prototype.render_ = function(atlasManager) {
  47935. var imageSize;
  47936. var lineDash = null;
  47937. var strokeStyle;
  47938. var strokeWidth = 0;
  47939. if (this.stroke_) {
  47940. strokeStyle = ol.color.asString(this.stroke_.getColor());
  47941. strokeWidth = this.stroke_.getWidth();
  47942. if (strokeWidth === undefined) {
  47943. strokeWidth = ol.render.canvas.defaultLineWidth;
  47944. }
  47945. lineDash = this.stroke_.getLineDash();
  47946. if (!ol.has.CANVAS_LINE_DASH) {
  47947. lineDash = null;
  47948. }
  47949. }
  47950. var size = 2 * (this.radius_ + strokeWidth) + 1;
  47951. /** @type {ol.style.Circle.RenderOptions} */
  47952. var renderOptions = {
  47953. strokeStyle: strokeStyle,
  47954. strokeWidth: strokeWidth,
  47955. size: size,
  47956. lineDash: lineDash
  47957. };
  47958. if (atlasManager === undefined) {
  47959. // no atlas manager is used, create a new canvas
  47960. this.canvas_ = /** @type {HTMLCanvasElement} */
  47961. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  47962. this.canvas_.height = size;
  47963. this.canvas_.width = size;
  47964. // canvas.width and height are rounded to the closest integer
  47965. size = this.canvas_.width;
  47966. imageSize = size;
  47967. // draw the circle on the canvas
  47968. var context = /** @type {CanvasRenderingContext2D} */
  47969. (this.canvas_.getContext('2d'));
  47970. this.draw_(renderOptions, context, 0, 0);
  47971. this.createHitDetectionCanvas_(renderOptions);
  47972. } else {
  47973. // an atlas manager is used, add the symbol to an atlas
  47974. size = Math.round(size);
  47975. var hasCustomHitDetectionImage = !this.fill_;
  47976. var renderHitDetectionCallback;
  47977. if (hasCustomHitDetectionImage) {
  47978. // render the hit-detection image into a separate atlas image
  47979. renderHitDetectionCallback =
  47980. goog.bind(this.drawHitDetectionCanvas_, this, renderOptions);
  47981. }
  47982. var id = this.getChecksum();
  47983. var info = atlasManager.add(
  47984. id, size, size, goog.bind(this.draw_, this, renderOptions),
  47985. renderHitDetectionCallback);
  47986. goog.asserts.assert(info, 'circle radius is too large');
  47987. this.canvas_ = info.image;
  47988. this.origin_ = [info.offsetX, info.offsetY];
  47989. imageSize = info.image.width;
  47990. if (hasCustomHitDetectionImage) {
  47991. this.hitDetectionCanvas_ = info.hitImage;
  47992. this.hitDetectionImageSize_ =
  47993. [info.hitImage.width, info.hitImage.height];
  47994. } else {
  47995. this.hitDetectionCanvas_ = this.canvas_;
  47996. this.hitDetectionImageSize_ = [imageSize, imageSize];
  47997. }
  47998. }
  47999. this.anchor_ = [size / 2, size / 2];
  48000. this.size_ = [size, size];
  48001. this.imageSize_ = [imageSize, imageSize];
  48002. };
  48003. /**
  48004. * @private
  48005. * @param {ol.style.Circle.RenderOptions} renderOptions
  48006. * @param {CanvasRenderingContext2D} context
  48007. * @param {number} x The origin for the symbol (x).
  48008. * @param {number} y The origin for the symbol (y).
  48009. */
  48010. ol.style.Circle.prototype.draw_ = function(renderOptions, context, x, y) {
  48011. // reset transform
  48012. context.setTransform(1, 0, 0, 1, 0, 0);
  48013. // then move to (x, y)
  48014. context.translate(x, y);
  48015. context.beginPath();
  48016. context.arc(
  48017. renderOptions.size / 2, renderOptions.size / 2,
  48018. this.radius_, 0, 2 * Math.PI, true);
  48019. if (this.fill_) {
  48020. context.fillStyle = ol.color.asString(this.fill_.getColor());
  48021. context.fill();
  48022. }
  48023. if (this.stroke_) {
  48024. context.strokeStyle = renderOptions.strokeStyle;
  48025. context.lineWidth = renderOptions.strokeWidth;
  48026. if (renderOptions.lineDash) {
  48027. context.setLineDash(renderOptions.lineDash);
  48028. }
  48029. context.stroke();
  48030. }
  48031. context.closePath();
  48032. };
  48033. /**
  48034. * @private
  48035. * @param {ol.style.Circle.RenderOptions} renderOptions
  48036. */
  48037. ol.style.Circle.prototype.createHitDetectionCanvas_ = function(renderOptions) {
  48038. this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
  48039. if (this.fill_) {
  48040. this.hitDetectionCanvas_ = this.canvas_;
  48041. return;
  48042. }
  48043. // if no fill style is set, create an extra hit-detection image with a
  48044. // default fill style
  48045. this.hitDetectionCanvas_ = /** @type {HTMLCanvasElement} */
  48046. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  48047. var canvas = this.hitDetectionCanvas_;
  48048. canvas.height = renderOptions.size;
  48049. canvas.width = renderOptions.size;
  48050. var context = /** @type {CanvasRenderingContext2D} */
  48051. (canvas.getContext('2d'));
  48052. this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
  48053. };
  48054. /**
  48055. * @private
  48056. * @param {ol.style.Circle.RenderOptions} renderOptions
  48057. * @param {CanvasRenderingContext2D} context
  48058. * @param {number} x The origin for the symbol (x).
  48059. * @param {number} y The origin for the symbol (y).
  48060. */
  48061. ol.style.Circle.prototype.drawHitDetectionCanvas_ =
  48062. function(renderOptions, context, x, y) {
  48063. // reset transform
  48064. context.setTransform(1, 0, 0, 1, 0, 0);
  48065. // then move to (x, y)
  48066. context.translate(x, y);
  48067. context.beginPath();
  48068. context.arc(
  48069. renderOptions.size / 2, renderOptions.size / 2,
  48070. this.radius_, 0, 2 * Math.PI, true);
  48071. context.fillStyle = ol.color.asString(ol.render.canvas.defaultFillStyle);
  48072. context.fill();
  48073. if (this.stroke_) {
  48074. context.strokeStyle = renderOptions.strokeStyle;
  48075. context.lineWidth = renderOptions.strokeWidth;
  48076. if (renderOptions.lineDash) {
  48077. context.setLineDash(renderOptions.lineDash);
  48078. }
  48079. context.stroke();
  48080. }
  48081. context.closePath();
  48082. };
  48083. /**
  48084. * @inheritDoc
  48085. */
  48086. ol.style.Circle.prototype.getChecksum = function() {
  48087. var strokeChecksum = this.stroke_ ?
  48088. this.stroke_.getChecksum() : '-';
  48089. var fillChecksum = this.fill_ ?
  48090. this.fill_.getChecksum() : '-';
  48091. var recalculate = !this.checksums_ ||
  48092. (strokeChecksum != this.checksums_[1] ||
  48093. fillChecksum != this.checksums_[2] ||
  48094. this.radius_ != this.checksums_[3]);
  48095. if (recalculate) {
  48096. var checksum = 'c' + strokeChecksum + fillChecksum +
  48097. (this.radius_ !== undefined ? this.radius_.toString() : '-');
  48098. this.checksums_ = [checksum, strokeChecksum, fillChecksum, this.radius_];
  48099. }
  48100. return this.checksums_[0];
  48101. };
  48102. goog.provide('ol.style.GeometryFunction');
  48103. goog.provide('ol.style.Style');
  48104. goog.provide('ol.style.StyleFunction');
  48105. goog.provide('ol.style.defaultGeometryFunction');
  48106. goog.require('goog.asserts');
  48107. goog.require('ol.geom.Geometry');
  48108. goog.require('ol.geom.GeometryType');
  48109. goog.require('ol.style.Circle');
  48110. goog.require('ol.style.Fill');
  48111. goog.require('ol.style.Image');
  48112. goog.require('ol.style.Stroke');
  48113. /**
  48114. * @classdesc
  48115. * Container for vector feature rendering styles. Any changes made to the style
  48116. * or its children through `set*()` methods will not take effect until the
  48117. * feature or layer that uses the style is re-rendered.
  48118. *
  48119. * @constructor
  48120. * @param {olx.style.StyleOptions=} opt_options Style options.
  48121. * @api
  48122. */
  48123. ol.style.Style = function(opt_options) {
  48124. var options = opt_options || {};
  48125. /**
  48126. * @private
  48127. * @type {string|ol.geom.Geometry|ol.style.GeometryFunction}
  48128. */
  48129. this.geometry_ = null;
  48130. /**
  48131. * @private
  48132. * @type {!ol.style.GeometryFunction}
  48133. */
  48134. this.geometryFunction_ = ol.style.defaultGeometryFunction;
  48135. if (options.geometry !== undefined) {
  48136. this.setGeometry(options.geometry);
  48137. }
  48138. /**
  48139. * @private
  48140. * @type {ol.style.Fill}
  48141. */
  48142. this.fill_ = options.fill !== undefined ? options.fill : null;
  48143. /**
  48144. * @private
  48145. * @type {ol.style.Image}
  48146. */
  48147. this.image_ = options.image !== undefined ? options.image : null;
  48148. /**
  48149. * @private
  48150. * @type {ol.style.Stroke}
  48151. */
  48152. this.stroke_ = options.stroke !== undefined ? options.stroke : null;
  48153. /**
  48154. * @private
  48155. * @type {ol.style.Text}
  48156. */
  48157. this.text_ = options.text !== undefined ? options.text : null;
  48158. /**
  48159. * @private
  48160. * @type {number|undefined}
  48161. */
  48162. this.zIndex_ = options.zIndex;
  48163. };
  48164. /**
  48165. * Get the geometry to be rendered.
  48166. * @return {string|ol.geom.Geometry|ol.style.GeometryFunction}
  48167. * Feature property or geometry or function that returns the geometry that will
  48168. * be rendered with this style.
  48169. * @api
  48170. */
  48171. ol.style.Style.prototype.getGeometry = function() {
  48172. return this.geometry_;
  48173. };
  48174. /**
  48175. * Get the function used to generate a geometry for rendering.
  48176. * @return {!ol.style.GeometryFunction} Function that is called with a feature
  48177. * and returns the geometry to render instead of the feature's geometry.
  48178. * @api
  48179. */
  48180. ol.style.Style.prototype.getGeometryFunction = function() {
  48181. return this.geometryFunction_;
  48182. };
  48183. /**
  48184. * Get the fill style.
  48185. * @return {ol.style.Fill} Fill style.
  48186. * @api
  48187. */
  48188. ol.style.Style.prototype.getFill = function() {
  48189. return this.fill_;
  48190. };
  48191. /**
  48192. * Get the image style.
  48193. * @return {ol.style.Image} Image style.
  48194. * @api
  48195. */
  48196. ol.style.Style.prototype.getImage = function() {
  48197. return this.image_;
  48198. };
  48199. /**
  48200. * Get the stroke style.
  48201. * @return {ol.style.Stroke} Stroke style.
  48202. * @api
  48203. */
  48204. ol.style.Style.prototype.getStroke = function() {
  48205. return this.stroke_;
  48206. };
  48207. /**
  48208. * Get the text style.
  48209. * @return {ol.style.Text} Text style.
  48210. * @api
  48211. */
  48212. ol.style.Style.prototype.getText = function() {
  48213. return this.text_;
  48214. };
  48215. /**
  48216. * Get the z-index for the style.
  48217. * @return {number|undefined} ZIndex.
  48218. * @api
  48219. */
  48220. ol.style.Style.prototype.getZIndex = function() {
  48221. return this.zIndex_;
  48222. };
  48223. /**
  48224. * Set a geometry that is rendered instead of the feature's geometry.
  48225. *
  48226. * @param {string|ol.geom.Geometry|ol.style.GeometryFunction} geometry
  48227. * Feature property or geometry or function returning a geometry to render
  48228. * for this style.
  48229. * @api
  48230. */
  48231. ol.style.Style.prototype.setGeometry = function(geometry) {
  48232. if (goog.isFunction(geometry)) {
  48233. this.geometryFunction_ = geometry;
  48234. } else if (goog.isString(geometry)) {
  48235. this.geometryFunction_ = function(feature) {
  48236. var result = feature.get(geometry);
  48237. if (result) {
  48238. goog.asserts.assertInstanceof(result, ol.geom.Geometry,
  48239. 'feature geometry must be an ol.geom.Geometry instance');
  48240. }
  48241. return result;
  48242. };
  48243. } else if (!geometry) {
  48244. this.geometryFunction_ = ol.style.defaultGeometryFunction;
  48245. } else if (geometry !== undefined) {
  48246. goog.asserts.assertInstanceof(geometry, ol.geom.Geometry,
  48247. 'geometry must be an ol.geom.Geometry instance');
  48248. this.geometryFunction_ = function() {
  48249. return geometry;
  48250. };
  48251. }
  48252. this.geometry_ = geometry;
  48253. };
  48254. /**
  48255. * Set the z-index.
  48256. *
  48257. * @param {number|undefined} zIndex ZIndex.
  48258. * @api
  48259. */
  48260. ol.style.Style.prototype.setZIndex = function(zIndex) {
  48261. this.zIndex_ = zIndex;
  48262. };
  48263. /**
  48264. * A function that takes an {@link ol.Feature} and a `{number}` representing
  48265. * the view's resolution. The function should return an array of
  48266. * {@link ol.style.Style}. This way e.g. a vector layer can be styled.
  48267. *
  48268. * @typedef {function(ol.Feature, number): Array.<ol.style.Style>}
  48269. * @api
  48270. */
  48271. ol.style.StyleFunction;
  48272. /**
  48273. * Convert the provided object into a style function. Functions passed through
  48274. * unchanged. Arrays of ol.style.Style or single style objects wrapped in a
  48275. * new style function.
  48276. * @param {ol.style.StyleFunction|Array.<ol.style.Style>|ol.style.Style} obj
  48277. * A style function, a single style, or an array of styles.
  48278. * @return {ol.style.StyleFunction} A style function.
  48279. */
  48280. ol.style.createStyleFunction = function(obj) {
  48281. var styleFunction;
  48282. if (goog.isFunction(obj)) {
  48283. styleFunction = obj;
  48284. } else {
  48285. /**
  48286. * @type {Array.<ol.style.Style>}
  48287. */
  48288. var styles;
  48289. if (goog.isArray(obj)) {
  48290. styles = obj;
  48291. } else {
  48292. goog.asserts.assertInstanceof(obj, ol.style.Style,
  48293. 'obj geometry must be an ol.style.Style instance');
  48294. styles = [obj];
  48295. }
  48296. styleFunction = function() {
  48297. return styles;
  48298. };
  48299. }
  48300. return styleFunction;
  48301. };
  48302. /**
  48303. * @type {Array.<ol.style.Style>}
  48304. * @private
  48305. */
  48306. ol.style.defaultStyle_ = null;
  48307. /**
  48308. * @param {ol.Feature} feature Feature.
  48309. * @param {number} resolution Resolution.
  48310. * @return {Array.<ol.style.Style>} Style.
  48311. */
  48312. ol.style.defaultStyleFunction = function(feature, resolution) {
  48313. // We don't use an immediately-invoked function
  48314. // and a closure so we don't get an error at script evaluation time in
  48315. // browsers that do not support Canvas. (ol.style.Circle does
  48316. // canvas.getContext('2d') at construction time, which will cause an.error
  48317. // in such browsers.)
  48318. if (!ol.style.defaultStyle_) {
  48319. var fill = new ol.style.Fill({
  48320. color: 'rgba(255,255,255,0.4)'
  48321. });
  48322. var stroke = new ol.style.Stroke({
  48323. color: '#3399CC',
  48324. width: 1.25
  48325. });
  48326. ol.style.defaultStyle_ = [
  48327. new ol.style.Style({
  48328. image: new ol.style.Circle({
  48329. fill: fill,
  48330. stroke: stroke,
  48331. radius: 5
  48332. }),
  48333. fill: fill,
  48334. stroke: stroke
  48335. })
  48336. ];
  48337. }
  48338. return ol.style.defaultStyle_;
  48339. };
  48340. /**
  48341. * Default styles for editing features.
  48342. * @return {Object.<ol.geom.GeometryType, Array.<ol.style.Style>>} Styles
  48343. */
  48344. ol.style.createDefaultEditingStyles = function() {
  48345. /** @type {Object.<ol.geom.GeometryType, Array.<ol.style.Style>>} */
  48346. var styles = {};
  48347. var white = [255, 255, 255, 1];
  48348. var blue = [0, 153, 255, 1];
  48349. var width = 3;
  48350. styles[ol.geom.GeometryType.POLYGON] = [
  48351. new ol.style.Style({
  48352. fill: new ol.style.Fill({
  48353. color: [255, 255, 255, 0.5]
  48354. })
  48355. })
  48356. ];
  48357. styles[ol.geom.GeometryType.MULTI_POLYGON] =
  48358. styles[ol.geom.GeometryType.POLYGON];
  48359. styles[ol.geom.GeometryType.LINE_STRING] = [
  48360. new ol.style.Style({
  48361. stroke: new ol.style.Stroke({
  48362. color: white,
  48363. width: width + 2
  48364. })
  48365. }),
  48366. new ol.style.Style({
  48367. stroke: new ol.style.Stroke({
  48368. color: blue,
  48369. width: width
  48370. })
  48371. })
  48372. ];
  48373. styles[ol.geom.GeometryType.MULTI_LINE_STRING] =
  48374. styles[ol.geom.GeometryType.LINE_STRING];
  48375. styles[ol.geom.GeometryType.CIRCLE] =
  48376. styles[ol.geom.GeometryType.POLYGON].concat(
  48377. styles[ol.geom.GeometryType.LINE_STRING]
  48378. );
  48379. styles[ol.geom.GeometryType.POINT] = [
  48380. new ol.style.Style({
  48381. image: new ol.style.Circle({
  48382. radius: width * 2,
  48383. fill: new ol.style.Fill({
  48384. color: blue
  48385. }),
  48386. stroke: new ol.style.Stroke({
  48387. color: white,
  48388. width: width / 2
  48389. })
  48390. }),
  48391. zIndex: Infinity
  48392. })
  48393. ];
  48394. styles[ol.geom.GeometryType.MULTI_POINT] =
  48395. styles[ol.geom.GeometryType.POINT];
  48396. styles[ol.geom.GeometryType.GEOMETRY_COLLECTION] =
  48397. styles[ol.geom.GeometryType.POLYGON].concat(
  48398. styles[ol.geom.GeometryType.LINE_STRING],
  48399. styles[ol.geom.GeometryType.POINT]
  48400. );
  48401. return styles;
  48402. };
  48403. /**
  48404. * A function that takes an {@link ol.Feature} as argument and returns an
  48405. * {@link ol.geom.Geometry} that will be rendered and styled for the feature.
  48406. *
  48407. * @typedef {function(ol.Feature): (ol.geom.Geometry|undefined)}
  48408. * @api
  48409. */
  48410. ol.style.GeometryFunction;
  48411. /**
  48412. * Function that is called with a feature and returns its default geometry.
  48413. * @param {ol.Feature} feature Feature to get the geometry for.
  48414. * @return {ol.geom.Geometry|undefined} Geometry to render.
  48415. */
  48416. ol.style.defaultGeometryFunction = function(feature) {
  48417. goog.asserts.assert(feature, 'feature must not be null');
  48418. return feature.getGeometry();
  48419. };
  48420. goog.provide('ol.interaction.DragZoom');
  48421. goog.require('goog.asserts');
  48422. goog.require('ol.animation');
  48423. goog.require('ol.easing');
  48424. goog.require('ol.events.condition');
  48425. goog.require('ol.extent');
  48426. goog.require('ol.interaction.DragBox');
  48427. goog.require('ol.style.Stroke');
  48428. goog.require('ol.style.Style');
  48429. /**
  48430. * @classdesc
  48431. * Allows the user to zoom the map by clicking and dragging on the map,
  48432. * normally combined with an {@link ol.events.condition} that limits
  48433. * it to when a key, shift by default, is held down.
  48434. *
  48435. * @constructor
  48436. * @extends {ol.interaction.DragBox}
  48437. * @param {olx.interaction.DragZoomOptions=} opt_options Options.
  48438. * @api stable
  48439. */
  48440. ol.interaction.DragZoom = function(opt_options) {
  48441. var options = opt_options ? opt_options : {};
  48442. var condition = options.condition ?
  48443. options.condition : ol.events.condition.shiftKeyOnly;
  48444. /**
  48445. * @private
  48446. * @type {number}
  48447. */
  48448. this.duration_ = options.duration ? options.duration : 200;
  48449. /**
  48450. * @private
  48451. * @type {ol.style.Style}
  48452. */
  48453. var style = options.style ?
  48454. options.style : new ol.style.Style({
  48455. stroke: new ol.style.Stroke({
  48456. color: [0, 0, 255, 1]
  48457. })
  48458. });
  48459. goog.base(this, {
  48460. condition: condition,
  48461. style: style
  48462. });
  48463. };
  48464. goog.inherits(ol.interaction.DragZoom, ol.interaction.DragBox);
  48465. /**
  48466. * @inheritDoc
  48467. */
  48468. ol.interaction.DragZoom.prototype.onBoxEnd = function() {
  48469. var map = this.getMap();
  48470. var view = map.getView();
  48471. goog.asserts.assert(view, 'map must have view');
  48472. var size = map.getSize();
  48473. goog.asserts.assert(size !== undefined, 'size should be defined');
  48474. var extent = this.getGeometry().getExtent();
  48475. var resolution = view.constrainResolution(
  48476. view.getResolutionForExtent(extent, size));
  48477. var currentResolution = view.getResolution();
  48478. goog.asserts.assert(currentResolution !== undefined, 'res should be defined');
  48479. var currentCenter = view.getCenter();
  48480. goog.asserts.assert(currentCenter !== undefined, 'center should be defined');
  48481. map.beforeRender(ol.animation.zoom({
  48482. resolution: currentResolution,
  48483. duration: this.duration_,
  48484. easing: ol.easing.easeOut
  48485. }));
  48486. map.beforeRender(ol.animation.pan({
  48487. source: currentCenter,
  48488. duration: this.duration_,
  48489. easing: ol.easing.easeOut
  48490. }));
  48491. view.setCenter(ol.extent.getCenter(extent));
  48492. view.setResolution(resolution);
  48493. };
  48494. goog.provide('ol.interaction.KeyboardPan');
  48495. goog.require('goog.asserts');
  48496. goog.require('goog.events.KeyCodes');
  48497. goog.require('goog.events.KeyHandler.EventType');
  48498. goog.require('goog.functions');
  48499. goog.require('ol');
  48500. goog.require('ol.coordinate');
  48501. goog.require('ol.events.ConditionType');
  48502. goog.require('ol.events.condition');
  48503. goog.require('ol.interaction.Interaction');
  48504. /**
  48505. * @classdesc
  48506. * Allows the user to pan the map using keyboard arrows.
  48507. * Note that, although this interaction is by default included in maps,
  48508. * the keys can only be used when browser focus is on the element to which
  48509. * the keyboard events are attached. By default, this is the map div,
  48510. * though you can change this with the `keyboardEventTarget` in
  48511. * {@link ol.Map}. `document` never loses focus but, for any other element,
  48512. * focus will have to be on, and returned to, this element if the keys are to
  48513. * function.
  48514. * See also {@link ol.interaction.KeyboardZoom}.
  48515. *
  48516. * @constructor
  48517. * @extends {ol.interaction.Interaction}
  48518. * @param {olx.interaction.KeyboardPanOptions=} opt_options Options.
  48519. * @api stable
  48520. */
  48521. ol.interaction.KeyboardPan = function(opt_options) {
  48522. goog.base(this, {
  48523. handleEvent: ol.interaction.KeyboardPan.handleEvent
  48524. });
  48525. var options = opt_options || {};
  48526. /**
  48527. * @private
  48528. * @type {ol.events.ConditionType}
  48529. */
  48530. this.condition_ = options.condition !== undefined ?
  48531. options.condition :
  48532. goog.functions.and(ol.events.condition.noModifierKeys,
  48533. ol.events.condition.targetNotEditable);
  48534. /**
  48535. * @private
  48536. * @type {number}
  48537. */
  48538. this.duration_ = options.duration !== undefined ? options.duration : 100;
  48539. /**
  48540. * @private
  48541. * @type {number}
  48542. */
  48543. this.pixelDelta_ = options.pixelDelta !== undefined ?
  48544. options.pixelDelta : 128;
  48545. };
  48546. goog.inherits(ol.interaction.KeyboardPan, ol.interaction.Interaction);
  48547. /**
  48548. * Handles the {@link ol.MapBrowserEvent map browser event} if it was a
  48549. * `KeyEvent`, and decides the direction to pan to (if an arrow key was
  48550. * pressed).
  48551. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  48552. * @return {boolean} `false` to stop event propagation.
  48553. * @this {ol.interaction.KeyboardPan}
  48554. * @api
  48555. */
  48556. ol.interaction.KeyboardPan.handleEvent = function(mapBrowserEvent) {
  48557. var stopEvent = false;
  48558. if (mapBrowserEvent.type == goog.events.KeyHandler.EventType.KEY) {
  48559. var keyEvent = /** @type {goog.events.KeyEvent} */
  48560. (mapBrowserEvent.browserEvent);
  48561. var keyCode = keyEvent.keyCode;
  48562. if (this.condition_(mapBrowserEvent) &&
  48563. (keyCode == goog.events.KeyCodes.DOWN ||
  48564. keyCode == goog.events.KeyCodes.LEFT ||
  48565. keyCode == goog.events.KeyCodes.RIGHT ||
  48566. keyCode == goog.events.KeyCodes.UP)) {
  48567. var map = mapBrowserEvent.map;
  48568. var view = map.getView();
  48569. goog.asserts.assert(view, 'map must have view');
  48570. var mapUnitsDelta = view.getResolution() * this.pixelDelta_;
  48571. var deltaX = 0, deltaY = 0;
  48572. if (keyCode == goog.events.KeyCodes.DOWN) {
  48573. deltaY = -mapUnitsDelta;
  48574. } else if (keyCode == goog.events.KeyCodes.LEFT) {
  48575. deltaX = -mapUnitsDelta;
  48576. } else if (keyCode == goog.events.KeyCodes.RIGHT) {
  48577. deltaX = mapUnitsDelta;
  48578. } else {
  48579. deltaY = mapUnitsDelta;
  48580. }
  48581. var delta = [deltaX, deltaY];
  48582. ol.coordinate.rotate(delta, view.getRotation());
  48583. ol.interaction.Interaction.pan(map, view, delta, this.duration_);
  48584. mapBrowserEvent.preventDefault();
  48585. stopEvent = true;
  48586. }
  48587. }
  48588. return !stopEvent;
  48589. };
  48590. goog.provide('ol.interaction.KeyboardZoom');
  48591. goog.require('goog.asserts');
  48592. goog.require('goog.events.KeyHandler.EventType');
  48593. goog.require('ol.events.ConditionType');
  48594. goog.require('ol.events.condition');
  48595. goog.require('ol.interaction.Interaction');
  48596. /**
  48597. * @classdesc
  48598. * Allows the user to zoom the map using keyboard + and -.
  48599. * Note that, although this interaction is by default included in maps,
  48600. * the keys can only be used when browser focus is on the element to which
  48601. * the keyboard events are attached. By default, this is the map div,
  48602. * though you can change this with the `keyboardEventTarget` in
  48603. * {@link ol.Map}. `document` never loses focus but, for any other element,
  48604. * focus will have to be on, and returned to, this element if the keys are to
  48605. * function.
  48606. * See also {@link ol.interaction.KeyboardPan}.
  48607. *
  48608. * @constructor
  48609. * @param {olx.interaction.KeyboardZoomOptions=} opt_options Options.
  48610. * @extends {ol.interaction.Interaction}
  48611. * @api stable
  48612. */
  48613. ol.interaction.KeyboardZoom = function(opt_options) {
  48614. goog.base(this, {
  48615. handleEvent: ol.interaction.KeyboardZoom.handleEvent
  48616. });
  48617. var options = opt_options ? opt_options : {};
  48618. /**
  48619. * @private
  48620. * @type {ol.events.ConditionType}
  48621. */
  48622. this.condition_ = options.condition ? options.condition :
  48623. ol.events.condition.targetNotEditable;
  48624. /**
  48625. * @private
  48626. * @type {number}
  48627. */
  48628. this.delta_ = options.delta ? options.delta : 1;
  48629. /**
  48630. * @private
  48631. * @type {number}
  48632. */
  48633. this.duration_ = options.duration ? options.duration : 100;
  48634. };
  48635. goog.inherits(ol.interaction.KeyboardZoom, ol.interaction.Interaction);
  48636. /**
  48637. * Handles the {@link ol.MapBrowserEvent map browser event} if it was a
  48638. * `KeyEvent`, and decides whether to zoom in or out (depending on whether the
  48639. * key pressed was '+' or '-').
  48640. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  48641. * @return {boolean} `false` to stop event propagation.
  48642. * @this {ol.interaction.KeyboardZoom}
  48643. * @api
  48644. */
  48645. ol.interaction.KeyboardZoom.handleEvent = function(mapBrowserEvent) {
  48646. var stopEvent = false;
  48647. if (mapBrowserEvent.type == goog.events.KeyHandler.EventType.KEY) {
  48648. var keyEvent = /** @type {goog.events.KeyEvent} */
  48649. (mapBrowserEvent.browserEvent);
  48650. var charCode = keyEvent.charCode;
  48651. if (this.condition_(mapBrowserEvent) &&
  48652. (charCode == '+'.charCodeAt(0) || charCode == '-'.charCodeAt(0))) {
  48653. var map = mapBrowserEvent.map;
  48654. var delta = (charCode == '+'.charCodeAt(0)) ? this.delta_ : -this.delta_;
  48655. map.render();
  48656. var view = map.getView();
  48657. goog.asserts.assert(view, 'map must have view');
  48658. ol.interaction.Interaction.zoomByDelta(
  48659. map, view, delta, undefined, this.duration_);
  48660. mapBrowserEvent.preventDefault();
  48661. stopEvent = true;
  48662. }
  48663. }
  48664. return !stopEvent;
  48665. };
  48666. goog.provide('ol.interaction.MouseWheelZoom');
  48667. goog.require('goog.asserts');
  48668. goog.require('goog.events.MouseWheelEvent');
  48669. goog.require('goog.events.MouseWheelHandler.EventType');
  48670. goog.require('ol');
  48671. goog.require('ol.Coordinate');
  48672. goog.require('ol.interaction.Interaction');
  48673. goog.require('ol.math');
  48674. /**
  48675. * @classdesc
  48676. * Allows the user to zoom the map by scrolling the mouse wheel.
  48677. *
  48678. * @constructor
  48679. * @extends {ol.interaction.Interaction}
  48680. * @param {olx.interaction.MouseWheelZoomOptions=} opt_options Options.
  48681. * @api stable
  48682. */
  48683. ol.interaction.MouseWheelZoom = function(opt_options) {
  48684. goog.base(this, {
  48685. handleEvent: ol.interaction.MouseWheelZoom.handleEvent
  48686. });
  48687. var options = opt_options || {};
  48688. /**
  48689. * @private
  48690. * @type {number}
  48691. */
  48692. this.delta_ = 0;
  48693. /**
  48694. * @private
  48695. * @type {number}
  48696. */
  48697. this.duration_ = options.duration !== undefined ? options.duration : 250;
  48698. /**
  48699. * @private
  48700. * @type {boolean}
  48701. */
  48702. this.useAnchor_ = options.useAnchor !== undefined ? options.useAnchor : true;
  48703. /**
  48704. * @private
  48705. * @type {?ol.Coordinate}
  48706. */
  48707. this.lastAnchor_ = null;
  48708. /**
  48709. * @private
  48710. * @type {number|undefined}
  48711. */
  48712. this.startTime_ = undefined;
  48713. /**
  48714. * @private
  48715. * @type {number|undefined}
  48716. */
  48717. this.timeoutId_ = undefined;
  48718. };
  48719. goog.inherits(ol.interaction.MouseWheelZoom, ol.interaction.Interaction);
  48720. /**
  48721. * Handles the {@link ol.MapBrowserEvent map browser event} (if it was a
  48722. * mousewheel-event) and eventually zooms the map.
  48723. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  48724. * @return {boolean} `false` to stop event propagation.
  48725. * @this {ol.interaction.MouseWheelZoom}
  48726. * @api
  48727. */
  48728. ol.interaction.MouseWheelZoom.handleEvent = function(mapBrowserEvent) {
  48729. var stopEvent = false;
  48730. if (mapBrowserEvent.type ==
  48731. goog.events.MouseWheelHandler.EventType.MOUSEWHEEL) {
  48732. var map = mapBrowserEvent.map;
  48733. var mouseWheelEvent = mapBrowserEvent.browserEvent;
  48734. goog.asserts.assertInstanceof(mouseWheelEvent, goog.events.MouseWheelEvent,
  48735. 'mouseWheelEvent should be of type MouseWheelEvent');
  48736. if (this.useAnchor_) {
  48737. this.lastAnchor_ = mapBrowserEvent.coordinate;
  48738. }
  48739. this.delta_ += mouseWheelEvent.deltaY;
  48740. if (this.startTime_ === undefined) {
  48741. this.startTime_ = Date.now();
  48742. }
  48743. var duration = ol.MOUSEWHEELZOOM_TIMEOUT_DURATION;
  48744. var timeLeft = Math.max(duration - (Date.now() - this.startTime_), 0);
  48745. goog.global.clearTimeout(this.timeoutId_);
  48746. this.timeoutId_ = goog.global.setTimeout(
  48747. goog.bind(this.doZoom_, this, map), timeLeft);
  48748. mapBrowserEvent.preventDefault();
  48749. stopEvent = true;
  48750. }
  48751. return !stopEvent;
  48752. };
  48753. /**
  48754. * @private
  48755. * @param {ol.Map} map Map.
  48756. */
  48757. ol.interaction.MouseWheelZoom.prototype.doZoom_ = function(map) {
  48758. var maxDelta = ol.MOUSEWHEELZOOM_MAXDELTA;
  48759. var delta = ol.math.clamp(this.delta_, -maxDelta, maxDelta);
  48760. var view = map.getView();
  48761. goog.asserts.assert(view, 'map must have view');
  48762. map.render();
  48763. ol.interaction.Interaction.zoomByDelta(map, view, -delta, this.lastAnchor_,
  48764. this.duration_);
  48765. this.delta_ = 0;
  48766. this.lastAnchor_ = null;
  48767. this.startTime_ = undefined;
  48768. this.timeoutId_ = undefined;
  48769. };
  48770. /**
  48771. * Enable or disable using the mouse's location as an anchor when zooming
  48772. * @param {boolean} useAnchor true to zoom to the mouse's location, false
  48773. * to zoom to the center of the map
  48774. * @api
  48775. */
  48776. ol.interaction.MouseWheelZoom.prototype.setMouseAnchor = function(useAnchor) {
  48777. this.useAnchor_ = useAnchor;
  48778. if (!useAnchor) {
  48779. this.lastAnchor_ = null;
  48780. }
  48781. };
  48782. goog.provide('ol.interaction.PinchRotate');
  48783. goog.require('goog.asserts');
  48784. goog.require('goog.functions');
  48785. goog.require('goog.style');
  48786. goog.require('ol');
  48787. goog.require('ol.Coordinate');
  48788. goog.require('ol.ViewHint');
  48789. goog.require('ol.interaction.Interaction');
  48790. goog.require('ol.interaction.Pointer');
  48791. /**
  48792. * @classdesc
  48793. * Allows the user to rotate the map by twisting with two fingers
  48794. * on a touch screen.
  48795. *
  48796. * @constructor
  48797. * @extends {ol.interaction.Pointer}
  48798. * @param {olx.interaction.PinchRotateOptions=} opt_options Options.
  48799. * @api stable
  48800. */
  48801. ol.interaction.PinchRotate = function(opt_options) {
  48802. goog.base(this, {
  48803. handleDownEvent: ol.interaction.PinchRotate.handleDownEvent_,
  48804. handleDragEvent: ol.interaction.PinchRotate.handleDragEvent_,
  48805. handleUpEvent: ol.interaction.PinchRotate.handleUpEvent_
  48806. });
  48807. var options = opt_options || {};
  48808. /**
  48809. * @private
  48810. * @type {ol.Coordinate}
  48811. */
  48812. this.anchor_ = null;
  48813. /**
  48814. * @private
  48815. * @type {number|undefined}
  48816. */
  48817. this.lastAngle_ = undefined;
  48818. /**
  48819. * @private
  48820. * @type {boolean}
  48821. */
  48822. this.rotating_ = false;
  48823. /**
  48824. * @private
  48825. * @type {number}
  48826. */
  48827. this.rotationDelta_ = 0.0;
  48828. /**
  48829. * @private
  48830. * @type {number}
  48831. */
  48832. this.threshold_ = options.threshold !== undefined ? options.threshold : 0.3;
  48833. /**
  48834. * @private
  48835. * @type {number}
  48836. */
  48837. this.duration_ = options.duration !== undefined ? options.duration : 250;
  48838. };
  48839. goog.inherits(ol.interaction.PinchRotate, ol.interaction.Pointer);
  48840. /**
  48841. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  48842. * @this {ol.interaction.PinchRotate}
  48843. * @private
  48844. */
  48845. ol.interaction.PinchRotate.handleDragEvent_ = function(mapBrowserEvent) {
  48846. goog.asserts.assert(this.targetPointers.length >= 2,
  48847. 'length of this.targetPointers should be greater than or equal to 2');
  48848. var rotationDelta = 0.0;
  48849. var touch0 = this.targetPointers[0];
  48850. var touch1 = this.targetPointers[1];
  48851. // angle between touches
  48852. var angle = Math.atan2(
  48853. touch1.clientY - touch0.clientY,
  48854. touch1.clientX - touch0.clientX);
  48855. if (this.lastAngle_ !== undefined) {
  48856. var delta = angle - this.lastAngle_;
  48857. this.rotationDelta_ += delta;
  48858. if (!this.rotating_ &&
  48859. Math.abs(this.rotationDelta_) > this.threshold_) {
  48860. this.rotating_ = true;
  48861. }
  48862. rotationDelta = delta;
  48863. }
  48864. this.lastAngle_ = angle;
  48865. var map = mapBrowserEvent.map;
  48866. // rotate anchor point.
  48867. // FIXME: should be the intersection point between the lines:
  48868. // touch0,touch1 and previousTouch0,previousTouch1
  48869. var viewportPosition = goog.style.getClientPosition(map.getViewport());
  48870. var centroid =
  48871. ol.interaction.Pointer.centroid(this.targetPointers);
  48872. centroid[0] -= viewportPosition.x;
  48873. centroid[1] -= viewportPosition.y;
  48874. this.anchor_ = map.getCoordinateFromPixel(centroid);
  48875. // rotate
  48876. if (this.rotating_) {
  48877. var view = map.getView();
  48878. var rotation = view.getRotation();
  48879. map.render();
  48880. ol.interaction.Interaction.rotateWithoutConstraints(map, view,
  48881. rotation + rotationDelta, this.anchor_);
  48882. }
  48883. };
  48884. /**
  48885. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  48886. * @return {boolean} Stop drag sequence?
  48887. * @this {ol.interaction.PinchRotate}
  48888. * @private
  48889. */
  48890. ol.interaction.PinchRotate.handleUpEvent_ = function(mapBrowserEvent) {
  48891. if (this.targetPointers.length < 2) {
  48892. var map = mapBrowserEvent.map;
  48893. var view = map.getView();
  48894. view.setHint(ol.ViewHint.INTERACTING, -1);
  48895. if (this.rotating_) {
  48896. var rotation = view.getRotation();
  48897. ol.interaction.Interaction.rotate(
  48898. map, view, rotation, this.anchor_, this.duration_);
  48899. }
  48900. return false;
  48901. } else {
  48902. return true;
  48903. }
  48904. };
  48905. /**
  48906. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  48907. * @return {boolean} Start drag sequence?
  48908. * @this {ol.interaction.PinchRotate}
  48909. * @private
  48910. */
  48911. ol.interaction.PinchRotate.handleDownEvent_ = function(mapBrowserEvent) {
  48912. if (this.targetPointers.length >= 2) {
  48913. var map = mapBrowserEvent.map;
  48914. this.anchor_ = null;
  48915. this.lastAngle_ = undefined;
  48916. this.rotating_ = false;
  48917. this.rotationDelta_ = 0.0;
  48918. if (!this.handlingDownUpSequence) {
  48919. map.getView().setHint(ol.ViewHint.INTERACTING, 1);
  48920. }
  48921. map.render();
  48922. return true;
  48923. } else {
  48924. return false;
  48925. }
  48926. };
  48927. /**
  48928. * @inheritDoc
  48929. */
  48930. ol.interaction.PinchRotate.prototype.shouldStopEvent = goog.functions.FALSE;
  48931. goog.provide('ol.interaction.PinchZoom');
  48932. goog.require('goog.asserts');
  48933. goog.require('goog.functions');
  48934. goog.require('goog.style');
  48935. goog.require('ol');
  48936. goog.require('ol.Coordinate');
  48937. goog.require('ol.ViewHint');
  48938. goog.require('ol.interaction.Interaction');
  48939. goog.require('ol.interaction.Pointer');
  48940. /**
  48941. * @classdesc
  48942. * Allows the user to zoom the map by pinching with two fingers
  48943. * on a touch screen.
  48944. *
  48945. * @constructor
  48946. * @extends {ol.interaction.Pointer}
  48947. * @param {olx.interaction.PinchZoomOptions=} opt_options Options.
  48948. * @api stable
  48949. */
  48950. ol.interaction.PinchZoom = function(opt_options) {
  48951. goog.base(this, {
  48952. handleDownEvent: ol.interaction.PinchZoom.handleDownEvent_,
  48953. handleDragEvent: ol.interaction.PinchZoom.handleDragEvent_,
  48954. handleUpEvent: ol.interaction.PinchZoom.handleUpEvent_
  48955. });
  48956. var options = opt_options ? opt_options : {};
  48957. /**
  48958. * @private
  48959. * @type {ol.Coordinate}
  48960. */
  48961. this.anchor_ = null;
  48962. /**
  48963. * @private
  48964. * @type {number}
  48965. */
  48966. this.duration_ = options.duration !== undefined ? options.duration : 400;
  48967. /**
  48968. * @private
  48969. * @type {number|undefined}
  48970. */
  48971. this.lastDistance_ = undefined;
  48972. /**
  48973. * @private
  48974. * @type {number}
  48975. */
  48976. this.lastScaleDelta_ = 1;
  48977. };
  48978. goog.inherits(ol.interaction.PinchZoom, ol.interaction.Pointer);
  48979. /**
  48980. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  48981. * @this {ol.interaction.PinchZoom}
  48982. * @private
  48983. */
  48984. ol.interaction.PinchZoom.handleDragEvent_ = function(mapBrowserEvent) {
  48985. goog.asserts.assert(this.targetPointers.length >= 2,
  48986. 'length of this.targetPointers should be 2 or more');
  48987. var scaleDelta = 1.0;
  48988. var touch0 = this.targetPointers[0];
  48989. var touch1 = this.targetPointers[1];
  48990. var dx = touch0.clientX - touch1.clientX;
  48991. var dy = touch0.clientY - touch1.clientY;
  48992. // distance between touches
  48993. var distance = Math.sqrt(dx * dx + dy * dy);
  48994. if (this.lastDistance_ !== undefined) {
  48995. scaleDelta = this.lastDistance_ / distance;
  48996. }
  48997. this.lastDistance_ = distance;
  48998. if (scaleDelta != 1.0) {
  48999. this.lastScaleDelta_ = scaleDelta;
  49000. }
  49001. var map = mapBrowserEvent.map;
  49002. var view = map.getView();
  49003. var resolution = view.getResolution();
  49004. // scale anchor point.
  49005. var viewportPosition = goog.style.getClientPosition(map.getViewport());
  49006. var centroid =
  49007. ol.interaction.Pointer.centroid(this.targetPointers);
  49008. centroid[0] -= viewportPosition.x;
  49009. centroid[1] -= viewportPosition.y;
  49010. this.anchor_ = map.getCoordinateFromPixel(centroid);
  49011. // scale, bypass the resolution constraint
  49012. map.render();
  49013. ol.interaction.Interaction.zoomWithoutConstraints(
  49014. map, view, resolution * scaleDelta, this.anchor_);
  49015. };
  49016. /**
  49017. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  49018. * @return {boolean} Stop drag sequence?
  49019. * @this {ol.interaction.PinchZoom}
  49020. * @private
  49021. */
  49022. ol.interaction.PinchZoom.handleUpEvent_ = function(mapBrowserEvent) {
  49023. if (this.targetPointers.length < 2) {
  49024. var map = mapBrowserEvent.map;
  49025. var view = map.getView();
  49026. view.setHint(ol.ViewHint.INTERACTING, -1);
  49027. var resolution = view.getResolution();
  49028. // Zoom to final resolution, with an animation, and provide a
  49029. // direction not to zoom out/in if user was pinching in/out.
  49030. // Direction is > 0 if pinching out, and < 0 if pinching in.
  49031. var direction = this.lastScaleDelta_ - 1;
  49032. ol.interaction.Interaction.zoom(map, view, resolution,
  49033. this.anchor_, this.duration_, direction);
  49034. return false;
  49035. } else {
  49036. return true;
  49037. }
  49038. };
  49039. /**
  49040. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  49041. * @return {boolean} Start drag sequence?
  49042. * @this {ol.interaction.PinchZoom}
  49043. * @private
  49044. */
  49045. ol.interaction.PinchZoom.handleDownEvent_ = function(mapBrowserEvent) {
  49046. if (this.targetPointers.length >= 2) {
  49047. var map = mapBrowserEvent.map;
  49048. this.anchor_ = null;
  49049. this.lastDistance_ = undefined;
  49050. this.lastScaleDelta_ = 1;
  49051. if (!this.handlingDownUpSequence) {
  49052. map.getView().setHint(ol.ViewHint.INTERACTING, 1);
  49053. }
  49054. map.render();
  49055. return true;
  49056. } else {
  49057. return false;
  49058. }
  49059. };
  49060. /**
  49061. * @inheritDoc
  49062. */
  49063. ol.interaction.PinchZoom.prototype.shouldStopEvent = goog.functions.FALSE;
  49064. goog.provide('ol.interaction');
  49065. goog.require('ol');
  49066. goog.require('ol.Collection');
  49067. goog.require('ol.Kinetic');
  49068. goog.require('ol.interaction.DoubleClickZoom');
  49069. goog.require('ol.interaction.DragPan');
  49070. goog.require('ol.interaction.DragRotate');
  49071. goog.require('ol.interaction.DragZoom');
  49072. goog.require('ol.interaction.KeyboardPan');
  49073. goog.require('ol.interaction.KeyboardZoom');
  49074. goog.require('ol.interaction.MouseWheelZoom');
  49075. goog.require('ol.interaction.PinchRotate');
  49076. goog.require('ol.interaction.PinchZoom');
  49077. /**
  49078. * Set of interactions included in maps by default. Specific interactions can be
  49079. * excluded by setting the appropriate option to false in the constructor
  49080. * options, but the order of the interactions is fixed. If you want to specify
  49081. * a different order for interactions, you will need to create your own
  49082. * {@link ol.interaction.Interaction} instances and insert them into a
  49083. * {@link ol.Collection} in the order you want before creating your
  49084. * {@link ol.Map} instance. The default set of interactions, in sequence, is:
  49085. * * {@link ol.interaction.DragRotate}
  49086. * * {@link ol.interaction.DoubleClickZoom}
  49087. * * {@link ol.interaction.DragPan}
  49088. * * {@link ol.interaction.PinchRotate}
  49089. * * {@link ol.interaction.PinchZoom}
  49090. * * {@link ol.interaction.KeyboardPan}
  49091. * * {@link ol.interaction.KeyboardZoom}
  49092. * * {@link ol.interaction.MouseWheelZoom}
  49093. * * {@link ol.interaction.DragZoom}
  49094. *
  49095. * Note that DragZoom renders a box as a vector polygon, so this interaction
  49096. * should be excluded if you want a build with no vector support.
  49097. *
  49098. * @param {olx.interaction.DefaultsOptions=} opt_options Defaults options.
  49099. * @return {ol.Collection.<ol.interaction.Interaction>} A collection of
  49100. * interactions to be used with the ol.Map constructor's interactions option.
  49101. * @api stable
  49102. */
  49103. ol.interaction.defaults = function(opt_options) {
  49104. var options = opt_options ? opt_options : {};
  49105. var interactions = new ol.Collection();
  49106. var kinetic = new ol.Kinetic(-0.005, 0.05, 100);
  49107. var altShiftDragRotate = options.altShiftDragRotate !== undefined ?
  49108. options.altShiftDragRotate : true;
  49109. if (altShiftDragRotate) {
  49110. interactions.push(new ol.interaction.DragRotate());
  49111. }
  49112. var doubleClickZoom = options.doubleClickZoom !== undefined ?
  49113. options.doubleClickZoom : true;
  49114. if (doubleClickZoom) {
  49115. interactions.push(new ol.interaction.DoubleClickZoom({
  49116. delta: options.zoomDelta,
  49117. duration: options.zoomDuration
  49118. }));
  49119. }
  49120. var dragPan = options.dragPan !== undefined ? options.dragPan : true;
  49121. if (dragPan) {
  49122. interactions.push(new ol.interaction.DragPan({
  49123. kinetic: kinetic
  49124. }));
  49125. }
  49126. var pinchRotate = options.pinchRotate !== undefined ? options.pinchRotate :
  49127. true;
  49128. if (pinchRotate) {
  49129. interactions.push(new ol.interaction.PinchRotate());
  49130. }
  49131. var pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true;
  49132. if (pinchZoom) {
  49133. interactions.push(new ol.interaction.PinchZoom({
  49134. duration: options.zoomDuration
  49135. }));
  49136. }
  49137. var keyboard = options.keyboard !== undefined ? options.keyboard : true;
  49138. if (keyboard) {
  49139. interactions.push(new ol.interaction.KeyboardPan());
  49140. interactions.push(new ol.interaction.KeyboardZoom({
  49141. delta: options.zoomDelta,
  49142. duration: options.zoomDuration
  49143. }));
  49144. }
  49145. var mouseWheelZoom = options.mouseWheelZoom !== undefined ?
  49146. options.mouseWheelZoom : true;
  49147. if (mouseWheelZoom) {
  49148. interactions.push(new ol.interaction.MouseWheelZoom({
  49149. duration: options.zoomDuration
  49150. }));
  49151. }
  49152. var shiftDragZoom = options.shiftDragZoom !== undefined ?
  49153. options.shiftDragZoom : true;
  49154. if (shiftDragZoom) {
  49155. interactions.push(new ol.interaction.DragZoom());
  49156. }
  49157. return interactions;
  49158. };
  49159. goog.provide('ol.layer.Group');
  49160. goog.require('goog.asserts');
  49161. goog.require('goog.events');
  49162. goog.require('goog.events.EventType');
  49163. goog.require('goog.object');
  49164. goog.require('ol.Collection');
  49165. goog.require('ol.CollectionEvent');
  49166. goog.require('ol.CollectionEventType');
  49167. goog.require('ol.Object');
  49168. goog.require('ol.ObjectEventType');
  49169. goog.require('ol.extent');
  49170. goog.require('ol.layer.Base');
  49171. goog.require('ol.source.State');
  49172. /**
  49173. * @enum {string}
  49174. */
  49175. ol.layer.GroupProperty = {
  49176. LAYERS: 'layers'
  49177. };
  49178. /**
  49179. * @classdesc
  49180. * A {@link ol.Collection} of layers that are handled together.
  49181. *
  49182. * A generic `change` event is triggered when the group/Collection changes.
  49183. *
  49184. * @constructor
  49185. * @extends {ol.layer.Base}
  49186. * @param {olx.layer.GroupOptions=} opt_options Layer options.
  49187. * @api stable
  49188. */
  49189. ol.layer.Group = function(opt_options) {
  49190. var options = opt_options || {};
  49191. var baseOptions = /** @type {olx.layer.GroupOptions} */
  49192. (goog.object.clone(options));
  49193. delete baseOptions.layers;
  49194. var layers = options.layers;
  49195. goog.base(this, baseOptions);
  49196. /**
  49197. * @private
  49198. * @type {Array.<goog.events.Key>}
  49199. */
  49200. this.layersListenerKeys_ = [];
  49201. /**
  49202. * @private
  49203. * @type {Object.<string, Array.<goog.events.Key>>}
  49204. */
  49205. this.listenerKeys_ = {};
  49206. goog.events.listen(this,
  49207. ol.Object.getChangeEventType(ol.layer.GroupProperty.LAYERS),
  49208. this.handleLayersChanged_, false, this);
  49209. if (layers) {
  49210. if (goog.isArray(layers)) {
  49211. layers = new ol.Collection(layers.slice());
  49212. } else {
  49213. goog.asserts.assertInstanceof(layers, ol.Collection,
  49214. 'layers should be an ol.Collection');
  49215. layers = layers;
  49216. }
  49217. } else {
  49218. layers = new ol.Collection();
  49219. }
  49220. this.setLayers(layers);
  49221. };
  49222. goog.inherits(ol.layer.Group, ol.layer.Base);
  49223. /**
  49224. * @private
  49225. */
  49226. ol.layer.Group.prototype.handleLayerChange_ = function() {
  49227. if (this.getVisible()) {
  49228. this.changed();
  49229. }
  49230. };
  49231. /**
  49232. * @param {goog.events.Event} event Event.
  49233. * @private
  49234. */
  49235. ol.layer.Group.prototype.handleLayersChanged_ = function(event) {
  49236. this.layersListenerKeys_.forEach(goog.events.unlistenByKey);
  49237. this.layersListenerKeys_.length = 0;
  49238. var layers = this.getLayers();
  49239. this.layersListenerKeys_.push(
  49240. goog.events.listen(layers, ol.CollectionEventType.ADD,
  49241. this.handleLayersAdd_, false, this),
  49242. goog.events.listen(layers, ol.CollectionEventType.REMOVE,
  49243. this.handleLayersRemove_, false, this));
  49244. goog.object.forEach(this.listenerKeys_, function(keys) {
  49245. keys.forEach(goog.events.unlistenByKey);
  49246. });
  49247. goog.object.clear(this.listenerKeys_);
  49248. var layersArray = layers.getArray();
  49249. var i, ii, layer;
  49250. for (i = 0, ii = layersArray.length; i < ii; i++) {
  49251. layer = layersArray[i];
  49252. this.listenerKeys_[goog.getUid(layer).toString()] = [
  49253. goog.events.listen(layer, ol.ObjectEventType.PROPERTYCHANGE,
  49254. this.handleLayerChange_, false, this),
  49255. goog.events.listen(layer, goog.events.EventType.CHANGE,
  49256. this.handleLayerChange_, false, this)
  49257. ];
  49258. }
  49259. this.changed();
  49260. };
  49261. /**
  49262. * @param {ol.CollectionEvent} collectionEvent Collection event.
  49263. * @private
  49264. */
  49265. ol.layer.Group.prototype.handleLayersAdd_ = function(collectionEvent) {
  49266. var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
  49267. var key = goog.getUid(layer).toString();
  49268. goog.asserts.assert(!(key in this.listenerKeys_),
  49269. 'listeners already registered');
  49270. this.listenerKeys_[key] = [
  49271. goog.events.listen(layer, ol.ObjectEventType.PROPERTYCHANGE,
  49272. this.handleLayerChange_, false, this),
  49273. goog.events.listen(layer, goog.events.EventType.CHANGE,
  49274. this.handleLayerChange_, false, this)
  49275. ];
  49276. this.changed();
  49277. };
  49278. /**
  49279. * @param {ol.CollectionEvent} collectionEvent Collection event.
  49280. * @private
  49281. */
  49282. ol.layer.Group.prototype.handleLayersRemove_ = function(collectionEvent) {
  49283. var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
  49284. var key = goog.getUid(layer).toString();
  49285. goog.asserts.assert(key in this.listenerKeys_, 'no listeners to unregister');
  49286. this.listenerKeys_[key].forEach(goog.events.unlistenByKey);
  49287. delete this.listenerKeys_[key];
  49288. this.changed();
  49289. };
  49290. /**
  49291. * Returns the {@link ol.Collection collection} of {@link ol.layer.Layer layers}
  49292. * in this group.
  49293. * @return {!ol.Collection.<ol.layer.Base>} Collection of
  49294. * {@link ol.layer.Base layers} that are part of this group.
  49295. * @observable
  49296. * @api stable
  49297. */
  49298. ol.layer.Group.prototype.getLayers = function() {
  49299. return /** @type {!ol.Collection.<ol.layer.Base>} */ (this.get(
  49300. ol.layer.GroupProperty.LAYERS));
  49301. };
  49302. /**
  49303. * Set the {@link ol.Collection collection} of {@link ol.layer.Layer layers}
  49304. * in this group.
  49305. * @param {!ol.Collection.<ol.layer.Base>} layers Collection of
  49306. * {@link ol.layer.Base layers} that are part of this group.
  49307. * @observable
  49308. * @api stable
  49309. */
  49310. ol.layer.Group.prototype.setLayers = function(layers) {
  49311. this.set(ol.layer.GroupProperty.LAYERS, layers);
  49312. };
  49313. /**
  49314. * @inheritDoc
  49315. */
  49316. ol.layer.Group.prototype.getLayersArray = function(opt_array) {
  49317. var array = opt_array !== undefined ? opt_array : [];
  49318. this.getLayers().forEach(function(layer) {
  49319. layer.getLayersArray(array);
  49320. });
  49321. return array;
  49322. };
  49323. /**
  49324. * @inheritDoc
  49325. */
  49326. ol.layer.Group.prototype.getLayerStatesArray = function(opt_states) {
  49327. var states = opt_states !== undefined ? opt_states : [];
  49328. var pos = states.length;
  49329. this.getLayers().forEach(function(layer) {
  49330. layer.getLayerStatesArray(states);
  49331. });
  49332. var ownLayerState = this.getLayerState();
  49333. var i, ii, layerState;
  49334. for (i = pos, ii = states.length; i < ii; i++) {
  49335. layerState = states[i];
  49336. layerState.opacity *= ownLayerState.opacity;
  49337. layerState.visible = layerState.visible && ownLayerState.visible;
  49338. layerState.maxResolution = Math.min(
  49339. layerState.maxResolution, ownLayerState.maxResolution);
  49340. layerState.minResolution = Math.max(
  49341. layerState.minResolution, ownLayerState.minResolution);
  49342. if (ownLayerState.extent !== undefined) {
  49343. if (layerState.extent !== undefined) {
  49344. layerState.extent = ol.extent.getIntersection(
  49345. layerState.extent, ownLayerState.extent);
  49346. } else {
  49347. layerState.extent = ownLayerState.extent;
  49348. }
  49349. }
  49350. }
  49351. return states;
  49352. };
  49353. /**
  49354. * @inheritDoc
  49355. */
  49356. ol.layer.Group.prototype.getSourceState = function() {
  49357. return ol.source.State.READY;
  49358. };
  49359. goog.provide('ol.proj.EPSG3857');
  49360. goog.require('goog.asserts');
  49361. goog.require('ol.math');
  49362. goog.require('ol.proj');
  49363. goog.require('ol.proj.Projection');
  49364. goog.require('ol.proj.Units');
  49365. /**
  49366. * @classdesc
  49367. * Projection object for web/spherical Mercator (EPSG:3857).
  49368. *
  49369. * @constructor
  49370. * @extends {ol.proj.Projection}
  49371. * @param {string} code Code.
  49372. * @private
  49373. */
  49374. ol.proj.EPSG3857_ = function(code) {
  49375. goog.base(this, {
  49376. code: code,
  49377. units: ol.proj.Units.METERS,
  49378. extent: ol.proj.EPSG3857.EXTENT,
  49379. global: true,
  49380. worldExtent: ol.proj.EPSG3857.WORLD_EXTENT
  49381. });
  49382. };
  49383. goog.inherits(ol.proj.EPSG3857_, ol.proj.Projection);
  49384. /**
  49385. * @inheritDoc
  49386. */
  49387. ol.proj.EPSG3857_.prototype.getPointResolution = function(resolution, point) {
  49388. return resolution / ol.math.cosh(point[1] / ol.proj.EPSG3857.RADIUS);
  49389. };
  49390. /**
  49391. * @const
  49392. * @type {number}
  49393. */
  49394. ol.proj.EPSG3857.RADIUS = 6378137;
  49395. /**
  49396. * @const
  49397. * @type {number}
  49398. */
  49399. ol.proj.EPSG3857.HALF_SIZE = Math.PI * ol.proj.EPSG3857.RADIUS;
  49400. /**
  49401. * @const
  49402. * @type {ol.Extent}
  49403. */
  49404. ol.proj.EPSG3857.EXTENT = [
  49405. -ol.proj.EPSG3857.HALF_SIZE, -ol.proj.EPSG3857.HALF_SIZE,
  49406. ol.proj.EPSG3857.HALF_SIZE, ol.proj.EPSG3857.HALF_SIZE
  49407. ];
  49408. /**
  49409. * @const
  49410. * @type {ol.Extent}
  49411. */
  49412. ol.proj.EPSG3857.WORLD_EXTENT = [-180, -85, 180, 85];
  49413. /**
  49414. * Lists several projection codes with the same meaning as EPSG:3857.
  49415. *
  49416. * @type {Array.<string>}
  49417. */
  49418. ol.proj.EPSG3857.CODES = [
  49419. 'EPSG:3857',
  49420. 'EPSG:102100',
  49421. 'EPSG:102113',
  49422. 'EPSG:900913',
  49423. 'urn:ogc:def:crs:EPSG:6.18:3:3857',
  49424. 'urn:ogc:def:crs:EPSG::3857',
  49425. 'http://www.opengis.net/gml/srs/epsg.xml#3857'
  49426. ];
  49427. /**
  49428. * Projections equal to EPSG:3857.
  49429. *
  49430. * @const
  49431. * @type {Array.<ol.proj.Projection>}
  49432. */
  49433. ol.proj.EPSG3857.PROJECTIONS = ol.proj.EPSG3857.CODES.map(function(code) {
  49434. return new ol.proj.EPSG3857_(code);
  49435. });
  49436. /**
  49437. * Transformation from EPSG:4326 to EPSG:3857.
  49438. *
  49439. * @param {Array.<number>} input Input array of coordinate values.
  49440. * @param {Array.<number>=} opt_output Output array of coordinate values.
  49441. * @param {number=} opt_dimension Dimension (default is `2`).
  49442. * @return {Array.<number>} Output array of coordinate values.
  49443. */
  49444. ol.proj.EPSG3857.fromEPSG4326 = function(input, opt_output, opt_dimension) {
  49445. var length = input.length,
  49446. dimension = opt_dimension > 1 ? opt_dimension : 2,
  49447. output = opt_output;
  49448. if (output === undefined) {
  49449. if (dimension > 2) {
  49450. // preserve values beyond second dimension
  49451. output = input.slice();
  49452. } else {
  49453. output = new Array(length);
  49454. }
  49455. }
  49456. goog.asserts.assert(output.length % dimension === 0,
  49457. 'modulus of output.length with dimension should be 0');
  49458. for (var i = 0; i < length; i += dimension) {
  49459. output[i] = ol.proj.EPSG3857.RADIUS * Math.PI * input[i] / 180;
  49460. output[i + 1] = ol.proj.EPSG3857.RADIUS *
  49461. Math.log(Math.tan(Math.PI * (input[i + 1] + 90) / 360));
  49462. }
  49463. return output;
  49464. };
  49465. /**
  49466. * Transformation from EPSG:3857 to EPSG:4326.
  49467. *
  49468. * @param {Array.<number>} input Input array of coordinate values.
  49469. * @param {Array.<number>=} opt_output Output array of coordinate values.
  49470. * @param {number=} opt_dimension Dimension (default is `2`).
  49471. * @return {Array.<number>} Output array of coordinate values.
  49472. */
  49473. ol.proj.EPSG3857.toEPSG4326 = function(input, opt_output, opt_dimension) {
  49474. var length = input.length,
  49475. dimension = opt_dimension > 1 ? opt_dimension : 2,
  49476. output = opt_output;
  49477. if (output === undefined) {
  49478. if (dimension > 2) {
  49479. // preserve values beyond second dimension
  49480. output = input.slice();
  49481. } else {
  49482. output = new Array(length);
  49483. }
  49484. }
  49485. goog.asserts.assert(output.length % dimension === 0,
  49486. 'modulus of output.length with dimension should be 0');
  49487. for (var i = 0; i < length; i += dimension) {
  49488. output[i] = 180 * input[i] / (ol.proj.EPSG3857.RADIUS * Math.PI);
  49489. output[i + 1] = 360 * Math.atan(
  49490. Math.exp(input[i + 1] / ol.proj.EPSG3857.RADIUS)) / Math.PI - 90;
  49491. }
  49492. return output;
  49493. };
  49494. goog.provide('ol.proj.EPSG4326');
  49495. goog.require('ol.proj');
  49496. goog.require('ol.proj.Projection');
  49497. goog.require('ol.proj.Units');
  49498. /**
  49499. * @classdesc
  49500. * Projection object for WGS84 geographic coordinates (EPSG:4326).
  49501. *
  49502. * Note that OpenLayers does not strictly comply with the EPSG definition.
  49503. * The EPSG registry defines 4326 as a CRS for Latitude,Longitude (y,x).
  49504. * OpenLayers treats EPSG:4326 as a pseudo-projection, with x,y coordinates.
  49505. *
  49506. * @constructor
  49507. * @extends {ol.proj.Projection}
  49508. * @param {string} code Code.
  49509. * @param {string=} opt_axisOrientation Axis orientation.
  49510. * @private
  49511. */
  49512. ol.proj.EPSG4326_ = function(code, opt_axisOrientation) {
  49513. goog.base(this, {
  49514. code: code,
  49515. units: ol.proj.Units.DEGREES,
  49516. extent: ol.proj.EPSG4326.EXTENT,
  49517. axisOrientation: opt_axisOrientation,
  49518. global: true,
  49519. worldExtent: ol.proj.EPSG4326.EXTENT
  49520. });
  49521. };
  49522. goog.inherits(ol.proj.EPSG4326_, ol.proj.Projection);
  49523. /**
  49524. * @inheritDoc
  49525. */
  49526. ol.proj.EPSG4326_.prototype.getPointResolution = function(resolution, point) {
  49527. return resolution;
  49528. };
  49529. /**
  49530. * Extent of the EPSG:4326 projection which is the whole world.
  49531. *
  49532. * @const
  49533. * @type {ol.Extent}
  49534. */
  49535. ol.proj.EPSG4326.EXTENT = [-180, -90, 180, 90];
  49536. /**
  49537. * Projections equal to EPSG:4326.
  49538. *
  49539. * @const
  49540. * @type {Array.<ol.proj.Projection>}
  49541. */
  49542. ol.proj.EPSG4326.PROJECTIONS = [
  49543. new ol.proj.EPSG4326_('CRS:84'),
  49544. new ol.proj.EPSG4326_('EPSG:4326', 'neu'),
  49545. new ol.proj.EPSG4326_('urn:ogc:def:crs:EPSG::4326', 'neu'),
  49546. new ol.proj.EPSG4326_('urn:ogc:def:crs:EPSG:6.6:4326', 'neu'),
  49547. new ol.proj.EPSG4326_('urn:ogc:def:crs:OGC:1.3:CRS84'),
  49548. new ol.proj.EPSG4326_('urn:ogc:def:crs:OGC:2:84'),
  49549. new ol.proj.EPSG4326_('http://www.opengis.net/gml/srs/epsg.xml#4326', 'neu'),
  49550. new ol.proj.EPSG4326_('urn:x-ogc:def:crs:EPSG:4326', 'neu')
  49551. ];
  49552. goog.provide('ol.proj.common');
  49553. goog.require('ol.proj');
  49554. goog.require('ol.proj.EPSG3857');
  49555. goog.require('ol.proj.EPSG4326');
  49556. /**
  49557. * FIXME empty description for jsdoc
  49558. * @api
  49559. */
  49560. ol.proj.common.add = function() {
  49561. // Add transformations that don't alter coordinates to convert within set of
  49562. // projections with equal meaning.
  49563. ol.proj.addEquivalentProjections(ol.proj.EPSG3857.PROJECTIONS);
  49564. ol.proj.addEquivalentProjections(ol.proj.EPSG4326.PROJECTIONS);
  49565. // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like
  49566. // coordinates and back.
  49567. ol.proj.addEquivalentTransforms(
  49568. ol.proj.EPSG4326.PROJECTIONS,
  49569. ol.proj.EPSG3857.PROJECTIONS,
  49570. ol.proj.EPSG3857.fromEPSG4326,
  49571. ol.proj.EPSG3857.toEPSG4326);
  49572. };
  49573. goog.provide('ol.layer.Image');
  49574. goog.require('ol.layer.Layer');
  49575. /**
  49576. * @classdesc
  49577. * Server-rendered images that are available for arbitrary extents and
  49578. * resolutions.
  49579. * Note that any property set in the options is set as a {@link ol.Object}
  49580. * property on the layer object; for example, setting `title: 'My Title'` in the
  49581. * options means that `title` is observable, and has get/set accessors.
  49582. *
  49583. * @constructor
  49584. * @extends {ol.layer.Layer}
  49585. * @fires ol.render.Event
  49586. * @param {olx.layer.ImageOptions=} opt_options Layer options.
  49587. * @api stable
  49588. */
  49589. ol.layer.Image = function(opt_options) {
  49590. var options = opt_options ? opt_options : {};
  49591. goog.base(this, /** @type {olx.layer.LayerOptions} */ (options));
  49592. };
  49593. goog.inherits(ol.layer.Image, ol.layer.Layer);
  49594. /**
  49595. * Return the associated {@link ol.source.Image source} of the image layer.
  49596. * @function
  49597. * @return {ol.source.Image} Source.
  49598. * @api stable
  49599. */
  49600. ol.layer.Image.prototype.getSource;
  49601. goog.provide('ol.layer.Tile');
  49602. goog.require('goog.object');
  49603. goog.require('ol');
  49604. goog.require('ol.layer.Layer');
  49605. /**
  49606. * @enum {string}
  49607. */
  49608. ol.layer.TileProperty = {
  49609. PRELOAD: 'preload',
  49610. USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError'
  49611. };
  49612. /**
  49613. * @classdesc
  49614. * For layer sources that provide pre-rendered, tiled images in grids that are
  49615. * organized by zoom levels for specific resolutions.
  49616. * Note that any property set in the options is set as a {@link ol.Object}
  49617. * property on the layer object; for example, setting `title: 'My Title'` in the
  49618. * options means that `title` is observable, and has get/set accessors.
  49619. *
  49620. * @constructor
  49621. * @extends {ol.layer.Layer}
  49622. * @fires ol.render.Event
  49623. * @param {olx.layer.TileOptions=} opt_options Tile layer options.
  49624. * @api stable
  49625. */
  49626. ol.layer.Tile = function(opt_options) {
  49627. var options = opt_options ? opt_options : {};
  49628. var baseOptions = goog.object.clone(options);
  49629. delete baseOptions.preload;
  49630. delete baseOptions.useInterimTilesOnError;
  49631. goog.base(this, /** @type {olx.layer.LayerOptions} */ (baseOptions));
  49632. this.setPreload(options.preload !== undefined ? options.preload : 0);
  49633. this.setUseInterimTilesOnError(options.useInterimTilesOnError !== undefined ?
  49634. options.useInterimTilesOnError : true);
  49635. };
  49636. goog.inherits(ol.layer.Tile, ol.layer.Layer);
  49637. /**
  49638. * Return the level as number to which we will preload tiles up to.
  49639. * @return {number} The level to preload tiles up to.
  49640. * @observable
  49641. * @api
  49642. */
  49643. ol.layer.Tile.prototype.getPreload = function() {
  49644. return /** @type {number} */ (this.get(ol.layer.TileProperty.PRELOAD));
  49645. };
  49646. /**
  49647. * Return the associated {@link ol.source.Tile tilesource} of the layer.
  49648. * @function
  49649. * @return {ol.source.Tile} Source.
  49650. * @api stable
  49651. */
  49652. ol.layer.Tile.prototype.getSource;
  49653. /**
  49654. * Set the level as number to which we will preload tiles up to.
  49655. * @param {number} preload The level to preload tiles up to.
  49656. * @observable
  49657. * @api
  49658. */
  49659. ol.layer.Tile.prototype.setPreload = function(preload) {
  49660. this.set(ol.layer.TileProperty.PRELOAD, preload);
  49661. };
  49662. /**
  49663. * Whether we use interim tiles on error.
  49664. * @return {boolean} Use interim tiles on error.
  49665. * @observable
  49666. * @api
  49667. */
  49668. ol.layer.Tile.prototype.getUseInterimTilesOnError = function() {
  49669. return /** @type {boolean} */ (
  49670. this.get(ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR));
  49671. };
  49672. /**
  49673. * Set whether we use interim tiles on error.
  49674. * @param {boolean} useInterimTilesOnError Use interim tiles on error.
  49675. * @observable
  49676. * @api
  49677. */
  49678. ol.layer.Tile.prototype.setUseInterimTilesOnError =
  49679. function(useInterimTilesOnError) {
  49680. this.set(
  49681. ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);
  49682. };
  49683. goog.provide('ol.layer.Vector');
  49684. goog.require('goog.asserts');
  49685. goog.require('goog.object');
  49686. goog.require('ol');
  49687. goog.require('ol.layer.Layer');
  49688. goog.require('ol.style.Style');
  49689. /**
  49690. * @enum {string}
  49691. */
  49692. ol.layer.VectorProperty = {
  49693. RENDER_ORDER: 'renderOrder'
  49694. };
  49695. /**
  49696. * @classdesc
  49697. * Vector data that is rendered client-side.
  49698. * Note that any property set in the options is set as a {@link ol.Object}
  49699. * property on the layer object; for example, setting `title: 'My Title'` in the
  49700. * options means that `title` is observable, and has get/set accessors.
  49701. *
  49702. * @constructor
  49703. * @extends {ol.layer.Layer}
  49704. * @fires ol.render.Event
  49705. * @param {olx.layer.VectorOptions=} opt_options Options.
  49706. * @api stable
  49707. */
  49708. ol.layer.Vector = function(opt_options) {
  49709. var options = opt_options ?
  49710. opt_options : /** @type {olx.layer.VectorOptions} */ ({});
  49711. goog.asserts.assert(
  49712. options.renderOrder === undefined || !options.renderOrder ||
  49713. goog.isFunction(options.renderOrder),
  49714. 'renderOrder must be a comparator function');
  49715. var baseOptions = goog.object.clone(options);
  49716. delete baseOptions.style;
  49717. delete baseOptions.renderBuffer;
  49718. delete baseOptions.updateWhileAnimating;
  49719. delete baseOptions.updateWhileInteracting;
  49720. goog.base(this, /** @type {olx.layer.LayerOptions} */ (baseOptions));
  49721. /**
  49722. * @type {number}
  49723. * @private
  49724. */
  49725. this.renderBuffer_ = options.renderBuffer !== undefined ?
  49726. options.renderBuffer : 100;
  49727. /**
  49728. * User provided style.
  49729. * @type {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
  49730. * @private
  49731. */
  49732. this.style_ = null;
  49733. /**
  49734. * Style function for use within the library.
  49735. * @type {ol.style.StyleFunction|undefined}
  49736. * @private
  49737. */
  49738. this.styleFunction_ = undefined;
  49739. this.setStyle(options.style);
  49740. /**
  49741. * @type {boolean}
  49742. * @private
  49743. */
  49744. this.updateWhileAnimating_ = options.updateWhileAnimating !== undefined ?
  49745. options.updateWhileAnimating : false;
  49746. /**
  49747. * @type {boolean}
  49748. * @private
  49749. */
  49750. this.updateWhileInteracting_ = options.updateWhileInteracting !== undefined ?
  49751. options.updateWhileInteracting : false;
  49752. };
  49753. goog.inherits(ol.layer.Vector, ol.layer.Layer);
  49754. /**
  49755. * @return {number|undefined} Render buffer.
  49756. */
  49757. ol.layer.Vector.prototype.getRenderBuffer = function() {
  49758. return this.renderBuffer_;
  49759. };
  49760. /**
  49761. * @return {function(ol.Feature, ol.Feature): number|null|undefined} Render
  49762. * order.
  49763. */
  49764. ol.layer.Vector.prototype.getRenderOrder = function() {
  49765. return /** @type {function(ol.Feature, ol.Feature):number|null|undefined} */ (
  49766. this.get(ol.layer.VectorProperty.RENDER_ORDER));
  49767. };
  49768. /**
  49769. * Return the associated {@link ol.source.Vector vectorsource} of the layer.
  49770. * @function
  49771. * @return {ol.source.Vector} Source.
  49772. * @api stable
  49773. */
  49774. ol.layer.Vector.prototype.getSource;
  49775. /**
  49776. * Get the style for features. This returns whatever was passed to the `style`
  49777. * option at construction or to the `setStyle` method.
  49778. * @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
  49779. * Layer style.
  49780. * @api stable
  49781. */
  49782. ol.layer.Vector.prototype.getStyle = function() {
  49783. return this.style_;
  49784. };
  49785. /**
  49786. * Get the style function.
  49787. * @return {ol.style.StyleFunction|undefined} Layer style function.
  49788. * @api stable
  49789. */
  49790. ol.layer.Vector.prototype.getStyleFunction = function() {
  49791. return this.styleFunction_;
  49792. };
  49793. /**
  49794. * @return {boolean} Whether the rendered layer should be updated while
  49795. * animating.
  49796. */
  49797. ol.layer.Vector.prototype.getUpdateWhileAnimating = function() {
  49798. return this.updateWhileAnimating_;
  49799. };
  49800. /**
  49801. * @return {boolean} Whether the rendered layer should be updated while
  49802. * interacting.
  49803. */
  49804. ol.layer.Vector.prototype.getUpdateWhileInteracting = function() {
  49805. return this.updateWhileInteracting_;
  49806. };
  49807. /**
  49808. * @param {function(ol.Feature, ol.Feature):number|null|undefined} renderOrder
  49809. * Render order.
  49810. */
  49811. ol.layer.Vector.prototype.setRenderOrder = function(renderOrder) {
  49812. goog.asserts.assert(
  49813. renderOrder === undefined || !renderOrder ||
  49814. goog.isFunction(renderOrder),
  49815. 'renderOrder must be a comparator function');
  49816. this.set(ol.layer.VectorProperty.RENDER_ORDER, renderOrder);
  49817. };
  49818. /**
  49819. * Set the style for features. This can be a single style object, an array
  49820. * of styles, or a function that takes a feature and resolution and returns
  49821. * an array of styles. If it is `undefined` the default style is used. If
  49822. * it is `null` the layer has no style (a `null` style), so only features
  49823. * that have their own styles will be rendered in the layer. See
  49824. * {@link ol.style} for information on the default style.
  49825. * @param {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction|null|undefined}
  49826. * style Layer style.
  49827. * @api stable
  49828. */
  49829. ol.layer.Vector.prototype.setStyle = function(style) {
  49830. this.style_ = style !== undefined ? style : ol.style.defaultStyleFunction;
  49831. this.styleFunction_ = style === null ?
  49832. undefined : ol.style.createStyleFunction(this.style_);
  49833. this.changed();
  49834. };
  49835. // FIXME test, especially polygons with holes and multipolygons
  49836. // FIXME need to handle large thick features (where pixel size matters)
  49837. // FIXME add offset and end to ol.geom.flat.transform.transform2D?
  49838. goog.provide('ol.render.canvas.Immediate');
  49839. goog.require('goog.array');
  49840. goog.require('goog.asserts');
  49841. goog.require('goog.vec.Mat4');
  49842. goog.require('ol.color');
  49843. goog.require('ol.extent');
  49844. goog.require('ol.geom.flat.transform');
  49845. goog.require('ol.has');
  49846. goog.require('ol.render.VectorContext');
  49847. goog.require('ol.render.canvas');
  49848. goog.require('ol.vec.Mat4');
  49849. /**
  49850. * @classdesc
  49851. * A concrete subclass of {@link ol.render.VectorContext} that implements
  49852. * direct rendering of features and geometries to an HTML5 Canvas context.
  49853. * Instances of this class are created internally by the library and
  49854. * provided to application code as vectorContext member of the
  49855. * {@link ol.render.Event} object associated with postcompose, precompose and
  49856. * render events emitted by layers and maps.
  49857. *
  49858. * @constructor
  49859. * @extends {ol.render.VectorContext}
  49860. * @param {CanvasRenderingContext2D} context Context.
  49861. * @param {number} pixelRatio Pixel ratio.
  49862. * @param {ol.Extent} extent Extent.
  49863. * @param {goog.vec.Mat4.Number} transform Transform.
  49864. * @param {number} viewRotation View rotation.
  49865. * @struct
  49866. */
  49867. ol.render.canvas.Immediate =
  49868. function(context, pixelRatio, extent, transform, viewRotation) {
  49869. /**
  49870. * @private
  49871. * @type {!Object.<string,
  49872. * Array.<function(ol.render.canvas.Immediate)>>}
  49873. */
  49874. this.callbacksByZIndex_ = {};
  49875. /**
  49876. * @private
  49877. * @type {CanvasRenderingContext2D}
  49878. */
  49879. this.context_ = context;
  49880. /**
  49881. * @private
  49882. * @type {number}
  49883. */
  49884. this.pixelRatio_ = pixelRatio;
  49885. /**
  49886. * @private
  49887. * @type {ol.Extent}
  49888. */
  49889. this.extent_ = extent;
  49890. /**
  49891. * @private
  49892. * @type {goog.vec.Mat4.Number}
  49893. */
  49894. this.transform_ = transform;
  49895. /**
  49896. * @private
  49897. * @type {number}
  49898. */
  49899. this.viewRotation_ = viewRotation;
  49900. /**
  49901. * @private
  49902. * @type {?ol.render.canvas.FillState}
  49903. */
  49904. this.contextFillState_ = null;
  49905. /**
  49906. * @private
  49907. * @type {?ol.render.canvas.StrokeState}
  49908. */
  49909. this.contextStrokeState_ = null;
  49910. /**
  49911. * @private
  49912. * @type {?ol.render.canvas.TextState}
  49913. */
  49914. this.contextTextState_ = null;
  49915. /**
  49916. * @private
  49917. * @type {?ol.render.canvas.FillState}
  49918. */
  49919. this.fillState_ = null;
  49920. /**
  49921. * @private
  49922. * @type {?ol.render.canvas.StrokeState}
  49923. */
  49924. this.strokeState_ = null;
  49925. /**
  49926. * @private
  49927. * @type {HTMLCanvasElement|HTMLVideoElement|Image}
  49928. */
  49929. this.image_ = null;
  49930. /**
  49931. * @private
  49932. * @type {number}
  49933. */
  49934. this.imageAnchorX_ = 0;
  49935. /**
  49936. * @private
  49937. * @type {number}
  49938. */
  49939. this.imageAnchorY_ = 0;
  49940. /**
  49941. * @private
  49942. * @type {number}
  49943. */
  49944. this.imageHeight_ = 0;
  49945. /**
  49946. * @private
  49947. * @type {number}
  49948. */
  49949. this.imageOpacity_ = 0;
  49950. /**
  49951. * @private
  49952. * @type {number}
  49953. */
  49954. this.imageOriginX_ = 0;
  49955. /**
  49956. * @private
  49957. * @type {number}
  49958. */
  49959. this.imageOriginY_ = 0;
  49960. /**
  49961. * @private
  49962. * @type {boolean}
  49963. */
  49964. this.imageRotateWithView_ = false;
  49965. /**
  49966. * @private
  49967. * @type {number}
  49968. */
  49969. this.imageRotation_ = 0;
  49970. /**
  49971. * @private
  49972. * @type {number}
  49973. */
  49974. this.imageScale_ = 0;
  49975. /**
  49976. * @private
  49977. * @type {boolean}
  49978. */
  49979. this.imageSnapToPixel_ = false;
  49980. /**
  49981. * @private
  49982. * @type {number}
  49983. */
  49984. this.imageWidth_ = 0;
  49985. /**
  49986. * @private
  49987. * @type {string}
  49988. */
  49989. this.text_ = '';
  49990. /**
  49991. * @private
  49992. * @type {number}
  49993. */
  49994. this.textOffsetX_ = 0;
  49995. /**
  49996. * @private
  49997. * @type {number}
  49998. */
  49999. this.textOffsetY_ = 0;
  50000. /**
  50001. * @private
  50002. * @type {number}
  50003. */
  50004. this.textRotation_ = 0;
  50005. /**
  50006. * @private
  50007. * @type {number}
  50008. */
  50009. this.textScale_ = 0;
  50010. /**
  50011. * @private
  50012. * @type {?ol.render.canvas.FillState}
  50013. */
  50014. this.textFillState_ = null;
  50015. /**
  50016. * @private
  50017. * @type {?ol.render.canvas.StrokeState}
  50018. */
  50019. this.textStrokeState_ = null;
  50020. /**
  50021. * @private
  50022. * @type {?ol.render.canvas.TextState}
  50023. */
  50024. this.textState_ = null;
  50025. /**
  50026. * @private
  50027. * @type {Array.<number>}
  50028. */
  50029. this.pixelCoordinates_ = [];
  50030. /**
  50031. * @private
  50032. * @type {!goog.vec.Mat4.Number}
  50033. */
  50034. this.tmpLocalTransform_ = goog.vec.Mat4.createNumber();
  50035. };
  50036. /**
  50037. * @param {Array.<number>} flatCoordinates Flat coordinates.
  50038. * @param {number} offset Offset.
  50039. * @param {number} end End.
  50040. * @param {number} stride Stride.
  50041. * @private
  50042. */
  50043. ol.render.canvas.Immediate.prototype.drawImages_ =
  50044. function(flatCoordinates, offset, end, stride) {
  50045. if (!this.image_) {
  50046. return;
  50047. }
  50048. goog.asserts.assert(offset === 0, 'offset should be 0');
  50049. goog.asserts.assert(end == flatCoordinates.length,
  50050. 'end should be equal to the length of flatCoordinates');
  50051. var pixelCoordinates = ol.geom.flat.transform.transform2D(
  50052. flatCoordinates, offset, end, 2, this.transform_,
  50053. this.pixelCoordinates_);
  50054. var context = this.context_;
  50055. var localTransform = this.tmpLocalTransform_;
  50056. var alpha = context.globalAlpha;
  50057. if (this.imageOpacity_ != 1) {
  50058. context.globalAlpha = alpha * this.imageOpacity_;
  50059. }
  50060. var rotation = this.imageRotation_;
  50061. if (this.imageRotateWithView_) {
  50062. rotation += this.viewRotation_;
  50063. }
  50064. var i, ii;
  50065. for (i = 0, ii = pixelCoordinates.length; i < ii; i += 2) {
  50066. var x = pixelCoordinates[i] - this.imageAnchorX_;
  50067. var y = pixelCoordinates[i + 1] - this.imageAnchorY_;
  50068. if (this.imageSnapToPixel_) {
  50069. x = (x + 0.5) | 0;
  50070. y = (y + 0.5) | 0;
  50071. }
  50072. if (rotation !== 0 || this.imageScale_ != 1) {
  50073. var centerX = x + this.imageAnchorX_;
  50074. var centerY = y + this.imageAnchorY_;
  50075. ol.vec.Mat4.makeTransform2D(localTransform,
  50076. centerX, centerY, this.imageScale_, this.imageScale_,
  50077. rotation, -centerX, -centerY);
  50078. context.setTransform(
  50079. goog.vec.Mat4.getElement(localTransform, 0, 0),
  50080. goog.vec.Mat4.getElement(localTransform, 1, 0),
  50081. goog.vec.Mat4.getElement(localTransform, 0, 1),
  50082. goog.vec.Mat4.getElement(localTransform, 1, 1),
  50083. goog.vec.Mat4.getElement(localTransform, 0, 3),
  50084. goog.vec.Mat4.getElement(localTransform, 1, 3));
  50085. }
  50086. context.drawImage(this.image_, this.imageOriginX_, this.imageOriginY_,
  50087. this.imageWidth_, this.imageHeight_, x, y,
  50088. this.imageWidth_, this.imageHeight_);
  50089. }
  50090. if (rotation !== 0 || this.imageScale_ != 1) {
  50091. context.setTransform(1, 0, 0, 1, 0, 0);
  50092. }
  50093. if (this.imageOpacity_ != 1) {
  50094. context.globalAlpha = alpha;
  50095. }
  50096. };
  50097. /**
  50098. * @param {Array.<number>} flatCoordinates Flat coordinates.
  50099. * @param {number} offset Offset.
  50100. * @param {number} end End.
  50101. * @param {number} stride Stride.
  50102. * @private
  50103. */
  50104. ol.render.canvas.Immediate.prototype.drawText_ =
  50105. function(flatCoordinates, offset, end, stride) {
  50106. if (!this.textState_ || this.text_ === '') {
  50107. return;
  50108. }
  50109. if (this.textFillState_) {
  50110. this.setContextFillState_(this.textFillState_);
  50111. }
  50112. if (this.textStrokeState_) {
  50113. this.setContextStrokeState_(this.textStrokeState_);
  50114. }
  50115. this.setContextTextState_(this.textState_);
  50116. goog.asserts.assert(offset === 0, 'offset should be 0');
  50117. goog.asserts.assert(end == flatCoordinates.length,
  50118. 'end should be equal to the length of flatCoordinates');
  50119. var pixelCoordinates = ol.geom.flat.transform.transform2D(
  50120. flatCoordinates, offset, end, stride, this.transform_,
  50121. this.pixelCoordinates_);
  50122. var context = this.context_;
  50123. for (; offset < end; offset += stride) {
  50124. var x = pixelCoordinates[offset] + this.textOffsetX_;
  50125. var y = pixelCoordinates[offset + 1] + this.textOffsetY_;
  50126. if (this.textRotation_ !== 0 || this.textScale_ != 1) {
  50127. var localTransform = ol.vec.Mat4.makeTransform2D(this.tmpLocalTransform_,
  50128. x, y, this.textScale_, this.textScale_, this.textRotation_, -x, -y);
  50129. context.setTransform(
  50130. goog.vec.Mat4.getElement(localTransform, 0, 0),
  50131. goog.vec.Mat4.getElement(localTransform, 1, 0),
  50132. goog.vec.Mat4.getElement(localTransform, 0, 1),
  50133. goog.vec.Mat4.getElement(localTransform, 1, 1),
  50134. goog.vec.Mat4.getElement(localTransform, 0, 3),
  50135. goog.vec.Mat4.getElement(localTransform, 1, 3));
  50136. }
  50137. if (this.textStrokeState_) {
  50138. context.strokeText(this.text_, x, y);
  50139. }
  50140. if (this.textFillState_) {
  50141. context.fillText(this.text_, x, y);
  50142. }
  50143. }
  50144. if (this.textRotation_ !== 0 || this.textScale_ != 1) {
  50145. context.setTransform(1, 0, 0, 1, 0, 0);
  50146. }
  50147. };
  50148. /**
  50149. * @param {Array.<number>} flatCoordinates Flat coordinates.
  50150. * @param {number} offset Offset.
  50151. * @param {number} end End.
  50152. * @param {number} stride Stride.
  50153. * @param {boolean} close Close.
  50154. * @private
  50155. * @return {number} end End.
  50156. */
  50157. ol.render.canvas.Immediate.prototype.moveToLineTo_ =
  50158. function(flatCoordinates, offset, end, stride, close) {
  50159. var context = this.context_;
  50160. var pixelCoordinates = ol.geom.flat.transform.transform2D(
  50161. flatCoordinates, offset, end, stride, this.transform_,
  50162. this.pixelCoordinates_);
  50163. context.moveTo(pixelCoordinates[0], pixelCoordinates[1]);
  50164. var i;
  50165. for (i = 2; i < pixelCoordinates.length; i += 2) {
  50166. context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]);
  50167. }
  50168. if (close) {
  50169. context.lineTo(pixelCoordinates[0], pixelCoordinates[1]);
  50170. }
  50171. return end;
  50172. };
  50173. /**
  50174. * @param {Array.<number>} flatCoordinates Flat coordinates.
  50175. * @param {number} offset Offset.
  50176. * @param {Array.<number>} ends Ends.
  50177. * @param {number} stride Stride.
  50178. * @private
  50179. * @return {number} End.
  50180. */
  50181. ol.render.canvas.Immediate.prototype.drawRings_ =
  50182. function(flatCoordinates, offset, ends, stride) {
  50183. var context = this.context_;
  50184. var i, ii;
  50185. for (i = 0, ii = ends.length; i < ii; ++i) {
  50186. offset = this.moveToLineTo_(
  50187. flatCoordinates, offset, ends[i], stride, true);
  50188. context.closePath(); // FIXME is this needed here?
  50189. }
  50190. return offset;
  50191. };
  50192. /**
  50193. * Register a function to be called for rendering at a given zIndex. The
  50194. * function will be called asynchronously. The callback will receive a
  50195. * reference to {@link ol.render.canvas.Immediate} context for drawing.
  50196. *
  50197. * @param {number} zIndex Z index.
  50198. * @param {function(ol.render.canvas.Immediate)} callback Callback.
  50199. * @api
  50200. */
  50201. ol.render.canvas.Immediate.prototype.drawAsync = function(zIndex, callback) {
  50202. var zIndexKey = zIndex.toString();
  50203. var callbacks = this.callbacksByZIndex_[zIndexKey];
  50204. if (callbacks !== undefined) {
  50205. callbacks.push(callback);
  50206. } else {
  50207. this.callbacksByZIndex_[zIndexKey] = [callback];
  50208. }
  50209. };
  50210. /**
  50211. * Render a circle geometry into the canvas. Rendering is immediate and uses
  50212. * the current fill and stroke styles.
  50213. *
  50214. * @param {ol.geom.Circle} circleGeometry Circle geometry.
  50215. * @param {ol.Feature} feature Feature,
  50216. * @api
  50217. */
  50218. ol.render.canvas.Immediate.prototype.drawCircleGeometry =
  50219. function(circleGeometry, feature) {
  50220. if (!ol.extent.intersects(this.extent_, circleGeometry.getExtent())) {
  50221. return;
  50222. }
  50223. if (this.fillState_ || this.strokeState_) {
  50224. if (this.fillState_) {
  50225. this.setContextFillState_(this.fillState_);
  50226. }
  50227. if (this.strokeState_) {
  50228. this.setContextStrokeState_(this.strokeState_);
  50229. }
  50230. var pixelCoordinates = ol.geom.transformSimpleGeometry2D(
  50231. circleGeometry, this.transform_, this.pixelCoordinates_);
  50232. var dx = pixelCoordinates[2] - pixelCoordinates[0];
  50233. var dy = pixelCoordinates[3] - pixelCoordinates[1];
  50234. var radius = Math.sqrt(dx * dx + dy * dy);
  50235. var context = this.context_;
  50236. context.beginPath();
  50237. context.arc(
  50238. pixelCoordinates[0], pixelCoordinates[1], radius, 0, 2 * Math.PI);
  50239. if (this.fillState_) {
  50240. context.fill();
  50241. }
  50242. if (this.strokeState_) {
  50243. context.stroke();
  50244. }
  50245. }
  50246. if (this.text_ !== '') {
  50247. this.drawText_(circleGeometry.getCenter(), 0, 2, 2);
  50248. }
  50249. };
  50250. /**
  50251. * Render a feature into the canvas. In order to respect the zIndex of the
  50252. * style this method draws asynchronously and thus *after* calls to
  50253. * drawXxxxGeometry have been finished, effectively drawing the feature
  50254. * *on top* of everything else. You probably should be using an
  50255. * {@link ol.layer.Vector} instead of calling this method directly.
  50256. *
  50257. * @param {ol.Feature} feature Feature.
  50258. * @param {ol.style.Style} style Style.
  50259. * @api
  50260. */
  50261. ol.render.canvas.Immediate.prototype.drawFeature = function(feature, style) {
  50262. var geometry = style.getGeometryFunction()(feature);
  50263. if (!geometry ||
  50264. !ol.extent.intersects(this.extent_, geometry.getExtent())) {
  50265. return;
  50266. }
  50267. var zIndex = style.getZIndex();
  50268. if (zIndex === undefined) {
  50269. zIndex = 0;
  50270. }
  50271. this.drawAsync(zIndex, function(render) {
  50272. render.setFillStrokeStyle(style.getFill(), style.getStroke());
  50273. render.setImageStyle(style.getImage());
  50274. render.setTextStyle(style.getText());
  50275. var renderGeometry =
  50276. ol.render.canvas.Immediate.GEOMETRY_RENDERERS_[geometry.getType()];
  50277. goog.asserts.assert(renderGeometry !== undefined,
  50278. 'renderGeometry should be defined');
  50279. renderGeometry.call(render, geometry, null);
  50280. });
  50281. };
  50282. /**
  50283. * Render a GeometryCollection to the canvas. Rendering is immediate and
  50284. * uses the current styles appropriate for each geometry in the collection.
  50285. *
  50286. * @param {ol.geom.GeometryCollection} geometryCollectionGeometry Geometry
  50287. * collection.
  50288. * @param {ol.Feature} feature Feature.
  50289. */
  50290. ol.render.canvas.Immediate.prototype.drawGeometryCollectionGeometry =
  50291. function(geometryCollectionGeometry, feature) {
  50292. var geometries = geometryCollectionGeometry.getGeometriesArray();
  50293. var i, ii;
  50294. for (i = 0, ii = geometries.length; i < ii; ++i) {
  50295. var geometry = geometries[i];
  50296. var geometryRenderer =
  50297. ol.render.canvas.Immediate.GEOMETRY_RENDERERS_[geometry.getType()];
  50298. goog.asserts.assert(geometryRenderer !== undefined,
  50299. 'geometryRenderer should be defined');
  50300. geometryRenderer.call(this, geometry, feature);
  50301. }
  50302. };
  50303. /**
  50304. * Render a Point geometry into the canvas. Rendering is immediate and uses
  50305. * the current style.
  50306. *
  50307. * @param {ol.geom.Point} pointGeometry Point geometry.
  50308. * @param {ol.Feature} feature Feature.
  50309. * @api
  50310. */
  50311. ol.render.canvas.Immediate.prototype.drawPointGeometry =
  50312. function(pointGeometry, feature) {
  50313. var flatCoordinates = pointGeometry.getFlatCoordinates();
  50314. var stride = pointGeometry.getStride();
  50315. if (this.image_) {
  50316. this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);
  50317. }
  50318. if (this.text_ !== '') {
  50319. this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);
  50320. }
  50321. };
  50322. /**
  50323. * Render a MultiPoint geometry into the canvas. Rendering is immediate and
  50324. * uses the current style.
  50325. *
  50326. * @param {ol.geom.MultiPoint} multiPointGeometry MultiPoint geometry.
  50327. * @param {ol.Feature} feature Feature.
  50328. * @api
  50329. */
  50330. ol.render.canvas.Immediate.prototype.drawMultiPointGeometry =
  50331. function(multiPointGeometry, feature) {
  50332. var flatCoordinates = multiPointGeometry.getFlatCoordinates();
  50333. var stride = multiPointGeometry.getStride();
  50334. if (this.image_) {
  50335. this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);
  50336. }
  50337. if (this.text_ !== '') {
  50338. this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);
  50339. }
  50340. };
  50341. /**
  50342. * Render a LineString into the canvas. Rendering is immediate and uses
  50343. * the current style.
  50344. *
  50345. * @param {ol.geom.LineString} lineStringGeometry Line string geometry.
  50346. * @param {ol.Feature} feature Feature.
  50347. * @api
  50348. */
  50349. ol.render.canvas.Immediate.prototype.drawLineStringGeometry =
  50350. function(lineStringGeometry, feature) {
  50351. if (!ol.extent.intersects(this.extent_, lineStringGeometry.getExtent())) {
  50352. return;
  50353. }
  50354. if (this.strokeState_) {
  50355. this.setContextStrokeState_(this.strokeState_);
  50356. var context = this.context_;
  50357. var flatCoordinates = lineStringGeometry.getFlatCoordinates();
  50358. context.beginPath();
  50359. this.moveToLineTo_(flatCoordinates, 0, flatCoordinates.length,
  50360. lineStringGeometry.getStride(), false);
  50361. context.stroke();
  50362. }
  50363. if (this.text_ !== '') {
  50364. var flatMidpoint = lineStringGeometry.getFlatMidpoint();
  50365. this.drawText_(flatMidpoint, 0, 2, 2);
  50366. }
  50367. };
  50368. /**
  50369. * Render a MultiLineString geometry into the canvas. Rendering is immediate
  50370. * and uses the current style.
  50371. *
  50372. * @param {ol.geom.MultiLineString} multiLineStringGeometry
  50373. * MultiLineString geometry.
  50374. * @param {ol.Feature} feature Feature.
  50375. * @api
  50376. */
  50377. ol.render.canvas.Immediate.prototype.drawMultiLineStringGeometry =
  50378. function(multiLineStringGeometry, feature) {
  50379. var geometryExtent = multiLineStringGeometry.getExtent();
  50380. if (!ol.extent.intersects(this.extent_, geometryExtent)) {
  50381. return;
  50382. }
  50383. if (this.strokeState_) {
  50384. this.setContextStrokeState_(this.strokeState_);
  50385. var context = this.context_;
  50386. var flatCoordinates = multiLineStringGeometry.getFlatCoordinates();
  50387. var offset = 0;
  50388. var ends = multiLineStringGeometry.getEnds();
  50389. var stride = multiLineStringGeometry.getStride();
  50390. context.beginPath();
  50391. var i, ii;
  50392. for (i = 0, ii = ends.length; i < ii; ++i) {
  50393. offset = this.moveToLineTo_(
  50394. flatCoordinates, offset, ends[i], stride, false);
  50395. }
  50396. context.stroke();
  50397. }
  50398. if (this.text_ !== '') {
  50399. var flatMidpoints = multiLineStringGeometry.getFlatMidpoints();
  50400. this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2);
  50401. }
  50402. };
  50403. /**
  50404. * Render a Polygon geometry into the canvas. Rendering is immediate and uses
  50405. * the current style.
  50406. *
  50407. * @param {ol.geom.Polygon} polygonGeometry Polygon geometry.
  50408. * @param {ol.Feature} feature Feature.
  50409. * @api
  50410. */
  50411. ol.render.canvas.Immediate.prototype.drawPolygonGeometry =
  50412. function(polygonGeometry, feature) {
  50413. if (!ol.extent.intersects(this.extent_, polygonGeometry.getExtent())) {
  50414. return;
  50415. }
  50416. if (this.strokeState_ || this.fillState_) {
  50417. if (this.fillState_) {
  50418. this.setContextFillState_(this.fillState_);
  50419. }
  50420. if (this.strokeState_) {
  50421. this.setContextStrokeState_(this.strokeState_);
  50422. }
  50423. var context = this.context_;
  50424. context.beginPath();
  50425. this.drawRings_(polygonGeometry.getOrientedFlatCoordinates(),
  50426. 0, polygonGeometry.getEnds(), polygonGeometry.getStride());
  50427. if (this.fillState_) {
  50428. context.fill();
  50429. }
  50430. if (this.strokeState_) {
  50431. context.stroke();
  50432. }
  50433. }
  50434. if (this.text_ !== '') {
  50435. var flatInteriorPoint = polygonGeometry.getFlatInteriorPoint();
  50436. this.drawText_(flatInteriorPoint, 0, 2, 2);
  50437. }
  50438. };
  50439. /**
  50440. * Render MultiPolygon geometry into the canvas. Rendering is immediate and
  50441. * uses the current style.
  50442. * @param {ol.geom.MultiPolygon} multiPolygonGeometry MultiPolygon geometry.
  50443. * @param {ol.Feature} feature Feature.
  50444. * @api
  50445. */
  50446. ol.render.canvas.Immediate.prototype.drawMultiPolygonGeometry =
  50447. function(multiPolygonGeometry, feature) {
  50448. if (!ol.extent.intersects(this.extent_, multiPolygonGeometry.getExtent())) {
  50449. return;
  50450. }
  50451. if (this.strokeState_ || this.fillState_) {
  50452. if (this.fillState_) {
  50453. this.setContextFillState_(this.fillState_);
  50454. }
  50455. if (this.strokeState_) {
  50456. this.setContextStrokeState_(this.strokeState_);
  50457. }
  50458. var context = this.context_;
  50459. var flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates();
  50460. var offset = 0;
  50461. var endss = multiPolygonGeometry.getEndss();
  50462. var stride = multiPolygonGeometry.getStride();
  50463. var i, ii;
  50464. for (i = 0, ii = endss.length; i < ii; ++i) {
  50465. var ends = endss[i];
  50466. context.beginPath();
  50467. offset = this.drawRings_(flatCoordinates, offset, ends, stride);
  50468. if (this.fillState_) {
  50469. context.fill();
  50470. }
  50471. if (this.strokeState_) {
  50472. context.stroke();
  50473. }
  50474. }
  50475. }
  50476. if (this.text_ !== '') {
  50477. var flatInteriorPoints = multiPolygonGeometry.getFlatInteriorPoints();
  50478. this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2);
  50479. }
  50480. };
  50481. /**
  50482. * @inheritDoc
  50483. */
  50484. ol.render.canvas.Immediate.prototype.drawText = goog.abstractMethod;
  50485. /**
  50486. * FIXME: empty description for jsdoc
  50487. */
  50488. ol.render.canvas.Immediate.prototype.flush = function() {
  50489. /** @type {Array.<number>} */
  50490. var zs = Object.keys(this.callbacksByZIndex_).map(Number);
  50491. goog.array.sort(zs);
  50492. var i, ii, callbacks, j, jj;
  50493. for (i = 0, ii = zs.length; i < ii; ++i) {
  50494. callbacks = this.callbacksByZIndex_[zs[i].toString()];
  50495. for (j = 0, jj = callbacks.length; j < jj; ++j) {
  50496. callbacks[j](this);
  50497. }
  50498. }
  50499. };
  50500. /**
  50501. * @param {ol.render.canvas.FillState} fillState Fill state.
  50502. * @private
  50503. */
  50504. ol.render.canvas.Immediate.prototype.setContextFillState_ =
  50505. function(fillState) {
  50506. var context = this.context_;
  50507. var contextFillState = this.contextFillState_;
  50508. if (!contextFillState) {
  50509. context.fillStyle = fillState.fillStyle;
  50510. this.contextFillState_ = {
  50511. fillStyle: fillState.fillStyle
  50512. };
  50513. } else {
  50514. if (contextFillState.fillStyle != fillState.fillStyle) {
  50515. contextFillState.fillStyle = context.fillStyle = fillState.fillStyle;
  50516. }
  50517. }
  50518. };
  50519. /**
  50520. * @param {ol.render.canvas.StrokeState} strokeState Stroke state.
  50521. * @private
  50522. */
  50523. ol.render.canvas.Immediate.prototype.setContextStrokeState_ =
  50524. function(strokeState) {
  50525. var context = this.context_;
  50526. var contextStrokeState = this.contextStrokeState_;
  50527. if (!contextStrokeState) {
  50528. context.lineCap = strokeState.lineCap;
  50529. if (ol.has.CANVAS_LINE_DASH) {
  50530. context.setLineDash(strokeState.lineDash);
  50531. }
  50532. context.lineJoin = strokeState.lineJoin;
  50533. context.lineWidth = strokeState.lineWidth;
  50534. context.miterLimit = strokeState.miterLimit;
  50535. context.strokeStyle = strokeState.strokeStyle;
  50536. this.contextStrokeState_ = {
  50537. lineCap: strokeState.lineCap,
  50538. lineDash: strokeState.lineDash,
  50539. lineJoin: strokeState.lineJoin,
  50540. lineWidth: strokeState.lineWidth,
  50541. miterLimit: strokeState.miterLimit,
  50542. strokeStyle: strokeState.strokeStyle
  50543. };
  50544. } else {
  50545. if (contextStrokeState.lineCap != strokeState.lineCap) {
  50546. contextStrokeState.lineCap = context.lineCap = strokeState.lineCap;
  50547. }
  50548. if (ol.has.CANVAS_LINE_DASH) {
  50549. if (!goog.array.equals(
  50550. contextStrokeState.lineDash, strokeState.lineDash)) {
  50551. context.setLineDash(contextStrokeState.lineDash = strokeState.lineDash);
  50552. }
  50553. }
  50554. if (contextStrokeState.lineJoin != strokeState.lineJoin) {
  50555. contextStrokeState.lineJoin = context.lineJoin = strokeState.lineJoin;
  50556. }
  50557. if (contextStrokeState.lineWidth != strokeState.lineWidth) {
  50558. contextStrokeState.lineWidth = context.lineWidth = strokeState.lineWidth;
  50559. }
  50560. if (contextStrokeState.miterLimit != strokeState.miterLimit) {
  50561. contextStrokeState.miterLimit = context.miterLimit =
  50562. strokeState.miterLimit;
  50563. }
  50564. if (contextStrokeState.strokeStyle != strokeState.strokeStyle) {
  50565. contextStrokeState.strokeStyle = context.strokeStyle =
  50566. strokeState.strokeStyle;
  50567. }
  50568. }
  50569. };
  50570. /**
  50571. * @param {ol.render.canvas.TextState} textState Text state.
  50572. * @private
  50573. */
  50574. ol.render.canvas.Immediate.prototype.setContextTextState_ =
  50575. function(textState) {
  50576. var context = this.context_;
  50577. var contextTextState = this.contextTextState_;
  50578. if (!contextTextState) {
  50579. context.font = textState.font;
  50580. context.textAlign = textState.textAlign;
  50581. context.textBaseline = textState.textBaseline;
  50582. this.contextTextState_ = {
  50583. font: textState.font,
  50584. textAlign: textState.textAlign,
  50585. textBaseline: textState.textBaseline
  50586. };
  50587. } else {
  50588. if (contextTextState.font != textState.font) {
  50589. contextTextState.font = context.font = textState.font;
  50590. }
  50591. if (contextTextState.textAlign != textState.textAlign) {
  50592. contextTextState.textAlign = context.textAlign = textState.textAlign;
  50593. }
  50594. if (contextTextState.textBaseline != textState.textBaseline) {
  50595. contextTextState.textBaseline = context.textBaseline =
  50596. textState.textBaseline;
  50597. }
  50598. }
  50599. };
  50600. /**
  50601. * Set the fill and stroke style for subsequent draw operations. To clear
  50602. * either fill or stroke styles, pass null for the appropriate parameter.
  50603. *
  50604. * @param {ol.style.Fill} fillStyle Fill style.
  50605. * @param {ol.style.Stroke} strokeStyle Stroke style.
  50606. * @api
  50607. */
  50608. ol.render.canvas.Immediate.prototype.setFillStrokeStyle =
  50609. function(fillStyle, strokeStyle) {
  50610. if (!fillStyle) {
  50611. this.fillState_ = null;
  50612. } else {
  50613. var fillStyleColor = fillStyle.getColor();
  50614. this.fillState_ = {
  50615. fillStyle: ol.color.asString(fillStyleColor ?
  50616. fillStyleColor : ol.render.canvas.defaultFillStyle)
  50617. };
  50618. }
  50619. if (!strokeStyle) {
  50620. this.strokeState_ = null;
  50621. } else {
  50622. var strokeStyleColor = strokeStyle.getColor();
  50623. var strokeStyleLineCap = strokeStyle.getLineCap();
  50624. var strokeStyleLineDash = strokeStyle.getLineDash();
  50625. var strokeStyleLineJoin = strokeStyle.getLineJoin();
  50626. var strokeStyleWidth = strokeStyle.getWidth();
  50627. var strokeStyleMiterLimit = strokeStyle.getMiterLimit();
  50628. this.strokeState_ = {
  50629. lineCap: strokeStyleLineCap !== undefined ?
  50630. strokeStyleLineCap : ol.render.canvas.defaultLineCap,
  50631. lineDash: strokeStyleLineDash ?
  50632. strokeStyleLineDash : ol.render.canvas.defaultLineDash,
  50633. lineJoin: strokeStyleLineJoin !== undefined ?
  50634. strokeStyleLineJoin : ol.render.canvas.defaultLineJoin,
  50635. lineWidth: this.pixelRatio_ * (strokeStyleWidth !== undefined ?
  50636. strokeStyleWidth : ol.render.canvas.defaultLineWidth),
  50637. miterLimit: strokeStyleMiterLimit !== undefined ?
  50638. strokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit,
  50639. strokeStyle: ol.color.asString(strokeStyleColor ?
  50640. strokeStyleColor : ol.render.canvas.defaultStrokeStyle)
  50641. };
  50642. }
  50643. };
  50644. /**
  50645. * Set the image style for subsequent draw operations. Pass null to remove
  50646. * the image style.
  50647. *
  50648. * @param {ol.style.Image} imageStyle Image style.
  50649. * @api
  50650. */
  50651. ol.render.canvas.Immediate.prototype.setImageStyle = function(imageStyle) {
  50652. if (!imageStyle) {
  50653. this.image_ = null;
  50654. } else {
  50655. var imageAnchor = imageStyle.getAnchor();
  50656. // FIXME pixel ratio
  50657. var imageImage = imageStyle.getImage(1);
  50658. var imageOrigin = imageStyle.getOrigin();
  50659. var imageSize = imageStyle.getSize();
  50660. goog.asserts.assert(imageAnchor, 'imageAnchor must be truthy');
  50661. goog.asserts.assert(imageImage, 'imageImage must be truthy');
  50662. goog.asserts.assert(imageOrigin, 'imageOrigin must be truthy');
  50663. goog.asserts.assert(imageSize, 'imageSize must be truthy');
  50664. this.imageAnchorX_ = imageAnchor[0];
  50665. this.imageAnchorY_ = imageAnchor[1];
  50666. this.imageHeight_ = imageSize[1];
  50667. this.image_ = imageImage;
  50668. this.imageOpacity_ = imageStyle.getOpacity();
  50669. this.imageOriginX_ = imageOrigin[0];
  50670. this.imageOriginY_ = imageOrigin[1];
  50671. this.imageRotateWithView_ = imageStyle.getRotateWithView();
  50672. this.imageRotation_ = imageStyle.getRotation();
  50673. this.imageScale_ = imageStyle.getScale();
  50674. this.imageSnapToPixel_ = imageStyle.getSnapToPixel();
  50675. this.imageWidth_ = imageSize[0];
  50676. }
  50677. };
  50678. /**
  50679. * Set the text style for subsequent draw operations. Pass null to
  50680. * remove the text style.
  50681. *
  50682. * @param {ol.style.Text} textStyle Text style.
  50683. * @api
  50684. */
  50685. ol.render.canvas.Immediate.prototype.setTextStyle = function(textStyle) {
  50686. if (!textStyle) {
  50687. this.text_ = '';
  50688. } else {
  50689. var textFillStyle = textStyle.getFill();
  50690. if (!textFillStyle) {
  50691. this.textFillState_ = null;
  50692. } else {
  50693. var textFillStyleColor = textFillStyle.getColor();
  50694. this.textFillState_ = {
  50695. fillStyle: ol.color.asString(textFillStyleColor ?
  50696. textFillStyleColor : ol.render.canvas.defaultFillStyle)
  50697. };
  50698. }
  50699. var textStrokeStyle = textStyle.getStroke();
  50700. if (!textStrokeStyle) {
  50701. this.textStrokeState_ = null;
  50702. } else {
  50703. var textStrokeStyleColor = textStrokeStyle.getColor();
  50704. var textStrokeStyleLineCap = textStrokeStyle.getLineCap();
  50705. var textStrokeStyleLineDash = textStrokeStyle.getLineDash();
  50706. var textStrokeStyleLineJoin = textStrokeStyle.getLineJoin();
  50707. var textStrokeStyleWidth = textStrokeStyle.getWidth();
  50708. var textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit();
  50709. this.textStrokeState_ = {
  50710. lineCap: textStrokeStyleLineCap !== undefined ?
  50711. textStrokeStyleLineCap : ol.render.canvas.defaultLineCap,
  50712. lineDash: textStrokeStyleLineDash ?
  50713. textStrokeStyleLineDash : ol.render.canvas.defaultLineDash,
  50714. lineJoin: textStrokeStyleLineJoin !== undefined ?
  50715. textStrokeStyleLineJoin : ol.render.canvas.defaultLineJoin,
  50716. lineWidth: textStrokeStyleWidth !== undefined ?
  50717. textStrokeStyleWidth : ol.render.canvas.defaultLineWidth,
  50718. miterLimit: textStrokeStyleMiterLimit !== undefined ?
  50719. textStrokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit,
  50720. strokeStyle: ol.color.asString(textStrokeStyleColor ?
  50721. textStrokeStyleColor : ol.render.canvas.defaultStrokeStyle)
  50722. };
  50723. }
  50724. var textFont = textStyle.getFont();
  50725. var textOffsetX = textStyle.getOffsetX();
  50726. var textOffsetY = textStyle.getOffsetY();
  50727. var textRotation = textStyle.getRotation();
  50728. var textScale = textStyle.getScale();
  50729. var textText = textStyle.getText();
  50730. var textTextAlign = textStyle.getTextAlign();
  50731. var textTextBaseline = textStyle.getTextBaseline();
  50732. this.textState_ = {
  50733. font: textFont !== undefined ?
  50734. textFont : ol.render.canvas.defaultFont,
  50735. textAlign: textTextAlign !== undefined ?
  50736. textTextAlign : ol.render.canvas.defaultTextAlign,
  50737. textBaseline: textTextBaseline !== undefined ?
  50738. textTextBaseline : ol.render.canvas.defaultTextBaseline
  50739. };
  50740. this.text_ = textText !== undefined ? textText : '';
  50741. this.textOffsetX_ =
  50742. textOffsetX !== undefined ? (this.pixelRatio_ * textOffsetX) : 0;
  50743. this.textOffsetY_ =
  50744. textOffsetY !== undefined ? (this.pixelRatio_ * textOffsetY) : 0;
  50745. this.textRotation_ = textRotation !== undefined ? textRotation : 0;
  50746. this.textScale_ = this.pixelRatio_ * (textScale !== undefined ?
  50747. textScale : 1);
  50748. }
  50749. };
  50750. /**
  50751. * @const
  50752. * @private
  50753. * @type {Object.<ol.geom.GeometryType,
  50754. * function(this: ol.render.canvas.Immediate, ol.geom.Geometry,
  50755. * Object)>}
  50756. */
  50757. ol.render.canvas.Immediate.GEOMETRY_RENDERERS_ = {
  50758. 'Point': ol.render.canvas.Immediate.prototype.drawPointGeometry,
  50759. 'LineString': ol.render.canvas.Immediate.prototype.drawLineStringGeometry,
  50760. 'Polygon': ol.render.canvas.Immediate.prototype.drawPolygonGeometry,
  50761. 'MultiPoint': ol.render.canvas.Immediate.prototype.drawMultiPointGeometry,
  50762. 'MultiLineString':
  50763. ol.render.canvas.Immediate.prototype.drawMultiLineStringGeometry,
  50764. 'MultiPolygon': ol.render.canvas.Immediate.prototype.drawMultiPolygonGeometry,
  50765. 'GeometryCollection':
  50766. ol.render.canvas.Immediate.prototype.drawGeometryCollectionGeometry,
  50767. 'Circle': ol.render.canvas.Immediate.prototype.drawCircleGeometry
  50768. };
  50769. goog.provide('ol.renderer.canvas.Layer');
  50770. goog.require('goog.array');
  50771. goog.require('goog.asserts');
  50772. goog.require('goog.vec.Mat4');
  50773. goog.require('ol.dom');
  50774. goog.require('ol.extent');
  50775. goog.require('ol.layer.Layer');
  50776. goog.require('ol.render.Event');
  50777. goog.require('ol.render.EventType');
  50778. goog.require('ol.render.canvas.Immediate');
  50779. goog.require('ol.renderer.Layer');
  50780. goog.require('ol.vec.Mat4');
  50781. /**
  50782. * @constructor
  50783. * @extends {ol.renderer.Layer}
  50784. * @param {ol.layer.Layer} layer Layer.
  50785. */
  50786. ol.renderer.canvas.Layer = function(layer) {
  50787. goog.base(this, layer);
  50788. /**
  50789. * @private
  50790. * @type {!goog.vec.Mat4.Number}
  50791. */
  50792. this.transform_ = goog.vec.Mat4.createNumber();
  50793. };
  50794. goog.inherits(ol.renderer.canvas.Layer, ol.renderer.Layer);
  50795. /**
  50796. * @param {olx.FrameState} frameState Frame state.
  50797. * @param {ol.layer.LayerState} layerState Layer state.
  50798. * @param {CanvasRenderingContext2D} context Context.
  50799. */
  50800. ol.renderer.canvas.Layer.prototype.composeFrame =
  50801. function(frameState, layerState, context) {
  50802. this.dispatchPreComposeEvent(context, frameState);
  50803. var image = this.getImage();
  50804. if (image) {
  50805. // clipped rendering if layer extent is set
  50806. var extent = layerState.extent;
  50807. var clipped = extent !== undefined;
  50808. if (clipped) {
  50809. goog.asserts.assert(extent !== undefined,
  50810. 'layerState extent is defined');
  50811. var pixelRatio = frameState.pixelRatio;
  50812. var topLeft = ol.extent.getTopLeft(extent);
  50813. var topRight = ol.extent.getTopRight(extent);
  50814. var bottomRight = ol.extent.getBottomRight(extent);
  50815. var bottomLeft = ol.extent.getBottomLeft(extent);
  50816. ol.vec.Mat4.multVec2(frameState.coordinateToPixelMatrix,
  50817. topLeft, topLeft);
  50818. ol.vec.Mat4.multVec2(frameState.coordinateToPixelMatrix,
  50819. topRight, topRight);
  50820. ol.vec.Mat4.multVec2(frameState.coordinateToPixelMatrix,
  50821. bottomRight, bottomRight);
  50822. ol.vec.Mat4.multVec2(frameState.coordinateToPixelMatrix,
  50823. bottomLeft, bottomLeft);
  50824. context.save();
  50825. context.beginPath();
  50826. context.moveTo(topLeft[0] * pixelRatio, topLeft[1] * pixelRatio);
  50827. context.lineTo(topRight[0] * pixelRatio, topRight[1] * pixelRatio);
  50828. context.lineTo(bottomRight[0] * pixelRatio, bottomRight[1] * pixelRatio);
  50829. context.lineTo(bottomLeft[0] * pixelRatio, bottomLeft[1] * pixelRatio);
  50830. context.clip();
  50831. }
  50832. var imageTransform = this.getImageTransform();
  50833. // for performance reasons, context.save / context.restore is not used
  50834. // to save and restore the transformation matrix and the opacity.
  50835. // see http://jsperf.com/context-save-restore-versus-variable
  50836. var alpha = context.globalAlpha;
  50837. context.globalAlpha = layerState.opacity;
  50838. // for performance reasons, context.setTransform is only used
  50839. // when the view is rotated. see http://jsperf.com/canvas-transform
  50840. if (frameState.viewState.rotation === 0) {
  50841. var dx = goog.vec.Mat4.getElement(imageTransform, 0, 3);
  50842. var dy = goog.vec.Mat4.getElement(imageTransform, 1, 3);
  50843. var dw = image.width * goog.vec.Mat4.getElement(imageTransform, 0, 0);
  50844. var dh = image.height * goog.vec.Mat4.getElement(imageTransform, 1, 1);
  50845. context.drawImage(image, 0, 0, +image.width, +image.height,
  50846. Math.round(dx), Math.round(dy), Math.round(dw), Math.round(dh));
  50847. } else {
  50848. context.setTransform(
  50849. goog.vec.Mat4.getElement(imageTransform, 0, 0),
  50850. goog.vec.Mat4.getElement(imageTransform, 1, 0),
  50851. goog.vec.Mat4.getElement(imageTransform, 0, 1),
  50852. goog.vec.Mat4.getElement(imageTransform, 1, 1),
  50853. goog.vec.Mat4.getElement(imageTransform, 0, 3),
  50854. goog.vec.Mat4.getElement(imageTransform, 1, 3));
  50855. context.drawImage(image, 0, 0);
  50856. context.setTransform(1, 0, 0, 1, 0, 0);
  50857. }
  50858. context.globalAlpha = alpha;
  50859. if (clipped) {
  50860. context.restore();
  50861. }
  50862. }
  50863. this.dispatchPostComposeEvent(context, frameState);
  50864. };
  50865. /**
  50866. * @param {ol.render.EventType} type Event type.
  50867. * @param {CanvasRenderingContext2D} context Context.
  50868. * @param {olx.FrameState} frameState Frame state.
  50869. * @param {goog.vec.Mat4.Number=} opt_transform Transform.
  50870. * @private
  50871. */
  50872. ol.renderer.canvas.Layer.prototype.dispatchComposeEvent_ =
  50873. function(type, context, frameState, opt_transform) {
  50874. var layer = this.getLayer();
  50875. if (layer.hasListener(type)) {
  50876. var transform = opt_transform !== undefined ?
  50877. opt_transform : this.getTransform(frameState, 0);
  50878. var render = new ol.render.canvas.Immediate(
  50879. context, frameState.pixelRatio, frameState.extent, transform,
  50880. frameState.viewState.rotation);
  50881. var composeEvent = new ol.render.Event(type, layer, render, frameState,
  50882. context, null);
  50883. layer.dispatchEvent(composeEvent);
  50884. render.flush();
  50885. }
  50886. };
  50887. /**
  50888. * @param {CanvasRenderingContext2D} context Context.
  50889. * @param {olx.FrameState} frameState Frame state.
  50890. * @param {goog.vec.Mat4.Number=} opt_transform Transform.
  50891. * @protected
  50892. */
  50893. ol.renderer.canvas.Layer.prototype.dispatchPostComposeEvent =
  50894. function(context, frameState, opt_transform) {
  50895. this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE, context,
  50896. frameState, opt_transform);
  50897. };
  50898. /**
  50899. * @param {CanvasRenderingContext2D} context Context.
  50900. * @param {olx.FrameState} frameState Frame state.
  50901. * @param {goog.vec.Mat4.Number=} opt_transform Transform.
  50902. * @protected
  50903. */
  50904. ol.renderer.canvas.Layer.prototype.dispatchPreComposeEvent =
  50905. function(context, frameState, opt_transform) {
  50906. this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE, context,
  50907. frameState, opt_transform);
  50908. };
  50909. /**
  50910. * @param {CanvasRenderingContext2D} context Context.
  50911. * @param {olx.FrameState} frameState Frame state.
  50912. * @param {goog.vec.Mat4.Number=} opt_transform Transform.
  50913. * @protected
  50914. */
  50915. ol.renderer.canvas.Layer.prototype.dispatchRenderEvent =
  50916. function(context, frameState, opt_transform) {
  50917. this.dispatchComposeEvent_(ol.render.EventType.RENDER, context,
  50918. frameState, opt_transform);
  50919. };
  50920. /**
  50921. * @return {HTMLCanvasElement|HTMLVideoElement|Image} Canvas.
  50922. */
  50923. ol.renderer.canvas.Layer.prototype.getImage = goog.abstractMethod;
  50924. /**
  50925. * @return {!goog.vec.Mat4.Number} Image transform.
  50926. */
  50927. ol.renderer.canvas.Layer.prototype.getImageTransform = goog.abstractMethod;
  50928. /**
  50929. * @param {olx.FrameState} frameState Frame state.
  50930. * @param {number} offsetX Offset on the x-axis in view coordinates.
  50931. * @protected
  50932. * @return {!goog.vec.Mat4.Number} Transform.
  50933. */
  50934. ol.renderer.canvas.Layer.prototype.getTransform =
  50935. function(frameState, offsetX) {
  50936. var viewState = frameState.viewState;
  50937. var pixelRatio = frameState.pixelRatio;
  50938. return ol.vec.Mat4.makeTransform2D(this.transform_,
  50939. pixelRatio * frameState.size[0] / 2,
  50940. pixelRatio * frameState.size[1] / 2,
  50941. pixelRatio / viewState.resolution,
  50942. -pixelRatio / viewState.resolution,
  50943. -viewState.rotation,
  50944. -viewState.center[0] + offsetX,
  50945. -viewState.center[1]);
  50946. };
  50947. /**
  50948. * @param {olx.FrameState} frameState Frame state.
  50949. * @param {ol.layer.LayerState} layerState Layer state.
  50950. * @return {boolean} whether composeFrame should be called.
  50951. */
  50952. ol.renderer.canvas.Layer.prototype.prepareFrame = goog.abstractMethod;
  50953. /**
  50954. * @param {ol.Pixel} pixelOnMap Pixel.
  50955. * @param {goog.vec.Mat4.Number} imageTransformInv The transformation matrix
  50956. * to convert from a map pixel to a canvas pixel.
  50957. * @return {ol.Pixel}
  50958. * @protected
  50959. */
  50960. ol.renderer.canvas.Layer.prototype.getPixelOnCanvas =
  50961. function(pixelOnMap, imageTransformInv) {
  50962. var pixelOnCanvas = [0, 0];
  50963. ol.vec.Mat4.multVec2(imageTransformInv, pixelOnMap, pixelOnCanvas);
  50964. return pixelOnCanvas;
  50965. };
  50966. /**
  50967. * @param {ol.Size} size Size.
  50968. * @return {boolean} True when the canvas with the current size does not exceed
  50969. * the maximum dimensions.
  50970. */
  50971. ol.renderer.canvas.Layer.testCanvasSize = (function() {
  50972. /**
  50973. * @type {CanvasRenderingContext2D}
  50974. */
  50975. var context = null;
  50976. /**
  50977. * @type {ImageData}
  50978. */
  50979. var imageData = null;
  50980. return function(size) {
  50981. if (!context) {
  50982. context = ol.dom.createCanvasContext2D(1, 1);
  50983. imageData = context.createImageData(1, 1);
  50984. var data = imageData.data;
  50985. data[0] = 42;
  50986. data[1] = 84;
  50987. data[2] = 126;
  50988. data[3] = 255;
  50989. }
  50990. var canvas = context.canvas;
  50991. var good = size[0] <= canvas.width && size[1] <= canvas.height;
  50992. if (!good) {
  50993. canvas.width = size[0];
  50994. canvas.height = size[1];
  50995. var x = size[0] - 1;
  50996. var y = size[1] - 1;
  50997. context.putImageData(imageData, x, y);
  50998. var result = context.getImageData(x, y, 1, 1);
  50999. good = goog.array.equals(imageData.data, result.data);
  51000. }
  51001. return good;
  51002. };
  51003. })();
  51004. goog.provide('ol.render.IReplayGroup');
  51005. goog.require('ol.render.VectorContext');
  51006. /**
  51007. * @enum {string}
  51008. */
  51009. ol.render.ReplayType = {
  51010. IMAGE: 'Image',
  51011. LINE_STRING: 'LineString',
  51012. POLYGON: 'Polygon',
  51013. TEXT: 'Text'
  51014. };
  51015. /**
  51016. * @const
  51017. * @type {Array.<ol.render.ReplayType>}
  51018. */
  51019. ol.render.REPLAY_ORDER = [
  51020. ol.render.ReplayType.POLYGON,
  51021. ol.render.ReplayType.LINE_STRING,
  51022. ol.render.ReplayType.IMAGE,
  51023. ol.render.ReplayType.TEXT
  51024. ];
  51025. /**
  51026. * @interface
  51027. */
  51028. ol.render.IReplayGroup = function() {
  51029. };
  51030. /**
  51031. * @param {number|undefined} zIndex Z index.
  51032. * @param {ol.render.ReplayType} replayType Replay type.
  51033. * @return {ol.render.VectorContext} Replay.
  51034. */
  51035. ol.render.IReplayGroup.prototype.getReplay = function(zIndex, replayType) {
  51036. };
  51037. /**
  51038. * @return {boolean} Is empty.
  51039. */
  51040. ol.render.IReplayGroup.prototype.isEmpty = function() {
  51041. };
  51042. // FIXME add option to apply snapToPixel to all coordinates?
  51043. // FIXME can eliminate empty set styles and strokes (when all geoms skipped)
  51044. goog.provide('ol.render.canvas.ImageReplay');
  51045. goog.provide('ol.render.canvas.LineStringReplay');
  51046. goog.provide('ol.render.canvas.PolygonReplay');
  51047. goog.provide('ol.render.canvas.Replay');
  51048. goog.provide('ol.render.canvas.ReplayGroup');
  51049. goog.provide('ol.render.canvas.TextReplay');
  51050. goog.require('goog.array');
  51051. goog.require('goog.asserts');
  51052. goog.require('goog.object');
  51053. goog.require('goog.vec.Mat4');
  51054. goog.require('ol');
  51055. goog.require('ol.array');
  51056. goog.require('ol.color');
  51057. goog.require('ol.dom');
  51058. goog.require('ol.extent');
  51059. goog.require('ol.extent.Relationship');
  51060. goog.require('ol.geom.flat.simplify');
  51061. goog.require('ol.geom.flat.transform');
  51062. goog.require('ol.has');
  51063. goog.require('ol.render.IReplayGroup');
  51064. goog.require('ol.render.VectorContext');
  51065. goog.require('ol.render.canvas');
  51066. goog.require('ol.vec.Mat4');
  51067. /**
  51068. * @enum {number}
  51069. */
  51070. ol.render.canvas.Instruction = {
  51071. BEGIN_GEOMETRY: 0,
  51072. BEGIN_PATH: 1,
  51073. CIRCLE: 2,
  51074. CLOSE_PATH: 3,
  51075. DRAW_IMAGE: 4,
  51076. DRAW_TEXT: 5,
  51077. END_GEOMETRY: 6,
  51078. FILL: 7,
  51079. MOVE_TO_LINE_TO: 8,
  51080. SET_FILL_STYLE: 9,
  51081. SET_STROKE_STYLE: 10,
  51082. SET_TEXT_STYLE: 11,
  51083. STROKE: 12
  51084. };
  51085. /**
  51086. * @constructor
  51087. * @extends {ol.render.VectorContext}
  51088. * @param {number} tolerance Tolerance.
  51089. * @param {ol.Extent} maxExtent Maximum extent.
  51090. * @param {number} resolution Resolution.
  51091. * @protected
  51092. * @struct
  51093. */
  51094. ol.render.canvas.Replay = function(tolerance, maxExtent, resolution) {
  51095. goog.base(this);
  51096. /**
  51097. * @protected
  51098. * @type {number}
  51099. */
  51100. this.tolerance = tolerance;
  51101. /**
  51102. * @protected
  51103. * @const
  51104. * @type {ol.Extent}
  51105. */
  51106. this.maxExtent = maxExtent;
  51107. /**
  51108. * @private
  51109. * @type {ol.Extent}
  51110. */
  51111. this.bufferedMaxExtent_ = null;
  51112. /**
  51113. * @protected
  51114. * @type {number}
  51115. */
  51116. this.maxLineWidth = 0;
  51117. /**
  51118. * @protected
  51119. * @const
  51120. * @type {number}
  51121. */
  51122. this.resolution = resolution;
  51123. /**
  51124. * @private
  51125. * @type {Array.<*>}
  51126. */
  51127. this.beginGeometryInstruction1_ = null;
  51128. /**
  51129. * @private
  51130. * @type {Array.<*>}
  51131. */
  51132. this.beginGeometryInstruction2_ = null;
  51133. /**
  51134. * @protected
  51135. * @type {Array.<*>}
  51136. */
  51137. this.instructions = [];
  51138. /**
  51139. * @protected
  51140. * @type {Array.<number>}
  51141. */
  51142. this.coordinates = [];
  51143. /**
  51144. * @private
  51145. * @type {goog.vec.Mat4.Number}
  51146. */
  51147. this.renderedTransform_ = goog.vec.Mat4.createNumber();
  51148. /**
  51149. * @protected
  51150. * @type {Array.<*>}
  51151. */
  51152. this.hitDetectionInstructions = [];
  51153. /**
  51154. * @private
  51155. * @type {Array.<number>}
  51156. */
  51157. this.pixelCoordinates_ = [];
  51158. /**
  51159. * @private
  51160. * @type {!goog.vec.Mat4.Number}
  51161. */
  51162. this.tmpLocalTransform_ = goog.vec.Mat4.createNumber();
  51163. };
  51164. goog.inherits(ol.render.canvas.Replay, ol.render.VectorContext);
  51165. /**
  51166. * @param {Array.<number>} flatCoordinates Flat coordinates.
  51167. * @param {number} offset Offset.
  51168. * @param {number} end End.
  51169. * @param {number} stride Stride.
  51170. * @param {boolean} close Close.
  51171. * @protected
  51172. * @return {number} My end.
  51173. */
  51174. ol.render.canvas.Replay.prototype.appendFlatCoordinates =
  51175. function(flatCoordinates, offset, end, stride, close) {
  51176. var myEnd = this.coordinates.length;
  51177. var extent = this.getBufferedMaxExtent();
  51178. var lastCoord = [flatCoordinates[offset], flatCoordinates[offset + 1]];
  51179. var nextCoord = [NaN, NaN];
  51180. var skipped = true;
  51181. var i, lastRel, nextRel;
  51182. for (i = offset + stride; i < end; i += stride) {
  51183. nextCoord[0] = flatCoordinates[i];
  51184. nextCoord[1] = flatCoordinates[i + 1];
  51185. nextRel = ol.extent.coordinateRelationship(extent, nextCoord);
  51186. if (nextRel !== lastRel) {
  51187. if (skipped) {
  51188. this.coordinates[myEnd++] = lastCoord[0];
  51189. this.coordinates[myEnd++] = lastCoord[1];
  51190. }
  51191. this.coordinates[myEnd++] = nextCoord[0];
  51192. this.coordinates[myEnd++] = nextCoord[1];
  51193. skipped = false;
  51194. } else if (nextRel === ol.extent.Relationship.INTERSECTING) {
  51195. this.coordinates[myEnd++] = nextCoord[0];
  51196. this.coordinates[myEnd++] = nextCoord[1];
  51197. skipped = false;
  51198. } else {
  51199. skipped = true;
  51200. }
  51201. lastCoord[0] = nextCoord[0];
  51202. lastCoord[1] = nextCoord[1];
  51203. lastRel = nextRel;
  51204. }
  51205. // handle case where there is only one point to append
  51206. if (i === offset + stride) {
  51207. this.coordinates[myEnd++] = lastCoord[0];
  51208. this.coordinates[myEnd++] = lastCoord[1];
  51209. }
  51210. if (close) {
  51211. this.coordinates[myEnd++] = flatCoordinates[offset];
  51212. this.coordinates[myEnd++] = flatCoordinates[offset + 1];
  51213. }
  51214. return myEnd;
  51215. };
  51216. /**
  51217. * @protected
  51218. * @param {ol.geom.Geometry} geometry Geometry.
  51219. * @param {ol.Feature} feature Feature.
  51220. */
  51221. ol.render.canvas.Replay.prototype.beginGeometry = function(geometry, feature) {
  51222. this.beginGeometryInstruction1_ =
  51223. [ol.render.canvas.Instruction.BEGIN_GEOMETRY, feature, 0];
  51224. this.instructions.push(this.beginGeometryInstruction1_);
  51225. this.beginGeometryInstruction2_ =
  51226. [ol.render.canvas.Instruction.BEGIN_GEOMETRY, feature, 0];
  51227. this.hitDetectionInstructions.push(this.beginGeometryInstruction2_);
  51228. };
  51229. /**
  51230. * @private
  51231. * @param {CanvasRenderingContext2D} context Context.
  51232. * @param {number} pixelRatio Pixel ratio.
  51233. * @param {goog.vec.Mat4.Number} transform Transform.
  51234. * @param {number} viewRotation View rotation.
  51235. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  51236. * to skip.
  51237. * @param {Array.<*>} instructions Instructions array.
  51238. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  51239. * @param {ol.Extent=} opt_hitExtent Only check features that intersect this
  51240. * extent.
  51241. * @return {T|undefined} Callback result.
  51242. * @template T
  51243. */
  51244. ol.render.canvas.Replay.prototype.replay_ = function(
  51245. context, pixelRatio, transform, viewRotation, skippedFeaturesHash,
  51246. instructions, featureCallback, opt_hitExtent) {
  51247. /** @type {Array.<number>} */
  51248. var pixelCoordinates;
  51249. if (ol.vec.Mat4.equals2D(transform, this.renderedTransform_)) {
  51250. pixelCoordinates = this.pixelCoordinates_;
  51251. } else {
  51252. pixelCoordinates = ol.geom.flat.transform.transform2D(
  51253. this.coordinates, 0, this.coordinates.length, 2,
  51254. transform, this.pixelCoordinates_);
  51255. goog.vec.Mat4.setFromArray(this.renderedTransform_, transform);
  51256. goog.asserts.assert(pixelCoordinates === this.pixelCoordinates_,
  51257. 'pixelCoordinates should be the same as this.pixelCoordinates_');
  51258. }
  51259. var i = 0; // instruction index
  51260. var ii = instructions.length; // end of instructions
  51261. var d = 0; // data index
  51262. var dd; // end of per-instruction data
  51263. var localTransform = this.tmpLocalTransform_;
  51264. while (i < ii) {
  51265. var instruction = instructions[i];
  51266. var type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]);
  51267. var feature, fill, stroke, text, x, y;
  51268. switch (type) {
  51269. case ol.render.canvas.Instruction.BEGIN_GEOMETRY:
  51270. feature = /** @type {ol.Feature} */ (instruction[1]);
  51271. var featureUid = goog.getUid(feature).toString();
  51272. if (skippedFeaturesHash[featureUid] !== undefined ||
  51273. !feature.getGeometry()) {
  51274. i = /** @type {number} */ (instruction[2]);
  51275. } else if (opt_hitExtent !== undefined && !ol.extent.intersects(
  51276. /** @type {Array<number>} */ (opt_hitExtent),
  51277. feature.getGeometry().getExtent())) {
  51278. i = /** @type {number} */ (instruction[2]);
  51279. } else {
  51280. ++i;
  51281. }
  51282. break;
  51283. case ol.render.canvas.Instruction.BEGIN_PATH:
  51284. context.beginPath();
  51285. ++i;
  51286. break;
  51287. case ol.render.canvas.Instruction.CIRCLE:
  51288. goog.asserts.assert(goog.isNumber(instruction[1]),
  51289. 'second instruction should be a number');
  51290. d = /** @type {number} */ (instruction[1]);
  51291. var x1 = pixelCoordinates[d];
  51292. var y1 = pixelCoordinates[d + 1];
  51293. var x2 = pixelCoordinates[d + 2];
  51294. var y2 = pixelCoordinates[d + 3];
  51295. var dx = x2 - x1;
  51296. var dy = y2 - y1;
  51297. var r = Math.sqrt(dx * dx + dy * dy);
  51298. context.arc(x1, y1, r, 0, 2 * Math.PI, true);
  51299. ++i;
  51300. break;
  51301. case ol.render.canvas.Instruction.CLOSE_PATH:
  51302. context.closePath();
  51303. ++i;
  51304. break;
  51305. case ol.render.canvas.Instruction.DRAW_IMAGE:
  51306. goog.asserts.assert(goog.isNumber(instruction[1]),
  51307. 'second instruction should be a number');
  51308. d = /** @type {number} */ (instruction[1]);
  51309. goog.asserts.assert(goog.isNumber(instruction[2]),
  51310. 'third instruction should be a number');
  51311. dd = /** @type {number} */ (instruction[2]);
  51312. var image = /** @type {HTMLCanvasElement|HTMLVideoElement|Image} */
  51313. (instruction[3]);
  51314. // Remaining arguments in DRAW_IMAGE are in alphabetical order
  51315. var anchorX = /** @type {number} */ (instruction[4]) * pixelRatio;
  51316. var anchorY = /** @type {number} */ (instruction[5]) * pixelRatio;
  51317. var height = /** @type {number} */ (instruction[6]);
  51318. var opacity = /** @type {number} */ (instruction[7]);
  51319. var originX = /** @type {number} */ (instruction[8]);
  51320. var originY = /** @type {number} */ (instruction[9]);
  51321. var rotateWithView = /** @type {boolean} */ (instruction[10]);
  51322. var rotation = /** @type {number} */ (instruction[11]);
  51323. var scale = /** @type {number} */ (instruction[12]);
  51324. var snapToPixel = /** @type {boolean} */ (instruction[13]);
  51325. var width = /** @type {number} */ (instruction[14]);
  51326. if (rotateWithView) {
  51327. rotation += viewRotation;
  51328. }
  51329. for (; d < dd; d += 2) {
  51330. x = pixelCoordinates[d] - anchorX;
  51331. y = pixelCoordinates[d + 1] - anchorY;
  51332. if (snapToPixel) {
  51333. x = (x + 0.5) | 0;
  51334. y = (y + 0.5) | 0;
  51335. }
  51336. if (scale != 1 || rotation !== 0) {
  51337. var centerX = x + anchorX;
  51338. var centerY = y + anchorY;
  51339. ol.vec.Mat4.makeTransform2D(
  51340. localTransform, centerX, centerY, scale, scale,
  51341. rotation, -centerX, -centerY);
  51342. context.setTransform(
  51343. goog.vec.Mat4.getElement(localTransform, 0, 0),
  51344. goog.vec.Mat4.getElement(localTransform, 1, 0),
  51345. goog.vec.Mat4.getElement(localTransform, 0, 1),
  51346. goog.vec.Mat4.getElement(localTransform, 1, 1),
  51347. goog.vec.Mat4.getElement(localTransform, 0, 3),
  51348. goog.vec.Mat4.getElement(localTransform, 1, 3));
  51349. }
  51350. var alpha = context.globalAlpha;
  51351. if (opacity != 1) {
  51352. context.globalAlpha = alpha * opacity;
  51353. }
  51354. context.drawImage(image, originX, originY, width, height,
  51355. x, y, width * pixelRatio, height * pixelRatio);
  51356. if (opacity != 1) {
  51357. context.globalAlpha = alpha;
  51358. }
  51359. if (scale != 1 || rotation !== 0) {
  51360. context.setTransform(1, 0, 0, 1, 0, 0);
  51361. }
  51362. }
  51363. ++i;
  51364. break;
  51365. case ol.render.canvas.Instruction.DRAW_TEXT:
  51366. goog.asserts.assert(goog.isNumber(instruction[1]),
  51367. '2nd instruction should be a number');
  51368. d = /** @type {number} */ (instruction[1]);
  51369. goog.asserts.assert(goog.isNumber(instruction[2]),
  51370. '3rd instruction should be a number');
  51371. dd = /** @type {number} */ (instruction[2]);
  51372. goog.asserts.assert(goog.isString(instruction[3]),
  51373. '4th instruction should be a string');
  51374. text = /** @type {string} */ (instruction[3]);
  51375. goog.asserts.assert(goog.isNumber(instruction[4]),
  51376. '5th instruction should be a number');
  51377. var offsetX = /** @type {number} */ (instruction[4]) * pixelRatio;
  51378. goog.asserts.assert(goog.isNumber(instruction[5]),
  51379. '6th instruction should be a number');
  51380. var offsetY = /** @type {number} */ (instruction[5]) * pixelRatio;
  51381. goog.asserts.assert(goog.isNumber(instruction[6]),
  51382. '7th instruction should be a number');
  51383. rotation = /** @type {number} */ (instruction[6]);
  51384. goog.asserts.assert(goog.isNumber(instruction[7]),
  51385. '8th instruction should be a number');
  51386. scale = /** @type {number} */ (instruction[7]) * pixelRatio;
  51387. goog.asserts.assert(goog.isBoolean(instruction[8]),
  51388. '9th instruction should be a boolean');
  51389. fill = /** @type {boolean} */ (instruction[8]);
  51390. goog.asserts.assert(goog.isBoolean(instruction[9]),
  51391. '10th instruction should be a boolean');
  51392. stroke = /** @type {boolean} */ (instruction[9]);
  51393. for (; d < dd; d += 2) {
  51394. x = pixelCoordinates[d] + offsetX;
  51395. y = pixelCoordinates[d + 1] + offsetY;
  51396. if (scale != 1 || rotation !== 0) {
  51397. ol.vec.Mat4.makeTransform2D(
  51398. localTransform, x, y, scale, scale, rotation, -x, -y);
  51399. context.setTransform(
  51400. goog.vec.Mat4.getElement(localTransform, 0, 0),
  51401. goog.vec.Mat4.getElement(localTransform, 1, 0),
  51402. goog.vec.Mat4.getElement(localTransform, 0, 1),
  51403. goog.vec.Mat4.getElement(localTransform, 1, 1),
  51404. goog.vec.Mat4.getElement(localTransform, 0, 3),
  51405. goog.vec.Mat4.getElement(localTransform, 1, 3));
  51406. }
  51407. if (stroke) {
  51408. context.strokeText(text, x, y);
  51409. }
  51410. if (fill) {
  51411. context.fillText(text, x, y);
  51412. }
  51413. if (scale != 1 || rotation !== 0) {
  51414. context.setTransform(1, 0, 0, 1, 0, 0);
  51415. }
  51416. }
  51417. ++i;
  51418. break;
  51419. case ol.render.canvas.Instruction.END_GEOMETRY:
  51420. if (featureCallback !== undefined) {
  51421. feature = /** @type {ol.Feature} */ (instruction[1]);
  51422. var result = featureCallback(feature);
  51423. if (result) {
  51424. return result;
  51425. }
  51426. }
  51427. ++i;
  51428. break;
  51429. case ol.render.canvas.Instruction.FILL:
  51430. context.fill();
  51431. ++i;
  51432. break;
  51433. case ol.render.canvas.Instruction.MOVE_TO_LINE_TO:
  51434. goog.asserts.assert(goog.isNumber(instruction[1]),
  51435. '2nd instruction should be a number');
  51436. d = /** @type {number} */ (instruction[1]);
  51437. goog.asserts.assert(goog.isNumber(instruction[2]),
  51438. '3rd instruction should be a number');
  51439. dd = /** @type {number} */ (instruction[2]);
  51440. context.moveTo(pixelCoordinates[d], pixelCoordinates[d + 1]);
  51441. for (d += 2; d < dd; d += 2) {
  51442. context.lineTo(pixelCoordinates[d], pixelCoordinates[d + 1]);
  51443. }
  51444. ++i;
  51445. break;
  51446. case ol.render.canvas.Instruction.SET_FILL_STYLE:
  51447. goog.asserts.assert(goog.isString(instruction[1]),
  51448. '2nd instruction should be a string');
  51449. context.fillStyle = /** @type {string} */ (instruction[1]);
  51450. ++i;
  51451. break;
  51452. case ol.render.canvas.Instruction.SET_STROKE_STYLE:
  51453. goog.asserts.assert(goog.isString(instruction[1]),
  51454. '2nd instruction should be a string');
  51455. goog.asserts.assert(goog.isNumber(instruction[2]),
  51456. '3rd instruction should be a number');
  51457. goog.asserts.assert(goog.isString(instruction[3]),
  51458. '4rd instruction should be a string');
  51459. goog.asserts.assert(goog.isString(instruction[4]),
  51460. '5th instruction should be a string');
  51461. goog.asserts.assert(goog.isNumber(instruction[5]),
  51462. '6th instruction should be a number');
  51463. goog.asserts.assert(instruction[6],
  51464. '7th instruction should not be null');
  51465. var usePixelRatio = instruction[7] !== undefined ?
  51466. instruction[7] : true;
  51467. var lineWidth = /** @type {number} */ (instruction[2]);
  51468. context.strokeStyle = /** @type {string} */ (instruction[1]);
  51469. context.lineWidth = usePixelRatio ? lineWidth * pixelRatio : lineWidth;
  51470. context.lineCap = /** @type {string} */ (instruction[3]);
  51471. context.lineJoin = /** @type {string} */ (instruction[4]);
  51472. context.miterLimit = /** @type {number} */ (instruction[5]);
  51473. if (ol.has.CANVAS_LINE_DASH) {
  51474. context.setLineDash(/** @type {Array.<number>} */ (instruction[6]));
  51475. }
  51476. ++i;
  51477. break;
  51478. case ol.render.canvas.Instruction.SET_TEXT_STYLE:
  51479. goog.asserts.assert(goog.isString(instruction[1]),
  51480. '2nd instruction should be a string');
  51481. goog.asserts.assert(goog.isString(instruction[2]),
  51482. '3rd instruction should be a string');
  51483. goog.asserts.assert(goog.isString(instruction[3]),
  51484. '4th instruction should be a string');
  51485. context.font = /** @type {string} */ (instruction[1]);
  51486. context.textAlign = /** @type {string} */ (instruction[2]);
  51487. context.textBaseline = /** @type {string} */ (instruction[3]);
  51488. ++i;
  51489. break;
  51490. case ol.render.canvas.Instruction.STROKE:
  51491. context.stroke();
  51492. ++i;
  51493. break;
  51494. default:
  51495. goog.asserts.fail('Unknown canvas render instruction');
  51496. ++i; // consume the instruction anyway, to avoid an infinite loop
  51497. break;
  51498. }
  51499. }
  51500. // assert that all instructions were consumed
  51501. goog.asserts.assert(i == instructions.length,
  51502. 'all instructions should be consumed');
  51503. return undefined;
  51504. };
  51505. /**
  51506. * @param {CanvasRenderingContext2D} context Context.
  51507. * @param {number} pixelRatio Pixel ratio.
  51508. * @param {goog.vec.Mat4.Number} transform Transform.
  51509. * @param {number} viewRotation View rotation.
  51510. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  51511. * to skip.
  51512. */
  51513. ol.render.canvas.Replay.prototype.replay = function(
  51514. context, pixelRatio, transform, viewRotation, skippedFeaturesHash) {
  51515. var instructions = this.instructions;
  51516. this.replay_(context, pixelRatio, transform, viewRotation,
  51517. skippedFeaturesHash, instructions, undefined);
  51518. };
  51519. /**
  51520. * @param {CanvasRenderingContext2D} context Context.
  51521. * @param {goog.vec.Mat4.Number} transform Transform.
  51522. * @param {number} viewRotation View rotation.
  51523. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  51524. * to skip.
  51525. * @param {function(ol.Feature): T=} opt_featureCallback Feature callback.
  51526. * @param {ol.Extent=} opt_hitExtent Only check features that intersect this
  51527. * extent.
  51528. * @return {T|undefined} Callback result.
  51529. * @template T
  51530. */
  51531. ol.render.canvas.Replay.prototype.replayHitDetection = function(
  51532. context, transform, viewRotation, skippedFeaturesHash,
  51533. opt_featureCallback, opt_hitExtent) {
  51534. var instructions = this.hitDetectionInstructions;
  51535. return this.replay_(context, 1, transform, viewRotation,
  51536. skippedFeaturesHash, instructions, opt_featureCallback, opt_hitExtent);
  51537. };
  51538. /**
  51539. * @private
  51540. */
  51541. ol.render.canvas.Replay.prototype.reverseHitDetectionInstructions_ =
  51542. function() {
  51543. var hitDetectionInstructions = this.hitDetectionInstructions;
  51544. // step 1 - reverse array
  51545. hitDetectionInstructions.reverse();
  51546. // step 2 - reverse instructions within geometry blocks
  51547. var i;
  51548. var n = hitDetectionInstructions.length;
  51549. var instruction;
  51550. var type;
  51551. var begin = -1;
  51552. for (i = 0; i < n; ++i) {
  51553. instruction = hitDetectionInstructions[i];
  51554. type = /** @type {ol.render.canvas.Instruction} */ (instruction[0]);
  51555. if (type == ol.render.canvas.Instruction.END_GEOMETRY) {
  51556. goog.asserts.assert(begin == -1, 'begin should be -1');
  51557. begin = i;
  51558. } else if (type == ol.render.canvas.Instruction.BEGIN_GEOMETRY) {
  51559. instruction[2] = i;
  51560. goog.asserts.assert(begin >= 0,
  51561. 'begin should be larger than or equal to 0');
  51562. ol.array.reverseSubArray(this.hitDetectionInstructions, begin, i);
  51563. begin = -1;
  51564. }
  51565. }
  51566. };
  51567. /**
  51568. * @param {ol.geom.Geometry} geometry Geometry.
  51569. * @param {ol.Feature} feature Feature.
  51570. */
  51571. ol.render.canvas.Replay.prototype.endGeometry = function(geometry, feature) {
  51572. goog.asserts.assert(this.beginGeometryInstruction1_,
  51573. 'this.beginGeometryInstruction1_ should not be null');
  51574. this.beginGeometryInstruction1_[2] = this.instructions.length;
  51575. this.beginGeometryInstruction1_ = null;
  51576. goog.asserts.assert(this.beginGeometryInstruction2_,
  51577. 'this.beginGeometryInstruction2_ should not be null');
  51578. this.beginGeometryInstruction2_[2] = this.hitDetectionInstructions.length;
  51579. this.beginGeometryInstruction2_ = null;
  51580. var endGeometryInstruction =
  51581. [ol.render.canvas.Instruction.END_GEOMETRY, feature];
  51582. this.instructions.push(endGeometryInstruction);
  51583. this.hitDetectionInstructions.push(endGeometryInstruction);
  51584. };
  51585. /**
  51586. * FIXME empty description for jsdoc
  51587. */
  51588. ol.render.canvas.Replay.prototype.finish = ol.nullFunction;
  51589. /**
  51590. * Get the buffered rendering extent. Rendering will be clipped to the extent
  51591. * provided to the constructor. To account for symbolizers that may intersect
  51592. * this extent, we calculate a buffered extent (e.g. based on stroke width).
  51593. * @return {ol.Extent} The buffered rendering extent.
  51594. * @protected
  51595. */
  51596. ol.render.canvas.Replay.prototype.getBufferedMaxExtent = function() {
  51597. return this.maxExtent;
  51598. };
  51599. /**
  51600. * @constructor
  51601. * @extends {ol.render.canvas.Replay}
  51602. * @param {number} tolerance Tolerance.
  51603. * @param {ol.Extent} maxExtent Maximum extent.
  51604. * @param {number} resolution Resolution.
  51605. * @protected
  51606. * @struct
  51607. */
  51608. ol.render.canvas.ImageReplay = function(tolerance, maxExtent, resolution) {
  51609. goog.base(this, tolerance, maxExtent, resolution);
  51610. /**
  51611. * @private
  51612. * @type {HTMLCanvasElement|HTMLVideoElement|Image}
  51613. */
  51614. this.hitDetectionImage_ = null;
  51615. /**
  51616. * @private
  51617. * @type {HTMLCanvasElement|HTMLVideoElement|Image}
  51618. */
  51619. this.image_ = null;
  51620. /**
  51621. * @private
  51622. * @type {number|undefined}
  51623. */
  51624. this.anchorX_ = undefined;
  51625. /**
  51626. * @private
  51627. * @type {number|undefined}
  51628. */
  51629. this.anchorY_ = undefined;
  51630. /**
  51631. * @private
  51632. * @type {number|undefined}
  51633. */
  51634. this.height_ = undefined;
  51635. /**
  51636. * @private
  51637. * @type {number|undefined}
  51638. */
  51639. this.opacity_ = undefined;
  51640. /**
  51641. * @private
  51642. * @type {number|undefined}
  51643. */
  51644. this.originX_ = undefined;
  51645. /**
  51646. * @private
  51647. * @type {number|undefined}
  51648. */
  51649. this.originY_ = undefined;
  51650. /**
  51651. * @private
  51652. * @type {boolean|undefined}
  51653. */
  51654. this.rotateWithView_ = undefined;
  51655. /**
  51656. * @private
  51657. * @type {number|undefined}
  51658. */
  51659. this.rotation_ = undefined;
  51660. /**
  51661. * @private
  51662. * @type {number|undefined}
  51663. */
  51664. this.scale_ = undefined;
  51665. /**
  51666. * @private
  51667. * @type {boolean|undefined}
  51668. */
  51669. this.snapToPixel_ = undefined;
  51670. /**
  51671. * @private
  51672. * @type {number|undefined}
  51673. */
  51674. this.width_ = undefined;
  51675. };
  51676. goog.inherits(ol.render.canvas.ImageReplay, ol.render.canvas.Replay);
  51677. /**
  51678. * @param {Array.<number>} flatCoordinates Flat coordinates.
  51679. * @param {number} offset Offset.
  51680. * @param {number} end End.
  51681. * @param {number} stride Stride.
  51682. * @private
  51683. * @return {number} My end.
  51684. */
  51685. ol.render.canvas.ImageReplay.prototype.drawCoordinates_ =
  51686. function(flatCoordinates, offset, end, stride) {
  51687. return this.appendFlatCoordinates(
  51688. flatCoordinates, offset, end, stride, false);
  51689. };
  51690. /**
  51691. * @inheritDoc
  51692. */
  51693. ol.render.canvas.ImageReplay.prototype.drawPointGeometry =
  51694. function(pointGeometry, feature) {
  51695. if (!this.image_) {
  51696. return;
  51697. }
  51698. goog.asserts.assert(this.anchorX_ !== undefined,
  51699. 'this.anchorX_ should be defined');
  51700. goog.asserts.assert(this.anchorY_ !== undefined,
  51701. 'this.anchorY_ should be defined');
  51702. goog.asserts.assert(this.height_ !== undefined,
  51703. 'this.height_ should be defined');
  51704. goog.asserts.assert(this.opacity_ !== undefined,
  51705. 'this.opacity_ should be defined');
  51706. goog.asserts.assert(this.originX_ !== undefined,
  51707. 'this.originX_ should be defined');
  51708. goog.asserts.assert(this.originY_ !== undefined,
  51709. 'this.originY_ should be defined');
  51710. goog.asserts.assert(this.rotateWithView_ !== undefined,
  51711. 'this.rotateWithView_ should be defined');
  51712. goog.asserts.assert(this.rotation_ !== undefined,
  51713. 'this.rotation_ should be defined');
  51714. goog.asserts.assert(this.scale_ !== undefined,
  51715. 'this.scale_ should be defined');
  51716. goog.asserts.assert(this.width_ !== undefined,
  51717. 'this.width_ should be defined');
  51718. this.beginGeometry(pointGeometry, feature);
  51719. var flatCoordinates = pointGeometry.getFlatCoordinates();
  51720. var stride = pointGeometry.getStride();
  51721. var myBegin = this.coordinates.length;
  51722. var myEnd = this.drawCoordinates_(
  51723. flatCoordinates, 0, flatCoordinates.length, stride);
  51724. this.instructions.push([
  51725. ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd, this.image_,
  51726. // Remaining arguments to DRAW_IMAGE are in alphabetical order
  51727. this.anchorX_, this.anchorY_, this.height_, this.opacity_,
  51728. this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
  51729. this.scale_, this.snapToPixel_, this.width_
  51730. ]);
  51731. this.hitDetectionInstructions.push([
  51732. ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd,
  51733. this.hitDetectionImage_,
  51734. // Remaining arguments to DRAW_IMAGE are in alphabetical order
  51735. this.anchorX_, this.anchorY_, this.height_, this.opacity_,
  51736. this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
  51737. this.scale_, this.snapToPixel_, this.width_
  51738. ]);
  51739. this.endGeometry(pointGeometry, feature);
  51740. };
  51741. /**
  51742. * @inheritDoc
  51743. */
  51744. ol.render.canvas.ImageReplay.prototype.drawMultiPointGeometry =
  51745. function(multiPointGeometry, feature) {
  51746. if (!this.image_) {
  51747. return;
  51748. }
  51749. goog.asserts.assert(this.anchorX_ !== undefined,
  51750. 'this.anchorX_ should be defined');
  51751. goog.asserts.assert(this.anchorY_ !== undefined,
  51752. 'this.anchorY_ should be defined');
  51753. goog.asserts.assert(this.height_ !== undefined,
  51754. 'this.height_ should be defined');
  51755. goog.asserts.assert(this.opacity_ !== undefined,
  51756. 'this.opacity_ should be defined');
  51757. goog.asserts.assert(this.originX_ !== undefined,
  51758. 'this.originX_ should be defined');
  51759. goog.asserts.assert(this.originY_ !== undefined,
  51760. 'this.originY_ should be defined');
  51761. goog.asserts.assert(this.rotateWithView_ !== undefined,
  51762. 'this.rotateWithView_ should be defined');
  51763. goog.asserts.assert(this.rotation_ !== undefined,
  51764. 'this.rotation_ should be defined');
  51765. goog.asserts.assert(this.scale_ !== undefined,
  51766. 'this.scale_ should be defined');
  51767. goog.asserts.assert(this.width_ !== undefined,
  51768. 'this.width_ should be defined');
  51769. this.beginGeometry(multiPointGeometry, feature);
  51770. var flatCoordinates = multiPointGeometry.getFlatCoordinates();
  51771. var stride = multiPointGeometry.getStride();
  51772. var myBegin = this.coordinates.length;
  51773. var myEnd = this.drawCoordinates_(
  51774. flatCoordinates, 0, flatCoordinates.length, stride);
  51775. this.instructions.push([
  51776. ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd, this.image_,
  51777. // Remaining arguments to DRAW_IMAGE are in alphabetical order
  51778. this.anchorX_, this.anchorY_, this.height_, this.opacity_,
  51779. this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
  51780. this.scale_, this.snapToPixel_, this.width_
  51781. ]);
  51782. this.hitDetectionInstructions.push([
  51783. ol.render.canvas.Instruction.DRAW_IMAGE, myBegin, myEnd,
  51784. this.hitDetectionImage_,
  51785. // Remaining arguments to DRAW_IMAGE are in alphabetical order
  51786. this.anchorX_, this.anchorY_, this.height_, this.opacity_,
  51787. this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
  51788. this.scale_, this.snapToPixel_, this.width_
  51789. ]);
  51790. this.endGeometry(multiPointGeometry, feature);
  51791. };
  51792. /**
  51793. * @inheritDoc
  51794. */
  51795. ol.render.canvas.ImageReplay.prototype.finish = function() {
  51796. this.reverseHitDetectionInstructions_();
  51797. // FIXME this doesn't really protect us against further calls to draw*Geometry
  51798. this.anchorX_ = undefined;
  51799. this.anchorY_ = undefined;
  51800. this.hitDetectionImage_ = null;
  51801. this.image_ = null;
  51802. this.height_ = undefined;
  51803. this.scale_ = undefined;
  51804. this.opacity_ = undefined;
  51805. this.originX_ = undefined;
  51806. this.originY_ = undefined;
  51807. this.rotateWithView_ = undefined;
  51808. this.rotation_ = undefined;
  51809. this.snapToPixel_ = undefined;
  51810. this.width_ = undefined;
  51811. };
  51812. /**
  51813. * @inheritDoc
  51814. */
  51815. ol.render.canvas.ImageReplay.prototype.setImageStyle = function(imageStyle) {
  51816. goog.asserts.assert(imageStyle, 'imageStyle should not be null');
  51817. var anchor = imageStyle.getAnchor();
  51818. goog.asserts.assert(anchor, 'anchor should not be null');
  51819. var size = imageStyle.getSize();
  51820. goog.asserts.assert(size, 'size should not be null');
  51821. var hitDetectionImage = imageStyle.getHitDetectionImage(1);
  51822. goog.asserts.assert(hitDetectionImage,
  51823. 'hitDetectionImage should not be null');
  51824. var image = imageStyle.getImage(1);
  51825. goog.asserts.assert(image, 'image should not be null');
  51826. var origin = imageStyle.getOrigin();
  51827. goog.asserts.assert(origin, 'origin should not be null');
  51828. this.anchorX_ = anchor[0];
  51829. this.anchorY_ = anchor[1];
  51830. this.hitDetectionImage_ = hitDetectionImage;
  51831. this.image_ = image;
  51832. this.height_ = size[1];
  51833. this.opacity_ = imageStyle.getOpacity();
  51834. this.originX_ = origin[0];
  51835. this.originY_ = origin[1];
  51836. this.rotateWithView_ = imageStyle.getRotateWithView();
  51837. this.rotation_ = imageStyle.getRotation();
  51838. this.scale_ = imageStyle.getScale();
  51839. this.snapToPixel_ = imageStyle.getSnapToPixel();
  51840. this.width_ = size[0];
  51841. };
  51842. /**
  51843. * @constructor
  51844. * @extends {ol.render.canvas.Replay}
  51845. * @param {number} tolerance Tolerance.
  51846. * @param {ol.Extent} maxExtent Maximum extent.
  51847. * @param {number} resolution Resolution.
  51848. * @protected
  51849. * @struct
  51850. */
  51851. ol.render.canvas.LineStringReplay = function(tolerance, maxExtent, resolution) {
  51852. goog.base(this, tolerance, maxExtent, resolution);
  51853. /**
  51854. * @private
  51855. * @type {{currentStrokeStyle: (string|undefined),
  51856. * currentLineCap: (string|undefined),
  51857. * currentLineDash: Array.<number>,
  51858. * currentLineJoin: (string|undefined),
  51859. * currentLineWidth: (number|undefined),
  51860. * currentMiterLimit: (number|undefined),
  51861. * lastStroke: number,
  51862. * strokeStyle: (string|undefined),
  51863. * lineCap: (string|undefined),
  51864. * lineDash: Array.<number>,
  51865. * lineJoin: (string|undefined),
  51866. * lineWidth: (number|undefined),
  51867. * miterLimit: (number|undefined)}|null}
  51868. */
  51869. this.state_ = {
  51870. currentStrokeStyle: undefined,
  51871. currentLineCap: undefined,
  51872. currentLineDash: null,
  51873. currentLineJoin: undefined,
  51874. currentLineWidth: undefined,
  51875. currentMiterLimit: undefined,
  51876. lastStroke: 0,
  51877. strokeStyle: undefined,
  51878. lineCap: undefined,
  51879. lineDash: null,
  51880. lineJoin: undefined,
  51881. lineWidth: undefined,
  51882. miterLimit: undefined
  51883. };
  51884. };
  51885. goog.inherits(ol.render.canvas.LineStringReplay, ol.render.canvas.Replay);
  51886. /**
  51887. * @param {Array.<number>} flatCoordinates Flat coordinates.
  51888. * @param {number} offset Offset.
  51889. * @param {number} end End.
  51890. * @param {number} stride Stride.
  51891. * @private
  51892. * @return {number} end.
  51893. */
  51894. ol.render.canvas.LineStringReplay.prototype.drawFlatCoordinates_ =
  51895. function(flatCoordinates, offset, end, stride) {
  51896. var myBegin = this.coordinates.length;
  51897. var myEnd = this.appendFlatCoordinates(
  51898. flatCoordinates, offset, end, stride, false);
  51899. var moveToLineToInstruction =
  51900. [ol.render.canvas.Instruction.MOVE_TO_LINE_TO, myBegin, myEnd];
  51901. this.instructions.push(moveToLineToInstruction);
  51902. this.hitDetectionInstructions.push(moveToLineToInstruction);
  51903. return end;
  51904. };
  51905. /**
  51906. * @inheritDoc
  51907. */
  51908. ol.render.canvas.LineStringReplay.prototype.getBufferedMaxExtent = function() {
  51909. if (!this.bufferedMaxExtent_) {
  51910. this.bufferedMaxExtent_ = ol.extent.clone(this.maxExtent);
  51911. if (this.maxLineWidth > 0) {
  51912. var width = this.resolution * (this.maxLineWidth + 1) / 2;
  51913. ol.extent.buffer(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_);
  51914. }
  51915. }
  51916. return this.bufferedMaxExtent_;
  51917. };
  51918. /**
  51919. * @private
  51920. */
  51921. ol.render.canvas.LineStringReplay.prototype.setStrokeStyle_ = function() {
  51922. var state = this.state_;
  51923. var strokeStyle = state.strokeStyle;
  51924. var lineCap = state.lineCap;
  51925. var lineDash = state.lineDash;
  51926. var lineJoin = state.lineJoin;
  51927. var lineWidth = state.lineWidth;
  51928. var miterLimit = state.miterLimit;
  51929. goog.asserts.assert(strokeStyle !== undefined,
  51930. 'strokeStyle should be defined');
  51931. goog.asserts.assert(lineCap !== undefined, 'lineCap should be defined');
  51932. goog.asserts.assert(lineDash, 'lineDash should not be null');
  51933. goog.asserts.assert(lineJoin !== undefined, 'lineJoin should be defined');
  51934. goog.asserts.assert(lineWidth !== undefined, 'lineWidth should be defined');
  51935. goog.asserts.assert(miterLimit !== undefined, 'miterLimit should be defined');
  51936. if (state.currentStrokeStyle != strokeStyle ||
  51937. state.currentLineCap != lineCap ||
  51938. !goog.array.equals(state.currentLineDash, lineDash) ||
  51939. state.currentLineJoin != lineJoin ||
  51940. state.currentLineWidth != lineWidth ||
  51941. state.currentMiterLimit != miterLimit) {
  51942. if (state.lastStroke != this.coordinates.length) {
  51943. this.instructions.push(
  51944. [ol.render.canvas.Instruction.STROKE]);
  51945. state.lastStroke = this.coordinates.length;
  51946. }
  51947. this.instructions.push(
  51948. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  51949. strokeStyle, lineWidth, lineCap, lineJoin, miterLimit, lineDash],
  51950. [ol.render.canvas.Instruction.BEGIN_PATH]);
  51951. state.currentStrokeStyle = strokeStyle;
  51952. state.currentLineCap = lineCap;
  51953. state.currentLineDash = lineDash;
  51954. state.currentLineJoin = lineJoin;
  51955. state.currentLineWidth = lineWidth;
  51956. state.currentMiterLimit = miterLimit;
  51957. }
  51958. };
  51959. /**
  51960. * @inheritDoc
  51961. */
  51962. ol.render.canvas.LineStringReplay.prototype.drawLineStringGeometry =
  51963. function(lineStringGeometry, feature) {
  51964. var state = this.state_;
  51965. goog.asserts.assert(state, 'state should not be null');
  51966. var strokeStyle = state.strokeStyle;
  51967. var lineWidth = state.lineWidth;
  51968. if (strokeStyle === undefined || lineWidth === undefined) {
  51969. return;
  51970. }
  51971. this.setStrokeStyle_();
  51972. this.beginGeometry(lineStringGeometry, feature);
  51973. this.hitDetectionInstructions.push(
  51974. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  51975. state.strokeStyle, state.lineWidth, state.lineCap, state.lineJoin,
  51976. state.miterLimit, state.lineDash],
  51977. [ol.render.canvas.Instruction.BEGIN_PATH]);
  51978. var flatCoordinates = lineStringGeometry.getFlatCoordinates();
  51979. var stride = lineStringGeometry.getStride();
  51980. this.drawFlatCoordinates_(
  51981. flatCoordinates, 0, flatCoordinates.length, stride);
  51982. this.hitDetectionInstructions.push([ol.render.canvas.Instruction.STROKE]);
  51983. this.endGeometry(lineStringGeometry, feature);
  51984. };
  51985. /**
  51986. * @inheritDoc
  51987. */
  51988. ol.render.canvas.LineStringReplay.prototype.drawMultiLineStringGeometry =
  51989. function(multiLineStringGeometry, feature) {
  51990. var state = this.state_;
  51991. goog.asserts.assert(state, 'state should not be null');
  51992. var strokeStyle = state.strokeStyle;
  51993. var lineWidth = state.lineWidth;
  51994. if (strokeStyle === undefined || lineWidth === undefined) {
  51995. return;
  51996. }
  51997. this.setStrokeStyle_();
  51998. this.beginGeometry(multiLineStringGeometry, feature);
  51999. this.hitDetectionInstructions.push(
  52000. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  52001. state.strokeStyle, state.lineWidth, state.lineCap, state.lineJoin,
  52002. state.miterLimit, state.lineDash],
  52003. [ol.render.canvas.Instruction.BEGIN_PATH]);
  52004. var ends = multiLineStringGeometry.getEnds();
  52005. var flatCoordinates = multiLineStringGeometry.getFlatCoordinates();
  52006. var stride = multiLineStringGeometry.getStride();
  52007. var offset = 0;
  52008. var i, ii;
  52009. for (i = 0, ii = ends.length; i < ii; ++i) {
  52010. offset = this.drawFlatCoordinates_(
  52011. flatCoordinates, offset, ends[i], stride);
  52012. }
  52013. this.hitDetectionInstructions.push([ol.render.canvas.Instruction.STROKE]);
  52014. this.endGeometry(multiLineStringGeometry, feature);
  52015. };
  52016. /**
  52017. * @inheritDoc
  52018. */
  52019. ol.render.canvas.LineStringReplay.prototype.finish = function() {
  52020. var state = this.state_;
  52021. goog.asserts.assert(state, 'state should not be null');
  52022. if (state.lastStroke != this.coordinates.length) {
  52023. this.instructions.push([ol.render.canvas.Instruction.STROKE]);
  52024. }
  52025. this.reverseHitDetectionInstructions_();
  52026. this.state_ = null;
  52027. };
  52028. /**
  52029. * @inheritDoc
  52030. */
  52031. ol.render.canvas.LineStringReplay.prototype.setFillStrokeStyle =
  52032. function(fillStyle, strokeStyle) {
  52033. goog.asserts.assert(this.state_, 'this.state_ should not be null');
  52034. goog.asserts.assert(!fillStyle, 'fillStyle should be null');
  52035. goog.asserts.assert(strokeStyle, 'strokeStyle should not be null');
  52036. var strokeStyleColor = strokeStyle.getColor();
  52037. this.state_.strokeStyle = ol.color.asString(strokeStyleColor ?
  52038. strokeStyleColor : ol.render.canvas.defaultStrokeStyle);
  52039. var strokeStyleLineCap = strokeStyle.getLineCap();
  52040. this.state_.lineCap = strokeStyleLineCap !== undefined ?
  52041. strokeStyleLineCap : ol.render.canvas.defaultLineCap;
  52042. var strokeStyleLineDash = strokeStyle.getLineDash();
  52043. this.state_.lineDash = strokeStyleLineDash ?
  52044. strokeStyleLineDash : ol.render.canvas.defaultLineDash;
  52045. var strokeStyleLineJoin = strokeStyle.getLineJoin();
  52046. this.state_.lineJoin = strokeStyleLineJoin !== undefined ?
  52047. strokeStyleLineJoin : ol.render.canvas.defaultLineJoin;
  52048. var strokeStyleWidth = strokeStyle.getWidth();
  52049. this.state_.lineWidth = strokeStyleWidth !== undefined ?
  52050. strokeStyleWidth : ol.render.canvas.defaultLineWidth;
  52051. var strokeStyleMiterLimit = strokeStyle.getMiterLimit();
  52052. this.state_.miterLimit = strokeStyleMiterLimit !== undefined ?
  52053. strokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit;
  52054. if (this.state_.lineWidth > this.maxLineWidth) {
  52055. this.maxLineWidth = this.state_.lineWidth;
  52056. // invalidate the buffered max extent cache
  52057. this.bufferedMaxExtent_ = null;
  52058. }
  52059. };
  52060. /**
  52061. * @constructor
  52062. * @extends {ol.render.canvas.Replay}
  52063. * @param {number} tolerance Tolerance.
  52064. * @param {ol.Extent} maxExtent Maximum extent.
  52065. * @param {number} resolution Resolution.
  52066. * @protected
  52067. * @struct
  52068. */
  52069. ol.render.canvas.PolygonReplay = function(tolerance, maxExtent, resolution) {
  52070. goog.base(this, tolerance, maxExtent, resolution);
  52071. /**
  52072. * @private
  52073. * @type {{currentFillStyle: (string|undefined),
  52074. * currentStrokeStyle: (string|undefined),
  52075. * currentLineCap: (string|undefined),
  52076. * currentLineDash: Array.<number>,
  52077. * currentLineJoin: (string|undefined),
  52078. * currentLineWidth: (number|undefined),
  52079. * currentMiterLimit: (number|undefined),
  52080. * fillStyle: (string|undefined),
  52081. * strokeStyle: (string|undefined),
  52082. * lineCap: (string|undefined),
  52083. * lineDash: Array.<number>,
  52084. * lineJoin: (string|undefined),
  52085. * lineWidth: (number|undefined),
  52086. * miterLimit: (number|undefined)}|null}
  52087. */
  52088. this.state_ = {
  52089. currentFillStyle: undefined,
  52090. currentStrokeStyle: undefined,
  52091. currentLineCap: undefined,
  52092. currentLineDash: null,
  52093. currentLineJoin: undefined,
  52094. currentLineWidth: undefined,
  52095. currentMiterLimit: undefined,
  52096. fillStyle: undefined,
  52097. strokeStyle: undefined,
  52098. lineCap: undefined,
  52099. lineDash: null,
  52100. lineJoin: undefined,
  52101. lineWidth: undefined,
  52102. miterLimit: undefined
  52103. };
  52104. };
  52105. goog.inherits(ol.render.canvas.PolygonReplay, ol.render.canvas.Replay);
  52106. /**
  52107. * @param {Array.<number>} flatCoordinates Flat coordinates.
  52108. * @param {number} offset Offset.
  52109. * @param {Array.<number>} ends Ends.
  52110. * @param {number} stride Stride.
  52111. * @private
  52112. * @return {number} End.
  52113. */
  52114. ol.render.canvas.PolygonReplay.prototype.drawFlatCoordinatess_ =
  52115. function(flatCoordinates, offset, ends, stride) {
  52116. var state = this.state_;
  52117. var beginPathInstruction = [ol.render.canvas.Instruction.BEGIN_PATH];
  52118. this.instructions.push(beginPathInstruction);
  52119. this.hitDetectionInstructions.push(beginPathInstruction);
  52120. var i, ii;
  52121. for (i = 0, ii = ends.length; i < ii; ++i) {
  52122. var end = ends[i];
  52123. var myBegin = this.coordinates.length;
  52124. var myEnd = this.appendFlatCoordinates(
  52125. flatCoordinates, offset, end, stride, true);
  52126. var moveToLineToInstruction =
  52127. [ol.render.canvas.Instruction.MOVE_TO_LINE_TO, myBegin, myEnd];
  52128. var closePathInstruction = [ol.render.canvas.Instruction.CLOSE_PATH];
  52129. this.instructions.push(moveToLineToInstruction, closePathInstruction);
  52130. this.hitDetectionInstructions.push(moveToLineToInstruction,
  52131. closePathInstruction);
  52132. offset = end;
  52133. }
  52134. // FIXME is it quicker to fill and stroke each polygon individually,
  52135. // FIXME or all polygons together?
  52136. var fillInstruction = [ol.render.canvas.Instruction.FILL];
  52137. this.hitDetectionInstructions.push(fillInstruction);
  52138. if (state.fillStyle !== undefined) {
  52139. this.instructions.push(fillInstruction);
  52140. }
  52141. if (state.strokeStyle !== undefined) {
  52142. goog.asserts.assert(state.lineWidth !== undefined,
  52143. 'state.lineWidth should be defined');
  52144. var strokeInstruction = [ol.render.canvas.Instruction.STROKE];
  52145. this.instructions.push(strokeInstruction);
  52146. this.hitDetectionInstructions.push(strokeInstruction);
  52147. }
  52148. return offset;
  52149. };
  52150. /**
  52151. * @inheritDoc
  52152. */
  52153. ol.render.canvas.PolygonReplay.prototype.drawCircleGeometry =
  52154. function(circleGeometry, feature) {
  52155. var state = this.state_;
  52156. goog.asserts.assert(state, 'state should not be null');
  52157. var fillStyle = state.fillStyle;
  52158. var strokeStyle = state.strokeStyle;
  52159. if (fillStyle === undefined && strokeStyle === undefined) {
  52160. return;
  52161. }
  52162. if (strokeStyle !== undefined) {
  52163. goog.asserts.assert(state.lineWidth !== undefined,
  52164. 'state.lineWidth should be defined');
  52165. }
  52166. this.setFillStrokeStyles_();
  52167. this.beginGeometry(circleGeometry, feature);
  52168. // always fill the circle for hit detection
  52169. this.hitDetectionInstructions.push(
  52170. [ol.render.canvas.Instruction.SET_FILL_STYLE,
  52171. ol.color.asString(ol.render.canvas.defaultFillStyle)]);
  52172. if (state.strokeStyle !== undefined) {
  52173. this.hitDetectionInstructions.push(
  52174. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  52175. state.strokeStyle, state.lineWidth, state.lineCap, state.lineJoin,
  52176. state.miterLimit, state.lineDash]);
  52177. }
  52178. var flatCoordinates = circleGeometry.getFlatCoordinates();
  52179. var stride = circleGeometry.getStride();
  52180. var myBegin = this.coordinates.length;
  52181. this.appendFlatCoordinates(
  52182. flatCoordinates, 0, flatCoordinates.length, stride, false);
  52183. var beginPathInstruction = [ol.render.canvas.Instruction.BEGIN_PATH];
  52184. var circleInstruction = [ol.render.canvas.Instruction.CIRCLE, myBegin];
  52185. this.instructions.push(beginPathInstruction, circleInstruction);
  52186. this.hitDetectionInstructions.push(beginPathInstruction, circleInstruction);
  52187. var fillInstruction = [ol.render.canvas.Instruction.FILL];
  52188. this.hitDetectionInstructions.push(fillInstruction);
  52189. if (state.fillStyle !== undefined) {
  52190. this.instructions.push(fillInstruction);
  52191. }
  52192. if (state.strokeStyle !== undefined) {
  52193. goog.asserts.assert(state.lineWidth !== undefined,
  52194. 'state.lineWidth should be defined');
  52195. var strokeInstruction = [ol.render.canvas.Instruction.STROKE];
  52196. this.instructions.push(strokeInstruction);
  52197. this.hitDetectionInstructions.push(strokeInstruction);
  52198. }
  52199. this.endGeometry(circleGeometry, feature);
  52200. };
  52201. /**
  52202. * @inheritDoc
  52203. */
  52204. ol.render.canvas.PolygonReplay.prototype.drawPolygonGeometry =
  52205. function(polygonGeometry, feature) {
  52206. var state = this.state_;
  52207. goog.asserts.assert(state, 'state should not be null');
  52208. var fillStyle = state.fillStyle;
  52209. var strokeStyle = state.strokeStyle;
  52210. if (fillStyle === undefined && strokeStyle === undefined) {
  52211. return;
  52212. }
  52213. if (strokeStyle !== undefined) {
  52214. goog.asserts.assert(state.lineWidth !== undefined,
  52215. 'state.lineWidth should be defined');
  52216. }
  52217. this.setFillStrokeStyles_();
  52218. this.beginGeometry(polygonGeometry, feature);
  52219. // always fill the polygon for hit detection
  52220. this.hitDetectionInstructions.push(
  52221. [ol.render.canvas.Instruction.SET_FILL_STYLE,
  52222. ol.color.asString(ol.render.canvas.defaultFillStyle)]);
  52223. if (state.strokeStyle !== undefined) {
  52224. this.hitDetectionInstructions.push(
  52225. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  52226. state.strokeStyle, state.lineWidth, state.lineCap, state.lineJoin,
  52227. state.miterLimit, state.lineDash]);
  52228. }
  52229. var ends = polygonGeometry.getEnds();
  52230. var flatCoordinates = polygonGeometry.getOrientedFlatCoordinates();
  52231. var stride = polygonGeometry.getStride();
  52232. this.drawFlatCoordinatess_(flatCoordinates, 0, ends, stride);
  52233. this.endGeometry(polygonGeometry, feature);
  52234. };
  52235. /**
  52236. * @inheritDoc
  52237. */
  52238. ol.render.canvas.PolygonReplay.prototype.drawMultiPolygonGeometry =
  52239. function(multiPolygonGeometry, feature) {
  52240. var state = this.state_;
  52241. goog.asserts.assert(state, 'state should not be null');
  52242. var fillStyle = state.fillStyle;
  52243. var strokeStyle = state.strokeStyle;
  52244. if (fillStyle === undefined && strokeStyle === undefined) {
  52245. return;
  52246. }
  52247. if (strokeStyle !== undefined) {
  52248. goog.asserts.assert(state.lineWidth !== undefined,
  52249. 'state.lineWidth should be defined');
  52250. }
  52251. this.setFillStrokeStyles_();
  52252. this.beginGeometry(multiPolygonGeometry, feature);
  52253. // always fill the multi-polygon for hit detection
  52254. this.hitDetectionInstructions.push(
  52255. [ol.render.canvas.Instruction.SET_FILL_STYLE,
  52256. ol.color.asString(ol.render.canvas.defaultFillStyle)]);
  52257. if (state.strokeStyle !== undefined) {
  52258. this.hitDetectionInstructions.push(
  52259. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  52260. state.strokeStyle, state.lineWidth, state.lineCap, state.lineJoin,
  52261. state.miterLimit, state.lineDash]);
  52262. }
  52263. var endss = multiPolygonGeometry.getEndss();
  52264. var flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates();
  52265. var stride = multiPolygonGeometry.getStride();
  52266. var offset = 0;
  52267. var i, ii;
  52268. for (i = 0, ii = endss.length; i < ii; ++i) {
  52269. offset = this.drawFlatCoordinatess_(
  52270. flatCoordinates, offset, endss[i], stride);
  52271. }
  52272. this.endGeometry(multiPolygonGeometry, feature);
  52273. };
  52274. /**
  52275. * @inheritDoc
  52276. */
  52277. ol.render.canvas.PolygonReplay.prototype.finish = function() {
  52278. goog.asserts.assert(this.state_, 'this.state_ should not be null');
  52279. this.reverseHitDetectionInstructions_();
  52280. this.state_ = null;
  52281. // We want to preserve topology when drawing polygons. Polygons are
  52282. // simplified using quantization and point elimination. However, we might
  52283. // have received a mix of quantized and non-quantized geometries, so ensure
  52284. // that all are quantized by quantizing all coordinates in the batch.
  52285. var tolerance = this.tolerance;
  52286. if (tolerance !== 0) {
  52287. var coordinates = this.coordinates;
  52288. var i, ii;
  52289. for (i = 0, ii = coordinates.length; i < ii; ++i) {
  52290. coordinates[i] = ol.geom.flat.simplify.snap(coordinates[i], tolerance);
  52291. }
  52292. }
  52293. };
  52294. /**
  52295. * @inheritDoc
  52296. */
  52297. ol.render.canvas.PolygonReplay.prototype.getBufferedMaxExtent = function() {
  52298. if (!this.bufferedMaxExtent_) {
  52299. this.bufferedMaxExtent_ = ol.extent.clone(this.maxExtent);
  52300. if (this.maxLineWidth > 0) {
  52301. var width = this.resolution * (this.maxLineWidth + 1) / 2;
  52302. ol.extent.buffer(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_);
  52303. }
  52304. }
  52305. return this.bufferedMaxExtent_;
  52306. };
  52307. /**
  52308. * @inheritDoc
  52309. */
  52310. ol.render.canvas.PolygonReplay.prototype.setFillStrokeStyle =
  52311. function(fillStyle, strokeStyle) {
  52312. goog.asserts.assert(this.state_, 'this.state_ should not be null');
  52313. goog.asserts.assert(fillStyle || strokeStyle,
  52314. 'fillStyle or strokeStyle should not be null');
  52315. var state = this.state_;
  52316. if (fillStyle) {
  52317. var fillStyleColor = fillStyle.getColor();
  52318. state.fillStyle = ol.color.asString(fillStyleColor ?
  52319. fillStyleColor : ol.render.canvas.defaultFillStyle);
  52320. } else {
  52321. state.fillStyle = undefined;
  52322. }
  52323. if (strokeStyle) {
  52324. var strokeStyleColor = strokeStyle.getColor();
  52325. state.strokeStyle = ol.color.asString(strokeStyleColor ?
  52326. strokeStyleColor : ol.render.canvas.defaultStrokeStyle);
  52327. var strokeStyleLineCap = strokeStyle.getLineCap();
  52328. state.lineCap = strokeStyleLineCap !== undefined ?
  52329. strokeStyleLineCap : ol.render.canvas.defaultLineCap;
  52330. var strokeStyleLineDash = strokeStyle.getLineDash();
  52331. state.lineDash = strokeStyleLineDash ?
  52332. strokeStyleLineDash.slice() : ol.render.canvas.defaultLineDash;
  52333. var strokeStyleLineJoin = strokeStyle.getLineJoin();
  52334. state.lineJoin = strokeStyleLineJoin !== undefined ?
  52335. strokeStyleLineJoin : ol.render.canvas.defaultLineJoin;
  52336. var strokeStyleWidth = strokeStyle.getWidth();
  52337. state.lineWidth = strokeStyleWidth !== undefined ?
  52338. strokeStyleWidth : ol.render.canvas.defaultLineWidth;
  52339. var strokeStyleMiterLimit = strokeStyle.getMiterLimit();
  52340. state.miterLimit = strokeStyleMiterLimit !== undefined ?
  52341. strokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit;
  52342. if (state.lineWidth > this.maxLineWidth) {
  52343. this.maxLineWidth = state.lineWidth;
  52344. // invalidate the buffered max extent cache
  52345. this.bufferedMaxExtent_ = null;
  52346. }
  52347. } else {
  52348. state.strokeStyle = undefined;
  52349. state.lineCap = undefined;
  52350. state.lineDash = null;
  52351. state.lineJoin = undefined;
  52352. state.lineWidth = undefined;
  52353. state.miterLimit = undefined;
  52354. }
  52355. };
  52356. /**
  52357. * @private
  52358. */
  52359. ol.render.canvas.PolygonReplay.prototype.setFillStrokeStyles_ = function() {
  52360. var state = this.state_;
  52361. var fillStyle = state.fillStyle;
  52362. var strokeStyle = state.strokeStyle;
  52363. var lineCap = state.lineCap;
  52364. var lineDash = state.lineDash;
  52365. var lineJoin = state.lineJoin;
  52366. var lineWidth = state.lineWidth;
  52367. var miterLimit = state.miterLimit;
  52368. if (fillStyle !== undefined && state.currentFillStyle != fillStyle) {
  52369. this.instructions.push(
  52370. [ol.render.canvas.Instruction.SET_FILL_STYLE, fillStyle]);
  52371. state.currentFillStyle = state.fillStyle;
  52372. }
  52373. if (strokeStyle !== undefined) {
  52374. goog.asserts.assert(lineCap !== undefined, 'lineCap should be defined');
  52375. goog.asserts.assert(lineDash, 'lineDash should not be null');
  52376. goog.asserts.assert(lineJoin !== undefined, 'lineJoin should be defined');
  52377. goog.asserts.assert(lineWidth !== undefined, 'lineWidth should be defined');
  52378. goog.asserts.assert(miterLimit !== undefined,
  52379. 'miterLimit should be defined');
  52380. if (state.currentStrokeStyle != strokeStyle ||
  52381. state.currentLineCap != lineCap ||
  52382. state.currentLineDash != lineDash ||
  52383. state.currentLineJoin != lineJoin ||
  52384. state.currentLineWidth != lineWidth ||
  52385. state.currentMiterLimit != miterLimit) {
  52386. this.instructions.push(
  52387. [ol.render.canvas.Instruction.SET_STROKE_STYLE,
  52388. strokeStyle, lineWidth, lineCap, lineJoin, miterLimit, lineDash]);
  52389. state.currentStrokeStyle = strokeStyle;
  52390. state.currentLineCap = lineCap;
  52391. state.currentLineDash = lineDash;
  52392. state.currentLineJoin = lineJoin;
  52393. state.currentLineWidth = lineWidth;
  52394. state.currentMiterLimit = miterLimit;
  52395. }
  52396. }
  52397. };
  52398. /**
  52399. * @constructor
  52400. * @extends {ol.render.canvas.Replay}
  52401. * @param {number} tolerance Tolerance.
  52402. * @param {ol.Extent} maxExtent Maximum extent.
  52403. * @param {number} resolution Resolution.
  52404. * @protected
  52405. * @struct
  52406. */
  52407. ol.render.canvas.TextReplay = function(tolerance, maxExtent, resolution) {
  52408. goog.base(this, tolerance, maxExtent, resolution);
  52409. /**
  52410. * @private
  52411. * @type {?ol.render.canvas.FillState}
  52412. */
  52413. this.replayFillState_ = null;
  52414. /**
  52415. * @private
  52416. * @type {?ol.render.canvas.StrokeState}
  52417. */
  52418. this.replayStrokeState_ = null;
  52419. /**
  52420. * @private
  52421. * @type {?ol.render.canvas.TextState}
  52422. */
  52423. this.replayTextState_ = null;
  52424. /**
  52425. * @private
  52426. * @type {string}
  52427. */
  52428. this.text_ = '';
  52429. /**
  52430. * @private
  52431. * @type {number}
  52432. */
  52433. this.textOffsetX_ = 0;
  52434. /**
  52435. * @private
  52436. * @type {number}
  52437. */
  52438. this.textOffsetY_ = 0;
  52439. /**
  52440. * @private
  52441. * @type {number}
  52442. */
  52443. this.textRotation_ = 0;
  52444. /**
  52445. * @private
  52446. * @type {number}
  52447. */
  52448. this.textScale_ = 0;
  52449. /**
  52450. * @private
  52451. * @type {?ol.render.canvas.FillState}
  52452. */
  52453. this.textFillState_ = null;
  52454. /**
  52455. * @private
  52456. * @type {?ol.render.canvas.StrokeState}
  52457. */
  52458. this.textStrokeState_ = null;
  52459. /**
  52460. * @private
  52461. * @type {?ol.render.canvas.TextState}
  52462. */
  52463. this.textState_ = null;
  52464. };
  52465. goog.inherits(ol.render.canvas.TextReplay, ol.render.canvas.Replay);
  52466. /**
  52467. * @inheritDoc
  52468. */
  52469. ol.render.canvas.TextReplay.prototype.drawText =
  52470. function(flatCoordinates, offset, end, stride, geometry, feature) {
  52471. if (this.text_ === '' || !this.textState_ ||
  52472. (!this.textFillState_ && !this.textStrokeState_)) {
  52473. return;
  52474. }
  52475. if (this.textFillState_) {
  52476. this.setReplayFillState_(this.textFillState_);
  52477. }
  52478. if (this.textStrokeState_) {
  52479. this.setReplayStrokeState_(this.textStrokeState_);
  52480. }
  52481. this.setReplayTextState_(this.textState_);
  52482. this.beginGeometry(geometry, feature);
  52483. var myBegin = this.coordinates.length;
  52484. var myEnd =
  52485. this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false);
  52486. var fill = !!this.textFillState_;
  52487. var stroke = !!this.textStrokeState_;
  52488. var drawTextInstruction = [
  52489. ol.render.canvas.Instruction.DRAW_TEXT, myBegin, myEnd, this.text_,
  52490. this.textOffsetX_, this.textOffsetY_, this.textRotation_, this.textScale_,
  52491. fill, stroke];
  52492. this.instructions.push(drawTextInstruction);
  52493. this.hitDetectionInstructions.push(drawTextInstruction);
  52494. this.endGeometry(geometry, feature);
  52495. };
  52496. /**
  52497. * @param {ol.render.canvas.FillState} fillState Fill state.
  52498. * @private
  52499. */
  52500. ol.render.canvas.TextReplay.prototype.setReplayFillState_ =
  52501. function(fillState) {
  52502. var replayFillState = this.replayFillState_;
  52503. if (replayFillState &&
  52504. replayFillState.fillStyle == fillState.fillStyle) {
  52505. return;
  52506. }
  52507. var setFillStyleInstruction =
  52508. [ol.render.canvas.Instruction.SET_FILL_STYLE, fillState.fillStyle];
  52509. this.instructions.push(setFillStyleInstruction);
  52510. this.hitDetectionInstructions.push(setFillStyleInstruction);
  52511. if (!replayFillState) {
  52512. this.replayFillState_ = {
  52513. fillStyle: fillState.fillStyle
  52514. };
  52515. } else {
  52516. replayFillState.fillStyle = fillState.fillStyle;
  52517. }
  52518. };
  52519. /**
  52520. * @param {ol.render.canvas.StrokeState} strokeState Stroke state.
  52521. * @private
  52522. */
  52523. ol.render.canvas.TextReplay.prototype.setReplayStrokeState_ =
  52524. function(strokeState) {
  52525. var replayStrokeState = this.replayStrokeState_;
  52526. if (replayStrokeState &&
  52527. replayStrokeState.lineCap == strokeState.lineCap &&
  52528. replayStrokeState.lineDash == strokeState.lineDash &&
  52529. replayStrokeState.lineJoin == strokeState.lineJoin &&
  52530. replayStrokeState.lineWidth == strokeState.lineWidth &&
  52531. replayStrokeState.miterLimit == strokeState.miterLimit &&
  52532. replayStrokeState.strokeStyle == strokeState.strokeStyle) {
  52533. return;
  52534. }
  52535. var setStrokeStyleInstruction = [
  52536. ol.render.canvas.Instruction.SET_STROKE_STYLE, strokeState.strokeStyle,
  52537. strokeState.lineWidth, strokeState.lineCap, strokeState.lineJoin,
  52538. strokeState.miterLimit, strokeState.lineDash, false
  52539. ];
  52540. this.instructions.push(setStrokeStyleInstruction);
  52541. this.hitDetectionInstructions.push(setStrokeStyleInstruction);
  52542. if (!replayStrokeState) {
  52543. this.replayStrokeState_ = {
  52544. lineCap: strokeState.lineCap,
  52545. lineDash: strokeState.lineDash,
  52546. lineJoin: strokeState.lineJoin,
  52547. lineWidth: strokeState.lineWidth,
  52548. miterLimit: strokeState.miterLimit,
  52549. strokeStyle: strokeState.strokeStyle
  52550. };
  52551. } else {
  52552. replayStrokeState.lineCap = strokeState.lineCap;
  52553. replayStrokeState.lineDash = strokeState.lineDash;
  52554. replayStrokeState.lineJoin = strokeState.lineJoin;
  52555. replayStrokeState.lineWidth = strokeState.lineWidth;
  52556. replayStrokeState.miterLimit = strokeState.miterLimit;
  52557. replayStrokeState.strokeStyle = strokeState.strokeStyle;
  52558. }
  52559. };
  52560. /**
  52561. * @param {ol.render.canvas.TextState} textState Text state.
  52562. * @private
  52563. */
  52564. ol.render.canvas.TextReplay.prototype.setReplayTextState_ =
  52565. function(textState) {
  52566. var replayTextState = this.replayTextState_;
  52567. if (replayTextState &&
  52568. replayTextState.font == textState.font &&
  52569. replayTextState.textAlign == textState.textAlign &&
  52570. replayTextState.textBaseline == textState.textBaseline) {
  52571. return;
  52572. }
  52573. var setTextStyleInstruction = [ol.render.canvas.Instruction.SET_TEXT_STYLE,
  52574. textState.font, textState.textAlign, textState.textBaseline];
  52575. this.instructions.push(setTextStyleInstruction);
  52576. this.hitDetectionInstructions.push(setTextStyleInstruction);
  52577. if (!replayTextState) {
  52578. this.replayTextState_ = {
  52579. font: textState.font,
  52580. textAlign: textState.textAlign,
  52581. textBaseline: textState.textBaseline
  52582. };
  52583. } else {
  52584. replayTextState.font = textState.font;
  52585. replayTextState.textAlign = textState.textAlign;
  52586. replayTextState.textBaseline = textState.textBaseline;
  52587. }
  52588. };
  52589. /**
  52590. * @inheritDoc
  52591. */
  52592. ol.render.canvas.TextReplay.prototype.setTextStyle = function(textStyle) {
  52593. if (!textStyle) {
  52594. this.text_ = '';
  52595. } else {
  52596. var textFillStyle = textStyle.getFill();
  52597. if (!textFillStyle) {
  52598. this.textFillState_ = null;
  52599. } else {
  52600. var textFillStyleColor = textFillStyle.getColor();
  52601. var fillStyle = ol.color.asString(textFillStyleColor ?
  52602. textFillStyleColor : ol.render.canvas.defaultFillStyle);
  52603. if (!this.textFillState_) {
  52604. this.textFillState_ = {
  52605. fillStyle: fillStyle
  52606. };
  52607. } else {
  52608. var textFillState = this.textFillState_;
  52609. textFillState.fillStyle = fillStyle;
  52610. }
  52611. }
  52612. var textStrokeStyle = textStyle.getStroke();
  52613. if (!textStrokeStyle) {
  52614. this.textStrokeState_ = null;
  52615. } else {
  52616. var textStrokeStyleColor = textStrokeStyle.getColor();
  52617. var textStrokeStyleLineCap = textStrokeStyle.getLineCap();
  52618. var textStrokeStyleLineDash = textStrokeStyle.getLineDash();
  52619. var textStrokeStyleLineJoin = textStrokeStyle.getLineJoin();
  52620. var textStrokeStyleWidth = textStrokeStyle.getWidth();
  52621. var textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit();
  52622. var lineCap = textStrokeStyleLineCap !== undefined ?
  52623. textStrokeStyleLineCap : ol.render.canvas.defaultLineCap;
  52624. var lineDash = textStrokeStyleLineDash ?
  52625. textStrokeStyleLineDash.slice() : ol.render.canvas.defaultLineDash;
  52626. var lineJoin = textStrokeStyleLineJoin !== undefined ?
  52627. textStrokeStyleLineJoin : ol.render.canvas.defaultLineJoin;
  52628. var lineWidth = textStrokeStyleWidth !== undefined ?
  52629. textStrokeStyleWidth : ol.render.canvas.defaultLineWidth;
  52630. var miterLimit = textStrokeStyleMiterLimit !== undefined ?
  52631. textStrokeStyleMiterLimit : ol.render.canvas.defaultMiterLimit;
  52632. var strokeStyle = ol.color.asString(textStrokeStyleColor ?
  52633. textStrokeStyleColor : ol.render.canvas.defaultStrokeStyle);
  52634. if (!this.textStrokeState_) {
  52635. this.textStrokeState_ = {
  52636. lineCap: lineCap,
  52637. lineDash: lineDash,
  52638. lineJoin: lineJoin,
  52639. lineWidth: lineWidth,
  52640. miterLimit: miterLimit,
  52641. strokeStyle: strokeStyle
  52642. };
  52643. } else {
  52644. var textStrokeState = this.textStrokeState_;
  52645. textStrokeState.lineCap = lineCap;
  52646. textStrokeState.lineDash = lineDash;
  52647. textStrokeState.lineJoin = lineJoin;
  52648. textStrokeState.lineWidth = lineWidth;
  52649. textStrokeState.miterLimit = miterLimit;
  52650. textStrokeState.strokeStyle = strokeStyle;
  52651. }
  52652. }
  52653. var textFont = textStyle.getFont();
  52654. var textOffsetX = textStyle.getOffsetX();
  52655. var textOffsetY = textStyle.getOffsetY();
  52656. var textRotation = textStyle.getRotation();
  52657. var textScale = textStyle.getScale();
  52658. var textText = textStyle.getText();
  52659. var textTextAlign = textStyle.getTextAlign();
  52660. var textTextBaseline = textStyle.getTextBaseline();
  52661. var font = textFont !== undefined ?
  52662. textFont : ol.render.canvas.defaultFont;
  52663. var textAlign = textTextAlign !== undefined ?
  52664. textTextAlign : ol.render.canvas.defaultTextAlign;
  52665. var textBaseline = textTextBaseline !== undefined ?
  52666. textTextBaseline : ol.render.canvas.defaultTextBaseline;
  52667. if (!this.textState_) {
  52668. this.textState_ = {
  52669. font: font,
  52670. textAlign: textAlign,
  52671. textBaseline: textBaseline
  52672. };
  52673. } else {
  52674. var textState = this.textState_;
  52675. textState.font = font;
  52676. textState.textAlign = textAlign;
  52677. textState.textBaseline = textBaseline;
  52678. }
  52679. this.text_ = textText !== undefined ? textText : '';
  52680. this.textOffsetX_ = textOffsetX !== undefined ? textOffsetX : 0;
  52681. this.textOffsetY_ = textOffsetY !== undefined ? textOffsetY : 0;
  52682. this.textRotation_ = textRotation !== undefined ? textRotation : 0;
  52683. this.textScale_ = textScale !== undefined ? textScale : 1;
  52684. }
  52685. };
  52686. /**
  52687. * @constructor
  52688. * @implements {ol.render.IReplayGroup}
  52689. * @param {number} tolerance Tolerance.
  52690. * @param {ol.Extent} maxExtent Max extent.
  52691. * @param {number} resolution Resolution.
  52692. * @param {number=} opt_renderBuffer Optional rendering buffer.
  52693. * @struct
  52694. */
  52695. ol.render.canvas.ReplayGroup = function(
  52696. tolerance, maxExtent, resolution, opt_renderBuffer) {
  52697. /**
  52698. * @private
  52699. * @type {number}
  52700. */
  52701. this.tolerance_ = tolerance;
  52702. /**
  52703. * @private
  52704. * @type {ol.Extent}
  52705. */
  52706. this.maxExtent_ = maxExtent;
  52707. /**
  52708. * @private
  52709. * @type {number}
  52710. */
  52711. this.resolution_ = resolution;
  52712. /**
  52713. * @private
  52714. * @type {number|undefined}
  52715. */
  52716. this.renderBuffer_ = opt_renderBuffer;
  52717. /**
  52718. * @private
  52719. * @type {!Object.<string,
  52720. * Object.<ol.render.ReplayType, ol.render.canvas.Replay>>}
  52721. */
  52722. this.replaysByZIndex_ = {};
  52723. /**
  52724. * @private
  52725. * @type {CanvasRenderingContext2D}
  52726. */
  52727. this.hitDetectionContext_ = ol.dom.createCanvasContext2D(1, 1);
  52728. /**
  52729. * @private
  52730. * @type {!goog.vec.Mat4.Number}
  52731. */
  52732. this.hitDetectionTransform_ = goog.vec.Mat4.createNumber();
  52733. };
  52734. /**
  52735. * FIXME empty description for jsdoc
  52736. */
  52737. ol.render.canvas.ReplayGroup.prototype.finish = function() {
  52738. var zKey;
  52739. for (zKey in this.replaysByZIndex_) {
  52740. var replays = this.replaysByZIndex_[zKey];
  52741. var replayKey;
  52742. for (replayKey in replays) {
  52743. replays[replayKey].finish();
  52744. }
  52745. }
  52746. };
  52747. /**
  52748. * @param {ol.Coordinate} coordinate Coordinate.
  52749. * @param {number} resolution Resolution.
  52750. * @param {number} rotation Rotation.
  52751. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  52752. * to skip.
  52753. * @param {function(ol.Feature): T} callback Feature callback.
  52754. * @return {T|undefined} Callback result.
  52755. * @template T
  52756. */
  52757. ol.render.canvas.ReplayGroup.prototype.forEachFeatureAtCoordinate = function(
  52758. coordinate, resolution, rotation, skippedFeaturesHash, callback) {
  52759. var transform = this.hitDetectionTransform_;
  52760. ol.vec.Mat4.makeTransform2D(transform, 0.5, 0.5,
  52761. 1 / resolution, -1 / resolution, -rotation,
  52762. -coordinate[0], -coordinate[1]);
  52763. var context = this.hitDetectionContext_;
  52764. context.clearRect(0, 0, 1, 1);
  52765. /**
  52766. * @type {ol.Extent}
  52767. */
  52768. var hitExtent;
  52769. if (this.renderBuffer_ !== undefined) {
  52770. hitExtent = ol.extent.createEmpty();
  52771. ol.extent.extendCoordinate(hitExtent, coordinate);
  52772. ol.extent.buffer(hitExtent, resolution * this.renderBuffer_, hitExtent);
  52773. }
  52774. return this.replayHitDetection_(context, transform, rotation,
  52775. skippedFeaturesHash,
  52776. /**
  52777. * @param {ol.Feature} feature Feature.
  52778. * @return {?} Callback result.
  52779. */
  52780. function(feature) {
  52781. var imageData = context.getImageData(0, 0, 1, 1).data;
  52782. if (imageData[3] > 0) {
  52783. var result = callback(feature);
  52784. if (result) {
  52785. return result;
  52786. }
  52787. context.clearRect(0, 0, 1, 1);
  52788. }
  52789. }, hitExtent);
  52790. };
  52791. /**
  52792. * @inheritDoc
  52793. */
  52794. ol.render.canvas.ReplayGroup.prototype.getReplay =
  52795. function(zIndex, replayType) {
  52796. var zIndexKey = zIndex !== undefined ? zIndex.toString() : '0';
  52797. var replays = this.replaysByZIndex_[zIndexKey];
  52798. if (replays === undefined) {
  52799. replays = {};
  52800. this.replaysByZIndex_[zIndexKey] = replays;
  52801. }
  52802. var replay = replays[replayType];
  52803. if (replay === undefined) {
  52804. var Constructor = ol.render.canvas.BATCH_CONSTRUCTORS_[replayType];
  52805. goog.asserts.assert(Constructor !== undefined,
  52806. replayType +
  52807. ' constructor missing from ol.render.canvas.BATCH_CONSTRUCTORS_');
  52808. replay = new Constructor(this.tolerance_, this.maxExtent_,
  52809. this.resolution_);
  52810. replays[replayType] = replay;
  52811. }
  52812. return replay;
  52813. };
  52814. /**
  52815. * @inheritDoc
  52816. */
  52817. ol.render.canvas.ReplayGroup.prototype.isEmpty = function() {
  52818. return goog.object.isEmpty(this.replaysByZIndex_);
  52819. };
  52820. /**
  52821. * @param {CanvasRenderingContext2D} context Context.
  52822. * @param {number} pixelRatio Pixel ratio.
  52823. * @param {goog.vec.Mat4.Number} transform Transform.
  52824. * @param {number} viewRotation View rotation.
  52825. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  52826. * to skip.
  52827. */
  52828. ol.render.canvas.ReplayGroup.prototype.replay = function(
  52829. context, pixelRatio, transform, viewRotation, skippedFeaturesHash) {
  52830. /** @type {Array.<number>} */
  52831. var zs = Object.keys(this.replaysByZIndex_).map(Number);
  52832. goog.array.sort(zs);
  52833. // setup clipping so that the parts of over-simplified geometries are not
  52834. // visible outside the current extent when panning
  52835. var maxExtent = this.maxExtent_;
  52836. var minX = maxExtent[0];
  52837. var minY = maxExtent[1];
  52838. var maxX = maxExtent[2];
  52839. var maxY = maxExtent[3];
  52840. var flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY];
  52841. ol.geom.flat.transform.transform2D(
  52842. flatClipCoords, 0, 8, 2, transform, flatClipCoords);
  52843. context.save();
  52844. context.beginPath();
  52845. context.moveTo(flatClipCoords[0], flatClipCoords[1]);
  52846. context.lineTo(flatClipCoords[2], flatClipCoords[3]);
  52847. context.lineTo(flatClipCoords[4], flatClipCoords[5]);
  52848. context.lineTo(flatClipCoords[6], flatClipCoords[7]);
  52849. context.closePath();
  52850. context.clip();
  52851. var i, ii, j, jj, replays, replay;
  52852. for (i = 0, ii = zs.length; i < ii; ++i) {
  52853. replays = this.replaysByZIndex_[zs[i].toString()];
  52854. for (j = 0, jj = ol.render.REPLAY_ORDER.length; j < jj; ++j) {
  52855. replay = replays[ol.render.REPLAY_ORDER[j]];
  52856. if (replay !== undefined) {
  52857. replay.replay(context, pixelRatio, transform, viewRotation,
  52858. skippedFeaturesHash);
  52859. }
  52860. }
  52861. }
  52862. context.restore();
  52863. };
  52864. /**
  52865. * @private
  52866. * @param {CanvasRenderingContext2D} context Context.
  52867. * @param {goog.vec.Mat4.Number} transform Transform.
  52868. * @param {number} viewRotation View rotation.
  52869. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  52870. * to skip.
  52871. * @param {function(ol.Feature): T} featureCallback Feature callback.
  52872. * @param {ol.Extent=} opt_hitExtent Only check features that intersect this
  52873. * extent.
  52874. * @return {T|undefined} Callback result.
  52875. * @template T
  52876. */
  52877. ol.render.canvas.ReplayGroup.prototype.replayHitDetection_ = function(
  52878. context, transform, viewRotation, skippedFeaturesHash,
  52879. featureCallback, opt_hitExtent) {
  52880. /** @type {Array.<number>} */
  52881. var zs = Object.keys(this.replaysByZIndex_).map(Number);
  52882. goog.array.sort(zs, function(a, b) { return b - a; });
  52883. var i, ii, j, replays, replay, result;
  52884. for (i = 0, ii = zs.length; i < ii; ++i) {
  52885. replays = this.replaysByZIndex_[zs[i].toString()];
  52886. for (j = ol.render.REPLAY_ORDER.length - 1; j >= 0; --j) {
  52887. replay = replays[ol.render.REPLAY_ORDER[j]];
  52888. if (replay !== undefined) {
  52889. result = replay.replayHitDetection(context, transform, viewRotation,
  52890. skippedFeaturesHash, featureCallback, opt_hitExtent);
  52891. if (result) {
  52892. return result;
  52893. }
  52894. }
  52895. }
  52896. }
  52897. return undefined;
  52898. };
  52899. /**
  52900. * @const
  52901. * @private
  52902. * @type {Object.<ol.render.ReplayType,
  52903. * function(new: ol.render.canvas.Replay, number, ol.Extent,
  52904. * number)>}
  52905. */
  52906. ol.render.canvas.BATCH_CONSTRUCTORS_ = {
  52907. 'Image': ol.render.canvas.ImageReplay,
  52908. 'LineString': ol.render.canvas.LineStringReplay,
  52909. 'Polygon': ol.render.canvas.PolygonReplay,
  52910. 'Text': ol.render.canvas.TextReplay
  52911. };
  52912. goog.provide('ol.geom.Circle');
  52913. goog.require('goog.asserts');
  52914. goog.require('ol.extent');
  52915. goog.require('ol.geom.GeometryLayout');
  52916. goog.require('ol.geom.GeometryType');
  52917. goog.require('ol.geom.SimpleGeometry');
  52918. goog.require('ol.geom.flat.deflate');
  52919. goog.require('ol.proj');
  52920. /**
  52921. * @classdesc
  52922. * Circle geometry.
  52923. *
  52924. * @constructor
  52925. * @extends {ol.geom.SimpleGeometry}
  52926. * @param {ol.Coordinate} center Center.
  52927. * @param {number=} opt_radius Radius.
  52928. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  52929. * @api
  52930. */
  52931. ol.geom.Circle = function(center, opt_radius, opt_layout) {
  52932. goog.base(this);
  52933. var radius = opt_radius ? opt_radius : 0;
  52934. this.setCenterAndRadius(center, radius, opt_layout);
  52935. };
  52936. goog.inherits(ol.geom.Circle, ol.geom.SimpleGeometry);
  52937. /**
  52938. * Make a complete copy of the geometry.
  52939. * @return {!ol.geom.Circle} Clone.
  52940. * @api
  52941. */
  52942. ol.geom.Circle.prototype.clone = function() {
  52943. var circle = new ol.geom.Circle(null);
  52944. circle.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  52945. return circle;
  52946. };
  52947. /**
  52948. * @inheritDoc
  52949. */
  52950. ol.geom.Circle.prototype.closestPointXY =
  52951. function(x, y, closestPoint, minSquaredDistance) {
  52952. var flatCoordinates = this.flatCoordinates;
  52953. var dx = x - flatCoordinates[0];
  52954. var dy = y - flatCoordinates[1];
  52955. var squaredDistance = dx * dx + dy * dy;
  52956. if (squaredDistance < minSquaredDistance) {
  52957. var i;
  52958. if (squaredDistance === 0) {
  52959. for (i = 0; i < this.stride; ++i) {
  52960. closestPoint[i] = flatCoordinates[i];
  52961. }
  52962. } else {
  52963. var delta = this.getRadius() / Math.sqrt(squaredDistance);
  52964. closestPoint[0] = flatCoordinates[0] + delta * dx;
  52965. closestPoint[1] = flatCoordinates[1] + delta * dy;
  52966. for (i = 2; i < this.stride; ++i) {
  52967. closestPoint[i] = flatCoordinates[i];
  52968. }
  52969. }
  52970. closestPoint.length = this.stride;
  52971. return squaredDistance;
  52972. } else {
  52973. return minSquaredDistance;
  52974. }
  52975. };
  52976. /**
  52977. * @inheritDoc
  52978. */
  52979. ol.geom.Circle.prototype.containsXY = function(x, y) {
  52980. var flatCoordinates = this.flatCoordinates;
  52981. var dx = x - flatCoordinates[0];
  52982. var dy = y - flatCoordinates[1];
  52983. return dx * dx + dy * dy <= this.getRadiusSquared_();
  52984. };
  52985. /**
  52986. * Return the center of the circle as {@link ol.Coordinate coordinate}.
  52987. * @return {ol.Coordinate} Center.
  52988. * @api
  52989. */
  52990. ol.geom.Circle.prototype.getCenter = function() {
  52991. return this.flatCoordinates.slice(0, this.stride);
  52992. };
  52993. /**
  52994. * @inheritDoc
  52995. */
  52996. ol.geom.Circle.prototype.computeExtent = function(extent) {
  52997. var flatCoordinates = this.flatCoordinates;
  52998. var radius = flatCoordinates[this.stride] - flatCoordinates[0];
  52999. return ol.extent.createOrUpdate(
  53000. flatCoordinates[0] - radius, flatCoordinates[1] - radius,
  53001. flatCoordinates[0] + radius, flatCoordinates[1] + radius,
  53002. extent);
  53003. };
  53004. /**
  53005. * Return the radius of the circle.
  53006. * @return {number} Radius.
  53007. * @api
  53008. */
  53009. ol.geom.Circle.prototype.getRadius = function() {
  53010. return Math.sqrt(this.getRadiusSquared_());
  53011. };
  53012. /**
  53013. * @private
  53014. * @return {number} Radius squared.
  53015. */
  53016. ol.geom.Circle.prototype.getRadiusSquared_ = function() {
  53017. var dx = this.flatCoordinates[this.stride] - this.flatCoordinates[0];
  53018. var dy = this.flatCoordinates[this.stride + 1] - this.flatCoordinates[1];
  53019. return dx * dx + dy * dy;
  53020. };
  53021. /**
  53022. * @inheritDoc
  53023. * @api
  53024. */
  53025. ol.geom.Circle.prototype.getType = function() {
  53026. return ol.geom.GeometryType.CIRCLE;
  53027. };
  53028. /**
  53029. * @inheritDoc
  53030. * @api stable
  53031. */
  53032. ol.geom.Circle.prototype.intersectsExtent = function(extent) {
  53033. var circleExtent = this.getExtent();
  53034. if (ol.extent.intersects(extent, circleExtent)) {
  53035. var center = this.getCenter();
  53036. if (extent[0] <= center[0] && extent[2] >= center[0]) {
  53037. return true;
  53038. }
  53039. if (extent[1] <= center[1] && extent[3] >= center[1]) {
  53040. return true;
  53041. }
  53042. return ol.extent.forEachCorner(extent, this.containsCoordinate, this);
  53043. }
  53044. return false;
  53045. };
  53046. /**
  53047. * Set the center of the circle as {@link ol.Coordinate coordinate}.
  53048. * @param {ol.Coordinate} center Center.
  53049. * @api
  53050. */
  53051. ol.geom.Circle.prototype.setCenter = function(center) {
  53052. var stride = this.stride;
  53053. goog.asserts.assert(center.length == stride,
  53054. 'center array length should match stride');
  53055. var radius = this.flatCoordinates[stride] - this.flatCoordinates[0];
  53056. var flatCoordinates = center.slice();
  53057. flatCoordinates[stride] = flatCoordinates[0] + radius;
  53058. var i;
  53059. for (i = 1; i < stride; ++i) {
  53060. flatCoordinates[stride + i] = center[i];
  53061. }
  53062. this.setFlatCoordinates(this.layout, flatCoordinates);
  53063. };
  53064. /**
  53065. * Set the center (as {@link ol.Coordinate coordinate}) and the radius (as
  53066. * number) of the circle.
  53067. * @param {ol.Coordinate} center Center.
  53068. * @param {number} radius Radius.
  53069. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  53070. * @api
  53071. */
  53072. ol.geom.Circle.prototype.setCenterAndRadius =
  53073. function(center, radius, opt_layout) {
  53074. if (!center) {
  53075. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  53076. } else {
  53077. this.setLayout(opt_layout, center, 0);
  53078. if (!this.flatCoordinates) {
  53079. this.flatCoordinates = [];
  53080. }
  53081. /** @type {Array.<number>} */
  53082. var flatCoordinates = this.flatCoordinates;
  53083. var offset = ol.geom.flat.deflate.coordinate(
  53084. flatCoordinates, 0, center, this.stride);
  53085. flatCoordinates[offset++] = flatCoordinates[0] + radius;
  53086. var i, ii;
  53087. for (i = 1, ii = this.stride; i < ii; ++i) {
  53088. flatCoordinates[offset++] = flatCoordinates[i];
  53089. }
  53090. flatCoordinates.length = offset;
  53091. this.changed();
  53092. }
  53093. };
  53094. /**
  53095. * @param {ol.geom.GeometryLayout} layout Layout.
  53096. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53097. */
  53098. ol.geom.Circle.prototype.setFlatCoordinates =
  53099. function(layout, flatCoordinates) {
  53100. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  53101. this.changed();
  53102. };
  53103. /**
  53104. * Set the radius of the circle. The radius is in the units of the projection.
  53105. * @param {number} radius Radius.
  53106. * @api
  53107. */
  53108. ol.geom.Circle.prototype.setRadius = function(radius) {
  53109. goog.asserts.assert(this.flatCoordinates,
  53110. 'truthy this.flatCoordinates expected');
  53111. this.flatCoordinates[this.stride] = this.flatCoordinates[0] + radius;
  53112. this.changed();
  53113. };
  53114. /**
  53115. * Transform each coordinate of the circle from one coordinate reference system
  53116. * to another. The geometry is modified in place.
  53117. * If you do not want the geometry modified in place, first clone() it and
  53118. * then use this function on the clone.
  53119. *
  53120. * Internally a circle is currently represented by two points: the center of
  53121. * the circle `[cx, cy]`, and the point to the right of the circle
  53122. * `[cx + r, cy]`. This `transform` function just transforms these two points.
  53123. * So the resulting geometry is also a circle, and that circle does not
  53124. * correspond to the shape that would be obtained by transforming every point
  53125. * of the original circle.
  53126. *
  53127. * @param {ol.proj.ProjectionLike} source The current projection. Can be a
  53128. * string identifier or a {@link ol.proj.Projection} object.
  53129. * @param {ol.proj.ProjectionLike} destination The desired projection. Can be a
  53130. * string identifier or a {@link ol.proj.Projection} object.
  53131. * @return {ol.geom.Circle} This geometry. Note that original geometry is
  53132. * modified in place.
  53133. * @function
  53134. * @api stable
  53135. */
  53136. ol.geom.Circle.prototype.transform;
  53137. goog.provide('ol.geom.GeometryCollection');
  53138. goog.require('goog.events');
  53139. goog.require('goog.events.EventType');
  53140. goog.require('goog.object');
  53141. goog.require('ol.extent');
  53142. goog.require('ol.geom.Geometry');
  53143. goog.require('ol.geom.GeometryType');
  53144. /**
  53145. * @classdesc
  53146. * An array of {@link ol.geom.Geometry} objects.
  53147. *
  53148. * @constructor
  53149. * @extends {ol.geom.Geometry}
  53150. * @param {Array.<ol.geom.Geometry>=} opt_geometries Geometries.
  53151. * @api stable
  53152. */
  53153. ol.geom.GeometryCollection = function(opt_geometries) {
  53154. goog.base(this);
  53155. /**
  53156. * @private
  53157. * @type {Array.<ol.geom.Geometry>}
  53158. */
  53159. this.geometries_ = opt_geometries ? opt_geometries : null;
  53160. this.listenGeometriesChange_();
  53161. };
  53162. goog.inherits(ol.geom.GeometryCollection, ol.geom.Geometry);
  53163. /**
  53164. * @param {Array.<ol.geom.Geometry>} geometries Geometries.
  53165. * @private
  53166. * @return {Array.<ol.geom.Geometry>} Cloned geometries.
  53167. */
  53168. ol.geom.GeometryCollection.cloneGeometries_ = function(geometries) {
  53169. var clonedGeometries = [];
  53170. var i, ii;
  53171. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53172. clonedGeometries.push(geometries[i].clone());
  53173. }
  53174. return clonedGeometries;
  53175. };
  53176. /**
  53177. * @private
  53178. */
  53179. ol.geom.GeometryCollection.prototype.unlistenGeometriesChange_ = function() {
  53180. var i, ii;
  53181. if (!this.geometries_) {
  53182. return;
  53183. }
  53184. for (i = 0, ii = this.geometries_.length; i < ii; ++i) {
  53185. goog.events.unlisten(
  53186. this.geometries_[i], goog.events.EventType.CHANGE,
  53187. this.changed, false, this);
  53188. }
  53189. };
  53190. /**
  53191. * @private
  53192. */
  53193. ol.geom.GeometryCollection.prototype.listenGeometriesChange_ = function() {
  53194. var i, ii;
  53195. if (!this.geometries_) {
  53196. return;
  53197. }
  53198. for (i = 0, ii = this.geometries_.length; i < ii; ++i) {
  53199. goog.events.listen(
  53200. this.geometries_[i], goog.events.EventType.CHANGE,
  53201. this.changed, false, this);
  53202. }
  53203. };
  53204. /**
  53205. * Make a complete copy of the geometry.
  53206. * @return {!ol.geom.GeometryCollection} Clone.
  53207. * @api stable
  53208. */
  53209. ol.geom.GeometryCollection.prototype.clone = function() {
  53210. var geometryCollection = new ol.geom.GeometryCollection(null);
  53211. geometryCollection.setGeometries(this.geometries_);
  53212. return geometryCollection;
  53213. };
  53214. /**
  53215. * @inheritDoc
  53216. */
  53217. ol.geom.GeometryCollection.prototype.closestPointXY =
  53218. function(x, y, closestPoint, minSquaredDistance) {
  53219. if (minSquaredDistance <
  53220. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  53221. return minSquaredDistance;
  53222. }
  53223. var geometries = this.geometries_;
  53224. var i, ii;
  53225. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53226. minSquaredDistance = geometries[i].closestPointXY(
  53227. x, y, closestPoint, minSquaredDistance);
  53228. }
  53229. return minSquaredDistance;
  53230. };
  53231. /**
  53232. * @inheritDoc
  53233. */
  53234. ol.geom.GeometryCollection.prototype.containsXY = function(x, y) {
  53235. var geometries = this.geometries_;
  53236. var i, ii;
  53237. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53238. if (geometries[i].containsXY(x, y)) {
  53239. return true;
  53240. }
  53241. }
  53242. return false;
  53243. };
  53244. /**
  53245. * @inheritDoc
  53246. */
  53247. ol.geom.GeometryCollection.prototype.computeExtent = function(extent) {
  53248. ol.extent.createOrUpdateEmpty(extent);
  53249. var geometries = this.geometries_;
  53250. for (var i = 0, ii = geometries.length; i < ii; ++i) {
  53251. ol.extent.extend(extent, geometries[i].getExtent());
  53252. }
  53253. return extent;
  53254. };
  53255. /**
  53256. * Return the geometries that make up this geometry collection.
  53257. * @return {Array.<ol.geom.Geometry>} Geometries.
  53258. * @api stable
  53259. */
  53260. ol.geom.GeometryCollection.prototype.getGeometries = function() {
  53261. return ol.geom.GeometryCollection.cloneGeometries_(this.geometries_);
  53262. };
  53263. /**
  53264. * @return {Array.<ol.geom.Geometry>} Geometries.
  53265. */
  53266. ol.geom.GeometryCollection.prototype.getGeometriesArray = function() {
  53267. return this.geometries_;
  53268. };
  53269. /**
  53270. * @inheritDoc
  53271. */
  53272. ol.geom.GeometryCollection.prototype.getSimplifiedGeometry =
  53273. function(squaredTolerance) {
  53274. if (this.simplifiedGeometryRevision != this.getRevision()) {
  53275. goog.object.clear(this.simplifiedGeometryCache);
  53276. this.simplifiedGeometryMaxMinSquaredTolerance = 0;
  53277. this.simplifiedGeometryRevision = this.getRevision();
  53278. }
  53279. if (squaredTolerance < 0 ||
  53280. (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&
  53281. squaredTolerance < this.simplifiedGeometryMaxMinSquaredTolerance)) {
  53282. return this;
  53283. }
  53284. var key = squaredTolerance.toString();
  53285. if (this.simplifiedGeometryCache.hasOwnProperty(key)) {
  53286. return this.simplifiedGeometryCache[key];
  53287. } else {
  53288. var simplifiedGeometries = [];
  53289. var geometries = this.geometries_;
  53290. var simplified = false;
  53291. var i, ii;
  53292. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53293. var geometry = geometries[i];
  53294. var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance);
  53295. simplifiedGeometries.push(simplifiedGeometry);
  53296. if (simplifiedGeometry !== geometry) {
  53297. simplified = true;
  53298. }
  53299. }
  53300. if (simplified) {
  53301. var simplifiedGeometryCollection = new ol.geom.GeometryCollection(null);
  53302. simplifiedGeometryCollection.setGeometriesArray(simplifiedGeometries);
  53303. this.simplifiedGeometryCache[key] = simplifiedGeometryCollection;
  53304. return simplifiedGeometryCollection;
  53305. } else {
  53306. this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;
  53307. return this;
  53308. }
  53309. }
  53310. };
  53311. /**
  53312. * @inheritDoc
  53313. * @api stable
  53314. */
  53315. ol.geom.GeometryCollection.prototype.getType = function() {
  53316. return ol.geom.GeometryType.GEOMETRY_COLLECTION;
  53317. };
  53318. /**
  53319. * @inheritDoc
  53320. * @api stable
  53321. */
  53322. ol.geom.GeometryCollection.prototype.intersectsExtent = function(extent) {
  53323. var geometries = this.geometries_;
  53324. var i, ii;
  53325. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53326. if (geometries[i].intersectsExtent(extent)) {
  53327. return true;
  53328. }
  53329. }
  53330. return false;
  53331. };
  53332. /**
  53333. * @return {boolean} Is empty.
  53334. */
  53335. ol.geom.GeometryCollection.prototype.isEmpty = function() {
  53336. return this.geometries_.length === 0;
  53337. };
  53338. /**
  53339. * Set the geometries that make up this geometry collection.
  53340. * @param {Array.<ol.geom.Geometry>} geometries Geometries.
  53341. * @api stable
  53342. */
  53343. ol.geom.GeometryCollection.prototype.setGeometries = function(geometries) {
  53344. this.setGeometriesArray(
  53345. ol.geom.GeometryCollection.cloneGeometries_(geometries));
  53346. };
  53347. /**
  53348. * @param {Array.<ol.geom.Geometry>} geometries Geometries.
  53349. */
  53350. ol.geom.GeometryCollection.prototype.setGeometriesArray = function(geometries) {
  53351. this.unlistenGeometriesChange_();
  53352. this.geometries_ = geometries;
  53353. this.listenGeometriesChange_();
  53354. this.changed();
  53355. };
  53356. /**
  53357. * @inheritDoc
  53358. * @api stable
  53359. */
  53360. ol.geom.GeometryCollection.prototype.applyTransform = function(transformFn) {
  53361. var geometries = this.geometries_;
  53362. var i, ii;
  53363. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53364. geometries[i].applyTransform(transformFn);
  53365. }
  53366. this.changed();
  53367. };
  53368. /**
  53369. * Translate the geometry.
  53370. * @param {number} deltaX Delta X.
  53371. * @param {number} deltaY Delta Y.
  53372. * @api
  53373. */
  53374. ol.geom.GeometryCollection.prototype.translate = function(deltaX, deltaY) {
  53375. var geometries = this.geometries_;
  53376. var i, ii;
  53377. for (i = 0, ii = geometries.length; i < ii; ++i) {
  53378. geometries[i].translate(deltaX, deltaY);
  53379. }
  53380. this.changed();
  53381. };
  53382. /**
  53383. * @inheritDoc
  53384. */
  53385. ol.geom.GeometryCollection.prototype.disposeInternal = function() {
  53386. this.unlistenGeometriesChange_();
  53387. goog.base(this, 'disposeInternal');
  53388. };
  53389. goog.provide('ol.geom.flat.interpolate');
  53390. goog.require('goog.array');
  53391. goog.require('goog.asserts');
  53392. goog.require('goog.math');
  53393. /**
  53394. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53395. * @param {number} offset Offset.
  53396. * @param {number} end End.
  53397. * @param {number} stride Stride.
  53398. * @param {number} fraction Fraction.
  53399. * @param {Array.<number>=} opt_dest Destination.
  53400. * @return {Array.<number>} Destination.
  53401. */
  53402. ol.geom.flat.interpolate.lineString =
  53403. function(flatCoordinates, offset, end, stride, fraction, opt_dest) {
  53404. // FIXME interpolate extra dimensions
  53405. goog.asserts.assert(0 <= fraction && fraction <= 1,
  53406. 'fraction should be in between 0 and 1');
  53407. var pointX = NaN;
  53408. var pointY = NaN;
  53409. var n = (end - offset) / stride;
  53410. if (n === 0) {
  53411. goog.asserts.fail('n cannot be 0');
  53412. } else if (n == 1) {
  53413. pointX = flatCoordinates[offset];
  53414. pointY = flatCoordinates[offset + 1];
  53415. } else if (n == 2) {
  53416. pointX = (1 - fraction) * flatCoordinates[offset] +
  53417. fraction * flatCoordinates[offset + stride];
  53418. pointY = (1 - fraction) * flatCoordinates[offset + 1] +
  53419. fraction * flatCoordinates[offset + stride + 1];
  53420. } else {
  53421. var x1 = flatCoordinates[offset];
  53422. var y1 = flatCoordinates[offset + 1];
  53423. var length = 0;
  53424. var cumulativeLengths = [0];
  53425. var i;
  53426. for (i = offset + stride; i < end; i += stride) {
  53427. var x2 = flatCoordinates[i];
  53428. var y2 = flatCoordinates[i + 1];
  53429. length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  53430. cumulativeLengths.push(length);
  53431. x1 = x2;
  53432. y1 = y2;
  53433. }
  53434. var target = fraction * length;
  53435. var index = goog.array.binarySearch(cumulativeLengths, target);
  53436. if (index < 0) {
  53437. var t = (target - cumulativeLengths[-index - 2]) /
  53438. (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]);
  53439. var o = offset + (-index - 2) * stride;
  53440. pointX = goog.math.lerp(
  53441. flatCoordinates[o], flatCoordinates[o + stride], t);
  53442. pointY = goog.math.lerp(
  53443. flatCoordinates[o + 1], flatCoordinates[o + stride + 1], t);
  53444. } else {
  53445. pointX = flatCoordinates[offset + index * stride];
  53446. pointY = flatCoordinates[offset + index * stride + 1];
  53447. }
  53448. }
  53449. if (opt_dest) {
  53450. opt_dest[0] = pointX;
  53451. opt_dest[1] = pointY;
  53452. return opt_dest;
  53453. } else {
  53454. return [pointX, pointY];
  53455. }
  53456. };
  53457. /**
  53458. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53459. * @param {number} offset Offset.
  53460. * @param {number} end End.
  53461. * @param {number} stride Stride.
  53462. * @param {number} m M.
  53463. * @param {boolean} extrapolate Extrapolate.
  53464. * @return {ol.Coordinate} Coordinate.
  53465. */
  53466. ol.geom.flat.lineStringCoordinateAtM =
  53467. function(flatCoordinates, offset, end, stride, m, extrapolate) {
  53468. if (end == offset) {
  53469. return null;
  53470. }
  53471. var coordinate;
  53472. if (m < flatCoordinates[offset + stride - 1]) {
  53473. if (extrapolate) {
  53474. coordinate = flatCoordinates.slice(offset, offset + stride);
  53475. coordinate[stride - 1] = m;
  53476. return coordinate;
  53477. } else {
  53478. return null;
  53479. }
  53480. } else if (flatCoordinates[end - 1] < m) {
  53481. if (extrapolate) {
  53482. coordinate = flatCoordinates.slice(end - stride, end);
  53483. coordinate[stride - 1] = m;
  53484. return coordinate;
  53485. } else {
  53486. return null;
  53487. }
  53488. }
  53489. // FIXME use O(1) search
  53490. if (m == flatCoordinates[offset + stride - 1]) {
  53491. return flatCoordinates.slice(offset, offset + stride);
  53492. }
  53493. var lo = offset / stride;
  53494. var hi = end / stride;
  53495. while (lo < hi) {
  53496. var mid = (lo + hi) >> 1;
  53497. if (m < flatCoordinates[(mid + 1) * stride - 1]) {
  53498. hi = mid;
  53499. } else {
  53500. lo = mid + 1;
  53501. }
  53502. }
  53503. var m0 = flatCoordinates[lo * stride - 1];
  53504. if (m == m0) {
  53505. return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride);
  53506. }
  53507. var m1 = flatCoordinates[(lo + 1) * stride - 1];
  53508. goog.asserts.assert(m0 < m, 'm0 should be less than m');
  53509. goog.asserts.assert(m <= m1, 'm should be less than or equal to m1');
  53510. var t = (m - m0) / (m1 - m0);
  53511. coordinate = [];
  53512. var i;
  53513. for (i = 0; i < stride - 1; ++i) {
  53514. coordinate.push(goog.math.lerp(flatCoordinates[(lo - 1) * stride + i],
  53515. flatCoordinates[lo * stride + i], t));
  53516. }
  53517. coordinate.push(m);
  53518. goog.asserts.assert(coordinate.length == stride,
  53519. 'length of coordinate array should match stride');
  53520. return coordinate;
  53521. };
  53522. /**
  53523. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53524. * @param {number} offset Offset.
  53525. * @param {Array.<number>} ends Ends.
  53526. * @param {number} stride Stride.
  53527. * @param {number} m M.
  53528. * @param {boolean} extrapolate Extrapolate.
  53529. * @param {boolean} interpolate Interpolate.
  53530. * @return {ol.Coordinate} Coordinate.
  53531. */
  53532. ol.geom.flat.lineStringsCoordinateAtM = function(
  53533. flatCoordinates, offset, ends, stride, m, extrapolate, interpolate) {
  53534. if (interpolate) {
  53535. return ol.geom.flat.lineStringCoordinateAtM(
  53536. flatCoordinates, offset, ends[ends.length - 1], stride, m, extrapolate);
  53537. }
  53538. var coordinate;
  53539. if (m < flatCoordinates[stride - 1]) {
  53540. if (extrapolate) {
  53541. coordinate = flatCoordinates.slice(0, stride);
  53542. coordinate[stride - 1] = m;
  53543. return coordinate;
  53544. } else {
  53545. return null;
  53546. }
  53547. }
  53548. if (flatCoordinates[flatCoordinates.length - 1] < m) {
  53549. if (extrapolate) {
  53550. coordinate = flatCoordinates.slice(flatCoordinates.length - stride);
  53551. coordinate[stride - 1] = m;
  53552. return coordinate;
  53553. } else {
  53554. return null;
  53555. }
  53556. }
  53557. var i, ii;
  53558. for (i = 0, ii = ends.length; i < ii; ++i) {
  53559. var end = ends[i];
  53560. if (offset == end) {
  53561. continue;
  53562. }
  53563. if (m < flatCoordinates[offset + stride - 1]) {
  53564. return null;
  53565. } else if (m <= flatCoordinates[end - 1]) {
  53566. return ol.geom.flat.lineStringCoordinateAtM(
  53567. flatCoordinates, offset, end, stride, m, false);
  53568. }
  53569. offset = end;
  53570. }
  53571. goog.asserts.fail(
  53572. 'ol.geom.flat.lineStringsCoordinateAtM should have returned');
  53573. return null;
  53574. };
  53575. goog.provide('ol.geom.flat.length');
  53576. /**
  53577. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53578. * @param {number} offset Offset.
  53579. * @param {number} end End.
  53580. * @param {number} stride Stride.
  53581. * @return {number} Length.
  53582. */
  53583. ol.geom.flat.length.lineString =
  53584. function(flatCoordinates, offset, end, stride) {
  53585. var x1 = flatCoordinates[offset];
  53586. var y1 = flatCoordinates[offset + 1];
  53587. var length = 0;
  53588. var i;
  53589. for (i = offset + stride; i < end; i += stride) {
  53590. var x2 = flatCoordinates[i];
  53591. var y2 = flatCoordinates[i + 1];
  53592. length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  53593. x1 = x2;
  53594. y1 = y2;
  53595. }
  53596. return length;
  53597. };
  53598. /**
  53599. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53600. * @param {number} offset Offset.
  53601. * @param {number} end End.
  53602. * @param {number} stride Stride.
  53603. * @return {number} Perimeter.
  53604. */
  53605. ol.geom.flat.length.linearRing =
  53606. function(flatCoordinates, offset, end, stride) {
  53607. var perimeter =
  53608. ol.geom.flat.length.lineString(flatCoordinates, offset, end, stride);
  53609. var dx = flatCoordinates[end - stride] - flatCoordinates[offset];
  53610. var dy = flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1];
  53611. perimeter += Math.sqrt(dx * dx + dy * dy);
  53612. return perimeter;
  53613. };
  53614. goog.provide('ol.geom.LineString');
  53615. goog.require('goog.array');
  53616. goog.require('goog.asserts');
  53617. goog.require('ol');
  53618. goog.require('ol.extent');
  53619. goog.require('ol.geom.GeometryLayout');
  53620. goog.require('ol.geom.GeometryType');
  53621. goog.require('ol.geom.SimpleGeometry');
  53622. goog.require('ol.geom.flat.closest');
  53623. goog.require('ol.geom.flat.deflate');
  53624. goog.require('ol.geom.flat.inflate');
  53625. goog.require('ol.geom.flat.interpolate');
  53626. goog.require('ol.geom.flat.intersectsextent');
  53627. goog.require('ol.geom.flat.length');
  53628. goog.require('ol.geom.flat.segments');
  53629. goog.require('ol.geom.flat.simplify');
  53630. /**
  53631. * @classdesc
  53632. * Linestring geometry.
  53633. *
  53634. * @constructor
  53635. * @extends {ol.geom.SimpleGeometry}
  53636. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  53637. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  53638. * @api stable
  53639. */
  53640. ol.geom.LineString = function(coordinates, opt_layout) {
  53641. goog.base(this);
  53642. /**
  53643. * @private
  53644. * @type {ol.Coordinate}
  53645. */
  53646. this.flatMidpoint_ = null;
  53647. /**
  53648. * @private
  53649. * @type {number}
  53650. */
  53651. this.flatMidpointRevision_ = -1;
  53652. /**
  53653. * @private
  53654. * @type {number}
  53655. */
  53656. this.maxDelta_ = -1;
  53657. /**
  53658. * @private
  53659. * @type {number}
  53660. */
  53661. this.maxDeltaRevision_ = -1;
  53662. this.setCoordinates(coordinates, opt_layout);
  53663. };
  53664. goog.inherits(ol.geom.LineString, ol.geom.SimpleGeometry);
  53665. /**
  53666. * Append the passed coordinate to the coordinates of the linestring.
  53667. * @param {ol.Coordinate} coordinate Coordinate.
  53668. * @api stable
  53669. */
  53670. ol.geom.LineString.prototype.appendCoordinate = function(coordinate) {
  53671. goog.asserts.assert(coordinate.length == this.stride,
  53672. 'length of coordinate array should match stride');
  53673. if (!this.flatCoordinates) {
  53674. this.flatCoordinates = coordinate.slice();
  53675. } else {
  53676. goog.array.extend(this.flatCoordinates, coordinate);
  53677. }
  53678. this.changed();
  53679. };
  53680. /**
  53681. * Make a complete copy of the geometry.
  53682. * @return {!ol.geom.LineString} Clone.
  53683. * @api stable
  53684. */
  53685. ol.geom.LineString.prototype.clone = function() {
  53686. var lineString = new ol.geom.LineString(null);
  53687. lineString.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  53688. return lineString;
  53689. };
  53690. /**
  53691. * @inheritDoc
  53692. */
  53693. ol.geom.LineString.prototype.closestPointXY =
  53694. function(x, y, closestPoint, minSquaredDistance) {
  53695. if (minSquaredDistance <
  53696. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  53697. return minSquaredDistance;
  53698. }
  53699. if (this.maxDeltaRevision_ != this.getRevision()) {
  53700. this.maxDelta_ = Math.sqrt(ol.geom.flat.closest.getMaxSquaredDelta(
  53701. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride, 0));
  53702. this.maxDeltaRevision_ = this.getRevision();
  53703. }
  53704. return ol.geom.flat.closest.getClosestPoint(
  53705. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  53706. this.maxDelta_, false, x, y, closestPoint, minSquaredDistance);
  53707. };
  53708. /**
  53709. * Iterate over each segment, calling the provided callback.
  53710. * If the callback returns a truthy value the function returns that
  53711. * value immediately. Otherwise the function returns `false`.
  53712. *
  53713. * @param {function(this: S, ol.Coordinate, ol.Coordinate): T} callback Function
  53714. * called for each segment.
  53715. * @param {S=} opt_this The object to be used as the value of 'this'
  53716. * within callback.
  53717. * @return {T|boolean} Value.
  53718. * @template T,S
  53719. * @api
  53720. */
  53721. ol.geom.LineString.prototype.forEachSegment = function(callback, opt_this) {
  53722. return ol.geom.flat.segments.forEach(this.flatCoordinates, 0,
  53723. this.flatCoordinates.length, this.stride, callback, opt_this);
  53724. };
  53725. /**
  53726. * Returns the coordinate at `m` using linear interpolation, or `null` if no
  53727. * such coordinate exists.
  53728. *
  53729. * `opt_extrapolate` controls extrapolation beyond the range of Ms in the
  53730. * MultiLineString. If `opt_extrapolate` is `true` then Ms less than the first
  53731. * M will return the first coordinate and Ms greater than the last M will
  53732. * return the last coordinate.
  53733. *
  53734. * @param {number} m M.
  53735. * @param {boolean=} opt_extrapolate Extrapolate. Default is `false`.
  53736. * @return {ol.Coordinate} Coordinate.
  53737. * @api stable
  53738. */
  53739. ol.geom.LineString.prototype.getCoordinateAtM = function(m, opt_extrapolate) {
  53740. if (this.layout != ol.geom.GeometryLayout.XYM &&
  53741. this.layout != ol.geom.GeometryLayout.XYZM) {
  53742. return null;
  53743. }
  53744. var extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false;
  53745. return ol.geom.flat.lineStringCoordinateAtM(this.flatCoordinates, 0,
  53746. this.flatCoordinates.length, this.stride, m, extrapolate);
  53747. };
  53748. /**
  53749. * Return the coordinates of the linestring.
  53750. * @return {Array.<ol.Coordinate>} Coordinates.
  53751. * @api stable
  53752. */
  53753. ol.geom.LineString.prototype.getCoordinates = function() {
  53754. return ol.geom.flat.inflate.coordinates(
  53755. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
  53756. };
  53757. /**
  53758. * Return the length of the linestring on projected plane.
  53759. * @return {number} Length (on projected plane).
  53760. * @api stable
  53761. */
  53762. ol.geom.LineString.prototype.getLength = function() {
  53763. return ol.geom.flat.length.lineString(
  53764. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
  53765. };
  53766. /**
  53767. * @return {Array.<number>} Flat midpoint.
  53768. */
  53769. ol.geom.LineString.prototype.getFlatMidpoint = function() {
  53770. if (this.flatMidpointRevision_ != this.getRevision()) {
  53771. this.flatMidpoint_ = ol.geom.flat.interpolate.lineString(
  53772. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  53773. 0.5, this.flatMidpoint_);
  53774. this.flatMidpointRevision_ = this.getRevision();
  53775. }
  53776. return this.flatMidpoint_;
  53777. };
  53778. /**
  53779. * @inheritDoc
  53780. */
  53781. ol.geom.LineString.prototype.getSimplifiedGeometryInternal =
  53782. function(squaredTolerance) {
  53783. var simplifiedFlatCoordinates = [];
  53784. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.douglasPeucker(
  53785. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  53786. squaredTolerance, simplifiedFlatCoordinates, 0);
  53787. var simplifiedLineString = new ol.geom.LineString(null);
  53788. simplifiedLineString.setFlatCoordinates(
  53789. ol.geom.GeometryLayout.XY, simplifiedFlatCoordinates);
  53790. return simplifiedLineString;
  53791. };
  53792. /**
  53793. * @inheritDoc
  53794. * @api stable
  53795. */
  53796. ol.geom.LineString.prototype.getType = function() {
  53797. return ol.geom.GeometryType.LINE_STRING;
  53798. };
  53799. /**
  53800. * @inheritDoc
  53801. * @api stable
  53802. */
  53803. ol.geom.LineString.prototype.intersectsExtent = function(extent) {
  53804. return ol.geom.flat.intersectsextent.lineString(
  53805. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride,
  53806. extent);
  53807. };
  53808. /**
  53809. * Set the coordinates of the linestring.
  53810. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  53811. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  53812. * @api stable
  53813. */
  53814. ol.geom.LineString.prototype.setCoordinates =
  53815. function(coordinates, opt_layout) {
  53816. if (!coordinates) {
  53817. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  53818. } else {
  53819. this.setLayout(opt_layout, coordinates, 1);
  53820. if (!this.flatCoordinates) {
  53821. this.flatCoordinates = [];
  53822. }
  53823. this.flatCoordinates.length = ol.geom.flat.deflate.coordinates(
  53824. this.flatCoordinates, 0, coordinates, this.stride);
  53825. this.changed();
  53826. }
  53827. };
  53828. /**
  53829. * @param {ol.geom.GeometryLayout} layout Layout.
  53830. * @param {Array.<number>} flatCoordinates Flat coordinates.
  53831. */
  53832. ol.geom.LineString.prototype.setFlatCoordinates =
  53833. function(layout, flatCoordinates) {
  53834. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  53835. this.changed();
  53836. };
  53837. goog.provide('ol.geom.MultiLineString');
  53838. goog.require('goog.array');
  53839. goog.require('goog.asserts');
  53840. goog.require('ol');
  53841. goog.require('ol.extent');
  53842. goog.require('ol.geom.GeometryLayout');
  53843. goog.require('ol.geom.GeometryType');
  53844. goog.require('ol.geom.LineString');
  53845. goog.require('ol.geom.SimpleGeometry');
  53846. goog.require('ol.geom.flat.closest');
  53847. goog.require('ol.geom.flat.deflate');
  53848. goog.require('ol.geom.flat.inflate');
  53849. goog.require('ol.geom.flat.interpolate');
  53850. goog.require('ol.geom.flat.intersectsextent');
  53851. goog.require('ol.geom.flat.simplify');
  53852. /**
  53853. * @classdesc
  53854. * Multi-linestring geometry.
  53855. *
  53856. * @constructor
  53857. * @extends {ol.geom.SimpleGeometry}
  53858. * @param {Array.<Array.<ol.Coordinate>>} coordinates Coordinates.
  53859. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  53860. * @api stable
  53861. */
  53862. ol.geom.MultiLineString = function(coordinates, opt_layout) {
  53863. goog.base(this);
  53864. /**
  53865. * @type {Array.<number>}
  53866. * @private
  53867. */
  53868. this.ends_ = [];
  53869. /**
  53870. * @private
  53871. * @type {number}
  53872. */
  53873. this.maxDelta_ = -1;
  53874. /**
  53875. * @private
  53876. * @type {number}
  53877. */
  53878. this.maxDeltaRevision_ = -1;
  53879. this.setCoordinates(coordinates, opt_layout);
  53880. };
  53881. goog.inherits(ol.geom.MultiLineString, ol.geom.SimpleGeometry);
  53882. /**
  53883. * Append the passed linestring to the multilinestring.
  53884. * @param {ol.geom.LineString} lineString LineString.
  53885. * @api stable
  53886. */
  53887. ol.geom.MultiLineString.prototype.appendLineString = function(lineString) {
  53888. goog.asserts.assert(lineString.getLayout() == this.layout,
  53889. 'layout of lineString should match the layout');
  53890. if (!this.flatCoordinates) {
  53891. this.flatCoordinates = lineString.getFlatCoordinates().slice();
  53892. } else {
  53893. goog.array.extend(
  53894. this.flatCoordinates, lineString.getFlatCoordinates().slice());
  53895. }
  53896. this.ends_.push(this.flatCoordinates.length);
  53897. this.changed();
  53898. };
  53899. /**
  53900. * Make a complete copy of the geometry.
  53901. * @return {!ol.geom.MultiLineString} Clone.
  53902. * @api stable
  53903. */
  53904. ol.geom.MultiLineString.prototype.clone = function() {
  53905. var multiLineString = new ol.geom.MultiLineString(null);
  53906. multiLineString.setFlatCoordinates(
  53907. this.layout, this.flatCoordinates.slice(), this.ends_.slice());
  53908. return multiLineString;
  53909. };
  53910. /**
  53911. * @inheritDoc
  53912. */
  53913. ol.geom.MultiLineString.prototype.closestPointXY =
  53914. function(x, y, closestPoint, minSquaredDistance) {
  53915. if (minSquaredDistance <
  53916. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  53917. return minSquaredDistance;
  53918. }
  53919. if (this.maxDeltaRevision_ != this.getRevision()) {
  53920. this.maxDelta_ = Math.sqrt(ol.geom.flat.closest.getsMaxSquaredDelta(
  53921. this.flatCoordinates, 0, this.ends_, this.stride, 0));
  53922. this.maxDeltaRevision_ = this.getRevision();
  53923. }
  53924. return ol.geom.flat.closest.getsClosestPoint(
  53925. this.flatCoordinates, 0, this.ends_, this.stride,
  53926. this.maxDelta_, false, x, y, closestPoint, minSquaredDistance);
  53927. };
  53928. /**
  53929. * Returns the coordinate at `m` using linear interpolation, or `null` if no
  53930. * such coordinate exists.
  53931. *
  53932. * `opt_extrapolate` controls extrapolation beyond the range of Ms in the
  53933. * MultiLineString. If `opt_extrapolate` is `true` then Ms less than the first
  53934. * M will return the first coordinate and Ms greater than the last M will
  53935. * return the last coordinate.
  53936. *
  53937. * `opt_interpolate` controls interpolation between consecutive LineStrings
  53938. * within the MultiLineString. If `opt_interpolate` is `true` the coordinates
  53939. * will be linearly interpolated between the last coordinate of one LineString
  53940. * and the first coordinate of the next LineString. If `opt_interpolate` is
  53941. * `false` then the function will return `null` for Ms falling between
  53942. * LineStrings.
  53943. *
  53944. * @param {number} m M.
  53945. * @param {boolean=} opt_extrapolate Extrapolate. Default is `false`.
  53946. * @param {boolean=} opt_interpolate Interpolate. Default is `false`.
  53947. * @return {ol.Coordinate} Coordinate.
  53948. * @api stable
  53949. */
  53950. ol.geom.MultiLineString.prototype.getCoordinateAtM =
  53951. function(m, opt_extrapolate, opt_interpolate) {
  53952. if ((this.layout != ol.geom.GeometryLayout.XYM &&
  53953. this.layout != ol.geom.GeometryLayout.XYZM) ||
  53954. this.flatCoordinates.length === 0) {
  53955. return null;
  53956. }
  53957. var extrapolate = opt_extrapolate !== undefined ? opt_extrapolate : false;
  53958. var interpolate = opt_interpolate !== undefined ? opt_interpolate : false;
  53959. return ol.geom.flat.lineStringsCoordinateAtM(this.flatCoordinates, 0,
  53960. this.ends_, this.stride, m, extrapolate, interpolate);
  53961. };
  53962. /**
  53963. * Return the coordinates of the multilinestring.
  53964. * @return {Array.<Array.<ol.Coordinate>>} Coordinates.
  53965. * @api stable
  53966. */
  53967. ol.geom.MultiLineString.prototype.getCoordinates = function() {
  53968. return ol.geom.flat.inflate.coordinatess(
  53969. this.flatCoordinates, 0, this.ends_, this.stride);
  53970. };
  53971. /**
  53972. * @return {Array.<number>} Ends.
  53973. */
  53974. ol.geom.MultiLineString.prototype.getEnds = function() {
  53975. return this.ends_;
  53976. };
  53977. /**
  53978. * Return the linestring at the specified index.
  53979. * @param {number} index Index.
  53980. * @return {ol.geom.LineString} LineString.
  53981. * @api stable
  53982. */
  53983. ol.geom.MultiLineString.prototype.getLineString = function(index) {
  53984. goog.asserts.assert(0 <= index && index < this.ends_.length,
  53985. 'index should be in between 0 and length of the this.ends_ array');
  53986. if (index < 0 || this.ends_.length <= index) {
  53987. return null;
  53988. }
  53989. var lineString = new ol.geom.LineString(null);
  53990. lineString.setFlatCoordinates(this.layout, this.flatCoordinates.slice(
  53991. index === 0 ? 0 : this.ends_[index - 1], this.ends_[index]));
  53992. return lineString;
  53993. };
  53994. /**
  53995. * Return the linestrings of this multilinestring.
  53996. * @return {Array.<ol.geom.LineString>} LineStrings.
  53997. * @api stable
  53998. */
  53999. ol.geom.MultiLineString.prototype.getLineStrings = function() {
  54000. var flatCoordinates = this.flatCoordinates;
  54001. var ends = this.ends_;
  54002. var layout = this.layout;
  54003. /** @type {Array.<ol.geom.LineString>} */
  54004. var lineStrings = [];
  54005. var offset = 0;
  54006. var i, ii;
  54007. for (i = 0, ii = ends.length; i < ii; ++i) {
  54008. var end = ends[i];
  54009. var lineString = new ol.geom.LineString(null);
  54010. lineString.setFlatCoordinates(layout, flatCoordinates.slice(offset, end));
  54011. lineStrings.push(lineString);
  54012. offset = end;
  54013. }
  54014. return lineStrings;
  54015. };
  54016. /**
  54017. * @return {Array.<number>} Flat midpoints.
  54018. */
  54019. ol.geom.MultiLineString.prototype.getFlatMidpoints = function() {
  54020. var midpoints = [];
  54021. var flatCoordinates = this.flatCoordinates;
  54022. var offset = 0;
  54023. var ends = this.ends_;
  54024. var stride = this.stride;
  54025. var i, ii;
  54026. for (i = 0, ii = ends.length; i < ii; ++i) {
  54027. var end = ends[i];
  54028. var midpoint = ol.geom.flat.interpolate.lineString(
  54029. flatCoordinates, offset, end, stride, 0.5);
  54030. goog.array.extend(midpoints, midpoint);
  54031. offset = end;
  54032. }
  54033. return midpoints;
  54034. };
  54035. /**
  54036. * @inheritDoc
  54037. */
  54038. ol.geom.MultiLineString.prototype.getSimplifiedGeometryInternal =
  54039. function(squaredTolerance) {
  54040. var simplifiedFlatCoordinates = [];
  54041. var simplifiedEnds = [];
  54042. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.douglasPeuckers(
  54043. this.flatCoordinates, 0, this.ends_, this.stride, squaredTolerance,
  54044. simplifiedFlatCoordinates, 0, simplifiedEnds);
  54045. var simplifiedMultiLineString = new ol.geom.MultiLineString(null);
  54046. simplifiedMultiLineString.setFlatCoordinates(
  54047. ol.geom.GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEnds);
  54048. return simplifiedMultiLineString;
  54049. };
  54050. /**
  54051. * @inheritDoc
  54052. * @api stable
  54053. */
  54054. ol.geom.MultiLineString.prototype.getType = function() {
  54055. return ol.geom.GeometryType.MULTI_LINE_STRING;
  54056. };
  54057. /**
  54058. * @inheritDoc
  54059. * @api stable
  54060. */
  54061. ol.geom.MultiLineString.prototype.intersectsExtent = function(extent) {
  54062. return ol.geom.flat.intersectsextent.lineStrings(
  54063. this.flatCoordinates, 0, this.ends_, this.stride, extent);
  54064. };
  54065. /**
  54066. * Set the coordinates of the multilinestring.
  54067. * @param {Array.<Array.<ol.Coordinate>>} coordinates Coordinates.
  54068. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  54069. * @api stable
  54070. */
  54071. ol.geom.MultiLineString.prototype.setCoordinates =
  54072. function(coordinates, opt_layout) {
  54073. if (!coordinates) {
  54074. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null, this.ends_);
  54075. } else {
  54076. this.setLayout(opt_layout, coordinates, 2);
  54077. if (!this.flatCoordinates) {
  54078. this.flatCoordinates = [];
  54079. }
  54080. var ends = ol.geom.flat.deflate.coordinatess(
  54081. this.flatCoordinates, 0, coordinates, this.stride, this.ends_);
  54082. this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];
  54083. this.changed();
  54084. }
  54085. };
  54086. /**
  54087. * @param {ol.geom.GeometryLayout} layout Layout.
  54088. * @param {Array.<number>} flatCoordinates Flat coordinates.
  54089. * @param {Array.<number>} ends Ends.
  54090. */
  54091. ol.geom.MultiLineString.prototype.setFlatCoordinates =
  54092. function(layout, flatCoordinates, ends) {
  54093. if (!flatCoordinates) {
  54094. goog.asserts.assert(ends && ends.length === 0,
  54095. 'ends must be truthy and ends.length should be 0');
  54096. } else if (ends.length === 0) {
  54097. goog.asserts.assert(flatCoordinates.length === 0,
  54098. 'flatCoordinates should be an empty array');
  54099. } else {
  54100. goog.asserts.assert(flatCoordinates.length == ends[ends.length - 1],
  54101. 'length of flatCoordinates array should match the last value of ends');
  54102. }
  54103. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  54104. this.ends_ = ends;
  54105. this.changed();
  54106. };
  54107. /**
  54108. * @param {Array.<ol.geom.LineString>} lineStrings LineStrings.
  54109. */
  54110. ol.geom.MultiLineString.prototype.setLineStrings = function(lineStrings) {
  54111. var layout = this.getLayout();
  54112. var flatCoordinates = [];
  54113. var ends = [];
  54114. var i, ii;
  54115. for (i = 0, ii = lineStrings.length; i < ii; ++i) {
  54116. var lineString = lineStrings[i];
  54117. if (i === 0) {
  54118. layout = lineString.getLayout();
  54119. } else {
  54120. // FIXME better handle the case of non-matching layouts
  54121. goog.asserts.assert(lineString.getLayout() == layout,
  54122. 'layout of lineString should match layout');
  54123. }
  54124. goog.array.extend(flatCoordinates, lineString.getFlatCoordinates());
  54125. ends.push(flatCoordinates.length);
  54126. }
  54127. this.setFlatCoordinates(layout, flatCoordinates, ends);
  54128. };
  54129. goog.provide('ol.geom.MultiPoint');
  54130. goog.require('goog.array');
  54131. goog.require('goog.asserts');
  54132. goog.require('ol.extent');
  54133. goog.require('ol.geom.GeometryLayout');
  54134. goog.require('ol.geom.GeometryType');
  54135. goog.require('ol.geom.Point');
  54136. goog.require('ol.geom.SimpleGeometry');
  54137. goog.require('ol.geom.flat.deflate');
  54138. goog.require('ol.geom.flat.inflate');
  54139. goog.require('ol.math');
  54140. /**
  54141. * @classdesc
  54142. * Multi-point geometry.
  54143. *
  54144. * @constructor
  54145. * @extends {ol.geom.SimpleGeometry}
  54146. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  54147. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  54148. * @api stable
  54149. */
  54150. ol.geom.MultiPoint = function(coordinates, opt_layout) {
  54151. goog.base(this);
  54152. this.setCoordinates(coordinates, opt_layout);
  54153. };
  54154. goog.inherits(ol.geom.MultiPoint, ol.geom.SimpleGeometry);
  54155. /**
  54156. * Append the passed point to this multipoint.
  54157. * @param {ol.geom.Point} point Point.
  54158. * @api stable
  54159. */
  54160. ol.geom.MultiPoint.prototype.appendPoint = function(point) {
  54161. goog.asserts.assert(point.getLayout() == this.layout,
  54162. 'the layout of point should match layout');
  54163. if (!this.flatCoordinates) {
  54164. this.flatCoordinates = point.getFlatCoordinates().slice();
  54165. } else {
  54166. goog.array.extend(this.flatCoordinates, point.getFlatCoordinates());
  54167. }
  54168. this.changed();
  54169. };
  54170. /**
  54171. * Make a complete copy of the geometry.
  54172. * @return {!ol.geom.MultiPoint} Clone.
  54173. * @api stable
  54174. */
  54175. ol.geom.MultiPoint.prototype.clone = function() {
  54176. var multiPoint = new ol.geom.MultiPoint(null);
  54177. multiPoint.setFlatCoordinates(this.layout, this.flatCoordinates.slice());
  54178. return multiPoint;
  54179. };
  54180. /**
  54181. * @inheritDoc
  54182. */
  54183. ol.geom.MultiPoint.prototype.closestPointXY =
  54184. function(x, y, closestPoint, minSquaredDistance) {
  54185. if (minSquaredDistance <
  54186. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  54187. return minSquaredDistance;
  54188. }
  54189. var flatCoordinates = this.flatCoordinates;
  54190. var stride = this.stride;
  54191. var i, ii, j;
  54192. for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
  54193. var squaredDistance = ol.math.squaredDistance(
  54194. x, y, flatCoordinates[i], flatCoordinates[i + 1]);
  54195. if (squaredDistance < minSquaredDistance) {
  54196. minSquaredDistance = squaredDistance;
  54197. for (j = 0; j < stride; ++j) {
  54198. closestPoint[j] = flatCoordinates[i + j];
  54199. }
  54200. closestPoint.length = stride;
  54201. }
  54202. }
  54203. return minSquaredDistance;
  54204. };
  54205. /**
  54206. * Return the coordinates of the multipoint.
  54207. * @return {Array.<ol.Coordinate>} Coordinates.
  54208. * @api stable
  54209. */
  54210. ol.geom.MultiPoint.prototype.getCoordinates = function() {
  54211. return ol.geom.flat.inflate.coordinates(
  54212. this.flatCoordinates, 0, this.flatCoordinates.length, this.stride);
  54213. };
  54214. /**
  54215. * Return the point at the specified index.
  54216. * @param {number} index Index.
  54217. * @return {ol.geom.Point} Point.
  54218. * @api stable
  54219. */
  54220. ol.geom.MultiPoint.prototype.getPoint = function(index) {
  54221. var n = !this.flatCoordinates ?
  54222. 0 : this.flatCoordinates.length / this.stride;
  54223. goog.asserts.assert(0 <= index && index < n,
  54224. 'index should be in between 0 and n');
  54225. if (index < 0 || n <= index) {
  54226. return null;
  54227. }
  54228. var point = new ol.geom.Point(null);
  54229. point.setFlatCoordinates(this.layout, this.flatCoordinates.slice(
  54230. index * this.stride, (index + 1) * this.stride));
  54231. return point;
  54232. };
  54233. /**
  54234. * Return the points of this multipoint.
  54235. * @return {Array.<ol.geom.Point>} Points.
  54236. * @api stable
  54237. */
  54238. ol.geom.MultiPoint.prototype.getPoints = function() {
  54239. var flatCoordinates = this.flatCoordinates;
  54240. var layout = this.layout;
  54241. var stride = this.stride;
  54242. /** @type {Array.<ol.geom.Point>} */
  54243. var points = [];
  54244. var i, ii;
  54245. for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
  54246. var point = new ol.geom.Point(null);
  54247. point.setFlatCoordinates(layout, flatCoordinates.slice(i, i + stride));
  54248. points.push(point);
  54249. }
  54250. return points;
  54251. };
  54252. /**
  54253. * @inheritDoc
  54254. * @api stable
  54255. */
  54256. ol.geom.MultiPoint.prototype.getType = function() {
  54257. return ol.geom.GeometryType.MULTI_POINT;
  54258. };
  54259. /**
  54260. * @inheritDoc
  54261. * @api stable
  54262. */
  54263. ol.geom.MultiPoint.prototype.intersectsExtent = function(extent) {
  54264. var flatCoordinates = this.flatCoordinates;
  54265. var stride = this.stride;
  54266. var i, ii, x, y;
  54267. for (i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
  54268. x = flatCoordinates[i];
  54269. y = flatCoordinates[i + 1];
  54270. if (ol.extent.containsXY(extent, x, y)) {
  54271. return true;
  54272. }
  54273. }
  54274. return false;
  54275. };
  54276. /**
  54277. * Set the coordinates of the multipoint.
  54278. * @param {Array.<ol.Coordinate>} coordinates Coordinates.
  54279. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  54280. * @api stable
  54281. */
  54282. ol.geom.MultiPoint.prototype.setCoordinates =
  54283. function(coordinates, opt_layout) {
  54284. if (!coordinates) {
  54285. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null);
  54286. } else {
  54287. this.setLayout(opt_layout, coordinates, 1);
  54288. if (!this.flatCoordinates) {
  54289. this.flatCoordinates = [];
  54290. }
  54291. this.flatCoordinates.length = ol.geom.flat.deflate.coordinates(
  54292. this.flatCoordinates, 0, coordinates, this.stride);
  54293. this.changed();
  54294. }
  54295. };
  54296. /**
  54297. * @param {ol.geom.GeometryLayout} layout Layout.
  54298. * @param {Array.<number>} flatCoordinates Flat coordinates.
  54299. */
  54300. ol.geom.MultiPoint.prototype.setFlatCoordinates =
  54301. function(layout, flatCoordinates) {
  54302. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  54303. this.changed();
  54304. };
  54305. goog.provide('ol.geom.flat.center');
  54306. goog.require('ol.extent');
  54307. /**
  54308. * @param {Array.<number>} flatCoordinates Flat coordinates.
  54309. * @param {number} offset Offset.
  54310. * @param {Array.<Array.<number>>} endss Endss.
  54311. * @param {number} stride Stride.
  54312. * @return {Array.<number>} Flat centers.
  54313. */
  54314. ol.geom.flat.center.linearRingss =
  54315. function(flatCoordinates, offset, endss, stride) {
  54316. var flatCenters = [];
  54317. var i, ii;
  54318. var extent = ol.extent.createEmpty();
  54319. for (i = 0, ii = endss.length; i < ii; ++i) {
  54320. var ends = endss[i];
  54321. extent = ol.extent.createOrUpdateFromFlatCoordinates(
  54322. flatCoordinates, offset, ends[0], stride);
  54323. flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2);
  54324. offset = ends[ends.length - 1];
  54325. }
  54326. return flatCenters;
  54327. };
  54328. goog.provide('ol.geom.MultiPolygon');
  54329. goog.require('goog.array');
  54330. goog.require('goog.asserts');
  54331. goog.require('goog.object');
  54332. goog.require('ol');
  54333. goog.require('ol.extent');
  54334. goog.require('ol.geom.GeometryLayout');
  54335. goog.require('ol.geom.GeometryType');
  54336. goog.require('ol.geom.MultiPoint');
  54337. goog.require('ol.geom.Polygon');
  54338. goog.require('ol.geom.SimpleGeometry');
  54339. goog.require('ol.geom.flat.area');
  54340. goog.require('ol.geom.flat.center');
  54341. goog.require('ol.geom.flat.closest');
  54342. goog.require('ol.geom.flat.contains');
  54343. goog.require('ol.geom.flat.deflate');
  54344. goog.require('ol.geom.flat.inflate');
  54345. goog.require('ol.geom.flat.interiorpoint');
  54346. goog.require('ol.geom.flat.intersectsextent');
  54347. goog.require('ol.geom.flat.orient');
  54348. goog.require('ol.geom.flat.simplify');
  54349. /**
  54350. * @classdesc
  54351. * Multi-polygon geometry.
  54352. *
  54353. * @constructor
  54354. * @extends {ol.geom.SimpleGeometry}
  54355. * @param {Array.<Array.<Array.<ol.Coordinate>>>} coordinates Coordinates.
  54356. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  54357. * @api stable
  54358. */
  54359. ol.geom.MultiPolygon = function(coordinates, opt_layout) {
  54360. goog.base(this);
  54361. /**
  54362. * @type {Array.<Array.<number>>}
  54363. * @private
  54364. */
  54365. this.endss_ = [];
  54366. /**
  54367. * @private
  54368. * @type {number}
  54369. */
  54370. this.flatInteriorPointsRevision_ = -1;
  54371. /**
  54372. * @private
  54373. * @type {Array.<number>}
  54374. */
  54375. this.flatInteriorPoints_ = null;
  54376. /**
  54377. * @private
  54378. * @type {number}
  54379. */
  54380. this.maxDelta_ = -1;
  54381. /**
  54382. * @private
  54383. * @type {number}
  54384. */
  54385. this.maxDeltaRevision_ = -1;
  54386. /**
  54387. * @private
  54388. * @type {number}
  54389. */
  54390. this.orientedRevision_ = -1;
  54391. /**
  54392. * @private
  54393. * @type {Array.<number>}
  54394. */
  54395. this.orientedFlatCoordinates_ = null;
  54396. this.setCoordinates(coordinates, opt_layout);
  54397. };
  54398. goog.inherits(ol.geom.MultiPolygon, ol.geom.SimpleGeometry);
  54399. /**
  54400. * Append the passed polygon to this multipolygon.
  54401. * @param {ol.geom.Polygon} polygon Polygon.
  54402. * @api stable
  54403. */
  54404. ol.geom.MultiPolygon.prototype.appendPolygon = function(polygon) {
  54405. goog.asserts.assert(polygon.getLayout() == this.layout,
  54406. 'layout of polygon should match layout');
  54407. /** @type {Array.<number>} */
  54408. var ends;
  54409. if (!this.flatCoordinates) {
  54410. this.flatCoordinates = polygon.getFlatCoordinates().slice();
  54411. ends = polygon.getEnds().slice();
  54412. this.endss_.push();
  54413. } else {
  54414. var offset = this.flatCoordinates.length;
  54415. goog.array.extend(this.flatCoordinates, polygon.getFlatCoordinates());
  54416. ends = polygon.getEnds().slice();
  54417. var i, ii;
  54418. for (i = 0, ii = ends.length; i < ii; ++i) {
  54419. ends[i] += offset;
  54420. }
  54421. }
  54422. this.endss_.push(ends);
  54423. this.changed();
  54424. };
  54425. /**
  54426. * Make a complete copy of the geometry.
  54427. * @return {!ol.geom.MultiPolygon} Clone.
  54428. * @api stable
  54429. */
  54430. ol.geom.MultiPolygon.prototype.clone = function() {
  54431. var multiPolygon = new ol.geom.MultiPolygon(null);
  54432. var newEndss = /** @type {Array.<Array.<number>>} */
  54433. (goog.object.unsafeClone(this.endss_));
  54434. multiPolygon.setFlatCoordinates(
  54435. this.layout, this.flatCoordinates.slice(), newEndss);
  54436. return multiPolygon;
  54437. };
  54438. /**
  54439. * @inheritDoc
  54440. */
  54441. ol.geom.MultiPolygon.prototype.closestPointXY =
  54442. function(x, y, closestPoint, minSquaredDistance) {
  54443. if (minSquaredDistance <
  54444. ol.extent.closestSquaredDistanceXY(this.getExtent(), x, y)) {
  54445. return minSquaredDistance;
  54446. }
  54447. if (this.maxDeltaRevision_ != this.getRevision()) {
  54448. this.maxDelta_ = Math.sqrt(ol.geom.flat.closest.getssMaxSquaredDelta(
  54449. this.flatCoordinates, 0, this.endss_, this.stride, 0));
  54450. this.maxDeltaRevision_ = this.getRevision();
  54451. }
  54452. return ol.geom.flat.closest.getssClosestPoint(
  54453. this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride,
  54454. this.maxDelta_, true, x, y, closestPoint, minSquaredDistance);
  54455. };
  54456. /**
  54457. * @inheritDoc
  54458. */
  54459. ol.geom.MultiPolygon.prototype.containsXY = function(x, y) {
  54460. return ol.geom.flat.contains.linearRingssContainsXY(
  54461. this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, x, y);
  54462. };
  54463. /**
  54464. * Return the area of the multipolygon on projected plane.
  54465. * @return {number} Area (on projected plane).
  54466. * @api stable
  54467. */
  54468. ol.geom.MultiPolygon.prototype.getArea = function() {
  54469. return ol.geom.flat.area.linearRingss(
  54470. this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride);
  54471. };
  54472. /**
  54473. * Get the coordinate array for this geometry. This array has the structure
  54474. * of a GeoJSON coordinate array for multi-polygons.
  54475. *
  54476. * @param {boolean=} opt_right Orient coordinates according to the right-hand
  54477. * rule (counter-clockwise for exterior and clockwise for interior rings).
  54478. * If `false`, coordinates will be oriented according to the left-hand rule
  54479. * (clockwise for exterior and counter-clockwise for interior rings).
  54480. * By default, coordinate orientation will depend on how the geometry was
  54481. * constructed.
  54482. * @return {Array.<Array.<Array.<ol.Coordinate>>>} Coordinates.
  54483. * @api stable
  54484. */
  54485. ol.geom.MultiPolygon.prototype.getCoordinates = function(opt_right) {
  54486. var flatCoordinates;
  54487. if (opt_right !== undefined) {
  54488. flatCoordinates = this.getOrientedFlatCoordinates().slice();
  54489. ol.geom.flat.orient.orientLinearRingss(
  54490. flatCoordinates, 0, this.endss_, this.stride, opt_right);
  54491. } else {
  54492. flatCoordinates = this.flatCoordinates;
  54493. }
  54494. return ol.geom.flat.inflate.coordinatesss(
  54495. flatCoordinates, 0, this.endss_, this.stride);
  54496. };
  54497. /**
  54498. * @return {Array.<Array.<number>>} Endss.
  54499. */
  54500. ol.geom.MultiPolygon.prototype.getEndss = function() {
  54501. return this.endss_;
  54502. };
  54503. /**
  54504. * @return {Array.<number>} Flat interior points.
  54505. */
  54506. ol.geom.MultiPolygon.prototype.getFlatInteriorPoints = function() {
  54507. if (this.flatInteriorPointsRevision_ != this.getRevision()) {
  54508. var flatCenters = ol.geom.flat.center.linearRingss(
  54509. this.flatCoordinates, 0, this.endss_, this.stride);
  54510. this.flatInteriorPoints_ = ol.geom.flat.interiorpoint.linearRingss(
  54511. this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride,
  54512. flatCenters);
  54513. this.flatInteriorPointsRevision_ = this.getRevision();
  54514. }
  54515. return this.flatInteriorPoints_;
  54516. };
  54517. /**
  54518. * Return the interior points as {@link ol.geom.MultiPoint multipoint}.
  54519. * @return {ol.geom.MultiPoint} Interior points.
  54520. * @api stable
  54521. */
  54522. ol.geom.MultiPolygon.prototype.getInteriorPoints = function() {
  54523. var interiorPoints = new ol.geom.MultiPoint(null);
  54524. interiorPoints.setFlatCoordinates(ol.geom.GeometryLayout.XY,
  54525. this.getFlatInteriorPoints().slice());
  54526. return interiorPoints;
  54527. };
  54528. /**
  54529. * @return {Array.<number>} Oriented flat coordinates.
  54530. */
  54531. ol.geom.MultiPolygon.prototype.getOrientedFlatCoordinates = function() {
  54532. if (this.orientedRevision_ != this.getRevision()) {
  54533. var flatCoordinates = this.flatCoordinates;
  54534. if (ol.geom.flat.orient.linearRingssAreOriented(
  54535. flatCoordinates, 0, this.endss_, this.stride)) {
  54536. this.orientedFlatCoordinates_ = flatCoordinates;
  54537. } else {
  54538. this.orientedFlatCoordinates_ = flatCoordinates.slice();
  54539. this.orientedFlatCoordinates_.length =
  54540. ol.geom.flat.orient.orientLinearRingss(
  54541. this.orientedFlatCoordinates_, 0, this.endss_, this.stride);
  54542. }
  54543. this.orientedRevision_ = this.getRevision();
  54544. }
  54545. return this.orientedFlatCoordinates_;
  54546. };
  54547. /**
  54548. * @inheritDoc
  54549. */
  54550. ol.geom.MultiPolygon.prototype.getSimplifiedGeometryInternal =
  54551. function(squaredTolerance) {
  54552. var simplifiedFlatCoordinates = [];
  54553. var simplifiedEndss = [];
  54554. simplifiedFlatCoordinates.length = ol.geom.flat.simplify.quantizess(
  54555. this.flatCoordinates, 0, this.endss_, this.stride,
  54556. Math.sqrt(squaredTolerance),
  54557. simplifiedFlatCoordinates, 0, simplifiedEndss);
  54558. var simplifiedMultiPolygon = new ol.geom.MultiPolygon(null);
  54559. simplifiedMultiPolygon.setFlatCoordinates(
  54560. ol.geom.GeometryLayout.XY, simplifiedFlatCoordinates, simplifiedEndss);
  54561. return simplifiedMultiPolygon;
  54562. };
  54563. /**
  54564. * Return the polygon at the specified index.
  54565. * @param {number} index Index.
  54566. * @return {ol.geom.Polygon} Polygon.
  54567. * @api stable
  54568. */
  54569. ol.geom.MultiPolygon.prototype.getPolygon = function(index) {
  54570. goog.asserts.assert(0 <= index && index < this.endss_.length,
  54571. 'index should be in between 0 and the length of this.endss_');
  54572. if (index < 0 || this.endss_.length <= index) {
  54573. return null;
  54574. }
  54575. var offset;
  54576. if (index === 0) {
  54577. offset = 0;
  54578. } else {
  54579. var prevEnds = this.endss_[index - 1];
  54580. offset = prevEnds[prevEnds.length - 1];
  54581. }
  54582. var ends = this.endss_[index].slice();
  54583. var end = ends[ends.length - 1];
  54584. if (offset !== 0) {
  54585. var i, ii;
  54586. for (i = 0, ii = ends.length; i < ii; ++i) {
  54587. ends[i] -= offset;
  54588. }
  54589. }
  54590. var polygon = new ol.geom.Polygon(null);
  54591. polygon.setFlatCoordinates(
  54592. this.layout, this.flatCoordinates.slice(offset, end), ends);
  54593. return polygon;
  54594. };
  54595. /**
  54596. * Return the polygons of this multipolygon.
  54597. * @return {Array.<ol.geom.Polygon>} Polygons.
  54598. * @api stable
  54599. */
  54600. ol.geom.MultiPolygon.prototype.getPolygons = function() {
  54601. var layout = this.layout;
  54602. var flatCoordinates = this.flatCoordinates;
  54603. var endss = this.endss_;
  54604. var polygons = [];
  54605. var offset = 0;
  54606. var i, ii, j, jj;
  54607. for (i = 0, ii = endss.length; i < ii; ++i) {
  54608. var ends = endss[i].slice();
  54609. var end = ends[ends.length - 1];
  54610. if (offset !== 0) {
  54611. for (j = 0, jj = ends.length; j < jj; ++j) {
  54612. ends[j] -= offset;
  54613. }
  54614. }
  54615. var polygon = new ol.geom.Polygon(null);
  54616. polygon.setFlatCoordinates(
  54617. layout, flatCoordinates.slice(offset, end), ends);
  54618. polygons.push(polygon);
  54619. offset = end;
  54620. }
  54621. return polygons;
  54622. };
  54623. /**
  54624. * @inheritDoc
  54625. * @api stable
  54626. */
  54627. ol.geom.MultiPolygon.prototype.getType = function() {
  54628. return ol.geom.GeometryType.MULTI_POLYGON;
  54629. };
  54630. /**
  54631. * @inheritDoc
  54632. * @api stable
  54633. */
  54634. ol.geom.MultiPolygon.prototype.intersectsExtent = function(extent) {
  54635. return ol.geom.flat.intersectsextent.linearRingss(
  54636. this.getOrientedFlatCoordinates(), 0, this.endss_, this.stride, extent);
  54637. };
  54638. /**
  54639. * Set the coordinates of the multipolygon.
  54640. * @param {Array.<Array.<Array.<ol.Coordinate>>>} coordinates Coordinates.
  54641. * @param {ol.geom.GeometryLayout=} opt_layout Layout.
  54642. * @api stable
  54643. */
  54644. ol.geom.MultiPolygon.prototype.setCoordinates =
  54645. function(coordinates, opt_layout) {
  54646. if (!coordinates) {
  54647. this.setFlatCoordinates(ol.geom.GeometryLayout.XY, null, this.endss_);
  54648. } else {
  54649. this.setLayout(opt_layout, coordinates, 3);
  54650. if (!this.flatCoordinates) {
  54651. this.flatCoordinates = [];
  54652. }
  54653. var endss = ol.geom.flat.deflate.coordinatesss(
  54654. this.flatCoordinates, 0, coordinates, this.stride, this.endss_);
  54655. if (endss.length === 0) {
  54656. this.flatCoordinates.length = 0;
  54657. } else {
  54658. var lastEnds = endss[endss.length - 1];
  54659. this.flatCoordinates.length = lastEnds.length === 0 ?
  54660. 0 : lastEnds[lastEnds.length - 1];
  54661. }
  54662. this.changed();
  54663. }
  54664. };
  54665. /**
  54666. * @param {ol.geom.GeometryLayout} layout Layout.
  54667. * @param {Array.<number>} flatCoordinates Flat coordinates.
  54668. * @param {Array.<Array.<number>>} endss Endss.
  54669. */
  54670. ol.geom.MultiPolygon.prototype.setFlatCoordinates =
  54671. function(layout, flatCoordinates, endss) {
  54672. goog.asserts.assert(endss, 'endss must be truthy');
  54673. if (!flatCoordinates || flatCoordinates.length === 0) {
  54674. goog.asserts.assert(endss.length === 0, 'the length of endss should be 0');
  54675. } else {
  54676. goog.asserts.assert(endss.length > 0, 'endss cannot be an empty array');
  54677. var ends = endss[endss.length - 1];
  54678. goog.asserts.assert(flatCoordinates.length == ends[ends.length - 1],
  54679. 'the length of flatCoordinates should be the last value of ends');
  54680. }
  54681. this.setFlatCoordinatesInternal(layout, flatCoordinates);
  54682. this.endss_ = endss;
  54683. this.changed();
  54684. };
  54685. /**
  54686. * @param {Array.<ol.geom.Polygon>} polygons Polygons.
  54687. */
  54688. ol.geom.MultiPolygon.prototype.setPolygons = function(polygons) {
  54689. var layout = this.getLayout();
  54690. var flatCoordinates = [];
  54691. var endss = [];
  54692. var i, ii, ends;
  54693. for (i = 0, ii = polygons.length; i < ii; ++i) {
  54694. var polygon = polygons[i];
  54695. if (i === 0) {
  54696. layout = polygon.getLayout();
  54697. } else {
  54698. // FIXME better handle the case of non-matching layouts
  54699. goog.asserts.assert(polygon.getLayout() == layout,
  54700. 'layout of polygon should be layout');
  54701. }
  54702. var offset = flatCoordinates.length;
  54703. ends = polygon.getEnds();
  54704. var j, jj;
  54705. for (j = 0, jj = ends.length; j < jj; ++j) {
  54706. ends[j] += offset;
  54707. }
  54708. goog.array.extend(flatCoordinates, polygon.getFlatCoordinates());
  54709. endss.push(ends);
  54710. }
  54711. this.setFlatCoordinates(layout, flatCoordinates, endss);
  54712. };
  54713. goog.provide('ol.renderer.vector');
  54714. goog.require('goog.asserts');
  54715. goog.require('ol.geom.Circle');
  54716. goog.require('ol.geom.GeometryCollection');
  54717. goog.require('ol.geom.LineString');
  54718. goog.require('ol.geom.MultiLineString');
  54719. goog.require('ol.geom.MultiPoint');
  54720. goog.require('ol.geom.MultiPolygon');
  54721. goog.require('ol.geom.Point');
  54722. goog.require('ol.geom.Polygon');
  54723. goog.require('ol.render.IReplayGroup');
  54724. goog.require('ol.style.ImageState');
  54725. goog.require('ol.style.Style');
  54726. /**
  54727. * @param {ol.Feature} feature1 Feature 1.
  54728. * @param {ol.Feature} feature2 Feature 2.
  54729. * @return {number} Order.
  54730. */
  54731. ol.renderer.vector.defaultOrder = function(feature1, feature2) {
  54732. return goog.getUid(feature1) - goog.getUid(feature2);
  54733. };
  54734. /**
  54735. * @param {number} resolution Resolution.
  54736. * @param {number} pixelRatio Pixel ratio.
  54737. * @return {number} Squared pixel tolerance.
  54738. */
  54739. ol.renderer.vector.getSquaredTolerance = function(resolution, pixelRatio) {
  54740. var tolerance = ol.renderer.vector.getTolerance(resolution, pixelRatio);
  54741. return tolerance * tolerance;
  54742. };
  54743. /**
  54744. * @param {number} resolution Resolution.
  54745. * @param {number} pixelRatio Pixel ratio.
  54746. * @return {number} Pixel tolerance.
  54747. */
  54748. ol.renderer.vector.getTolerance = function(resolution, pixelRatio) {
  54749. return ol.SIMPLIFY_TOLERANCE * resolution / pixelRatio;
  54750. };
  54751. /**
  54752. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54753. * @param {ol.geom.Geometry} geometry Geometry.
  54754. * @param {ol.style.Style} style Style.
  54755. * @param {ol.Feature} feature Feature.
  54756. * @private
  54757. */
  54758. ol.renderer.vector.renderCircleGeometry_ =
  54759. function(replayGroup, geometry, style, feature) {
  54760. goog.asserts.assertInstanceof(geometry, ol.geom.Circle,
  54761. 'geometry should be an ol.geom.Circle');
  54762. var fillStyle = style.getFill();
  54763. var strokeStyle = style.getStroke();
  54764. if (fillStyle || strokeStyle) {
  54765. var polygonReplay = replayGroup.getReplay(
  54766. style.getZIndex(), ol.render.ReplayType.POLYGON);
  54767. polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);
  54768. polygonReplay.drawCircleGeometry(geometry, feature);
  54769. }
  54770. var textStyle = style.getText();
  54771. if (textStyle) {
  54772. var textReplay = replayGroup.getReplay(
  54773. style.getZIndex(), ol.render.ReplayType.TEXT);
  54774. textReplay.setTextStyle(textStyle);
  54775. textReplay.drawText(geometry.getCenter(), 0, 2, 2, geometry, feature);
  54776. }
  54777. };
  54778. /**
  54779. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54780. * @param {ol.Feature} feature Feature.
  54781. * @param {ol.style.Style} style Style.
  54782. * @param {number} squaredTolerance Squared tolerance.
  54783. * @param {function(this: T, goog.events.Event)} listener Listener function.
  54784. * @param {T} thisArg Value to use as `this` when executing `listener`.
  54785. * @return {boolean} `true` if style is loading.
  54786. * @template T
  54787. */
  54788. ol.renderer.vector.renderFeature = function(
  54789. replayGroup, feature, style, squaredTolerance, listener, thisArg) {
  54790. var loading = false;
  54791. var imageStyle, imageState;
  54792. imageStyle = style.getImage();
  54793. if (imageStyle) {
  54794. imageState = imageStyle.getImageState();
  54795. if (imageState == ol.style.ImageState.LOADED ||
  54796. imageState == ol.style.ImageState.ERROR) {
  54797. imageStyle.unlistenImageChange(listener, thisArg);
  54798. } else {
  54799. if (imageState == ol.style.ImageState.IDLE) {
  54800. imageStyle.load();
  54801. }
  54802. imageState = imageStyle.getImageState();
  54803. goog.asserts.assert(imageState == ol.style.ImageState.LOADING,
  54804. 'imageState should be LOADING');
  54805. imageStyle.listenImageChange(listener, thisArg);
  54806. loading = true;
  54807. }
  54808. }
  54809. ol.renderer.vector.renderFeature_(replayGroup, feature, style,
  54810. squaredTolerance);
  54811. return loading;
  54812. };
  54813. /**
  54814. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54815. * @param {ol.Feature} feature Feature.
  54816. * @param {ol.style.Style} style Style.
  54817. * @param {number} squaredTolerance Squared tolerance.
  54818. * @private
  54819. */
  54820. ol.renderer.vector.renderFeature_ = function(
  54821. replayGroup, feature, style, squaredTolerance) {
  54822. var geometry = style.getGeometryFunction()(feature);
  54823. if (!geometry) {
  54824. return;
  54825. }
  54826. var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance);
  54827. var geometryRenderer =
  54828. ol.renderer.vector.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()];
  54829. goog.asserts.assert(geometryRenderer !== undefined,
  54830. 'geometryRenderer should be defined');
  54831. geometryRenderer(replayGroup, simplifiedGeometry, style, feature);
  54832. };
  54833. /**
  54834. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54835. * @param {ol.geom.Geometry} geometry Geometry.
  54836. * @param {ol.style.Style} style Style.
  54837. * @param {ol.Feature} feature Feature.
  54838. * @private
  54839. */
  54840. ol.renderer.vector.renderGeometryCollectionGeometry_ =
  54841. function(replayGroup, geometry, style, feature) {
  54842. goog.asserts.assertInstanceof(geometry, ol.geom.GeometryCollection,
  54843. 'geometry should be an ol.geom.GeometryCollection');
  54844. var geometries = geometry.getGeometriesArray();
  54845. var i, ii;
  54846. for (i = 0, ii = geometries.length; i < ii; ++i) {
  54847. var geometryRenderer =
  54848. ol.renderer.vector.GEOMETRY_RENDERERS_[geometries[i].getType()];
  54849. goog.asserts.assert(geometryRenderer !== undefined,
  54850. 'geometryRenderer should be defined');
  54851. geometryRenderer(replayGroup, geometries[i], style, feature);
  54852. }
  54853. };
  54854. /**
  54855. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54856. * @param {ol.geom.Geometry} geometry Geometry.
  54857. * @param {ol.style.Style} style Style.
  54858. * @param {ol.Feature} feature Feature.
  54859. * @private
  54860. */
  54861. ol.renderer.vector.renderLineStringGeometry_ =
  54862. function(replayGroup, geometry, style, feature) {
  54863. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  54864. 'geometry should be an ol.geom.LineString');
  54865. var strokeStyle = style.getStroke();
  54866. if (strokeStyle) {
  54867. var lineStringReplay = replayGroup.getReplay(
  54868. style.getZIndex(), ol.render.ReplayType.LINE_STRING);
  54869. lineStringReplay.setFillStrokeStyle(null, strokeStyle);
  54870. lineStringReplay.drawLineStringGeometry(geometry, feature);
  54871. }
  54872. var textStyle = style.getText();
  54873. if (textStyle) {
  54874. var textReplay = replayGroup.getReplay(
  54875. style.getZIndex(), ol.render.ReplayType.TEXT);
  54876. textReplay.setTextStyle(textStyle);
  54877. textReplay.drawText(geometry.getFlatMidpoint(), 0, 2, 2, geometry, feature);
  54878. }
  54879. };
  54880. /**
  54881. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54882. * @param {ol.geom.Geometry} geometry Geometry.
  54883. * @param {ol.style.Style} style Style.
  54884. * @param {ol.Feature} feature Feature.
  54885. * @private
  54886. */
  54887. ol.renderer.vector.renderMultiLineStringGeometry_ =
  54888. function(replayGroup, geometry, style, feature) {
  54889. goog.asserts.assertInstanceof(geometry, ol.geom.MultiLineString,
  54890. 'geometry should be an ol.geom.MultiLineString');
  54891. var strokeStyle = style.getStroke();
  54892. if (strokeStyle) {
  54893. var lineStringReplay = replayGroup.getReplay(
  54894. style.getZIndex(), ol.render.ReplayType.LINE_STRING);
  54895. lineStringReplay.setFillStrokeStyle(null, strokeStyle);
  54896. lineStringReplay.drawMultiLineStringGeometry(geometry, feature);
  54897. }
  54898. var textStyle = style.getText();
  54899. if (textStyle) {
  54900. var textReplay = replayGroup.getReplay(
  54901. style.getZIndex(), ol.render.ReplayType.TEXT);
  54902. textReplay.setTextStyle(textStyle);
  54903. var flatMidpointCoordinates = geometry.getFlatMidpoints();
  54904. textReplay.drawText(flatMidpointCoordinates, 0,
  54905. flatMidpointCoordinates.length, 2, geometry, feature);
  54906. }
  54907. };
  54908. /**
  54909. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54910. * @param {ol.geom.Geometry} geometry Geometry.
  54911. * @param {ol.style.Style} style Style.
  54912. * @param {ol.Feature} feature Feature.
  54913. * @private
  54914. */
  54915. ol.renderer.vector.renderMultiPolygonGeometry_ =
  54916. function(replayGroup, geometry, style, feature) {
  54917. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPolygon,
  54918. 'geometry should be an ol.geom.MultiPolygon');
  54919. var fillStyle = style.getFill();
  54920. var strokeStyle = style.getStroke();
  54921. if (strokeStyle || fillStyle) {
  54922. var polygonReplay = replayGroup.getReplay(
  54923. style.getZIndex(), ol.render.ReplayType.POLYGON);
  54924. polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);
  54925. polygonReplay.drawMultiPolygonGeometry(geometry, feature);
  54926. }
  54927. var textStyle = style.getText();
  54928. if (textStyle) {
  54929. var textReplay = replayGroup.getReplay(
  54930. style.getZIndex(), ol.render.ReplayType.TEXT);
  54931. textReplay.setTextStyle(textStyle);
  54932. var flatInteriorPointCoordinates = geometry.getFlatInteriorPoints();
  54933. textReplay.drawText(flatInteriorPointCoordinates, 0,
  54934. flatInteriorPointCoordinates.length, 2, geometry, feature);
  54935. }
  54936. };
  54937. /**
  54938. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54939. * @param {ol.geom.Geometry} geometry Geometry.
  54940. * @param {ol.style.Style} style Style.
  54941. * @param {ol.Feature} feature Feature.
  54942. * @private
  54943. */
  54944. ol.renderer.vector.renderPointGeometry_ =
  54945. function(replayGroup, geometry, style, feature) {
  54946. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  54947. 'geometry should be an ol.geom.Point');
  54948. var imageStyle = style.getImage();
  54949. if (imageStyle) {
  54950. if (imageStyle.getImageState() != ol.style.ImageState.LOADED) {
  54951. return;
  54952. }
  54953. var imageReplay = replayGroup.getReplay(
  54954. style.getZIndex(), ol.render.ReplayType.IMAGE);
  54955. imageReplay.setImageStyle(imageStyle);
  54956. imageReplay.drawPointGeometry(geometry, feature);
  54957. }
  54958. var textStyle = style.getText();
  54959. if (textStyle) {
  54960. var textReplay = replayGroup.getReplay(
  54961. style.getZIndex(), ol.render.ReplayType.TEXT);
  54962. textReplay.setTextStyle(textStyle);
  54963. textReplay.drawText(geometry.getCoordinates(), 0, 2, 2, geometry, feature);
  54964. }
  54965. };
  54966. /**
  54967. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54968. * @param {ol.geom.Geometry} geometry Geometry.
  54969. * @param {ol.style.Style} style Style.
  54970. * @param {ol.Feature} feature Feature.
  54971. * @private
  54972. */
  54973. ol.renderer.vector.renderMultiPointGeometry_ =
  54974. function(replayGroup, geometry, style, feature) {
  54975. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPoint,
  54976. 'geometry should be an ol.goem.MultiPoint');
  54977. var imageStyle = style.getImage();
  54978. if (imageStyle) {
  54979. if (imageStyle.getImageState() != ol.style.ImageState.LOADED) {
  54980. return;
  54981. }
  54982. var imageReplay = replayGroup.getReplay(
  54983. style.getZIndex(), ol.render.ReplayType.IMAGE);
  54984. imageReplay.setImageStyle(imageStyle);
  54985. imageReplay.drawMultiPointGeometry(geometry, feature);
  54986. }
  54987. var textStyle = style.getText();
  54988. if (textStyle) {
  54989. var textReplay = replayGroup.getReplay(
  54990. style.getZIndex(), ol.render.ReplayType.TEXT);
  54991. textReplay.setTextStyle(textStyle);
  54992. var flatCoordinates = geometry.getFlatCoordinates();
  54993. textReplay.drawText(flatCoordinates, 0, flatCoordinates.length,
  54994. geometry.getStride(), geometry, feature);
  54995. }
  54996. };
  54997. /**
  54998. * @param {ol.render.IReplayGroup} replayGroup Replay group.
  54999. * @param {ol.geom.Geometry} geometry Geometry.
  55000. * @param {ol.style.Style} style Style.
  55001. * @param {ol.Feature} feature Feature.
  55002. * @private
  55003. */
  55004. ol.renderer.vector.renderPolygonGeometry_ =
  55005. function(replayGroup, geometry, style, feature) {
  55006. goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
  55007. 'geometry should be an ol.geom.Polygon');
  55008. var fillStyle = style.getFill();
  55009. var strokeStyle = style.getStroke();
  55010. if (fillStyle || strokeStyle) {
  55011. var polygonReplay = replayGroup.getReplay(
  55012. style.getZIndex(), ol.render.ReplayType.POLYGON);
  55013. polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);
  55014. polygonReplay.drawPolygonGeometry(geometry, feature);
  55015. }
  55016. var textStyle = style.getText();
  55017. if (textStyle) {
  55018. var textReplay = replayGroup.getReplay(
  55019. style.getZIndex(), ol.render.ReplayType.TEXT);
  55020. textReplay.setTextStyle(textStyle);
  55021. textReplay.drawText(
  55022. geometry.getFlatInteriorPoint(), 0, 2, 2, geometry, feature);
  55023. }
  55024. };
  55025. /**
  55026. * @const
  55027. * @private
  55028. * @type {Object.<ol.geom.GeometryType,
  55029. * function(ol.render.IReplayGroup, ol.geom.Geometry,
  55030. * ol.style.Style, Object)>}
  55031. */
  55032. ol.renderer.vector.GEOMETRY_RENDERERS_ = {
  55033. 'Point': ol.renderer.vector.renderPointGeometry_,
  55034. 'LineString': ol.renderer.vector.renderLineStringGeometry_,
  55035. 'Polygon': ol.renderer.vector.renderPolygonGeometry_,
  55036. 'MultiPoint': ol.renderer.vector.renderMultiPointGeometry_,
  55037. 'MultiLineString': ol.renderer.vector.renderMultiLineStringGeometry_,
  55038. 'MultiPolygon': ol.renderer.vector.renderMultiPolygonGeometry_,
  55039. 'GeometryCollection': ol.renderer.vector.renderGeometryCollectionGeometry_,
  55040. 'Circle': ol.renderer.vector.renderCircleGeometry_
  55041. };
  55042. goog.provide('ol.ImageCanvas');
  55043. goog.require('goog.asserts');
  55044. goog.require('ol.ImageBase');
  55045. goog.require('ol.ImageState');
  55046. /**
  55047. * @constructor
  55048. * @extends {ol.ImageBase}
  55049. * @param {ol.Extent} extent Extent.
  55050. * @param {number} resolution Resolution.
  55051. * @param {number} pixelRatio Pixel ratio.
  55052. * @param {Array.<ol.Attribution>} attributions Attributions.
  55053. * @param {HTMLCanvasElement} canvas Canvas.
  55054. * @param {ol.ImageCanvasLoader=} opt_loader Optional loader function to
  55055. * support asynchronous canvas drawing.
  55056. */
  55057. ol.ImageCanvas = function(extent, resolution, pixelRatio, attributions,
  55058. canvas, opt_loader) {
  55059. /**
  55060. * Optional canvas loader function.
  55061. * @type {?ol.ImageCanvasLoader}
  55062. * @private
  55063. */
  55064. this.loader_ = opt_loader !== undefined ? opt_loader : null;
  55065. var state = opt_loader !== undefined ?
  55066. ol.ImageState.IDLE : ol.ImageState.LOADED;
  55067. goog.base(this, extent, resolution, pixelRatio, state, attributions);
  55068. /**
  55069. * @private
  55070. * @type {HTMLCanvasElement}
  55071. */
  55072. this.canvas_ = canvas;
  55073. /**
  55074. * @private
  55075. * @type {Error}
  55076. */
  55077. this.error_ = null;
  55078. };
  55079. goog.inherits(ol.ImageCanvas, ol.ImageBase);
  55080. /**
  55081. * Get any error associated with asynchronous rendering.
  55082. * @return {Error} Any error that occurred during rendering.
  55083. */
  55084. ol.ImageCanvas.prototype.getError = function() {
  55085. return this.error_;
  55086. };
  55087. /**
  55088. * Handle async drawing complete.
  55089. * @param {Error} err Any error during drawing.
  55090. * @private
  55091. */
  55092. ol.ImageCanvas.prototype.handleLoad_ = function(err) {
  55093. if (err) {
  55094. this.error_ = err;
  55095. this.state = ol.ImageState.ERROR;
  55096. } else {
  55097. this.state = ol.ImageState.LOADED;
  55098. }
  55099. this.changed();
  55100. };
  55101. /**
  55102. * Trigger drawing on canvas.
  55103. */
  55104. ol.ImageCanvas.prototype.load = function() {
  55105. if (this.state == ol.ImageState.IDLE) {
  55106. goog.asserts.assert(this.loader_, 'this.loader_ must be set');
  55107. this.state = ol.ImageState.LOADING;
  55108. this.changed();
  55109. this.loader_(goog.bind(this.handleLoad_, this));
  55110. }
  55111. };
  55112. /**
  55113. * @inheritDoc
  55114. */
  55115. ol.ImageCanvas.prototype.getImage = function(opt_context) {
  55116. return this.canvas_;
  55117. };
  55118. /**
  55119. * A function that is called to trigger asynchronous canvas drawing. It is
  55120. * called with a "done" callback that should be called when drawing is done.
  55121. * If any error occurs during drawing, the "done" callback should be called with
  55122. * that error.
  55123. *
  55124. * @typedef {function(function(Error))}
  55125. */
  55126. ol.ImageCanvasLoader;
  55127. goog.provide('ol.source.Image');
  55128. goog.provide('ol.source.ImageEvent');
  55129. goog.require('goog.array');
  55130. goog.require('goog.asserts');
  55131. goog.require('goog.events.Event');
  55132. goog.require('ol.Attribution');
  55133. goog.require('ol.Extent');
  55134. goog.require('ol.ImageState');
  55135. goog.require('ol.array');
  55136. goog.require('ol.source.Source');
  55137. /**
  55138. * @typedef {{attributions: (Array.<ol.Attribution>|undefined),
  55139. * extent: (null|ol.Extent|undefined),
  55140. * logo: (string|olx.LogoOptions|undefined),
  55141. * projection: ol.proj.ProjectionLike,
  55142. * resolutions: (Array.<number>|undefined),
  55143. * state: (ol.source.State|undefined)}}
  55144. */
  55145. ol.source.ImageOptions;
  55146. /**
  55147. * @classdesc
  55148. * Abstract base class; normally only used for creating subclasses and not
  55149. * instantiated in apps.
  55150. * Base class for sources providing a single image.
  55151. *
  55152. * @constructor
  55153. * @extends {ol.source.Source}
  55154. * @param {ol.source.ImageOptions} options Single image source options.
  55155. * @api
  55156. */
  55157. ol.source.Image = function(options) {
  55158. goog.base(this, {
  55159. attributions: options.attributions,
  55160. extent: options.extent,
  55161. logo: options.logo,
  55162. projection: options.projection,
  55163. state: options.state
  55164. });
  55165. /**
  55166. * @private
  55167. * @type {Array.<number>}
  55168. */
  55169. this.resolutions_ = options.resolutions !== undefined ?
  55170. options.resolutions : null;
  55171. goog.asserts.assert(!this.resolutions_ ||
  55172. goog.array.isSorted(this.resolutions_,
  55173. function(a, b) {
  55174. return b - a;
  55175. }, true), 'resolutions must be null or sorted in descending order');
  55176. };
  55177. goog.inherits(ol.source.Image, ol.source.Source);
  55178. /**
  55179. * @return {Array.<number>} Resolutions.
  55180. */
  55181. ol.source.Image.prototype.getResolutions = function() {
  55182. return this.resolutions_;
  55183. };
  55184. /**
  55185. * @protected
  55186. * @param {number} resolution Resolution.
  55187. * @return {number} Resolution.
  55188. */
  55189. ol.source.Image.prototype.findNearestResolution =
  55190. function(resolution) {
  55191. if (this.resolutions_) {
  55192. var idx = ol.array.linearFindNearest(this.resolutions_, resolution, 0);
  55193. resolution = this.resolutions_[idx];
  55194. }
  55195. return resolution;
  55196. };
  55197. /**
  55198. * @param {ol.Extent} extent Extent.
  55199. * @param {number} resolution Resolution.
  55200. * @param {number} pixelRatio Pixel ratio.
  55201. * @param {ol.proj.Projection} projection Projection.
  55202. * @return {ol.ImageBase} Single image.
  55203. */
  55204. ol.source.Image.prototype.getImage = goog.abstractMethod;
  55205. /**
  55206. * Handle image change events.
  55207. * @param {goog.events.Event} event Event.
  55208. * @protected
  55209. */
  55210. ol.source.Image.prototype.handleImageChange = function(event) {
  55211. var image = /** @type {ol.Image} */ (event.target);
  55212. switch (image.getState()) {
  55213. case ol.ImageState.LOADING:
  55214. this.dispatchEvent(
  55215. new ol.source.ImageEvent(ol.source.ImageEventType.IMAGELOADSTART,
  55216. image));
  55217. break;
  55218. case ol.ImageState.LOADED:
  55219. this.dispatchEvent(
  55220. new ol.source.ImageEvent(ol.source.ImageEventType.IMAGELOADEND,
  55221. image));
  55222. break;
  55223. case ol.ImageState.ERROR:
  55224. this.dispatchEvent(
  55225. new ol.source.ImageEvent(ol.source.ImageEventType.IMAGELOADERROR,
  55226. image));
  55227. break;
  55228. }
  55229. };
  55230. /**
  55231. * Default image load function for image sources that use ol.Image image
  55232. * instances.
  55233. * @param {ol.Image} image Image.
  55234. * @param {string} src Source.
  55235. */
  55236. ol.source.Image.defaultImageLoadFunction = function(image, src) {
  55237. image.getImage().src = src;
  55238. };
  55239. /**
  55240. * @classdesc
  55241. * Events emitted by {@link ol.source.Image} instances are instances of this
  55242. * type.
  55243. *
  55244. * @constructor
  55245. * @extends {goog.events.Event}
  55246. * @implements {oli.source.ImageEvent}
  55247. * @param {string} type Type.
  55248. * @param {ol.Image} image The image.
  55249. */
  55250. ol.source.ImageEvent = function(type, image) {
  55251. goog.base(this, type);
  55252. /**
  55253. * The image related to the event.
  55254. * @type {ol.Image}
  55255. * @api
  55256. */
  55257. this.image = image;
  55258. };
  55259. goog.inherits(ol.source.ImageEvent, goog.events.Event);
  55260. /**
  55261. * @enum {string}
  55262. */
  55263. ol.source.ImageEventType = {
  55264. /**
  55265. * Triggered when an image starts loading.
  55266. * @event ol.source.ImageEvent#imageloadstart
  55267. * @api
  55268. */
  55269. IMAGELOADSTART: 'imageloadstart',
  55270. /**
  55271. * Triggered when an image finishes loading.
  55272. * @event ol.source.ImageEvent#imageloadend
  55273. * @api
  55274. */
  55275. IMAGELOADEND: 'imageloadend',
  55276. /**
  55277. * Triggered if image loading results in an error.
  55278. * @event ol.source.ImageEvent#imageloaderror
  55279. * @api
  55280. */
  55281. IMAGELOADERROR: 'imageloaderror'
  55282. };
  55283. goog.provide('ol.source.ImageCanvas');
  55284. goog.require('ol.CanvasFunctionType');
  55285. goog.require('ol.ImageCanvas');
  55286. goog.require('ol.extent');
  55287. goog.require('ol.source.Image');
  55288. /**
  55289. * @classdesc
  55290. * Base class for image sources where a canvas element is the image.
  55291. *
  55292. * @constructor
  55293. * @extends {ol.source.Image}
  55294. * @param {olx.source.ImageCanvasOptions} options
  55295. * @api
  55296. */
  55297. ol.source.ImageCanvas = function(options) {
  55298. goog.base(this, {
  55299. attributions: options.attributions,
  55300. logo: options.logo,
  55301. projection: options.projection,
  55302. resolutions: options.resolutions,
  55303. state: options.state !== undefined ?
  55304. /** @type {ol.source.State} */ (options.state) : undefined
  55305. });
  55306. /**
  55307. * @private
  55308. * @type {ol.CanvasFunctionType}
  55309. */
  55310. this.canvasFunction_ = options.canvasFunction;
  55311. /**
  55312. * @private
  55313. * @type {ol.ImageCanvas}
  55314. */
  55315. this.canvas_ = null;
  55316. /**
  55317. * @private
  55318. * @type {number}
  55319. */
  55320. this.renderedRevision_ = 0;
  55321. /**
  55322. * @private
  55323. * @type {number}
  55324. */
  55325. this.ratio_ = options.ratio !== undefined ?
  55326. options.ratio : 1.5;
  55327. };
  55328. goog.inherits(ol.source.ImageCanvas, ol.source.Image);
  55329. /**
  55330. * @inheritDoc
  55331. */
  55332. ol.source.ImageCanvas.prototype.getImage =
  55333. function(extent, resolution, pixelRatio, projection) {
  55334. resolution = this.findNearestResolution(resolution);
  55335. var canvas = this.canvas_;
  55336. if (canvas &&
  55337. this.renderedRevision_ == this.getRevision() &&
  55338. canvas.getResolution() == resolution &&
  55339. canvas.getPixelRatio() == pixelRatio &&
  55340. ol.extent.containsExtent(canvas.getExtent(), extent)) {
  55341. return canvas;
  55342. }
  55343. extent = extent.slice();
  55344. ol.extent.scaleFromCenter(extent, this.ratio_);
  55345. var width = ol.extent.getWidth(extent) / resolution;
  55346. var height = ol.extent.getHeight(extent) / resolution;
  55347. var size = [width * pixelRatio, height * pixelRatio];
  55348. var canvasElement = this.canvasFunction_(
  55349. extent, resolution, pixelRatio, size, projection);
  55350. if (canvasElement) {
  55351. canvas = new ol.ImageCanvas(extent, resolution, pixelRatio,
  55352. this.getAttributions(), canvasElement);
  55353. }
  55354. this.canvas_ = canvas;
  55355. this.renderedRevision_ = this.getRevision();
  55356. return canvas;
  55357. };
  55358. goog.provide('ol.Feature');
  55359. goog.provide('ol.FeatureStyleFunction');
  55360. goog.require('goog.asserts');
  55361. goog.require('goog.events');
  55362. goog.require('goog.events.EventType');
  55363. goog.require('ol');
  55364. goog.require('ol.Object');
  55365. goog.require('ol.geom.Geometry');
  55366. goog.require('ol.style.Style');
  55367. /**
  55368. * @classdesc
  55369. * A vector object for geographic features with a geometry and other
  55370. * attribute properties, similar to the features in vector file formats like
  55371. * GeoJSON.
  55372. *
  55373. * Features can be styled individually with `setStyle`; otherwise they use the
  55374. * style of their vector layer.
  55375. *
  55376. * Note that attribute properties are set as {@link ol.Object} properties on
  55377. * the feature object, so they are observable, and have get/set accessors.
  55378. *
  55379. * Typically, a feature has a single geometry property. You can set the
  55380. * geometry using the `setGeometry` method and get it with `getGeometry`.
  55381. * It is possible to store more than one geometry on a feature using attribute
  55382. * properties. By default, the geometry used for rendering is identified by
  55383. * the property name `geometry`. If you want to use another geometry property
  55384. * for rendering, use the `setGeometryName` method to change the attribute
  55385. * property associated with the geometry for the feature. For example:
  55386. *
  55387. * ```js
  55388. * var feature = new ol.Feature({
  55389. * geometry: new ol.geom.Polygon(polyCoords),
  55390. * labelPoint: new ol.geom.Point(labelCoords),
  55391. * name: 'My Polygon'
  55392. * });
  55393. *
  55394. * // get the polygon geometry
  55395. * var poly = feature.getGeometry();
  55396. *
  55397. * // Render the feature as a point using the coordinates from labelPoint
  55398. * feature.setGeometryName('labelPoint');
  55399. *
  55400. * // get the point geometry
  55401. * var point = feature.getGeometry();
  55402. * ```
  55403. *
  55404. * @constructor
  55405. * @extends {ol.Object}
  55406. * @param {ol.geom.Geometry|Object.<string, *>=} opt_geometryOrProperties
  55407. * You may pass a Geometry object directly, or an object literal
  55408. * containing properties. If you pass an object literal, you may
  55409. * include a Geometry associated with a `geometry` key.
  55410. * @api stable
  55411. */
  55412. ol.Feature = function(opt_geometryOrProperties) {
  55413. goog.base(this);
  55414. /**
  55415. * @private
  55416. * @type {number|string|undefined}
  55417. */
  55418. this.id_ = undefined;
  55419. /**
  55420. * @type {string}
  55421. * @private
  55422. */
  55423. this.geometryName_ = 'geometry';
  55424. /**
  55425. * User provided style.
  55426. * @private
  55427. * @type {ol.style.Style|Array.<ol.style.Style>|
  55428. * ol.FeatureStyleFunction}
  55429. */
  55430. this.style_ = null;
  55431. /**
  55432. * @private
  55433. * @type {ol.FeatureStyleFunction|undefined}
  55434. */
  55435. this.styleFunction_ = undefined;
  55436. /**
  55437. * @private
  55438. * @type {goog.events.Key}
  55439. */
  55440. this.geometryChangeKey_ = null;
  55441. goog.events.listen(
  55442. this, ol.Object.getChangeEventType(this.geometryName_),
  55443. this.handleGeometryChanged_, false, this);
  55444. if (opt_geometryOrProperties !== undefined) {
  55445. if (opt_geometryOrProperties instanceof ol.geom.Geometry ||
  55446. !opt_geometryOrProperties) {
  55447. var geometry = /** @type {ol.geom.Geometry} */ (opt_geometryOrProperties);
  55448. this.setGeometry(geometry);
  55449. } else {
  55450. goog.asserts.assert(goog.isObject(opt_geometryOrProperties),
  55451. 'opt_geometryOrProperties should be an Object');
  55452. var properties = /** @type {Object.<string, *>} */
  55453. (opt_geometryOrProperties);
  55454. this.setProperties(properties);
  55455. }
  55456. }
  55457. };
  55458. goog.inherits(ol.Feature, ol.Object);
  55459. /**
  55460. * Clone this feature. If the original feature has a geometry it
  55461. * is also cloned. The feature id is not set in the clone.
  55462. * @return {ol.Feature} The clone.
  55463. * @api stable
  55464. */
  55465. ol.Feature.prototype.clone = function() {
  55466. var clone = new ol.Feature(this.getProperties());
  55467. clone.setGeometryName(this.getGeometryName());
  55468. var geometry = this.getGeometry();
  55469. if (geometry) {
  55470. clone.setGeometry(geometry.clone());
  55471. }
  55472. var style = this.getStyle();
  55473. if (style) {
  55474. clone.setStyle(style);
  55475. }
  55476. return clone;
  55477. };
  55478. /**
  55479. * Get the feature's default geometry. A feature may have any number of named
  55480. * geometries. The "default" geometry (the one that is rendered by default) is
  55481. * set when calling {@link ol.Feature#setGeometry}.
  55482. * @return {ol.geom.Geometry|undefined} The default geometry for the feature.
  55483. * @api stable
  55484. * @observable
  55485. */
  55486. ol.Feature.prototype.getGeometry = function() {
  55487. return /** @type {ol.geom.Geometry|undefined} */ (
  55488. this.get(this.geometryName_));
  55489. };
  55490. /**
  55491. * Get the feature identifier. This is a stable identifier for the feature and
  55492. * is either set when reading data from a remote source or set explicitly by
  55493. * calling {@link ol.Feature#setId}.
  55494. * @return {number|string|undefined} Id.
  55495. * @api stable
  55496. * @observable
  55497. */
  55498. ol.Feature.prototype.getId = function() {
  55499. return this.id_;
  55500. };
  55501. /**
  55502. * Get the name of the feature's default geometry. By default, the default
  55503. * geometry is named `geometry`.
  55504. * @return {string} Get the property name associated with the default geometry
  55505. * for this feature.
  55506. * @api stable
  55507. */
  55508. ol.Feature.prototype.getGeometryName = function() {
  55509. return this.geometryName_;
  55510. };
  55511. /**
  55512. * Get the feature's style. This return for this method depends on what was
  55513. * provided to the {@link ol.Feature#setStyle} method.
  55514. * @return {ol.style.Style|Array.<ol.style.Style>|
  55515. * ol.FeatureStyleFunction} The feature style.
  55516. * @api stable
  55517. * @observable
  55518. */
  55519. ol.Feature.prototype.getStyle = function() {
  55520. return this.style_;
  55521. };
  55522. /**
  55523. * Get the feature's style function.
  55524. * @return {ol.FeatureStyleFunction|undefined} Return a function
  55525. * representing the current style of this feature.
  55526. * @api stable
  55527. */
  55528. ol.Feature.prototype.getStyleFunction = function() {
  55529. return this.styleFunction_;
  55530. };
  55531. /**
  55532. * @private
  55533. */
  55534. ol.Feature.prototype.handleGeometryChange_ = function() {
  55535. this.changed();
  55536. };
  55537. /**
  55538. * @private
  55539. */
  55540. ol.Feature.prototype.handleGeometryChanged_ = function() {
  55541. if (this.geometryChangeKey_) {
  55542. goog.events.unlistenByKey(this.geometryChangeKey_);
  55543. this.geometryChangeKey_ = null;
  55544. }
  55545. var geometry = this.getGeometry();
  55546. if (geometry) {
  55547. this.geometryChangeKey_ = goog.events.listen(geometry,
  55548. goog.events.EventType.CHANGE, this.handleGeometryChange_, false, this);
  55549. }
  55550. this.changed();
  55551. };
  55552. /**
  55553. * Set the default geometry for the feature. This will update the property
  55554. * with the name returned by {@link ol.Feature#getGeometryName}.
  55555. * @param {ol.geom.Geometry|undefined} geometry The new geometry.
  55556. * @api stable
  55557. * @observable
  55558. */
  55559. ol.Feature.prototype.setGeometry = function(geometry) {
  55560. this.set(this.geometryName_, geometry);
  55561. };
  55562. /**
  55563. * Set the style for the feature. This can be a single style object, an array
  55564. * of styles, or a function that takes a resolution and returns an array of
  55565. * styles. If it is `null` the feature has no style (a `null` style).
  55566. * @param {ol.style.Style|Array.<ol.style.Style>|
  55567. * ol.FeatureStyleFunction} style Style for this feature.
  55568. * @api stable
  55569. * @observable
  55570. */
  55571. ol.Feature.prototype.setStyle = function(style) {
  55572. this.style_ = style;
  55573. this.styleFunction_ = !style ?
  55574. undefined : ol.Feature.createStyleFunction(style);
  55575. this.changed();
  55576. };
  55577. /**
  55578. * Set the feature id. The feature id is considered stable and may be used when
  55579. * requesting features or comparing identifiers returned from a remote source.
  55580. * The feature id can be used with the {@link ol.source.Vector#getFeatureById}
  55581. * method.
  55582. * @param {number|string|undefined} id The feature id.
  55583. * @api stable
  55584. * @observable
  55585. */
  55586. ol.Feature.prototype.setId = function(id) {
  55587. this.id_ = id;
  55588. this.changed();
  55589. };
  55590. /**
  55591. * Set the property name to be used when getting the feature's default geometry.
  55592. * When calling {@link ol.Feature#getGeometry}, the value of the property with
  55593. * this name will be returned.
  55594. * @param {string} name The property name of the default geometry.
  55595. * @api stable
  55596. */
  55597. ol.Feature.prototype.setGeometryName = function(name) {
  55598. goog.events.unlisten(
  55599. this, ol.Object.getChangeEventType(this.geometryName_),
  55600. this.handleGeometryChanged_, false, this);
  55601. this.geometryName_ = name;
  55602. goog.events.listen(
  55603. this, ol.Object.getChangeEventType(this.geometryName_),
  55604. this.handleGeometryChanged_, false, this);
  55605. this.handleGeometryChanged_();
  55606. };
  55607. /**
  55608. * A function that returns an array of {@link ol.style.Style styles} given a
  55609. * resolution. The `this` keyword inside the function references the
  55610. * {@link ol.Feature} to be styled.
  55611. *
  55612. * @typedef {function(this: ol.Feature, number): Array.<ol.style.Style>}
  55613. * @api stable
  55614. */
  55615. ol.FeatureStyleFunction;
  55616. /**
  55617. * Convert the provided object into a feature style function. Functions passed
  55618. * through unchanged. Arrays of ol.style.Style or single style objects wrapped
  55619. * in a new feature style function.
  55620. * @param {ol.FeatureStyleFunction|!Array.<ol.style.Style>|!ol.style.Style} obj
  55621. * A feature style function, a single style, or an array of styles.
  55622. * @return {ol.FeatureStyleFunction} A style function.
  55623. */
  55624. ol.Feature.createStyleFunction = function(obj) {
  55625. var styleFunction;
  55626. if (goog.isFunction(obj)) {
  55627. styleFunction = obj;
  55628. } else {
  55629. /**
  55630. * @type {Array.<ol.style.Style>}
  55631. */
  55632. var styles;
  55633. if (goog.isArray(obj)) {
  55634. styles = obj;
  55635. } else {
  55636. goog.asserts.assertInstanceof(obj, ol.style.Style,
  55637. 'obj should be an ol.style.Style');
  55638. styles = [obj];
  55639. }
  55640. styleFunction = function() {
  55641. return styles;
  55642. };
  55643. }
  55644. return styleFunction;
  55645. };
  55646. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  55647. //
  55648. // Licensed under the Apache License, Version 2.0 (the "License");
  55649. // you may not use this file except in compliance with the License.
  55650. // You may obtain a copy of the License at
  55651. //
  55652. // http://www.apache.org/licenses/LICENSE-2.0
  55653. //
  55654. // Unless required by applicable law or agreed to in writing, software
  55655. // distributed under the License is distributed on an "AS-IS" BASIS,
  55656. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55657. // See the License for the specific language governing permissions and
  55658. // limitations under the License.
  55659. /**
  55660. * @fileoverview Common events for the network classes.
  55661. */
  55662. goog.provide('goog.net.EventType');
  55663. /**
  55664. * Event names for network events
  55665. * @enum {string}
  55666. */
  55667. goog.net.EventType = {
  55668. COMPLETE: 'complete',
  55669. SUCCESS: 'success',
  55670. ERROR: 'error',
  55671. ABORT: 'abort',
  55672. READY: 'ready',
  55673. READY_STATE_CHANGE: 'readystatechange',
  55674. TIMEOUT: 'timeout',
  55675. INCREMENTAL_DATA: 'incrementaldata',
  55676. PROGRESS: 'progress'
  55677. };
  55678. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  55679. //
  55680. // Licensed under the Apache License, Version 2.0 (the "License");
  55681. // you may not use this file except in compliance with the License.
  55682. // You may obtain a copy of the License at
  55683. //
  55684. // http://www.apache.org/licenses/LICENSE-2.0
  55685. //
  55686. // Unless required by applicable law or agreed to in writing, software
  55687. // distributed under the License is distributed on an "AS-IS" BASIS,
  55688. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55689. // See the License for the specific language governing permissions and
  55690. // limitations under the License.
  55691. goog.provide('goog.Thenable');
  55692. /**
  55693. * Provides a more strict interface for Thenables in terms of
  55694. * http://promisesaplus.com for interop with {@see goog.Promise}.
  55695. *
  55696. * @interface
  55697. * @extends {IThenable<TYPE>}
  55698. * @template TYPE
  55699. */
  55700. goog.Thenable = function() {};
  55701. /**
  55702. * Adds callbacks that will operate on the result of the Thenable, returning a
  55703. * new child Promise.
  55704. *
  55705. * If the Thenable is fulfilled, the {@code onFulfilled} callback will be
  55706. * invoked with the fulfillment value as argument, and the child Promise will
  55707. * be fulfilled with the return value of the callback. If the callback throws
  55708. * an exception, the child Promise will be rejected with the thrown value
  55709. * instead.
  55710. *
  55711. * If the Thenable is rejected, the {@code onRejected} callback will be invoked
  55712. * with the rejection reason as argument, and the child Promise will be rejected
  55713. * with the return value of the callback or thrown value.
  55714. *
  55715. * @param {?(function(this:THIS, TYPE): VALUE)=} opt_onFulfilled A
  55716. * function that will be invoked with the fulfillment value if the Promise
  55717. * is fullfilled.
  55718. * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will
  55719. * be invoked with the rejection reason if the Promise is rejected.
  55720. * @param {THIS=} opt_context An optional context object that will be the
  55721. * execution context for the callbacks. By default, functions are executed
  55722. * with the default this.
  55723. *
  55724. * @return {RESULT} A new Promise that will receive the result
  55725. * of the fulfillment or rejection callback.
  55726. * @template VALUE
  55727. * @template THIS
  55728. *
  55729. * When a Promise (or thenable) is returned from the fulfilled callback,
  55730. * the result is the payload of that promise, not the promise itself.
  55731. *
  55732. * @template RESULT := type('goog.Promise',
  55733. * cond(isUnknown(VALUE), unknown(),
  55734. * mapunion(VALUE, (V) =>
  55735. * cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),
  55736. * templateTypeOf(V, 0),
  55737. * cond(sub(V, 'Thenable'),
  55738. * unknown(),
  55739. * V)))))
  55740. * =:
  55741. *
  55742. */
  55743. goog.Thenable.prototype.then = function(opt_onFulfilled, opt_onRejected,
  55744. opt_context) {};
  55745. /**
  55746. * An expando property to indicate that an object implements
  55747. * {@code goog.Thenable}.
  55748. *
  55749. * {@see addImplementation}.
  55750. *
  55751. * @const
  55752. */
  55753. goog.Thenable.IMPLEMENTED_BY_PROP = '$goog_Thenable';
  55754. /**
  55755. * Marks a given class (constructor) as an implementation of Thenable, so
  55756. * that we can query that fact at runtime. The class must have already
  55757. * implemented the interface.
  55758. * Exports a 'then' method on the constructor prototype, so that the objects
  55759. * also implement the extern {@see goog.Thenable} interface for interop with
  55760. * other Promise implementations.
  55761. * @param {function(new:goog.Thenable,...?)} ctor The class constructor. The
  55762. * corresponding class must have already implemented the interface.
  55763. */
  55764. goog.Thenable.addImplementation = function(ctor) {
  55765. goog.exportProperty(ctor.prototype, 'then', ctor.prototype.then);
  55766. if (COMPILED) {
  55767. ctor.prototype[goog.Thenable.IMPLEMENTED_BY_PROP] = true;
  55768. } else {
  55769. // Avoids dictionary access in uncompiled mode.
  55770. ctor.prototype.$goog_Thenable = true;
  55771. }
  55772. };
  55773. /**
  55774. * @param {*} object
  55775. * @return {boolean} Whether a given instance implements {@code goog.Thenable}.
  55776. * The class/superclass of the instance must call {@code addImplementation}.
  55777. */
  55778. goog.Thenable.isImplementedBy = function(object) {
  55779. if (!object) {
  55780. return false;
  55781. }
  55782. try {
  55783. if (COMPILED) {
  55784. return !!object[goog.Thenable.IMPLEMENTED_BY_PROP];
  55785. }
  55786. return !!object.$goog_Thenable;
  55787. } catch (e) {
  55788. // Property access seems to be forbidden.
  55789. return false;
  55790. }
  55791. };
  55792. // Copyright 2015 The Closure Library Authors. All Rights Reserved.
  55793. //
  55794. // Licensed under the Apache License, Version 2.0 (the "License");
  55795. // you may not use this file except in compliance with the License.
  55796. // You may obtain a copy of the License at
  55797. //
  55798. // http://www.apache.org/licenses/LICENSE-2.0
  55799. //
  55800. // Unless required by applicable law or agreed to in writing, software
  55801. // distributed under the License is distributed on an "AS-IS" BASIS,
  55802. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55803. // See the License for the specific language governing permissions and
  55804. // limitations under the License.
  55805. /**
  55806. * @fileoverview Simple freelist.
  55807. *
  55808. * An anterative to goog.structs.SimplePool, it imposes the requirement that the
  55809. * objects in the list contain a "next" property that can be used to maintain
  55810. * the pool.
  55811. */
  55812. goog.provide('goog.async.FreeList');
  55813. /**
  55814. * @template ITEM
  55815. */
  55816. goog.async.FreeList = goog.defineClass(null, {
  55817. /**
  55818. * @param {function():ITEM} create
  55819. * @param {function(ITEM):void} reset
  55820. * @param {number} limit
  55821. */
  55822. constructor: function(create, reset, limit) {
  55823. /** @const {number} */
  55824. this.limit_ = limit;
  55825. /** @const {function()} */
  55826. this.create_ = create;
  55827. /** @const {function(ITEM):void} */
  55828. this.reset_ = reset;
  55829. /** @type {number} */
  55830. this.occupants_ = 0;
  55831. /** @type {ITEM} */
  55832. this.head_ = null;
  55833. },
  55834. /**
  55835. * @return {ITEM}
  55836. */
  55837. get: function() {
  55838. var item;
  55839. if (this.occupants_ > 0) {
  55840. this.occupants_--;
  55841. item = this.head_;
  55842. this.head_ = item.next;
  55843. item.next = null;
  55844. } else {
  55845. item = this.create_();
  55846. }
  55847. return item;
  55848. },
  55849. /**
  55850. * @param {ITEM} item An item available for possible future reuse.
  55851. */
  55852. put: function(item) {
  55853. this.reset_(item);
  55854. if (this.occupants_ < this.limit_) {
  55855. this.occupants_++;
  55856. item.next = this.head_;
  55857. this.head_ = item;
  55858. }
  55859. },
  55860. /**
  55861. * Visible for testing.
  55862. * @package
  55863. * @return {number}
  55864. */
  55865. occupants: function() {
  55866. return this.occupants_;
  55867. }
  55868. });
  55869. // Copyright 2015 The Closure Library Authors. All Rights Reserved.
  55870. //
  55871. // Licensed under the Apache License, Version 2.0 (the "License");
  55872. // you may not use this file except in compliance with the License.
  55873. // You may obtain a copy of the License at
  55874. //
  55875. // http://www.apache.org/licenses/LICENSE-2.0
  55876. //
  55877. // Unless required by applicable law or agreed to in writing, software
  55878. // distributed under the License is distributed on an "AS-IS" BASIS,
  55879. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55880. // See the License for the specific language governing permissions and
  55881. // limitations under the License.
  55882. goog.provide('goog.async.WorkItem');
  55883. goog.provide('goog.async.WorkQueue');
  55884. goog.require('goog.asserts');
  55885. goog.require('goog.async.FreeList');
  55886. // TODO(johnlenz): generalize the WorkQueue if this is used by more
  55887. // than goog.async.run.
  55888. /**
  55889. * A low GC workqueue. The key elements of this design:
  55890. * - avoids the need for goog.bind or equivalent by carrying scope
  55891. * - avoids the need for array reallocation by using a linked list
  55892. * - minimizes work entry objects allocation by recycling objects
  55893. * @constructor
  55894. * @final
  55895. * @struct
  55896. */
  55897. goog.async.WorkQueue = function() {
  55898. this.workHead_ = null;
  55899. this.workTail_ = null;
  55900. };
  55901. /** @define {number} The maximum number of entries to keep for recycling. */
  55902. goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);
  55903. /** @const @private {goog.async.FreeList<goog.async.WorkItem>} */
  55904. goog.async.WorkQueue.freelist_ = new goog.async.FreeList(
  55905. function() {return new goog.async.WorkItem(); },
  55906. function(item) {item.reset()},
  55907. goog.async.WorkQueue.DEFAULT_MAX_UNUSED);
  55908. /**
  55909. * @param {function()} fn
  55910. * @param {Object|null|undefined} scope
  55911. */
  55912. goog.async.WorkQueue.prototype.add = function(fn, scope) {
  55913. var item = this.getUnusedItem_();
  55914. item.set(fn, scope);
  55915. if (this.workTail_) {
  55916. this.workTail_.next = item;
  55917. this.workTail_ = item;
  55918. } else {
  55919. goog.asserts.assert(!this.workHead_);
  55920. this.workHead_ = item;
  55921. this.workTail_ = item;
  55922. }
  55923. };
  55924. /**
  55925. * @return {goog.async.WorkItem}
  55926. */
  55927. goog.async.WorkQueue.prototype.remove = function() {
  55928. var item = null;
  55929. if (this.workHead_) {
  55930. item = this.workHead_;
  55931. this.workHead_ = this.workHead_.next;
  55932. if (!this.workHead_) {
  55933. this.workTail_ = null;
  55934. }
  55935. item.next = null;
  55936. }
  55937. return item;
  55938. };
  55939. /**
  55940. * @param {goog.async.WorkItem} item
  55941. */
  55942. goog.async.WorkQueue.prototype.returnUnused = function(item) {
  55943. goog.async.WorkQueue.freelist_.put(item);
  55944. };
  55945. /**
  55946. * @return {goog.async.WorkItem}
  55947. * @private
  55948. */
  55949. goog.async.WorkQueue.prototype.getUnusedItem_ = function() {
  55950. return goog.async.WorkQueue.freelist_.get();
  55951. };
  55952. /**
  55953. * @constructor
  55954. * @final
  55955. * @struct
  55956. */
  55957. goog.async.WorkItem = function() {
  55958. /** @type {?function()} */
  55959. this.fn = null;
  55960. /** @type {Object|null|undefined} */
  55961. this.scope = null;
  55962. /** @type {?goog.async.WorkItem} */
  55963. this.next = null;
  55964. };
  55965. /**
  55966. * @param {function()} fn
  55967. * @param {Object|null|undefined} scope
  55968. */
  55969. goog.async.WorkItem.prototype.set = function(fn, scope) {
  55970. this.fn = fn;
  55971. this.scope = scope;
  55972. this.next = null;
  55973. };
  55974. /** Reset the work item so they don't prevent GC before reuse */
  55975. goog.async.WorkItem.prototype.reset = function() {
  55976. this.fn = null;
  55977. this.scope = null;
  55978. this.next = null;
  55979. };
  55980. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  55981. //
  55982. // Licensed under the Apache License, Version 2.0 (the "License");
  55983. // you may not use this file except in compliance with the License.
  55984. // You may obtain a copy of the License at
  55985. //
  55986. // http://www.apache.org/licenses/LICENSE-2.0
  55987. //
  55988. // Unless required by applicable law or agreed to in writing, software
  55989. // distributed under the License is distributed on an "AS-IS" BASIS,
  55990. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  55991. // See the License for the specific language governing permissions and
  55992. // limitations under the License.
  55993. /**
  55994. * @fileoverview Simple notifiers for the Closure testing framework.
  55995. *
  55996. * @author johnlenz@google.com (John Lenz)
  55997. */
  55998. goog.provide('goog.testing.watchers');
  55999. /** @private {!Array<function()>} */
  56000. goog.testing.watchers.resetWatchers_ = [];
  56001. /**
  56002. * Fires clock reset watching functions.
  56003. */
  56004. goog.testing.watchers.signalClockReset = function() {
  56005. var watchers = goog.testing.watchers.resetWatchers_;
  56006. for (var i = 0; i < watchers.length; i++) {
  56007. goog.testing.watchers.resetWatchers_[i]();
  56008. }
  56009. };
  56010. /**
  56011. * Enqueues a function to be called when the clock used for setTimeout is reset.
  56012. * @param {function()} fn
  56013. */
  56014. goog.testing.watchers.watchClockReset = function(fn) {
  56015. goog.testing.watchers.resetWatchers_.push(fn);
  56016. };
  56017. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  56018. //
  56019. // Licensed under the Apache License, Version 2.0 (the "License");
  56020. // you may not use this file except in compliance with the License.
  56021. // You may obtain a copy of the License at
  56022. //
  56023. // http://www.apache.org/licenses/LICENSE-2.0
  56024. //
  56025. // Unless required by applicable law or agreed to in writing, software
  56026. // distributed under the License is distributed on an "AS-IS" BASIS,
  56027. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56028. // See the License for the specific language governing permissions and
  56029. // limitations under the License.
  56030. goog.provide('goog.async.run');
  56031. goog.require('goog.async.WorkQueue');
  56032. goog.require('goog.async.nextTick');
  56033. goog.require('goog.async.throwException');
  56034. goog.require('goog.testing.watchers');
  56035. /**
  56036. * Fires the provided callback just before the current callstack unwinds, or as
  56037. * soon as possible after the current JS execution context.
  56038. * @param {function(this:THIS)} callback
  56039. * @param {THIS=} opt_context Object to use as the "this value" when calling
  56040. * the provided function.
  56041. * @template THIS
  56042. */
  56043. goog.async.run = function(callback, opt_context) {
  56044. if (!goog.async.run.schedule_) {
  56045. goog.async.run.initializeRunner_();
  56046. }
  56047. if (!goog.async.run.workQueueScheduled_) {
  56048. // Nothing is currently scheduled, schedule it now.
  56049. goog.async.run.schedule_();
  56050. goog.async.run.workQueueScheduled_ = true;
  56051. }
  56052. goog.async.run.workQueue_.add(callback, opt_context);
  56053. };
  56054. /**
  56055. * Initializes the function to use to process the work queue.
  56056. * @private
  56057. */
  56058. goog.async.run.initializeRunner_ = function() {
  56059. // If native Promises are available in the browser, just schedule the callback
  56060. // on a fulfilled promise, which is specified to be async, but as fast as
  56061. // possible.
  56062. if (goog.global.Promise && goog.global.Promise.resolve) {
  56063. var promise = goog.global.Promise.resolve(undefined);
  56064. goog.async.run.schedule_ = function() {
  56065. promise.then(goog.async.run.processWorkQueue);
  56066. };
  56067. } else {
  56068. goog.async.run.schedule_ = function() {
  56069. goog.async.nextTick(goog.async.run.processWorkQueue);
  56070. };
  56071. }
  56072. };
  56073. /**
  56074. * Forces goog.async.run to use nextTick instead of Promise.
  56075. *
  56076. * This should only be done in unit tests. It's useful because MockClock
  56077. * replaces nextTick, but not the browser Promise implementation, so it allows
  56078. * Promise-based code to be tested with MockClock.
  56079. *
  56080. * However, we also want to run promises if the MockClock is no longer in
  56081. * control so we schedule a backup "setTimeout" to the unmocked timeout if
  56082. * provided.
  56083. *
  56084. * @param {function(function())=} opt_realSetTimeout
  56085. */
  56086. goog.async.run.forceNextTick = function(opt_realSetTimeout) {
  56087. goog.async.run.schedule_ = function() {
  56088. goog.async.nextTick(goog.async.run.processWorkQueue);
  56089. if (opt_realSetTimeout) {
  56090. opt_realSetTimeout(goog.async.run.processWorkQueue);
  56091. }
  56092. };
  56093. };
  56094. /**
  56095. * The function used to schedule work asynchronousely.
  56096. * @private {function()}
  56097. */
  56098. goog.async.run.schedule_;
  56099. /** @private {boolean} */
  56100. goog.async.run.workQueueScheduled_ = false;
  56101. /** @private {!goog.async.WorkQueue} */
  56102. goog.async.run.workQueue_ = new goog.async.WorkQueue();
  56103. if (goog.DEBUG) {
  56104. /**
  56105. * Reset the work queue.
  56106. * @private
  56107. */
  56108. goog.async.run.resetQueue_ = function() {
  56109. goog.async.run.workQueueScheduled_ = false;
  56110. goog.async.run.workQueue_ = new goog.async.WorkQueue();
  56111. };
  56112. // If there is a clock implemenation in use for testing
  56113. // and it is reset, reset the queue.
  56114. goog.testing.watchers.watchClockReset(goog.async.run.resetQueue_);
  56115. }
  56116. /**
  56117. * Run any pending goog.async.run work items. This function is not intended
  56118. * for general use, but for use by entry point handlers to run items ahead of
  56119. * goog.async.nextTick.
  56120. */
  56121. goog.async.run.processWorkQueue = function() {
  56122. // NOTE: additional work queue items may be added while processing.
  56123. var item = null;
  56124. while (item = goog.async.run.workQueue_.remove()) {
  56125. try {
  56126. item.fn.call(item.scope);
  56127. } catch (e) {
  56128. goog.async.throwException(e);
  56129. }
  56130. goog.async.run.workQueue_.returnUnused(item);
  56131. }
  56132. // There are no more work items, allow processing to be scheduled again.
  56133. goog.async.run.workQueueScheduled_ = false;
  56134. };
  56135. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  56136. //
  56137. // Licensed under the Apache License, Version 2.0 (the "License");
  56138. // you may not use this file except in compliance with the License.
  56139. // You may obtain a copy of the License at
  56140. //
  56141. // http://www.apache.org/licenses/LICENSE-2.0
  56142. //
  56143. // Unless required by applicable law or agreed to in writing, software
  56144. // distributed under the License is distributed on an "AS-IS" BASIS,
  56145. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56146. // See the License for the specific language governing permissions and
  56147. // limitations under the License.
  56148. goog.provide('goog.promise.Resolver');
  56149. /**
  56150. * Resolver interface for promises. The resolver is a convenience interface that
  56151. * bundles the promise and its associated resolve and reject functions together,
  56152. * for cases where the resolver needs to be persisted internally.
  56153. *
  56154. * @interface
  56155. * @template TYPE
  56156. */
  56157. goog.promise.Resolver = function() {};
  56158. /**
  56159. * The promise that created this resolver.
  56160. * @type {!goog.Promise<TYPE>}
  56161. */
  56162. goog.promise.Resolver.prototype.promise;
  56163. /**
  56164. * Resolves this resolver with the specified value.
  56165. * @type {function((TYPE|goog.Promise<TYPE>|Thenable)=)}
  56166. */
  56167. goog.promise.Resolver.prototype.resolve;
  56168. /**
  56169. * Rejects this resolver with the specified reason.
  56170. * @type {function(*=): void}
  56171. */
  56172. goog.promise.Resolver.prototype.reject;
  56173. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  56174. //
  56175. // Licensed under the Apache License, Version 2.0 (the "License");
  56176. // you may not use this file except in compliance with the License.
  56177. // You may obtain a copy of the License at
  56178. //
  56179. // http://www.apache.org/licenses/LICENSE-2.0
  56180. //
  56181. // Unless required by applicable law or agreed to in writing, software
  56182. // distributed under the License is distributed on an "AS-IS" BASIS,
  56183. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56184. // See the License for the specific language governing permissions and
  56185. // limitations under the License.
  56186. goog.provide('goog.Promise');
  56187. goog.require('goog.Thenable');
  56188. goog.require('goog.asserts');
  56189. goog.require('goog.async.FreeList');
  56190. goog.require('goog.async.run');
  56191. goog.require('goog.async.throwException');
  56192. goog.require('goog.debug.Error');
  56193. goog.require('goog.promise.Resolver');
  56194. /**
  56195. * Promises provide a result that may be resolved asynchronously. A Promise may
  56196. * be resolved by being fulfilled with a fulfillment value, rejected with a
  56197. * rejection reason, or blocked by another Promise. A Promise is said to be
  56198. * settled if it is either fulfilled or rejected. Once settled, the Promise
  56199. * result is immutable.
  56200. *
  56201. * Promises may represent results of any type, including undefined. Rejection
  56202. * reasons are typically Errors, but may also be of any type. Closure Promises
  56203. * allow for optional type annotations that enforce that fulfillment values are
  56204. * of the appropriate types at compile time.
  56205. *
  56206. * The result of a Promise is accessible by calling {@code then} and registering
  56207. * {@code onFulfilled} and {@code onRejected} callbacks. Once the Promise
  56208. * is settled, the relevant callbacks are invoked with the fulfillment value or
  56209. * rejection reason as argument. Callbacks are always invoked in the order they
  56210. * were registered, even when additional {@code then} calls are made from inside
  56211. * another callback. A callback is always run asynchronously sometime after the
  56212. * scope containing the registering {@code then} invocation has returned.
  56213. *
  56214. * If a Promise is resolved with another Promise, the first Promise will block
  56215. * until the second is settled, and then assumes the same result as the second
  56216. * Promise. This allows Promises to depend on the results of other Promises,
  56217. * linking together multiple asynchronous operations.
  56218. *
  56219. * This implementation is compatible with the Promises/A+ specification and
  56220. * passes that specification's conformance test suite. A Closure Promise may be
  56221. * resolved with a Promise instance (or sufficiently compatible Promise-like
  56222. * object) created by other Promise implementations. From the specification,
  56223. * Promise-like objects are known as "Thenables".
  56224. *
  56225. * @see http://promisesaplus.com/
  56226. *
  56227. * @param {function(
  56228. * this:RESOLVER_CONTEXT,
  56229. * function((TYPE|IThenable<TYPE>|Thenable)=),
  56230. * function(*=)): void} resolver
  56231. * Initialization function that is invoked immediately with {@code resolve}
  56232. * and {@code reject} functions as arguments. The Promise is resolved or
  56233. * rejected with the first argument passed to either function.
  56234. * @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the
  56235. * resolver function. If unspecified, the resolver function will be executed
  56236. * in the default scope.
  56237. * @constructor
  56238. * @struct
  56239. * @final
  56240. * @implements {goog.Thenable<TYPE>}
  56241. * @template TYPE,RESOLVER_CONTEXT
  56242. */
  56243. goog.Promise = function(resolver, opt_context) {
  56244. /**
  56245. * The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or
  56246. * BLOCKED.
  56247. * @private {goog.Promise.State_}
  56248. */
  56249. this.state_ = goog.Promise.State_.PENDING;
  56250. /**
  56251. * The settled result of the Promise. Immutable once set with either a
  56252. * fulfillment value or rejection reason.
  56253. * @private {*}
  56254. */
  56255. this.result_ = undefined;
  56256. /**
  56257. * For Promises created by calling {@code then()}, the originating parent.
  56258. * @private {goog.Promise}
  56259. */
  56260. this.parent_ = null;
  56261. /**
  56262. * The linked list of {@code onFulfilled} and {@code onRejected} callbacks
  56263. * added to this Promise by calls to {@code then()}.
  56264. * @private {?goog.Promise.CallbackEntry_}
  56265. */
  56266. this.callbackEntries_ = null;
  56267. /**
  56268. * The tail of the linked list of {@code onFulfilled} and {@code onRejected}
  56269. * callbacks added to this Promise by calls to {@code then()}.
  56270. * @private {?goog.Promise.CallbackEntry_}
  56271. */
  56272. this.callbackEntriesTail_ = null;
  56273. /**
  56274. * Whether the Promise is in the queue of Promises to execute.
  56275. * @private {boolean}
  56276. */
  56277. this.executing_ = false;
  56278. if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
  56279. /**
  56280. * A timeout ID used when the {@code UNHANDLED_REJECTION_DELAY} is greater
  56281. * than 0 milliseconds. The ID is set when the Promise is rejected, and
  56282. * cleared only if an {@code onRejected} callback is invoked for the
  56283. * Promise (or one of its descendants) before the delay is exceeded.
  56284. *
  56285. * If the rejection is not handled before the timeout completes, the
  56286. * rejection reason is passed to the unhandled rejection handler.
  56287. * @private {number}
  56288. */
  56289. this.unhandledRejectionId_ = 0;
  56290. } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
  56291. /**
  56292. * When the {@code UNHANDLED_REJECTION_DELAY} is set to 0 milliseconds, a
  56293. * boolean that is set if the Promise is rejected, and reset to false if an
  56294. * {@code onRejected} callback is invoked for the Promise (or one of its
  56295. * descendants). If the rejection is not handled before the next timestep,
  56296. * the rejection reason is passed to the unhandled rejection handler.
  56297. * @private {boolean}
  56298. */
  56299. this.hadUnhandledRejection_ = false;
  56300. }
  56301. if (goog.Promise.LONG_STACK_TRACES) {
  56302. /**
  56303. * A list of stack trace frames pointing to the locations where this Promise
  56304. * was created or had callbacks added to it. Saved to add additional context
  56305. * to stack traces when an exception is thrown.
  56306. * @private {!Array<string>}
  56307. */
  56308. this.stack_ = [];
  56309. this.addStackTrace_(new Error('created'));
  56310. /**
  56311. * Index of the most recently executed stack frame entry.
  56312. * @private {number}
  56313. */
  56314. this.currentStep_ = 0;
  56315. }
  56316. // As an optimization, we can skip this if resolver is goog.nullFunction.
  56317. // This value is passed internally when creating a promise which will be
  56318. // resolved through a more optimized path.
  56319. if (resolver != goog.nullFunction) {
  56320. try {
  56321. var self = this;
  56322. resolver.call(
  56323. opt_context,
  56324. function(value) {
  56325. self.resolve_(goog.Promise.State_.FULFILLED, value);
  56326. },
  56327. function(reason) {
  56328. if (goog.DEBUG &&
  56329. !(reason instanceof goog.Promise.CancellationError)) {
  56330. try {
  56331. // Promise was rejected. Step up one call frame to see why.
  56332. if (reason instanceof Error) {
  56333. throw reason;
  56334. } else {
  56335. throw new Error('Promise rejected.');
  56336. }
  56337. } catch (e) {
  56338. // Only thrown so browser dev tools can catch rejections of
  56339. // promises when the option to break on caught exceptions is
  56340. // activated.
  56341. }
  56342. }
  56343. self.resolve_(goog.Promise.State_.REJECTED, reason);
  56344. });
  56345. } catch (e) {
  56346. this.resolve_(goog.Promise.State_.REJECTED, e);
  56347. }
  56348. }
  56349. };
  56350. /**
  56351. * @define {boolean} Whether traces of {@code then} calls should be included in
  56352. * exceptions thrown
  56353. */
  56354. goog.define('goog.Promise.LONG_STACK_TRACES', false);
  56355. /**
  56356. * @define {number} The delay in milliseconds before a rejected Promise's reason
  56357. * is passed to the rejection handler. By default, the rejection handler
  56358. * rethrows the rejection reason so that it appears in the developer console or
  56359. * {@code window.onerror} handler.
  56360. *
  56361. * Rejections are rethrown as quickly as possible by default. A negative value
  56362. * disables rejection handling entirely.
  56363. */
  56364. goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);
  56365. /**
  56366. * The possible internal states for a Promise. These states are not directly
  56367. * observable to external callers.
  56368. * @enum {number}
  56369. * @private
  56370. */
  56371. goog.Promise.State_ = {
  56372. /** The Promise is waiting for resolution. */
  56373. PENDING: 0,
  56374. /** The Promise is blocked waiting for the result of another Thenable. */
  56375. BLOCKED: 1,
  56376. /** The Promise has been resolved with a fulfillment value. */
  56377. FULFILLED: 2,
  56378. /** The Promise has been resolved with a rejection reason. */
  56379. REJECTED: 3
  56380. };
  56381. /**
  56382. * Entries in the callback chain. Each call to {@code then},
  56383. * {@code thenCatch}, or {@code thenAlways} creates an entry containing the
  56384. * functions that may be invoked once the Promise is settled.
  56385. *
  56386. * @private @final @struct @constructor
  56387. */
  56388. goog.Promise.CallbackEntry_ = function() {
  56389. /** @type {?goog.Promise} */
  56390. this.child = null;
  56391. /** @type {Function} */
  56392. this.onFulfilled = null;
  56393. /** @type {Function} */
  56394. this.onRejected = null;
  56395. /** @type {?} */
  56396. this.context = null;
  56397. /** @type {?goog.Promise.CallbackEntry_} */
  56398. this.next = null;
  56399. /**
  56400. * A boolean value to indicate this is a "thenAlways" callback entry.
  56401. * Unlike a normal "then/thenVoid" a "thenAlways doesn't participate
  56402. * in "cancel" considerations but is simply an observer and requires
  56403. * special handling.
  56404. * @type {boolean}
  56405. */
  56406. this.always = false;
  56407. };
  56408. /** clear the object prior to reuse */
  56409. goog.Promise.CallbackEntry_.prototype.reset = function() {
  56410. this.child = null;
  56411. this.onFulfilled = null;
  56412. this.onRejected = null;
  56413. this.context = null;
  56414. this.always = false;
  56415. };
  56416. /**
  56417. * @define {number} The number of currently unused objects to keep around for
  56418. * reuse.
  56419. */
  56420. goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100);
  56421. /** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */
  56422. goog.Promise.freelist_ = new goog.async.FreeList(
  56423. function() {
  56424. return new goog.Promise.CallbackEntry_();
  56425. },
  56426. function(item) {
  56427. item.reset();
  56428. },
  56429. goog.Promise.DEFAULT_MAX_UNUSED);
  56430. /**
  56431. * @param {Function} onFulfilled
  56432. * @param {Function} onRejected
  56433. * @param {?} context
  56434. * @return {!goog.Promise.CallbackEntry_}
  56435. * @private
  56436. */
  56437. goog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) {
  56438. var entry = goog.Promise.freelist_.get();
  56439. entry.onFulfilled = onFulfilled;
  56440. entry.onRejected = onRejected;
  56441. entry.context = context;
  56442. return entry;
  56443. };
  56444. /**
  56445. * @param {!goog.Promise.CallbackEntry_} entry
  56446. * @private
  56447. */
  56448. goog.Promise.returnEntry_ = function(entry) {
  56449. goog.Promise.freelist_.put(entry);
  56450. };
  56451. // NOTE: this is the same template expression as is used for
  56452. // goog.IThenable.prototype.then
  56453. /**
  56454. * @param {VALUE=} opt_value
  56455. * @return {RESULT} A new Promise that is immediately resolved
  56456. * with the given value. If the input value is already a goog.Promise, it
  56457. * will be returned immediately without creating a new instance.
  56458. * @template VALUE
  56459. * @template RESULT := type('goog.Promise',
  56460. * cond(isUnknown(VALUE), unknown(),
  56461. * mapunion(VALUE, (V) =>
  56462. * cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),
  56463. * templateTypeOf(V, 0),
  56464. * cond(sub(V, 'Thenable'),
  56465. * unknown(),
  56466. * V)))))
  56467. * =:
  56468. */
  56469. goog.Promise.resolve = function(opt_value) {
  56470. if (opt_value instanceof goog.Promise) {
  56471. // Avoid creating a new object if we already have a promise object
  56472. // of the correct type.
  56473. return opt_value;
  56474. }
  56475. // Passing goog.nullFunction will cause the constructor to take an optimized
  56476. // path that skips calling the resolver function.
  56477. var promise = new goog.Promise(goog.nullFunction);
  56478. promise.resolve_(goog.Promise.State_.FULFILLED, opt_value);
  56479. return promise;
  56480. };
  56481. /**
  56482. * @param {*=} opt_reason
  56483. * @return {!goog.Promise} A new Promise that is immediately rejected with the
  56484. * given reason.
  56485. */
  56486. goog.Promise.reject = function(opt_reason) {
  56487. return new goog.Promise(function(resolve, reject) {
  56488. reject(opt_reason);
  56489. });
  56490. };
  56491. /**
  56492. * This is identical to
  56493. * {@code goog.Promise.resolve(value).then(onFulfilled, onRejected)}, but it
  56494. * avoids creating an unnecessary wrapper Promise when {@code value} is already
  56495. * thenable.
  56496. *
  56497. * @param {?(goog.Thenable<TYPE>|Thenable|TYPE)} value
  56498. * @param {function(TYPE): ?} onFulfilled
  56499. * @param {function(*): *} onRejected
  56500. * @template TYPE
  56501. * @private
  56502. */
  56503. goog.Promise.resolveThen_ = function(value, onFulfilled, onRejected) {
  56504. var isThenable = goog.Promise.maybeThen_(
  56505. value, onFulfilled, onRejected, null);
  56506. if (!isThenable) {
  56507. goog.async.run(goog.partial(onFulfilled, value));
  56508. }
  56509. };
  56510. /**
  56511. * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
  56512. * promises
  56513. * @return {!goog.Promise<TYPE>} A Promise that receives the result of the
  56514. * first Promise (or Promise-like) input to settle immediately after it
  56515. * settles.
  56516. * @template TYPE
  56517. */
  56518. goog.Promise.race = function(promises) {
  56519. return new goog.Promise(function(resolve, reject) {
  56520. if (!promises.length) {
  56521. resolve(undefined);
  56522. }
  56523. for (var i = 0, promise; i < promises.length; i++) {
  56524. promise = promises[i];
  56525. goog.Promise.resolveThen_(promise, resolve, reject);
  56526. }
  56527. });
  56528. };
  56529. /**
  56530. * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
  56531. * promises
  56532. * @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of
  56533. * every fulfilled value once every input Promise (or Promise-like) is
  56534. * successfully fulfilled, or is rejected with the first rejection reason
  56535. * immediately after it is rejected.
  56536. * @template TYPE
  56537. */
  56538. goog.Promise.all = function(promises) {
  56539. return new goog.Promise(function(resolve, reject) {
  56540. var toFulfill = promises.length;
  56541. var values = [];
  56542. if (!toFulfill) {
  56543. resolve(values);
  56544. return;
  56545. }
  56546. var onFulfill = function(index, value) {
  56547. toFulfill--;
  56548. values[index] = value;
  56549. if (toFulfill == 0) {
  56550. resolve(values);
  56551. }
  56552. };
  56553. var onReject = function(reason) {
  56554. reject(reason);
  56555. };
  56556. for (var i = 0, promise; i < promises.length; i++) {
  56557. promise = promises[i];
  56558. goog.Promise.resolveThen_(
  56559. promise, goog.partial(onFulfill, i), onReject);
  56560. }
  56561. });
  56562. };
  56563. /**
  56564. * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
  56565. * promises
  56566. * @return {!goog.Promise<!Array<{
  56567. * fulfilled: boolean,
  56568. * value: (TYPE|undefined),
  56569. * reason: (*|undefined)}>>} A Promise that resolves with a list of
  56570. * result objects once all input Promises (or Promise-like) have
  56571. * settled. Each result object contains a 'fulfilled' boolean indicating
  56572. * whether an input Promise was fulfilled or rejected. For fulfilled
  56573. * Promises, the resulting value is stored in the 'value' field. For
  56574. * rejected Promises, the rejection reason is stored in the 'reason'
  56575. * field.
  56576. * @template TYPE
  56577. */
  56578. goog.Promise.allSettled = function(promises) {
  56579. return new goog.Promise(function(resolve, reject) {
  56580. var toSettle = promises.length;
  56581. var results = [];
  56582. if (!toSettle) {
  56583. resolve(results);
  56584. return;
  56585. }
  56586. var onSettled = function(index, fulfilled, result) {
  56587. toSettle--;
  56588. results[index] = fulfilled ?
  56589. {fulfilled: true, value: result} :
  56590. {fulfilled: false, reason: result};
  56591. if (toSettle == 0) {
  56592. resolve(results);
  56593. }
  56594. };
  56595. for (var i = 0, promise; i < promises.length; i++) {
  56596. promise = promises[i];
  56597. goog.Promise.resolveThen_(promise,
  56598. goog.partial(onSettled, i, true /* fulfilled */),
  56599. goog.partial(onSettled, i, false /* fulfilled */));
  56600. }
  56601. });
  56602. };
  56603. /**
  56604. * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}
  56605. * promises
  56606. * @return {!goog.Promise<TYPE>} A Promise that receives the value of the first
  56607. * input to be fulfilled, or is rejected with a list of every rejection
  56608. * reason if all inputs are rejected.
  56609. * @template TYPE
  56610. */
  56611. goog.Promise.firstFulfilled = function(promises) {
  56612. return new goog.Promise(function(resolve, reject) {
  56613. var toReject = promises.length;
  56614. var reasons = [];
  56615. if (!toReject) {
  56616. resolve(undefined);
  56617. return;
  56618. }
  56619. var onFulfill = function(value) {
  56620. resolve(value);
  56621. };
  56622. var onReject = function(index, reason) {
  56623. toReject--;
  56624. reasons[index] = reason;
  56625. if (toReject == 0) {
  56626. reject(reasons);
  56627. }
  56628. };
  56629. for (var i = 0, promise; i < promises.length; i++) {
  56630. promise = promises[i];
  56631. goog.Promise.resolveThen_(
  56632. promise, onFulfill, goog.partial(onReject, i));
  56633. }
  56634. });
  56635. };
  56636. /**
  56637. * @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its
  56638. * resolve / reject functions. Resolving or rejecting the resolver
  56639. * resolves or rejects the promise.
  56640. * @template TYPE
  56641. */
  56642. goog.Promise.withResolver = function() {
  56643. var resolve, reject;
  56644. var promise = new goog.Promise(function(rs, rj) {
  56645. resolve = rs;
  56646. reject = rj;
  56647. });
  56648. return new goog.Promise.Resolver_(promise, resolve, reject);
  56649. };
  56650. /**
  56651. * Adds callbacks that will operate on the result of the Promise, returning a
  56652. * new child Promise.
  56653. *
  56654. * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked
  56655. * with the fulfillment value as argument, and the child Promise will be
  56656. * fulfilled with the return value of the callback. If the callback throws an
  56657. * exception, the child Promise will be rejected with the thrown value instead.
  56658. *
  56659. * If the Promise is rejected, the {@code onRejected} callback will be invoked
  56660. * with the rejection reason as argument, and the child Promise will be resolved
  56661. * with the return value or rejected with the thrown value of the callback.
  56662. *
  56663. * @override
  56664. */
  56665. goog.Promise.prototype.then = function(
  56666. opt_onFulfilled, opt_onRejected, opt_context) {
  56667. if (opt_onFulfilled != null) {
  56668. goog.asserts.assertFunction(opt_onFulfilled,
  56669. 'opt_onFulfilled should be a function.');
  56670. }
  56671. if (opt_onRejected != null) {
  56672. goog.asserts.assertFunction(opt_onRejected,
  56673. 'opt_onRejected should be a function. Did you pass opt_context ' +
  56674. 'as the second argument instead of the third?');
  56675. }
  56676. if (goog.Promise.LONG_STACK_TRACES) {
  56677. this.addStackTrace_(new Error('then'));
  56678. }
  56679. return this.addChildPromise_(
  56680. goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null,
  56681. goog.isFunction(opt_onRejected) ? opt_onRejected : null,
  56682. opt_context);
  56683. };
  56684. goog.Thenable.addImplementation(goog.Promise);
  56685. /**
  56686. * Adds callbacks that will operate on the result of the Promise without
  56687. * returning a child Promise (unlike "then").
  56688. *
  56689. * If the Promise is fulfilled, the {@code onFulfilled} callback will be invoked
  56690. * with the fulfillment value as argument.
  56691. *
  56692. * If the Promise is rejected, the {@code onRejected} callback will be invoked
  56693. * with the rejection reason as argument.
  56694. *
  56695. * @param {?(function(this:THIS, TYPE):?)=} opt_onFulfilled A
  56696. * function that will be invoked with the fulfillment value if the Promise
  56697. * is fulfilled.
  56698. * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will
  56699. * be invoked with the rejection reason if the Promise is rejected.
  56700. * @param {THIS=} opt_context An optional context object that will be the
  56701. * execution context for the callbacks. By default, functions are executed
  56702. * with the default this.
  56703. * @package
  56704. * @template THIS
  56705. */
  56706. goog.Promise.prototype.thenVoid = function(
  56707. opt_onFulfilled, opt_onRejected, opt_context) {
  56708. if (opt_onFulfilled != null) {
  56709. goog.asserts.assertFunction(opt_onFulfilled,
  56710. 'opt_onFulfilled should be a function.');
  56711. }
  56712. if (opt_onRejected != null) {
  56713. goog.asserts.assertFunction(opt_onRejected,
  56714. 'opt_onRejected should be a function. Did you pass opt_context ' +
  56715. 'as the second argument instead of the third?');
  56716. }
  56717. if (goog.Promise.LONG_STACK_TRACES) {
  56718. this.addStackTrace_(new Error('then'));
  56719. }
  56720. // Note: no default rejection handler is provided here as we need to
  56721. // distinguish unhandled rejections.
  56722. this.addCallbackEntry_(goog.Promise.getCallbackEntry_(
  56723. opt_onFulfilled || goog.nullFunction,
  56724. opt_onRejected || null,
  56725. opt_context));
  56726. };
  56727. /**
  56728. * Adds a callback that will be invoked when the Promise is settled (fulfilled
  56729. * or rejected). The callback receives no argument, and no new child Promise is
  56730. * created. This is useful for ensuring that cleanup takes place after certain
  56731. * asynchronous operations. Callbacks added with {@code thenAlways} will be
  56732. * executed in the same order with other calls to {@code then},
  56733. * {@code thenAlways}, or {@code thenCatch}.
  56734. *
  56735. * Since it does not produce a new child Promise, cancellation propagation is
  56736. * not prevented by adding callbacks with {@code thenAlways}. A Promise that has
  56737. * a cleanup handler added with {@code thenAlways} will be canceled if all of
  56738. * its children created by {@code then} (or {@code thenCatch}) are canceled.
  56739. * Additionally, since any rejections are not passed to the callback, it does
  56740. * not stop the unhandled rejection handler from running.
  56741. *
  56742. * @param {function(this:THIS): void} onSettled A function that will be invoked
  56743. * when the Promise is settled (fulfilled or rejected).
  56744. * @param {THIS=} opt_context An optional context object that will be the
  56745. * execution context for the callbacks. By default, functions are executed
  56746. * in the global scope.
  56747. * @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.
  56748. * @template THIS
  56749. */
  56750. goog.Promise.prototype.thenAlways = function(onSettled, opt_context) {
  56751. if (goog.Promise.LONG_STACK_TRACES) {
  56752. this.addStackTrace_(new Error('thenAlways'));
  56753. }
  56754. var entry = goog.Promise.getCallbackEntry_(onSettled, onSettled, opt_context);
  56755. entry.always = true;
  56756. this.addCallbackEntry_(entry);
  56757. return this;
  56758. };
  56759. /**
  56760. * Adds a callback that will be invoked only if the Promise is rejected. This
  56761. * is equivalent to {@code then(null, onRejected)}.
  56762. *
  56763. * @param {!function(this:THIS, *): *} onRejected A function that will be
  56764. * invoked with the rejection reason if the Promise is rejected.
  56765. * @param {THIS=} opt_context An optional context object that will be the
  56766. * execution context for the callbacks. By default, functions are executed
  56767. * in the global scope.
  56768. * @return {!goog.Promise} A new Promise that will receive the result of the
  56769. * callback.
  56770. * @template THIS
  56771. */
  56772. goog.Promise.prototype.thenCatch = function(onRejected, opt_context) {
  56773. if (goog.Promise.LONG_STACK_TRACES) {
  56774. this.addStackTrace_(new Error('thenCatch'));
  56775. }
  56776. return this.addChildPromise_(null, onRejected, opt_context);
  56777. };
  56778. /**
  56779. * Cancels the Promise if it is still pending by rejecting it with a cancel
  56780. * Error. No action is performed if the Promise is already resolved.
  56781. *
  56782. * All child Promises of the canceled Promise will be rejected with the same
  56783. * cancel error, as with normal Promise rejection. If the Promise to be canceled
  56784. * is the only child of a pending Promise, the parent Promise will also be
  56785. * canceled. Cancellation may propagate upward through multiple generations.
  56786. *
  56787. * @param {string=} opt_message An optional debugging message for describing the
  56788. * cancellation reason.
  56789. */
  56790. goog.Promise.prototype.cancel = function(opt_message) {
  56791. if (this.state_ == goog.Promise.State_.PENDING) {
  56792. goog.async.run(function() {
  56793. var err = new goog.Promise.CancellationError(opt_message);
  56794. this.cancelInternal_(err);
  56795. }, this);
  56796. }
  56797. };
  56798. /**
  56799. * Cancels this Promise with the given error.
  56800. *
  56801. * @param {!Error} err The cancellation error.
  56802. * @private
  56803. */
  56804. goog.Promise.prototype.cancelInternal_ = function(err) {
  56805. if (this.state_ == goog.Promise.State_.PENDING) {
  56806. if (this.parent_) {
  56807. // Cancel the Promise and remove it from the parent's child list.
  56808. this.parent_.cancelChild_(this, err);
  56809. this.parent_ = null;
  56810. } else {
  56811. this.resolve_(goog.Promise.State_.REJECTED, err);
  56812. }
  56813. }
  56814. };
  56815. /**
  56816. * Cancels a child Promise from the list of callback entries. If the Promise has
  56817. * not already been resolved, reject it with a cancel error. If there are no
  56818. * other children in the list of callback entries, propagate the cancellation
  56819. * by canceling this Promise as well.
  56820. *
  56821. * @param {!goog.Promise} childPromise The Promise to cancel.
  56822. * @param {!Error} err The cancel error to use for rejecting the Promise.
  56823. * @private
  56824. */
  56825. goog.Promise.prototype.cancelChild_ = function(childPromise, err) {
  56826. if (!this.callbackEntries_) {
  56827. return;
  56828. }
  56829. var childCount = 0;
  56830. var childEntry = null;
  56831. var beforeChildEntry = null;
  56832. // Find the callback entry for the childPromise, and count whether there are
  56833. // additional child Promises.
  56834. for (var entry = this.callbackEntries_; entry; entry = entry.next) {
  56835. if (!entry.always) {
  56836. childCount++;
  56837. if (entry.child == childPromise) {
  56838. childEntry = entry;
  56839. }
  56840. if (childEntry && childCount > 1) {
  56841. break;
  56842. }
  56843. }
  56844. if (!childEntry) {
  56845. beforeChildEntry = entry;
  56846. }
  56847. }
  56848. // Can a child entry be missing?
  56849. // If the child Promise was the only child, cancel this Promise as well.
  56850. // Otherwise, reject only the child Promise with the cancel error.
  56851. if (childEntry) {
  56852. if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {
  56853. this.cancelInternal_(err);
  56854. } else {
  56855. if (beforeChildEntry) {
  56856. this.removeEntryAfter_(beforeChildEntry);
  56857. } else {
  56858. this.popEntry_();
  56859. }
  56860. this.executeCallback_(
  56861. childEntry, goog.Promise.State_.REJECTED, err);
  56862. }
  56863. }
  56864. };
  56865. /**
  56866. * Adds a callback entry to the current Promise, and schedules callback
  56867. * execution if the Promise has already been settled.
  56868. *
  56869. * @param {goog.Promise.CallbackEntry_} callbackEntry Record containing
  56870. * {@code onFulfilled} and {@code onRejected} callbacks to execute after
  56871. * the Promise is settled.
  56872. * @private
  56873. */
  56874. goog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {
  56875. if (!this.hasEntry_() &&
  56876. (this.state_ == goog.Promise.State_.FULFILLED ||
  56877. this.state_ == goog.Promise.State_.REJECTED)) {
  56878. this.scheduleCallbacks_();
  56879. }
  56880. this.queueEntry_(callbackEntry);
  56881. };
  56882. /**
  56883. * Creates a child Promise and adds it to the callback entry list. The result of
  56884. * the child Promise is determined by the state of the parent Promise and the
  56885. * result of the {@code onFulfilled} or {@code onRejected} callbacks as
  56886. * specified in the Promise resolution procedure.
  56887. *
  56888. * @see http://promisesaplus.com/#the__method
  56889. *
  56890. * @param {?function(this:THIS, TYPE):
  56891. * (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that
  56892. * will be invoked if the Promise is fullfilled, or null.
  56893. * @param {?function(this:THIS, *): *} onRejected A callback that will be
  56894. * invoked if the Promise is rejected, or null.
  56895. * @param {THIS=} opt_context An optional execution context for the callbacks.
  56896. * in the default calling context.
  56897. * @return {!goog.Promise} The child Promise.
  56898. * @template RESULT,THIS
  56899. * @private
  56900. */
  56901. goog.Promise.prototype.addChildPromise_ = function(
  56902. onFulfilled, onRejected, opt_context) {
  56903. /** @type {goog.Promise.CallbackEntry_} */
  56904. var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null);
  56905. callbackEntry.child = new goog.Promise(function(resolve, reject) {
  56906. // Invoke onFulfilled, or resolve with the parent's value if absent.
  56907. callbackEntry.onFulfilled = onFulfilled ? function(value) {
  56908. try {
  56909. var result = onFulfilled.call(opt_context, value);
  56910. resolve(result);
  56911. } catch (err) {
  56912. reject(err);
  56913. }
  56914. } : resolve;
  56915. // Invoke onRejected, or reject with the parent's reason if absent.
  56916. callbackEntry.onRejected = onRejected ? function(reason) {
  56917. try {
  56918. var result = onRejected.call(opt_context, reason);
  56919. if (!goog.isDef(result) &&
  56920. reason instanceof goog.Promise.CancellationError) {
  56921. // Propagate cancellation to children if no other result is returned.
  56922. reject(reason);
  56923. } else {
  56924. resolve(result);
  56925. }
  56926. } catch (err) {
  56927. reject(err);
  56928. }
  56929. } : reject;
  56930. });
  56931. callbackEntry.child.parent_ = this;
  56932. this.addCallbackEntry_(callbackEntry);
  56933. return callbackEntry.child;
  56934. };
  56935. /**
  56936. * Unblocks the Promise and fulfills it with the given value.
  56937. *
  56938. * @param {TYPE} value
  56939. * @private
  56940. */
  56941. goog.Promise.prototype.unblockAndFulfill_ = function(value) {
  56942. goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
  56943. this.state_ = goog.Promise.State_.PENDING;
  56944. this.resolve_(goog.Promise.State_.FULFILLED, value);
  56945. };
  56946. /**
  56947. * Unblocks the Promise and rejects it with the given rejection reason.
  56948. *
  56949. * @param {*} reason
  56950. * @private
  56951. */
  56952. goog.Promise.prototype.unblockAndReject_ = function(reason) {
  56953. goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);
  56954. this.state_ = goog.Promise.State_.PENDING;
  56955. this.resolve_(goog.Promise.State_.REJECTED, reason);
  56956. };
  56957. /**
  56958. * Attempts to resolve a Promise with a given resolution state and value. This
  56959. * is a no-op if the given Promise has already been resolved.
  56960. *
  56961. * If the given result is a Thenable (such as another Promise), the Promise will
  56962. * be settled with the same state and result as the Thenable once it is itself
  56963. * settled.
  56964. *
  56965. * If the given result is not a Thenable, the Promise will be settled (fulfilled
  56966. * or rejected) with that result based on the given state.
  56967. *
  56968. * @see http://promisesaplus.com/#the_promise_resolution_procedure
  56969. *
  56970. * @param {goog.Promise.State_} state
  56971. * @param {*} x The result to apply to the Promise.
  56972. * @private
  56973. */
  56974. goog.Promise.prototype.resolve_ = function(state, x) {
  56975. if (this.state_ != goog.Promise.State_.PENDING) {
  56976. return;
  56977. }
  56978. if (this == x) {
  56979. state = goog.Promise.State_.REJECTED;
  56980. x = new TypeError('Promise cannot resolve to itself');
  56981. }
  56982. this.state_ = goog.Promise.State_.BLOCKED;
  56983. var isThenable = goog.Promise.maybeThen_(
  56984. x, this.unblockAndFulfill_, this.unblockAndReject_, this);
  56985. if (isThenable) {
  56986. return;
  56987. }
  56988. this.result_ = x;
  56989. this.state_ = state;
  56990. // Since we can no longer be canceled, remove link to parent, so that the
  56991. // child promise does not keep the parent promise alive.
  56992. this.parent_ = null;
  56993. this.scheduleCallbacks_();
  56994. if (state == goog.Promise.State_.REJECTED &&
  56995. !(x instanceof goog.Promise.CancellationError)) {
  56996. goog.Promise.addUnhandledRejection_(this, x);
  56997. }
  56998. };
  56999. /**
  57000. * Invokes the "then" method of an input value if that value is a Thenable. This
  57001. * is a no-op if the value is not thenable.
  57002. *
  57003. * @param {*} value A potentially thenable value.
  57004. * @param {!Function} onFulfilled
  57005. * @param {!Function} onRejected
  57006. * @param {*} context
  57007. * @return {boolean} Whether the input value was thenable.
  57008. * @private
  57009. */
  57010. goog.Promise.maybeThen_ = function(value, onFulfilled, onRejected, context) {
  57011. if (value instanceof goog.Promise) {
  57012. value.thenVoid(onFulfilled, onRejected, context);
  57013. return true;
  57014. } else if (goog.Thenable.isImplementedBy(value)) {
  57015. value = /** @type {!goog.Thenable} */ (value);
  57016. value.then(onFulfilled, onRejected, context);
  57017. return true;
  57018. } else if (goog.isObject(value)) {
  57019. try {
  57020. var then = value['then'];
  57021. if (goog.isFunction(then)) {
  57022. goog.Promise.tryThen_(
  57023. value, then, onFulfilled, onRejected, context);
  57024. return true;
  57025. }
  57026. } catch (e) {
  57027. onRejected.call(context, e);
  57028. return true;
  57029. }
  57030. }
  57031. return false;
  57032. };
  57033. /**
  57034. * Attempts to call the {@code then} method on an object in the hopes that it is
  57035. * a Promise-compatible instance. This allows interoperation between different
  57036. * Promise implementations, however a non-compliant object may cause a Promise
  57037. * to hang indefinitely. If the {@code then} method throws an exception, the
  57038. * dependent Promise will be rejected with the thrown value.
  57039. *
  57040. * @see http://promisesaplus.com/#point-70
  57041. *
  57042. * @param {Thenable} thenable An object with a {@code then} method that may be
  57043. * compatible with the Promise/A+ specification.
  57044. * @param {!Function} then The {@code then} method of the Thenable object.
  57045. * @param {!Function} onFulfilled
  57046. * @param {!Function} onRejected
  57047. * @param {*} context
  57048. * @private
  57049. */
  57050. goog.Promise.tryThen_ = function(
  57051. thenable, then, onFulfilled, onRejected, context) {
  57052. var called = false;
  57053. var resolve = function(value) {
  57054. if (!called) {
  57055. called = true;
  57056. onFulfilled.call(context, value);
  57057. }
  57058. };
  57059. var reject = function(reason) {
  57060. if (!called) {
  57061. called = true;
  57062. onRejected.call(context, reason);
  57063. }
  57064. };
  57065. try {
  57066. then.call(thenable, resolve, reject);
  57067. } catch (e) {
  57068. reject(e);
  57069. }
  57070. };
  57071. /**
  57072. * Executes the pending callbacks of a settled Promise after a timeout.
  57073. *
  57074. * Section 2.2.4 of the Promises/A+ specification requires that Promise
  57075. * callbacks must only be invoked from a call stack that only contains Promise
  57076. * implementation code, which we accomplish by invoking callback execution after
  57077. * a timeout. If {@code startExecution_} is called multiple times for the same
  57078. * Promise, the callback chain will be evaluated only once. Additional callbacks
  57079. * may be added during the evaluation phase, and will be executed in the same
  57080. * event loop.
  57081. *
  57082. * All Promises added to the waiting list during the same browser event loop
  57083. * will be executed in one batch to avoid using a separate timeout per Promise.
  57084. *
  57085. * @private
  57086. */
  57087. goog.Promise.prototype.scheduleCallbacks_ = function() {
  57088. if (!this.executing_) {
  57089. this.executing_ = true;
  57090. goog.async.run(this.executeCallbacks_, this);
  57091. }
  57092. };
  57093. /**
  57094. * @return {boolean} Whether there are any pending callbacks queued.
  57095. * @private
  57096. */
  57097. goog.Promise.prototype.hasEntry_ = function() {
  57098. return !!this.callbackEntries_;
  57099. };
  57100. /**
  57101. * @param {goog.Promise.CallbackEntry_} entry
  57102. * @private
  57103. */
  57104. goog.Promise.prototype.queueEntry_ = function(entry) {
  57105. goog.asserts.assert(entry.onFulfilled != null);
  57106. if (this.callbackEntriesTail_) {
  57107. this.callbackEntriesTail_.next = entry;
  57108. this.callbackEntriesTail_ = entry;
  57109. } else {
  57110. // It the work queue was empty set the head too.
  57111. this.callbackEntries_ = entry;
  57112. this.callbackEntriesTail_ = entry;
  57113. }
  57114. };
  57115. /**
  57116. * @return {goog.Promise.CallbackEntry_} entry
  57117. * @private
  57118. */
  57119. goog.Promise.prototype.popEntry_ = function() {
  57120. var entry = null;
  57121. if (this.callbackEntries_) {
  57122. entry = this.callbackEntries_;
  57123. this.callbackEntries_ = entry.next;
  57124. entry.next = null;
  57125. }
  57126. // It the work queue is empty clear the tail too.
  57127. if (!this.callbackEntries_) {
  57128. this.callbackEntriesTail_ = null;
  57129. }
  57130. if (entry != null) {
  57131. goog.asserts.assert(entry.onFulfilled != null);
  57132. }
  57133. return entry;
  57134. };
  57135. /**
  57136. * @param {goog.Promise.CallbackEntry_} previous
  57137. * @private
  57138. */
  57139. goog.Promise.prototype.removeEntryAfter_ = function(previous) {
  57140. goog.asserts.assert(this.callbackEntries_);
  57141. goog.asserts.assert(previous != null);
  57142. // If the last entry is being removed, update the tail
  57143. if (previous.next == this.callbackEntriesTail_) {
  57144. this.callbackEntriesTail_ = previous;
  57145. }
  57146. previous.next = previous.next.next;
  57147. };
  57148. /**
  57149. * Executes all pending callbacks for this Promise.
  57150. *
  57151. * @private
  57152. */
  57153. goog.Promise.prototype.executeCallbacks_ = function() {
  57154. var entry = null;
  57155. while (entry = this.popEntry_()) {
  57156. if (goog.Promise.LONG_STACK_TRACES) {
  57157. this.currentStep_++;
  57158. }
  57159. this.executeCallback_(entry, this.state_, this.result_);
  57160. }
  57161. this.executing_ = false;
  57162. };
  57163. /**
  57164. * Executes a pending callback for this Promise. Invokes an {@code onFulfilled}
  57165. * or {@code onRejected} callback based on the settled state of the Promise.
  57166. *
  57167. * @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the
  57168. * onFulfilled and/or onRejected callbacks for this step.
  57169. * @param {goog.Promise.State_} state The resolution status of the Promise,
  57170. * either FULFILLED or REJECTED.
  57171. * @param {*} result The settled result of the Promise.
  57172. * @private
  57173. */
  57174. goog.Promise.prototype.executeCallback_ = function(
  57175. callbackEntry, state, result) {
  57176. // Cancel an unhandled rejection if the then/thenVoid call had an onRejected.
  57177. if (state == goog.Promise.State_.REJECTED &&
  57178. callbackEntry.onRejected && !callbackEntry.always) {
  57179. this.removeUnhandledRejection_();
  57180. }
  57181. if (callbackEntry.child) {
  57182. // When the parent is settled, the child no longer needs to hold on to it,
  57183. // as the parent can no longer be canceled.
  57184. callbackEntry.child.parent_ = null;
  57185. goog.Promise.invokeCallback_(callbackEntry, state, result);
  57186. } else {
  57187. // Callbacks created with thenAlways or thenVoid do not have the rejection
  57188. // handling code normally set up in the child Promise.
  57189. try {
  57190. callbackEntry.always ?
  57191. callbackEntry.onFulfilled.call(callbackEntry.context) :
  57192. goog.Promise.invokeCallback_(callbackEntry, state, result);
  57193. } catch (err) {
  57194. goog.Promise.handleRejection_.call(null, err);
  57195. }
  57196. }
  57197. goog.Promise.returnEntry_(callbackEntry);
  57198. };
  57199. /**
  57200. * Executes the onFulfilled or onRejected callback for a callbackEntry.
  57201. *
  57202. * @param {!goog.Promise.CallbackEntry_} callbackEntry
  57203. * @param {goog.Promise.State_} state
  57204. * @param {*} result
  57205. * @private
  57206. */
  57207. goog.Promise.invokeCallback_ = function(callbackEntry, state, result) {
  57208. if (state == goog.Promise.State_.FULFILLED) {
  57209. callbackEntry.onFulfilled.call(callbackEntry.context, result);
  57210. } else if (callbackEntry.onRejected) {
  57211. callbackEntry.onRejected.call(callbackEntry.context, result);
  57212. }
  57213. };
  57214. /**
  57215. * Records a stack trace entry for functions that call {@code then} or the
  57216. * Promise constructor. May be disabled by unsetting {@code LONG_STACK_TRACES}.
  57217. *
  57218. * @param {!Error} err An Error object created by the calling function for
  57219. * providing a stack trace.
  57220. * @private
  57221. */
  57222. goog.Promise.prototype.addStackTrace_ = function(err) {
  57223. if (goog.Promise.LONG_STACK_TRACES && goog.isString(err.stack)) {
  57224. // Extract the third line of the stack trace, which is the entry for the
  57225. // user function that called into Promise code.
  57226. var trace = err.stack.split('\n', 4)[3];
  57227. var message = err.message;
  57228. // Pad the message to align the traces.
  57229. message += Array(11 - message.length).join(' ');
  57230. this.stack_.push(message + trace);
  57231. }
  57232. };
  57233. /**
  57234. * Adds extra stack trace information to an exception for the list of
  57235. * asynchronous {@code then} calls that have been run for this Promise. Stack
  57236. * trace information is recorded in {@see #addStackTrace_}, and appended to
  57237. * rethrown errors when {@code LONG_STACK_TRACES} is enabled.
  57238. *
  57239. * @param {*} err An unhandled exception captured during callback execution.
  57240. * @private
  57241. */
  57242. goog.Promise.prototype.appendLongStack_ = function(err) {
  57243. if (goog.Promise.LONG_STACK_TRACES &&
  57244. err && goog.isString(err.stack) && this.stack_.length) {
  57245. var longTrace = ['Promise trace:'];
  57246. for (var promise = this; promise; promise = promise.parent_) {
  57247. for (var i = this.currentStep_; i >= 0; i--) {
  57248. longTrace.push(promise.stack_[i]);
  57249. }
  57250. longTrace.push('Value: ' +
  57251. '[' + (promise.state_ == goog.Promise.State_.REJECTED ?
  57252. 'REJECTED' : 'FULFILLED') + '] ' +
  57253. '<' + String(promise.result_) + '>');
  57254. }
  57255. err.stack += '\n\n' + longTrace.join('\n');
  57256. }
  57257. };
  57258. /**
  57259. * Marks this rejected Promise as having being handled. Also marks any parent
  57260. * Promises in the rejected state as handled. The rejection handler will no
  57261. * longer be invoked for this Promise (if it has not been called already).
  57262. *
  57263. * @private
  57264. */
  57265. goog.Promise.prototype.removeUnhandledRejection_ = function() {
  57266. if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
  57267. for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {
  57268. goog.global.clearTimeout(p.unhandledRejectionId_);
  57269. p.unhandledRejectionId_ = 0;
  57270. }
  57271. } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
  57272. for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {
  57273. p.hadUnhandledRejection_ = false;
  57274. }
  57275. }
  57276. };
  57277. /**
  57278. * Marks this rejected Promise as unhandled. If no {@code onRejected} callback
  57279. * is called for this Promise before the {@code UNHANDLED_REJECTION_DELAY}
  57280. * expires, the reason will be passed to the unhandled rejection handler. The
  57281. * handler typically rethrows the rejection reason so that it becomes visible in
  57282. * the developer console.
  57283. *
  57284. * @param {!goog.Promise} promise The rejected Promise.
  57285. * @param {*} reason The Promise rejection reason.
  57286. * @private
  57287. */
  57288. goog.Promise.addUnhandledRejection_ = function(promise, reason) {
  57289. if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {
  57290. promise.unhandledRejectionId_ = goog.global.setTimeout(function() {
  57291. promise.appendLongStack_(reason);
  57292. goog.Promise.handleRejection_.call(null, reason);
  57293. }, goog.Promise.UNHANDLED_REJECTION_DELAY);
  57294. } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {
  57295. promise.hadUnhandledRejection_ = true;
  57296. goog.async.run(function() {
  57297. if (promise.hadUnhandledRejection_) {
  57298. promise.appendLongStack_(reason);
  57299. goog.Promise.handleRejection_.call(null, reason);
  57300. }
  57301. });
  57302. }
  57303. };
  57304. /**
  57305. * A method that is invoked with the rejection reasons for Promises that are
  57306. * rejected but have no {@code onRejected} callbacks registered yet.
  57307. * @type {function(*)}
  57308. * @private
  57309. */
  57310. goog.Promise.handleRejection_ = goog.async.throwException;
  57311. /**
  57312. * Sets a handler that will be called with reasons from unhandled rejected
  57313. * Promises. If the rejected Promise (or one of its descendants) has an
  57314. * {@code onRejected} callback registered, the rejection will be considered
  57315. * handled, and the rejection handler will not be called.
  57316. *
  57317. * By default, unhandled rejections are rethrown so that the error may be
  57318. * captured by the developer console or a {@code window.onerror} handler.
  57319. *
  57320. * @param {function(*)} handler A function that will be called with reasons from
  57321. * rejected Promises. Defaults to {@code goog.async.throwException}.
  57322. */
  57323. goog.Promise.setUnhandledRejectionHandler = function(handler) {
  57324. goog.Promise.handleRejection_ = handler;
  57325. };
  57326. /**
  57327. * Error used as a rejection reason for canceled Promises.
  57328. *
  57329. * @param {string=} opt_message
  57330. * @constructor
  57331. * @extends {goog.debug.Error}
  57332. * @final
  57333. */
  57334. goog.Promise.CancellationError = function(opt_message) {
  57335. goog.Promise.CancellationError.base(this, 'constructor', opt_message);
  57336. };
  57337. goog.inherits(goog.Promise.CancellationError, goog.debug.Error);
  57338. /** @override */
  57339. goog.Promise.CancellationError.prototype.name = 'cancel';
  57340. /**
  57341. * Internal implementation of the resolver interface.
  57342. *
  57343. * @param {!goog.Promise<TYPE>} promise
  57344. * @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve
  57345. * @param {function(*=): void} reject
  57346. * @implements {goog.promise.Resolver<TYPE>}
  57347. * @final @struct
  57348. * @constructor
  57349. * @private
  57350. * @template TYPE
  57351. */
  57352. goog.Promise.Resolver_ = function(promise, resolve, reject) {
  57353. /** @const */
  57354. this.promise = promise;
  57355. /** @const */
  57356. this.resolve = resolve;
  57357. /** @const */
  57358. this.reject = reject;
  57359. };
  57360. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  57361. //
  57362. // Licensed under the Apache License, Version 2.0 (the "License");
  57363. // you may not use this file except in compliance with the License.
  57364. // You may obtain a copy of the License at
  57365. //
  57366. // http://www.apache.org/licenses/LICENSE-2.0
  57367. //
  57368. // Unless required by applicable law or agreed to in writing, software
  57369. // distributed under the License is distributed on an "AS-IS" BASIS,
  57370. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57371. // See the License for the specific language governing permissions and
  57372. // limitations under the License.
  57373. /**
  57374. * @fileoverview A timer class to which other classes and objects can
  57375. * listen on. This is only an abstraction above setInterval.
  57376. *
  57377. * @see ../demos/timers.html
  57378. */
  57379. goog.provide('goog.Timer');
  57380. goog.require('goog.Promise');
  57381. goog.require('goog.events.EventTarget');
  57382. /**
  57383. * Class for handling timing events.
  57384. *
  57385. * @param {number=} opt_interval Number of ms between ticks (Default: 1ms).
  57386. * @param {Object=} opt_timerObject An object that has setTimeout, setInterval,
  57387. * clearTimeout and clearInterval (eg Window).
  57388. * @constructor
  57389. * @extends {goog.events.EventTarget}
  57390. */
  57391. goog.Timer = function(opt_interval, opt_timerObject) {
  57392. goog.events.EventTarget.call(this);
  57393. /**
  57394. * Number of ms between ticks
  57395. * @type {number}
  57396. * @private
  57397. */
  57398. this.interval_ = opt_interval || 1;
  57399. /**
  57400. * An object that implements setTimeout, setInterval, clearTimeout and
  57401. * clearInterval. We default to the window object. Changing this on
  57402. * goog.Timer.prototype changes the object for all timer instances which can
  57403. * be useful if your environment has some other implementation of timers than
  57404. * the window object.
  57405. * @type {Object}
  57406. * @private
  57407. */
  57408. this.timerObject_ = opt_timerObject || goog.Timer.defaultTimerObject;
  57409. /**
  57410. * Cached tick_ bound to the object for later use in the timer.
  57411. * @type {Function}
  57412. * @private
  57413. */
  57414. this.boundTick_ = goog.bind(this.tick_, this);
  57415. /**
  57416. * Firefox browser often fires the timer event sooner
  57417. * (sometimes MUCH sooner) than the requested timeout. So we
  57418. * compare the time to when the event was last fired, and
  57419. * reschedule if appropriate. See also goog.Timer.intervalScale
  57420. * @type {number}
  57421. * @private
  57422. */
  57423. this.last_ = goog.now();
  57424. };
  57425. goog.inherits(goog.Timer, goog.events.EventTarget);
  57426. /**
  57427. * Maximum timeout value.
  57428. *
  57429. * Timeout values too big to fit into a signed 32-bit integer may cause
  57430. * overflow in FF, Safari, and Chrome, resulting in the timeout being
  57431. * scheduled immediately. It makes more sense simply not to schedule these
  57432. * timeouts, since 24.8 days is beyond a reasonable expectation for the
  57433. * browser to stay open.
  57434. *
  57435. * @type {number}
  57436. * @private
  57437. */
  57438. goog.Timer.MAX_TIMEOUT_ = 2147483647;
  57439. /**
  57440. * A timer ID that cannot be returned by any known implmentation of
  57441. * Window.setTimeout. Passing this value to window.clearTimeout should
  57442. * therefore be a no-op.
  57443. *
  57444. * @const {number}
  57445. * @private
  57446. */
  57447. goog.Timer.INVALID_TIMEOUT_ID_ = -1;
  57448. /**
  57449. * Whether this timer is enabled
  57450. * @type {boolean}
  57451. */
  57452. goog.Timer.prototype.enabled = false;
  57453. /**
  57454. * An object that implements setTimout, setInterval, clearTimeout and
  57455. * clearInterval. We default to the global object. Changing
  57456. * goog.Timer.defaultTimerObject changes the object for all timer instances
  57457. * which can be useful if your environment has some other implementation of
  57458. * timers you'd like to use.
  57459. * @type {Object}
  57460. */
  57461. goog.Timer.defaultTimerObject = goog.global;
  57462. /**
  57463. * A variable that controls the timer error correction. If the
  57464. * timer is called before the requested interval times
  57465. * intervalScale, which often happens on mozilla, the timer is
  57466. * rescheduled. See also this.last_
  57467. * @type {number}
  57468. */
  57469. goog.Timer.intervalScale = 0.8;
  57470. /**
  57471. * Variable for storing the result of setInterval
  57472. * @type {?number}
  57473. * @private
  57474. */
  57475. goog.Timer.prototype.timer_ = null;
  57476. /**
  57477. * Gets the interval of the timer.
  57478. * @return {number} interval Number of ms between ticks.
  57479. */
  57480. goog.Timer.prototype.getInterval = function() {
  57481. return this.interval_;
  57482. };
  57483. /**
  57484. * Sets the interval of the timer.
  57485. * @param {number} interval Number of ms between ticks.
  57486. */
  57487. goog.Timer.prototype.setInterval = function(interval) {
  57488. this.interval_ = interval;
  57489. if (this.timer_ && this.enabled) {
  57490. // Stop and then start the timer to reset the interval.
  57491. this.stop();
  57492. this.start();
  57493. } else if (this.timer_) {
  57494. this.stop();
  57495. }
  57496. };
  57497. /**
  57498. * Callback for the setTimeout used by the timer
  57499. * @private
  57500. */
  57501. goog.Timer.prototype.tick_ = function() {
  57502. if (this.enabled) {
  57503. var elapsed = goog.now() - this.last_;
  57504. if (elapsed > 0 &&
  57505. elapsed < this.interval_ * goog.Timer.intervalScale) {
  57506. this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
  57507. this.interval_ - elapsed);
  57508. return;
  57509. }
  57510. // Prevents setInterval from registering a duplicate timeout when called
  57511. // in the timer event handler.
  57512. if (this.timer_) {
  57513. this.timerObject_.clearTimeout(this.timer_);
  57514. this.timer_ = null;
  57515. }
  57516. this.dispatchTick();
  57517. // The timer could be stopped in the timer event handler.
  57518. if (this.enabled) {
  57519. this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
  57520. this.interval_);
  57521. this.last_ = goog.now();
  57522. }
  57523. }
  57524. };
  57525. /**
  57526. * Dispatches the TICK event. This is its own method so subclasses can override.
  57527. */
  57528. goog.Timer.prototype.dispatchTick = function() {
  57529. this.dispatchEvent(goog.Timer.TICK);
  57530. };
  57531. /**
  57532. * Starts the timer.
  57533. */
  57534. goog.Timer.prototype.start = function() {
  57535. this.enabled = true;
  57536. // If there is no interval already registered, start it now
  57537. if (!this.timer_) {
  57538. // IMPORTANT!
  57539. // window.setInterval in FireFox has a bug - it fires based on
  57540. // absolute time, rather than on relative time. What this means
  57541. // is that if a computer is sleeping/hibernating for 24 hours
  57542. // and the timer interval was configured to fire every 1000ms,
  57543. // then after the PC wakes up the timer will fire, in rapid
  57544. // succession, 3600*24 times.
  57545. // This bug is described here and is already fixed, but it will
  57546. // take time to propagate, so for now I am switching this over
  57547. // to setTimeout logic.
  57548. // https://bugzilla.mozilla.org/show_bug.cgi?id=376643
  57549. //
  57550. this.timer_ = this.timerObject_.setTimeout(this.boundTick_,
  57551. this.interval_);
  57552. this.last_ = goog.now();
  57553. }
  57554. };
  57555. /**
  57556. * Stops the timer.
  57557. */
  57558. goog.Timer.prototype.stop = function() {
  57559. this.enabled = false;
  57560. if (this.timer_) {
  57561. this.timerObject_.clearTimeout(this.timer_);
  57562. this.timer_ = null;
  57563. }
  57564. };
  57565. /** @override */
  57566. goog.Timer.prototype.disposeInternal = function() {
  57567. goog.Timer.superClass_.disposeInternal.call(this);
  57568. this.stop();
  57569. delete this.timerObject_;
  57570. };
  57571. /**
  57572. * Constant for the timer's event type
  57573. * @type {string}
  57574. */
  57575. goog.Timer.TICK = 'tick';
  57576. /**
  57577. * Calls the given function once, after the optional pause.
  57578. *
  57579. * The function is always called asynchronously, even if the delay is 0. This
  57580. * is a common trick to schedule a function to run after a batch of browser
  57581. * event processing.
  57582. *
  57583. * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function
  57584. * or object that has a handleEvent method.
  57585. * @param {number=} opt_delay Milliseconds to wait; default is 0.
  57586. * @param {SCOPE=} opt_handler Object in whose scope to call the listener.
  57587. * @return {number} A handle to the timer ID.
  57588. * @template SCOPE
  57589. */
  57590. goog.Timer.callOnce = function(listener, opt_delay, opt_handler) {
  57591. if (goog.isFunction(listener)) {
  57592. if (opt_handler) {
  57593. listener = goog.bind(listener, opt_handler);
  57594. }
  57595. } else if (listener && typeof listener.handleEvent == 'function') {
  57596. // using typeof to prevent strict js warning
  57597. listener = goog.bind(listener.handleEvent, listener);
  57598. } else {
  57599. throw Error('Invalid listener argument');
  57600. }
  57601. if (opt_delay > goog.Timer.MAX_TIMEOUT_) {
  57602. // Timeouts greater than MAX_INT return immediately due to integer
  57603. // overflow in many browsers. Since MAX_INT is 24.8 days, just don't
  57604. // schedule anything at all.
  57605. return goog.Timer.INVALID_TIMEOUT_ID_;
  57606. } else {
  57607. return goog.Timer.defaultTimerObject.setTimeout(
  57608. listener, opt_delay || 0);
  57609. }
  57610. };
  57611. /**
  57612. * Clears a timeout initiated by callOnce
  57613. * @param {?number} timerId a timer ID.
  57614. */
  57615. goog.Timer.clear = function(timerId) {
  57616. goog.Timer.defaultTimerObject.clearTimeout(timerId);
  57617. };
  57618. /**
  57619. * @param {number} delay Milliseconds to wait.
  57620. * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value
  57621. * with which the promise will be resolved.
  57622. * @return {!goog.Promise<RESULT>} A promise that will be resolved after
  57623. * the specified delay, unless it is canceled first.
  57624. * @template RESULT
  57625. */
  57626. goog.Timer.promise = function(delay, opt_result) {
  57627. var timerKey = null;
  57628. return new goog.Promise(function(resolve, reject) {
  57629. timerKey = goog.Timer.callOnce(function() {
  57630. resolve(opt_result);
  57631. }, delay);
  57632. if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {
  57633. reject(new Error('Failed to schedule timer.'));
  57634. }
  57635. }).thenCatch(function(error) {
  57636. // Clear the timer. The most likely reason is "cancel" signal.
  57637. goog.Timer.clear(timerKey);
  57638. throw error;
  57639. });
  57640. };
  57641. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  57642. //
  57643. // Licensed under the Apache License, Version 2.0 (the "License");
  57644. // you may not use this file except in compliance with the License.
  57645. // You may obtain a copy of the License at
  57646. //
  57647. // http://www.apache.org/licenses/LICENSE-2.0
  57648. //
  57649. // Unless required by applicable law or agreed to in writing, software
  57650. // distributed under the License is distributed on an "AS-IS" BASIS,
  57651. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57652. // See the License for the specific language governing permissions and
  57653. // limitations under the License.
  57654. /**
  57655. * @fileoverview JSON utility functions.
  57656. * @author arv@google.com (Erik Arvidsson)
  57657. */
  57658. goog.provide('goog.json');
  57659. goog.provide('goog.json.Replacer');
  57660. goog.provide('goog.json.Reviver');
  57661. goog.provide('goog.json.Serializer');
  57662. /**
  57663. * @define {boolean} If true, use the native JSON parsing API.
  57664. * NOTE(ruilopes): EXPERIMENTAL, handle with care. Setting this to true might
  57665. * break your code. The default {@code goog.json.parse} implementation is able
  57666. * to handle invalid JSON, such as JSPB.
  57667. */
  57668. goog.define('goog.json.USE_NATIVE_JSON', false);
  57669. /**
  57670. * Tests if a string is an invalid JSON string. This only ensures that we are
  57671. * not using any invalid characters
  57672. * @param {string} s The string to test.
  57673. * @return {boolean} True if the input is a valid JSON string.
  57674. */
  57675. goog.json.isValid = function(s) {
  57676. // All empty whitespace is not valid.
  57677. if (/^\s*$/.test(s)) {
  57678. return false;
  57679. }
  57680. // This is taken from http://www.json.org/json2.js which is released to the
  57681. // public domain.
  57682. // Changes: We dissallow \u2028 Line separator and \u2029 Paragraph separator
  57683. // inside strings. We also treat \u2028 and \u2029 as whitespace which they
  57684. // are in the RFC but IE and Safari does not match \s to these so we need to
  57685. // include them in the reg exps in all places where whitespace is allowed.
  57686. // We allowed \x7f inside strings because some tools don't escape it,
  57687. // e.g. http://www.json.org/java/org/json/JSONObject.java
  57688. // Parsing happens in three stages. In the first stage, we run the text
  57689. // against regular expressions that look for non-JSON patterns. We are
  57690. // especially concerned with '()' and 'new' because they can cause invocation,
  57691. // and '=' because it can cause mutation. But just to be safe, we want to
  57692. // reject all unexpected forms.
  57693. // We split the first stage into 4 regexp operations in order to work around
  57694. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  57695. // replace all backslash pairs with '@' (a non-JSON character). Second, we
  57696. // replace all simple value tokens with ']' characters. Third, we delete all
  57697. // open brackets that follow a colon or comma or that begin the text. Finally,
  57698. // we look to see that the remaining characters are only whitespace or ']' or
  57699. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  57700. // Don't make these static since they have the global flag.
  57701. var backslashesRe = /\\["\\\/bfnrtu]/g;
  57702. var simpleValuesRe =
  57703. /"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  57704. var openBracketsRe = /(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g;
  57705. var remainderRe = /^[\],:{}\s\u2028\u2029]*$/;
  57706. return remainderRe.test(s.replace(backslashesRe, '@').
  57707. replace(simpleValuesRe, ']').
  57708. replace(openBracketsRe, ''));
  57709. };
  57710. /**
  57711. * Parses a JSON string and returns the result. This throws an exception if
  57712. * the string is an invalid JSON string.
  57713. *
  57714. * Note that this is very slow on large strings. If you trust the source of
  57715. * the string then you should use unsafeParse instead.
  57716. *
  57717. * @param {*} s The JSON string to parse.
  57718. * @throws Error if s is invalid JSON.
  57719. * @return {Object} The object generated from the JSON string, or null.
  57720. */
  57721. goog.json.parse = goog.json.USE_NATIVE_JSON ?
  57722. /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :
  57723. function(s) {
  57724. var o = String(s);
  57725. if (goog.json.isValid(o)) {
  57726. /** @preserveTry */
  57727. try {
  57728. return /** @type {Object} */ (eval('(' + o + ')'));
  57729. } catch (ex) {
  57730. }
  57731. }
  57732. throw Error('Invalid JSON string: ' + o);
  57733. };
  57734. /**
  57735. * Parses a JSON string and returns the result. This uses eval so it is open
  57736. * to security issues and it should only be used if you trust the source.
  57737. *
  57738. * @param {string} s The JSON string to parse.
  57739. * @return {Object} The object generated from the JSON string.
  57740. */
  57741. goog.json.unsafeParse = goog.json.USE_NATIVE_JSON ?
  57742. /** @type {function(string):Object} */ (goog.global['JSON']['parse']) :
  57743. function(s) {
  57744. return /** @type {Object} */ (eval('(' + s + ')'));
  57745. };
  57746. /**
  57747. * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.
  57748. * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3
  57749. *
  57750. * TODO(nicksantos): Array should also be a valid replacer.
  57751. *
  57752. * @typedef {function(this:Object, string, *): *}
  57753. */
  57754. goog.json.Replacer;
  57755. /**
  57756. * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.
  57757. * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3
  57758. *
  57759. * @typedef {function(this:Object, string, *): *}
  57760. */
  57761. goog.json.Reviver;
  57762. /**
  57763. * Serializes an object or a value to a JSON string.
  57764. *
  57765. * @param {*} object The object to serialize.
  57766. * @param {?goog.json.Replacer=} opt_replacer A replacer function
  57767. * called for each (key, value) pair that determines how the value
  57768. * should be serialized. By defult, this just returns the value
  57769. * and allows default serialization to kick in.
  57770. * @throws Error if there are loops in the object graph.
  57771. * @return {string} A JSON string representation of the input.
  57772. */
  57773. goog.json.serialize = goog.json.USE_NATIVE_JSON ?
  57774. /** @type {function(*, ?goog.json.Replacer=):string} */
  57775. (goog.global['JSON']['stringify']) :
  57776. function(object, opt_replacer) {
  57777. // NOTE(nicksantos): Currently, we never use JSON.stringify.
  57778. //
  57779. // The last time I evaluated this, JSON.stringify had subtle bugs and
  57780. // behavior differences on all browsers, and the performance win was not
  57781. // large enough to justify all the issues. This may change in the future
  57782. // as browser implementations get better.
  57783. //
  57784. // assertSerialize in json_test contains if branches for the cases
  57785. // that fail.
  57786. return new goog.json.Serializer(opt_replacer).serialize(object);
  57787. };
  57788. /**
  57789. * Class that is used to serialize JSON objects to a string.
  57790. * @param {?goog.json.Replacer=} opt_replacer Replacer.
  57791. * @constructor
  57792. */
  57793. goog.json.Serializer = function(opt_replacer) {
  57794. /**
  57795. * @type {goog.json.Replacer|null|undefined}
  57796. * @private
  57797. */
  57798. this.replacer_ = opt_replacer;
  57799. };
  57800. /**
  57801. * Serializes an object or a value to a JSON string.
  57802. *
  57803. * @param {*} object The object to serialize.
  57804. * @throws Error if there are loops in the object graph.
  57805. * @return {string} A JSON string representation of the input.
  57806. */
  57807. goog.json.Serializer.prototype.serialize = function(object) {
  57808. var sb = [];
  57809. this.serializeInternal(object, sb);
  57810. return sb.join('');
  57811. };
  57812. /**
  57813. * Serializes a generic value to a JSON string
  57814. * @protected
  57815. * @param {*} object The object to serialize.
  57816. * @param {Array<string>} sb Array used as a string builder.
  57817. * @throws Error if there are loops in the object graph.
  57818. */
  57819. goog.json.Serializer.prototype.serializeInternal = function(object, sb) {
  57820. if (object == null) {
  57821. // undefined == null so this branch covers undefined as well as null
  57822. sb.push('null');
  57823. return;
  57824. }
  57825. if (typeof object == 'object') {
  57826. if (goog.isArray(object)) {
  57827. this.serializeArray(object, sb);
  57828. return;
  57829. } else if (object instanceof String ||
  57830. object instanceof Number ||
  57831. object instanceof Boolean) {
  57832. object = object.valueOf();
  57833. // Fall through to switch below.
  57834. } else {
  57835. this.serializeObject_(/** @type {Object} */ (object), sb);
  57836. return;
  57837. }
  57838. }
  57839. switch (typeof object) {
  57840. case 'string':
  57841. this.serializeString_(object, sb);
  57842. break;
  57843. case 'number':
  57844. this.serializeNumber_(object, sb);
  57845. break;
  57846. case 'boolean':
  57847. sb.push(object);
  57848. break;
  57849. case 'function':
  57850. sb.push('null');
  57851. break;
  57852. default:
  57853. throw Error('Unknown type: ' + typeof object);
  57854. }
  57855. };
  57856. /**
  57857. * Character mappings used internally for goog.string.quote
  57858. * @private
  57859. * @type {!Object}
  57860. */
  57861. goog.json.Serializer.charToJsonCharCache_ = {
  57862. '\"': '\\"',
  57863. '\\': '\\\\',
  57864. '/': '\\/',
  57865. '\b': '\\b',
  57866. '\f': '\\f',
  57867. '\n': '\\n',
  57868. '\r': '\\r',
  57869. '\t': '\\t',
  57870. '\x0B': '\\u000b' // '\v' is not supported in JScript
  57871. };
  57872. /**
  57873. * Regular expression used to match characters that need to be replaced.
  57874. * The S60 browser has a bug where unicode characters are not matched by
  57875. * regular expressions. The condition below detects such behaviour and
  57876. * adjusts the regular expression accordingly.
  57877. * @private
  57878. * @type {!RegExp}
  57879. */
  57880. goog.json.Serializer.charsToReplace_ = /\uffff/.test('\uffff') ?
  57881. /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g;
  57882. /**
  57883. * Serializes a string to a JSON string
  57884. * @private
  57885. * @param {string} s The string to serialize.
  57886. * @param {Array<string>} sb Array used as a string builder.
  57887. */
  57888. goog.json.Serializer.prototype.serializeString_ = function(s, sb) {
  57889. // The official JSON implementation does not work with international
  57890. // characters.
  57891. sb.push('"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {
  57892. // caching the result improves performance by a factor 2-3
  57893. var rv = goog.json.Serializer.charToJsonCharCache_[c];
  57894. if (!rv) {
  57895. rv = '\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);
  57896. goog.json.Serializer.charToJsonCharCache_[c] = rv;
  57897. }
  57898. return rv;
  57899. }), '"');
  57900. };
  57901. /**
  57902. * Serializes a number to a JSON string
  57903. * @private
  57904. * @param {number} n The number to serialize.
  57905. * @param {Array<string>} sb Array used as a string builder.
  57906. */
  57907. goog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {
  57908. sb.push(isFinite(n) && !isNaN(n) ? n : 'null');
  57909. };
  57910. /**
  57911. * Serializes an array to a JSON string
  57912. * @param {Array<string>} arr The array to serialize.
  57913. * @param {Array<string>} sb Array used as a string builder.
  57914. * @protected
  57915. */
  57916. goog.json.Serializer.prototype.serializeArray = function(arr, sb) {
  57917. var l = arr.length;
  57918. sb.push('[');
  57919. var sep = '';
  57920. for (var i = 0; i < l; i++) {
  57921. sb.push(sep);
  57922. var value = arr[i];
  57923. this.serializeInternal(
  57924. this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,
  57925. sb);
  57926. sep = ',';
  57927. }
  57928. sb.push(']');
  57929. };
  57930. /**
  57931. * Serializes an object to a JSON string
  57932. * @private
  57933. * @param {Object} obj The object to serialize.
  57934. * @param {Array<string>} sb Array used as a string builder.
  57935. */
  57936. goog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {
  57937. sb.push('{');
  57938. var sep = '';
  57939. for (var key in obj) {
  57940. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  57941. var value = obj[key];
  57942. // Skip functions.
  57943. if (typeof value != 'function') {
  57944. sb.push(sep);
  57945. this.serializeString_(key, sb);
  57946. sb.push(':');
  57947. this.serializeInternal(
  57948. this.replacer_ ? this.replacer_.call(obj, key, value) : value,
  57949. sb);
  57950. sep = ',';
  57951. }
  57952. }
  57953. }
  57954. sb.push('}');
  57955. };
  57956. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  57957. //
  57958. // Licensed under the Apache License, Version 2.0 (the "License");
  57959. // you may not use this file except in compliance with the License.
  57960. // You may obtain a copy of the License at
  57961. //
  57962. // http://www.apache.org/licenses/LICENSE-2.0
  57963. //
  57964. // Unless required by applicable law or agreed to in writing, software
  57965. // distributed under the License is distributed on an "AS-IS" BASIS,
  57966. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57967. // See the License for the specific language governing permissions and
  57968. // limitations under the License.
  57969. /**
  57970. * @fileoverview Error codes shared between goog.net.IframeIo and
  57971. * goog.net.XhrIo.
  57972. */
  57973. goog.provide('goog.net.ErrorCode');
  57974. /**
  57975. * Error codes
  57976. * @enum {number}
  57977. */
  57978. goog.net.ErrorCode = {
  57979. /**
  57980. * There is no error condition.
  57981. */
  57982. NO_ERROR: 0,
  57983. /**
  57984. * The most common error from iframeio, unfortunately, is that the browser
  57985. * responded with an error page that is classed as a different domain. The
  57986. * situations, are when a browser error page is shown -- 404, access denied,
  57987. * DNS failure, connection reset etc.)
  57988. *
  57989. */
  57990. ACCESS_DENIED: 1,
  57991. /**
  57992. * Currently the only case where file not found will be caused is when the
  57993. * code is running on the local file system and a non-IE browser makes a
  57994. * request to a file that doesn't exist.
  57995. */
  57996. FILE_NOT_FOUND: 2,
  57997. /**
  57998. * If Firefox shows a browser error page, such as a connection reset by
  57999. * server or access denied, then it will fail silently without the error or
  58000. * load handlers firing.
  58001. */
  58002. FF_SILENT_ERROR: 3,
  58003. /**
  58004. * Custom error provided by the client through the error check hook.
  58005. */
  58006. CUSTOM_ERROR: 4,
  58007. /**
  58008. * Exception was thrown while processing the request.
  58009. */
  58010. EXCEPTION: 5,
  58011. /**
  58012. * The Http response returned a non-successful http status code.
  58013. */
  58014. HTTP_ERROR: 6,
  58015. /**
  58016. * The request was aborted.
  58017. */
  58018. ABORT: 7,
  58019. /**
  58020. * The request timed out.
  58021. */
  58022. TIMEOUT: 8,
  58023. /**
  58024. * The resource is not available offline.
  58025. */
  58026. OFFLINE: 9
  58027. };
  58028. /**
  58029. * Returns a friendly error message for an error code. These messages are for
  58030. * debugging and are not localized.
  58031. * @param {goog.net.ErrorCode} errorCode An error code.
  58032. * @return {string} A message for debugging.
  58033. */
  58034. goog.net.ErrorCode.getDebugMessage = function(errorCode) {
  58035. switch (errorCode) {
  58036. case goog.net.ErrorCode.NO_ERROR:
  58037. return 'No Error';
  58038. case goog.net.ErrorCode.ACCESS_DENIED:
  58039. return 'Access denied to content document';
  58040. case goog.net.ErrorCode.FILE_NOT_FOUND:
  58041. return 'File not found';
  58042. case goog.net.ErrorCode.FF_SILENT_ERROR:
  58043. return 'Firefox silently errored';
  58044. case goog.net.ErrorCode.CUSTOM_ERROR:
  58045. return 'Application custom error';
  58046. case goog.net.ErrorCode.EXCEPTION:
  58047. return 'An exception occurred';
  58048. case goog.net.ErrorCode.HTTP_ERROR:
  58049. return 'Http response at 400 or 500 level';
  58050. case goog.net.ErrorCode.ABORT:
  58051. return 'Request was aborted';
  58052. case goog.net.ErrorCode.TIMEOUT:
  58053. return 'Request timed out';
  58054. case goog.net.ErrorCode.OFFLINE:
  58055. return 'The resource is not available offline';
  58056. default:
  58057. return 'Unrecognized error code';
  58058. }
  58059. };
  58060. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  58061. //
  58062. // Licensed under the Apache License, Version 2.0 (the "License");
  58063. // you may not use this file except in compliance with the License.
  58064. // You may obtain a copy of the License at
  58065. //
  58066. // http://www.apache.org/licenses/LICENSE-2.0
  58067. //
  58068. // Unless required by applicable law or agreed to in writing, software
  58069. // distributed under the License is distributed on an "AS-IS" BASIS,
  58070. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58071. // See the License for the specific language governing permissions and
  58072. // limitations under the License.
  58073. /**
  58074. * @fileoverview Constants for HTTP status codes.
  58075. */
  58076. goog.provide('goog.net.HttpStatus');
  58077. /**
  58078. * HTTP Status Codes defined in RFC 2616 and RFC 6585.
  58079. * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  58080. * @see http://tools.ietf.org/html/rfc6585
  58081. * @enum {number}
  58082. */
  58083. goog.net.HttpStatus = {
  58084. // Informational 1xx
  58085. CONTINUE: 100,
  58086. SWITCHING_PROTOCOLS: 101,
  58087. // Successful 2xx
  58088. OK: 200,
  58089. CREATED: 201,
  58090. ACCEPTED: 202,
  58091. NON_AUTHORITATIVE_INFORMATION: 203,
  58092. NO_CONTENT: 204,
  58093. RESET_CONTENT: 205,
  58094. PARTIAL_CONTENT: 206,
  58095. // Redirection 3xx
  58096. MULTIPLE_CHOICES: 300,
  58097. MOVED_PERMANENTLY: 301,
  58098. FOUND: 302,
  58099. SEE_OTHER: 303,
  58100. NOT_MODIFIED: 304,
  58101. USE_PROXY: 305,
  58102. TEMPORARY_REDIRECT: 307,
  58103. // Client Error 4xx
  58104. BAD_REQUEST: 400,
  58105. UNAUTHORIZED: 401,
  58106. PAYMENT_REQUIRED: 402,
  58107. FORBIDDEN: 403,
  58108. NOT_FOUND: 404,
  58109. METHOD_NOT_ALLOWED: 405,
  58110. NOT_ACCEPTABLE: 406,
  58111. PROXY_AUTHENTICATION_REQUIRED: 407,
  58112. REQUEST_TIMEOUT: 408,
  58113. CONFLICT: 409,
  58114. GONE: 410,
  58115. LENGTH_REQUIRED: 411,
  58116. PRECONDITION_FAILED: 412,
  58117. REQUEST_ENTITY_TOO_LARGE: 413,
  58118. REQUEST_URI_TOO_LONG: 414,
  58119. UNSUPPORTED_MEDIA_TYPE: 415,
  58120. REQUEST_RANGE_NOT_SATISFIABLE: 416,
  58121. EXPECTATION_FAILED: 417,
  58122. PRECONDITION_REQUIRED: 428,
  58123. TOO_MANY_REQUESTS: 429,
  58124. REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
  58125. // Server Error 5xx
  58126. INTERNAL_SERVER_ERROR: 500,
  58127. NOT_IMPLEMENTED: 501,
  58128. BAD_GATEWAY: 502,
  58129. SERVICE_UNAVAILABLE: 503,
  58130. GATEWAY_TIMEOUT: 504,
  58131. HTTP_VERSION_NOT_SUPPORTED: 505,
  58132. NETWORK_AUTHENTICATION_REQUIRED: 511,
  58133. /*
  58134. * IE returns this code for 204 due to its use of URLMon, which returns this
  58135. * code for 'Operation Aborted'. The status text is 'Unknown', the response
  58136. * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.
  58137. */
  58138. QUIRK_IE_NO_CONTENT: 1223
  58139. };
  58140. /**
  58141. * Returns whether the given status should be considered successful.
  58142. *
  58143. * Successful codes are OK (200), CREATED (201), ACCEPTED (202),
  58144. * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),
  58145. * and IE's no content code (1223).
  58146. *
  58147. * @param {number} status The status code to test.
  58148. * @return {boolean} Whether the status code should be considered successful.
  58149. */
  58150. goog.net.HttpStatus.isSuccess = function(status) {
  58151. switch (status) {
  58152. case goog.net.HttpStatus.OK:
  58153. case goog.net.HttpStatus.CREATED:
  58154. case goog.net.HttpStatus.ACCEPTED:
  58155. case goog.net.HttpStatus.NO_CONTENT:
  58156. case goog.net.HttpStatus.PARTIAL_CONTENT:
  58157. case goog.net.HttpStatus.NOT_MODIFIED:
  58158. case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:
  58159. return true;
  58160. default:
  58161. return false;
  58162. }
  58163. };
  58164. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  58165. //
  58166. // Licensed under the Apache License, Version 2.0 (the "License");
  58167. // you may not use this file except in compliance with the License.
  58168. // You may obtain a copy of the License at
  58169. //
  58170. // http://www.apache.org/licenses/LICENSE-2.0
  58171. //
  58172. // Unless required by applicable law or agreed to in writing, software
  58173. // distributed under the License is distributed on an "AS-IS" BASIS,
  58174. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58175. // See the License for the specific language governing permissions and
  58176. // limitations under the License.
  58177. goog.provide('goog.net.XhrLike');
  58178. /**
  58179. * Interface for the common parts of XMLHttpRequest.
  58180. *
  58181. * Mostly copied from externs/w3c_xml.js.
  58182. *
  58183. * @interface
  58184. * @see http://www.w3.org/TR/XMLHttpRequest/
  58185. */
  58186. goog.net.XhrLike = function() {};
  58187. /**
  58188. * Typedef that refers to either native or custom-implemented XHR objects.
  58189. * @typedef {!goog.net.XhrLike|!XMLHttpRequest}
  58190. */
  58191. goog.net.XhrLike.OrNative;
  58192. /**
  58193. * @type {function()|null|undefined}
  58194. * @see http://www.w3.org/TR/XMLHttpRequest/#handler-xhr-onreadystatechange
  58195. */
  58196. goog.net.XhrLike.prototype.onreadystatechange;
  58197. /**
  58198. * @type {string}
  58199. * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
  58200. */
  58201. goog.net.XhrLike.prototype.responseText;
  58202. /**
  58203. * @type {Document}
  58204. * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsexml-attribute
  58205. */
  58206. goog.net.XhrLike.prototype.responseXML;
  58207. /**
  58208. * @type {number}
  58209. * @see http://www.w3.org/TR/XMLHttpRequest/#readystate
  58210. */
  58211. goog.net.XhrLike.prototype.readyState;
  58212. /**
  58213. * @type {number}
  58214. * @see http://www.w3.org/TR/XMLHttpRequest/#status
  58215. */
  58216. goog.net.XhrLike.prototype.status;
  58217. /**
  58218. * @type {string}
  58219. * @see http://www.w3.org/TR/XMLHttpRequest/#statustext
  58220. */
  58221. goog.net.XhrLike.prototype.statusText;
  58222. /**
  58223. * @param {string} method
  58224. * @param {string} url
  58225. * @param {?boolean=} opt_async
  58226. * @param {?string=} opt_user
  58227. * @param {?string=} opt_password
  58228. * @see http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
  58229. */
  58230. goog.net.XhrLike.prototype.open = function(method, url, opt_async, opt_user,
  58231. opt_password) {};
  58232. /**
  58233. * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=} opt_data
  58234. * @see http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
  58235. */
  58236. goog.net.XhrLike.prototype.send = function(opt_data) {};
  58237. /**
  58238. * @see http://www.w3.org/TR/XMLHttpRequest/#the-abort()-method
  58239. */
  58240. goog.net.XhrLike.prototype.abort = function() {};
  58241. /**
  58242. * @param {string} header
  58243. * @param {string} value
  58244. * @see http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
  58245. */
  58246. goog.net.XhrLike.prototype.setRequestHeader = function(header, value) {};
  58247. /**
  58248. * @param {string} header
  58249. * @return {string}
  58250. * @see http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
  58251. */
  58252. goog.net.XhrLike.prototype.getResponseHeader = function(header) {};
  58253. /**
  58254. * @return {string}
  58255. * @see http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  58256. */
  58257. goog.net.XhrLike.prototype.getAllResponseHeaders = function() {};
  58258. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  58259. //
  58260. // Licensed under the Apache License, Version 2.0 (the "License");
  58261. // you may not use this file except in compliance with the License.
  58262. // You may obtain a copy of the License at
  58263. //
  58264. // http://www.apache.org/licenses/LICENSE-2.0
  58265. //
  58266. // Unless required by applicable law or agreed to in writing, software
  58267. // distributed under the License is distributed on an "AS-IS" BASIS,
  58268. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58269. // See the License for the specific language governing permissions and
  58270. // limitations under the License.
  58271. /**
  58272. * @fileoverview Interface for a factory for creating XMLHttpRequest objects
  58273. * and metadata about them.
  58274. * @author dbk@google.com (David Barrett-Kahn)
  58275. */
  58276. goog.provide('goog.net.XmlHttpFactory');
  58277. /** @suppress {extraRequire} Typedef. */
  58278. goog.require('goog.net.XhrLike');
  58279. /**
  58280. * Abstract base class for an XmlHttpRequest factory.
  58281. * @constructor
  58282. */
  58283. goog.net.XmlHttpFactory = function() {
  58284. };
  58285. /**
  58286. * Cache of options - we only actually call internalGetOptions once.
  58287. * @type {Object}
  58288. * @private
  58289. */
  58290. goog.net.XmlHttpFactory.prototype.cachedOptions_ = null;
  58291. /**
  58292. * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.
  58293. */
  58294. goog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;
  58295. /**
  58296. * @return {Object} Options describing how xhr objects obtained from this
  58297. * factory should be used.
  58298. */
  58299. goog.net.XmlHttpFactory.prototype.getOptions = function() {
  58300. return this.cachedOptions_ ||
  58301. (this.cachedOptions_ = this.internalGetOptions());
  58302. };
  58303. /**
  58304. * Override this method in subclasses to preserve the caching offered by
  58305. * getOptions().
  58306. * @return {Object} Options describing how xhr objects obtained from this
  58307. * factory should be used.
  58308. * @protected
  58309. */
  58310. goog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;
  58311. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  58312. //
  58313. // Licensed under the Apache License, Version 2.0 (the "License");
  58314. // you may not use this file except in compliance with the License.
  58315. // You may obtain a copy of the License at
  58316. //
  58317. // http://www.apache.org/licenses/LICENSE-2.0
  58318. //
  58319. // Unless required by applicable law or agreed to in writing, software
  58320. // distributed under the License is distributed on an "AS-IS" BASIS,
  58321. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58322. // See the License for the specific language governing permissions and
  58323. // limitations under the License.
  58324. /**
  58325. * @fileoverview Implementation of XmlHttpFactory which allows construction from
  58326. * simple factory methods.
  58327. * @author dbk@google.com (David Barrett-Kahn)
  58328. */
  58329. goog.provide('goog.net.WrapperXmlHttpFactory');
  58330. /** @suppress {extraRequire} Typedef. */
  58331. goog.require('goog.net.XhrLike');
  58332. goog.require('goog.net.XmlHttpFactory');
  58333. /**
  58334. * An xhr factory subclass which can be constructed using two factory methods.
  58335. * This exists partly to allow the preservation of goog.net.XmlHttp.setFactory()
  58336. * with an unchanged signature.
  58337. * @param {function():!goog.net.XhrLike.OrNative} xhrFactory
  58338. * A function which returns a new XHR object.
  58339. * @param {function():!Object} optionsFactory A function which returns the
  58340. * options associated with xhr objects from this factory.
  58341. * @extends {goog.net.XmlHttpFactory}
  58342. * @constructor
  58343. * @final
  58344. */
  58345. goog.net.WrapperXmlHttpFactory = function(xhrFactory, optionsFactory) {
  58346. goog.net.XmlHttpFactory.call(this);
  58347. /**
  58348. * XHR factory method.
  58349. * @type {function() : !goog.net.XhrLike.OrNative}
  58350. * @private
  58351. */
  58352. this.xhrFactory_ = xhrFactory;
  58353. /**
  58354. * Options factory method.
  58355. * @type {function() : !Object}
  58356. * @private
  58357. */
  58358. this.optionsFactory_ = optionsFactory;
  58359. };
  58360. goog.inherits(goog.net.WrapperXmlHttpFactory, goog.net.XmlHttpFactory);
  58361. /** @override */
  58362. goog.net.WrapperXmlHttpFactory.prototype.createInstance = function() {
  58363. return this.xhrFactory_();
  58364. };
  58365. /** @override */
  58366. goog.net.WrapperXmlHttpFactory.prototype.getOptions = function() {
  58367. return this.optionsFactory_();
  58368. };
  58369. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  58370. //
  58371. // Licensed under the Apache License, Version 2.0 (the "License");
  58372. // you may not use this file except in compliance with the License.
  58373. // You may obtain a copy of the License at
  58374. //
  58375. // http://www.apache.org/licenses/LICENSE-2.0
  58376. //
  58377. // Unless required by applicable law or agreed to in writing, software
  58378. // distributed under the License is distributed on an "AS-IS" BASIS,
  58379. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58380. // See the License for the specific language governing permissions and
  58381. // limitations under the License.
  58382. /**
  58383. * @fileoverview Low level handling of XMLHttpRequest.
  58384. * @author arv@google.com (Erik Arvidsson)
  58385. * @author dbk@google.com (David Barrett-Kahn)
  58386. */
  58387. goog.provide('goog.net.DefaultXmlHttpFactory');
  58388. goog.provide('goog.net.XmlHttp');
  58389. goog.provide('goog.net.XmlHttp.OptionType');
  58390. goog.provide('goog.net.XmlHttp.ReadyState');
  58391. goog.provide('goog.net.XmlHttpDefines');
  58392. goog.require('goog.asserts');
  58393. goog.require('goog.net.WrapperXmlHttpFactory');
  58394. goog.require('goog.net.XmlHttpFactory');
  58395. /**
  58396. * Static class for creating XMLHttpRequest objects.
  58397. * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.
  58398. */
  58399. goog.net.XmlHttp = function() {
  58400. return goog.net.XmlHttp.factory_.createInstance();
  58401. };
  58402. /**
  58403. * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to
  58404. * true bypasses the ActiveX probing code.
  58405. * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip
  58406. * out the ActiveX probing code from binaries. To achieve this, use
  58407. * {@code goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR} instead.
  58408. * TODO(ruilopes): Collapse both defines.
  58409. */
  58410. goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);
  58411. /** @const */
  58412. goog.net.XmlHttpDefines = {};
  58413. /**
  58414. * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to
  58415. * true eliminates the ActiveX probing code.
  58416. */
  58417. goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);
  58418. /**
  58419. * Gets the options to use with the XMLHttpRequest objects obtained using
  58420. * the static methods.
  58421. * @return {Object} The options.
  58422. */
  58423. goog.net.XmlHttp.getOptions = function() {
  58424. return goog.net.XmlHttp.factory_.getOptions();
  58425. };
  58426. /**
  58427. * Type of options that an XmlHttp object can have.
  58428. * @enum {number}
  58429. */
  58430. goog.net.XmlHttp.OptionType = {
  58431. /**
  58432. * Whether a goog.nullFunction should be used to clear the onreadystatechange
  58433. * handler instead of null.
  58434. */
  58435. USE_NULL_FUNCTION: 0,
  58436. /**
  58437. * NOTE(user): In IE if send() errors on a *local* request the readystate
  58438. * is still changed to COMPLETE. We need to ignore it and allow the
  58439. * try/catch around send() to pick up the error.
  58440. */
  58441. LOCAL_REQUEST_ERROR: 1
  58442. };
  58443. /**
  58444. * Status constants for XMLHTTP, matches:
  58445. * http://msdn.microsoft.com/library/default.asp?url=/library/
  58446. * en-us/xmlsdk/html/0e6a34e4-f90c-489d-acff-cb44242fafc6.asp
  58447. * @enum {number}
  58448. */
  58449. goog.net.XmlHttp.ReadyState = {
  58450. /**
  58451. * Constant for when xmlhttprequest.readyState is uninitialized
  58452. */
  58453. UNINITIALIZED: 0,
  58454. /**
  58455. * Constant for when xmlhttprequest.readyState is loading.
  58456. */
  58457. LOADING: 1,
  58458. /**
  58459. * Constant for when xmlhttprequest.readyState is loaded.
  58460. */
  58461. LOADED: 2,
  58462. /**
  58463. * Constant for when xmlhttprequest.readyState is in an interactive state.
  58464. */
  58465. INTERACTIVE: 3,
  58466. /**
  58467. * Constant for when xmlhttprequest.readyState is completed
  58468. */
  58469. COMPLETE: 4
  58470. };
  58471. /**
  58472. * The global factory instance for creating XMLHttpRequest objects.
  58473. * @type {goog.net.XmlHttpFactory}
  58474. * @private
  58475. */
  58476. goog.net.XmlHttp.factory_;
  58477. /**
  58478. * Sets the factories for creating XMLHttpRequest objects and their options.
  58479. * @param {Function} factory The factory for XMLHttpRequest objects.
  58480. * @param {Function} optionsFactory The factory for options.
  58481. * @deprecated Use setGlobalFactory instead.
  58482. */
  58483. goog.net.XmlHttp.setFactory = function(factory, optionsFactory) {
  58484. goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory(
  58485. goog.asserts.assert(factory),
  58486. goog.asserts.assert(optionsFactory)));
  58487. };
  58488. /**
  58489. * Sets the global factory object.
  58490. * @param {!goog.net.XmlHttpFactory} factory New global factory object.
  58491. */
  58492. goog.net.XmlHttp.setGlobalFactory = function(factory) {
  58493. goog.net.XmlHttp.factory_ = factory;
  58494. };
  58495. /**
  58496. * Default factory to use when creating xhr objects. You probably shouldn't be
  58497. * instantiating this directly, but rather using it via goog.net.XmlHttp.
  58498. * @extends {goog.net.XmlHttpFactory}
  58499. * @constructor
  58500. */
  58501. goog.net.DefaultXmlHttpFactory = function() {
  58502. goog.net.XmlHttpFactory.call(this);
  58503. };
  58504. goog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);
  58505. /** @override */
  58506. goog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {
  58507. var progId = this.getProgId_();
  58508. if (progId) {
  58509. return new ActiveXObject(progId);
  58510. } else {
  58511. return new XMLHttpRequest();
  58512. }
  58513. };
  58514. /** @override */
  58515. goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {
  58516. var progId = this.getProgId_();
  58517. var options = {};
  58518. if (progId) {
  58519. options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;
  58520. options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;
  58521. }
  58522. return options;
  58523. };
  58524. /**
  58525. * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.
  58526. * @type {string|undefined}
  58527. * @private
  58528. */
  58529. goog.net.DefaultXmlHttpFactory.prototype.ieProgId_;
  58530. /**
  58531. * Initialize the private state used by other functions.
  58532. * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.
  58533. * @private
  58534. */
  58535. goog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {
  58536. if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||
  58537. goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {
  58538. return '';
  58539. }
  58540. // The following blog post describes what PROG IDs to use to create the
  58541. // XMLHTTP object in Internet Explorer:
  58542. // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
  58543. // However we do not (yet) fully trust that this will be OK for old versions
  58544. // of IE on Win9x so we therefore keep the last 2.
  58545. if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&
  58546. typeof ActiveXObject != 'undefined') {
  58547. // Candidate Active X types.
  58548. var ACTIVE_X_IDENTS = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0',
  58549. 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
  58550. for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) {
  58551. var candidate = ACTIVE_X_IDENTS[i];
  58552. /** @preserveTry */
  58553. try {
  58554. new ActiveXObject(candidate);
  58555. // NOTE(user): cannot assign progid and return candidate in one line
  58556. // because JSCompiler complaings: BUG 658126
  58557. this.ieProgId_ = candidate;
  58558. return candidate;
  58559. } catch (e) {
  58560. // do nothing; try next choice
  58561. }
  58562. }
  58563. // couldn't find any matches
  58564. throw Error('Could not create ActiveXObject. ActiveX might be disabled,' +
  58565. ' or MSXML might not be installed');
  58566. }
  58567. return /** @type {string} */ (this.ieProgId_);
  58568. };
  58569. //Set the global factory to an instance of the default factory.
  58570. goog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());
  58571. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  58572. //
  58573. // Licensed under the Apache License, Version 2.0 (the "License");
  58574. // you may not use this file except in compliance with the License.
  58575. // You may obtain a copy of the License at
  58576. //
  58577. // http://www.apache.org/licenses/LICENSE-2.0
  58578. //
  58579. // Unless required by applicable law or agreed to in writing, software
  58580. // distributed under the License is distributed on an "AS-IS" BASIS,
  58581. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58582. // See the License for the specific language governing permissions and
  58583. // limitations under the License.
  58584. /**
  58585. * @fileoverview Simple utilities for dealing with URI strings.
  58586. *
  58587. * This is intended to be a lightweight alternative to constructing goog.Uri
  58588. * objects. Whereas goog.Uri adds several kilobytes to the binary regardless
  58589. * of how much of its functionality you use, this is designed to be a set of
  58590. * mostly-independent utilities so that the compiler includes only what is
  58591. * necessary for the task. Estimated savings of porting is 5k pre-gzip and
  58592. * 1.5k post-gzip. To ensure the savings remain, future developers should
  58593. * avoid adding new functionality to existing functions, but instead create
  58594. * new ones and factor out shared code.
  58595. *
  58596. * Many of these utilities have limited functionality, tailored to common
  58597. * cases. The query parameter utilities assume that the parameter keys are
  58598. * already encoded, since most keys are compile-time alphanumeric strings. The
  58599. * query parameter mutation utilities also do not tolerate fragment identifiers.
  58600. *
  58601. * By design, these functions can be slower than goog.Uri equivalents.
  58602. * Repeated calls to some of functions may be quadratic in behavior for IE,
  58603. * although the effect is somewhat limited given the 2kb limit.
  58604. *
  58605. * One advantage of the limited functionality here is that this approach is
  58606. * less sensitive to differences in URI encodings than goog.Uri, since these
  58607. * functions operate on strings directly, rather than decoding them and
  58608. * then re-encoding.
  58609. *
  58610. * Uses features of RFC 3986 for parsing/formatting URIs:
  58611. * http://www.ietf.org/rfc/rfc3986.txt
  58612. *
  58613. * @author gboyer@google.com (Garrett Boyer) - The "lightened" design.
  58614. */
  58615. goog.provide('goog.uri.utils');
  58616. goog.provide('goog.uri.utils.ComponentIndex');
  58617. goog.provide('goog.uri.utils.QueryArray');
  58618. goog.provide('goog.uri.utils.QueryValue');
  58619. goog.provide('goog.uri.utils.StandardQueryParam');
  58620. goog.require('goog.asserts');
  58621. goog.require('goog.string');
  58622. /**
  58623. * Character codes inlined to avoid object allocations due to charCode.
  58624. * @enum {number}
  58625. * @private
  58626. */
  58627. goog.uri.utils.CharCode_ = {
  58628. AMPERSAND: 38,
  58629. EQUAL: 61,
  58630. HASH: 35,
  58631. QUESTION: 63
  58632. };
  58633. /**
  58634. * Builds a URI string from already-encoded parts.
  58635. *
  58636. * No encoding is performed. Any component may be omitted as either null or
  58637. * undefined.
  58638. *
  58639. * @param {?string=} opt_scheme The scheme such as 'http'.
  58640. * @param {?string=} opt_userInfo The user name before the '@'.
  58641. * @param {?string=} opt_domain The domain such as 'www.google.com', already
  58642. * URI-encoded.
  58643. * @param {(string|number|null)=} opt_port The port number.
  58644. * @param {?string=} opt_path The path, already URI-encoded. If it is not
  58645. * empty, it must begin with a slash.
  58646. * @param {?string=} opt_queryData The URI-encoded query data.
  58647. * @param {?string=} opt_fragment The URI-encoded fragment identifier.
  58648. * @return {string} The fully combined URI.
  58649. */
  58650. goog.uri.utils.buildFromEncodedParts = function(opt_scheme, opt_userInfo,
  58651. opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  58652. var out = '';
  58653. if (opt_scheme) {
  58654. out += opt_scheme + ':';
  58655. }
  58656. if (opt_domain) {
  58657. out += '//';
  58658. if (opt_userInfo) {
  58659. out += opt_userInfo + '@';
  58660. }
  58661. out += opt_domain;
  58662. if (opt_port) {
  58663. out += ':' + opt_port;
  58664. }
  58665. }
  58666. if (opt_path) {
  58667. out += opt_path;
  58668. }
  58669. if (opt_queryData) {
  58670. out += '?' + opt_queryData;
  58671. }
  58672. if (opt_fragment) {
  58673. out += '#' + opt_fragment;
  58674. }
  58675. return out;
  58676. };
  58677. /**
  58678. * A regular expression for breaking a URI into its component parts.
  58679. *
  58680. * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B
  58681. * As the "first-match-wins" algorithm is identical to the "greedy"
  58682. * disambiguation method used by POSIX regular expressions, it is natural and
  58683. * commonplace to use a regular expression for parsing the potential five
  58684. * components of a URI reference.
  58685. *
  58686. * The following line is the regular expression for breaking-down a
  58687. * well-formed URI reference into its components.
  58688. *
  58689. * <pre>
  58690. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  58691. * 12 3 4 5 6 7 8 9
  58692. * </pre>
  58693. *
  58694. * The numbers in the second line above are only to assist readability; they
  58695. * indicate the reference points for each subexpression (i.e., each paired
  58696. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  58697. * For example, matching the above expression to
  58698. * <pre>
  58699. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  58700. * </pre>
  58701. * results in the following subexpression matches:
  58702. * <pre>
  58703. * $1 = http:
  58704. * $2 = http
  58705. * $3 = //www.ics.uci.edu
  58706. * $4 = www.ics.uci.edu
  58707. * $5 = /pub/ietf/uri/
  58708. * $6 = <undefined>
  58709. * $7 = <undefined>
  58710. * $8 = #Related
  58711. * $9 = Related
  58712. * </pre>
  58713. * where <undefined> indicates that the component is not present, as is the
  58714. * case for the query component in the above example. Therefore, we can
  58715. * determine the value of the five components as
  58716. * <pre>
  58717. * scheme = $2
  58718. * authority = $4
  58719. * path = $5
  58720. * query = $7
  58721. * fragment = $9
  58722. * </pre>
  58723. *
  58724. * The regular expression has been modified slightly to expose the
  58725. * userInfo, domain, and port separately from the authority.
  58726. * The modified version yields
  58727. * <pre>
  58728. * $1 = http scheme
  58729. * $2 = <undefined> userInfo -\
  58730. * $3 = www.ics.uci.edu domain | authority
  58731. * $4 = <undefined> port -/
  58732. * $5 = /pub/ietf/uri/ path
  58733. * $6 = <undefined> query without ?
  58734. * $7 = Related fragment without #
  58735. * </pre>
  58736. * @type {!RegExp}
  58737. * @private
  58738. */
  58739. goog.uri.utils.splitRe_ = new RegExp(
  58740. '^' +
  58741. '(?:' +
  58742. '([^:/?#.]+)' + // scheme - ignore special characters
  58743. // used by other URL parts such as :,
  58744. // ?, /, #, and .
  58745. ':)?' +
  58746. '(?://' +
  58747. '(?:([^/?#]*)@)?' + // userInfo
  58748. '([^/#?]*?)' + // domain
  58749. '(?::([0-9]+))?' + // port
  58750. '(?=[/#?]|$)' + // authority-terminating character
  58751. ')?' +
  58752. '([^?#]+)?' + // path
  58753. '(?:\\?([^#]*))?' + // query
  58754. '(?:#(.*))?' + // fragment
  58755. '$');
  58756. /**
  58757. * The index of each URI component in the return value of goog.uri.utils.split.
  58758. * @enum {number}
  58759. */
  58760. goog.uri.utils.ComponentIndex = {
  58761. SCHEME: 1,
  58762. USER_INFO: 2,
  58763. DOMAIN: 3,
  58764. PORT: 4,
  58765. PATH: 5,
  58766. QUERY_DATA: 6,
  58767. FRAGMENT: 7
  58768. };
  58769. /**
  58770. * Splits a URI into its component parts.
  58771. *
  58772. * Each component can be accessed via the component indices; for example:
  58773. * <pre>
  58774. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  58775. * </pre>
  58776. *
  58777. * @param {string} uri The URI string to examine.
  58778. * @return {!Array<string|undefined>} Each component still URI-encoded.
  58779. * Each component that is present will contain the encoded value, whereas
  58780. * components that are not present will be undefined or empty, depending
  58781. * on the browser's regular expression implementation. Never null, since
  58782. * arbitrary strings may still look like path names.
  58783. */
  58784. goog.uri.utils.split = function(uri) {
  58785. // See @return comment -- never null.
  58786. return /** @type {!Array<string|undefined>} */ (
  58787. uri.match(goog.uri.utils.splitRe_));
  58788. };
  58789. /**
  58790. * @param {?string} uri A possibly null string.
  58791. * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986
  58792. * reserved characters will not be removed.
  58793. * @return {?string} The string URI-decoded, or null if uri is null.
  58794. * @private
  58795. */
  58796. goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {
  58797. if (!uri) {
  58798. return uri;
  58799. }
  58800. return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);
  58801. };
  58802. /**
  58803. * Gets a URI component by index.
  58804. *
  58805. * It is preferred to use the getPathEncoded() variety of functions ahead,
  58806. * since they are more readable.
  58807. *
  58808. * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.
  58809. * @param {string} uri The URI to examine.
  58810. * @return {?string} The still-encoded component, or null if the component
  58811. * is not present.
  58812. * @private
  58813. */
  58814. goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {
  58815. // Convert undefined, null, and empty string into null.
  58816. return goog.uri.utils.split(uri)[componentIndex] || null;
  58817. };
  58818. /**
  58819. * @param {string} uri The URI to examine.
  58820. * @return {?string} The protocol or scheme, or null if none. Does not
  58821. * include trailing colons or slashes.
  58822. */
  58823. goog.uri.utils.getScheme = function(uri) {
  58824. return goog.uri.utils.getComponentByIndex_(
  58825. goog.uri.utils.ComponentIndex.SCHEME, uri);
  58826. };
  58827. /**
  58828. * Gets the effective scheme for the URL. If the URL is relative then the
  58829. * scheme is derived from the page's location.
  58830. * @param {string} uri The URI to examine.
  58831. * @return {string} The protocol or scheme, always lower case.
  58832. */
  58833. goog.uri.utils.getEffectiveScheme = function(uri) {
  58834. var scheme = goog.uri.utils.getScheme(uri);
  58835. if (!scheme && goog.global.self && goog.global.self.location) {
  58836. var protocol = goog.global.self.location.protocol;
  58837. scheme = protocol.substr(0, protocol.length - 1);
  58838. }
  58839. // NOTE: When called from a web worker in Firefox 3.5, location maybe null.
  58840. // All other browsers with web workers support self.location from the worker.
  58841. return scheme ? scheme.toLowerCase() : '';
  58842. };
  58843. /**
  58844. * @param {string} uri The URI to examine.
  58845. * @return {?string} The user name still encoded, or null if none.
  58846. */
  58847. goog.uri.utils.getUserInfoEncoded = function(uri) {
  58848. return goog.uri.utils.getComponentByIndex_(
  58849. goog.uri.utils.ComponentIndex.USER_INFO, uri);
  58850. };
  58851. /**
  58852. * @param {string} uri The URI to examine.
  58853. * @return {?string} The decoded user info, or null if none.
  58854. */
  58855. goog.uri.utils.getUserInfo = function(uri) {
  58856. return goog.uri.utils.decodeIfPossible_(
  58857. goog.uri.utils.getUserInfoEncoded(uri));
  58858. };
  58859. /**
  58860. * @param {string} uri The URI to examine.
  58861. * @return {?string} The domain name still encoded, or null if none.
  58862. */
  58863. goog.uri.utils.getDomainEncoded = function(uri) {
  58864. return goog.uri.utils.getComponentByIndex_(
  58865. goog.uri.utils.ComponentIndex.DOMAIN, uri);
  58866. };
  58867. /**
  58868. * @param {string} uri The URI to examine.
  58869. * @return {?string} The decoded domain, or null if none.
  58870. */
  58871. goog.uri.utils.getDomain = function(uri) {
  58872. return goog.uri.utils.decodeIfPossible_(
  58873. goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);
  58874. };
  58875. /**
  58876. * @param {string} uri The URI to examine.
  58877. * @return {?number} The port number, or null if none.
  58878. */
  58879. goog.uri.utils.getPort = function(uri) {
  58880. // Coerce to a number. If the result of getComponentByIndex_ is null or
  58881. // non-numeric, the number coersion yields NaN. This will then return
  58882. // null for all non-numeric cases (though also zero, which isn't a relevant
  58883. // port number).
  58884. return Number(goog.uri.utils.getComponentByIndex_(
  58885. goog.uri.utils.ComponentIndex.PORT, uri)) || null;
  58886. };
  58887. /**
  58888. * @param {string} uri The URI to examine.
  58889. * @return {?string} The path still encoded, or null if none. Includes the
  58890. * leading slash, if any.
  58891. */
  58892. goog.uri.utils.getPathEncoded = function(uri) {
  58893. return goog.uri.utils.getComponentByIndex_(
  58894. goog.uri.utils.ComponentIndex.PATH, uri);
  58895. };
  58896. /**
  58897. * @param {string} uri The URI to examine.
  58898. * @return {?string} The decoded path, or null if none. Includes the leading
  58899. * slash, if any.
  58900. */
  58901. goog.uri.utils.getPath = function(uri) {
  58902. return goog.uri.utils.decodeIfPossible_(
  58903. goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);
  58904. };
  58905. /**
  58906. * @param {string} uri The URI to examine.
  58907. * @return {?string} The query data still encoded, or null if none. Does not
  58908. * include the question mark itself.
  58909. */
  58910. goog.uri.utils.getQueryData = function(uri) {
  58911. return goog.uri.utils.getComponentByIndex_(
  58912. goog.uri.utils.ComponentIndex.QUERY_DATA, uri);
  58913. };
  58914. /**
  58915. * @param {string} uri The URI to examine.
  58916. * @return {?string} The fragment identifier, or null if none. Does not
  58917. * include the hash mark itself.
  58918. */
  58919. goog.uri.utils.getFragmentEncoded = function(uri) {
  58920. // The hash mark may not appear in any other part of the URL.
  58921. var hashIndex = uri.indexOf('#');
  58922. return hashIndex < 0 ? null : uri.substr(hashIndex + 1);
  58923. };
  58924. /**
  58925. * @param {string} uri The URI to examine.
  58926. * @param {?string} fragment The encoded fragment identifier, or null if none.
  58927. * Does not include the hash mark itself.
  58928. * @return {string} The URI with the fragment set.
  58929. */
  58930. goog.uri.utils.setFragmentEncoded = function(uri, fragment) {
  58931. return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');
  58932. };
  58933. /**
  58934. * @param {string} uri The URI to examine.
  58935. * @return {?string} The decoded fragment identifier, or null if none. Does
  58936. * not include the hash mark.
  58937. */
  58938. goog.uri.utils.getFragment = function(uri) {
  58939. return goog.uri.utils.decodeIfPossible_(
  58940. goog.uri.utils.getFragmentEncoded(uri));
  58941. };
  58942. /**
  58943. * Extracts everything up to the port of the URI.
  58944. * @param {string} uri The URI string.
  58945. * @return {string} Everything up to and including the port.
  58946. */
  58947. goog.uri.utils.getHost = function(uri) {
  58948. var pieces = goog.uri.utils.split(uri);
  58949. return goog.uri.utils.buildFromEncodedParts(
  58950. pieces[goog.uri.utils.ComponentIndex.SCHEME],
  58951. pieces[goog.uri.utils.ComponentIndex.USER_INFO],
  58952. pieces[goog.uri.utils.ComponentIndex.DOMAIN],
  58953. pieces[goog.uri.utils.ComponentIndex.PORT]);
  58954. };
  58955. /**
  58956. * Extracts the path of the URL and everything after.
  58957. * @param {string} uri The URI string.
  58958. * @return {string} The URI, starting at the path and including the query
  58959. * parameters and fragment identifier.
  58960. */
  58961. goog.uri.utils.getPathAndAfter = function(uri) {
  58962. var pieces = goog.uri.utils.split(uri);
  58963. return goog.uri.utils.buildFromEncodedParts(null, null, null, null,
  58964. pieces[goog.uri.utils.ComponentIndex.PATH],
  58965. pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],
  58966. pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);
  58967. };
  58968. /**
  58969. * Gets the URI with the fragment identifier removed.
  58970. * @param {string} uri The URI to examine.
  58971. * @return {string} Everything preceding the hash mark.
  58972. */
  58973. goog.uri.utils.removeFragment = function(uri) {
  58974. // The hash mark may not appear in any other part of the URL.
  58975. var hashIndex = uri.indexOf('#');
  58976. return hashIndex < 0 ? uri : uri.substr(0, hashIndex);
  58977. };
  58978. /**
  58979. * Ensures that two URI's have the exact same domain, scheme, and port.
  58980. *
  58981. * Unlike the version in goog.Uri, this checks protocol, and therefore is
  58982. * suitable for checking against the browser's same-origin policy.
  58983. *
  58984. * @param {string} uri1 The first URI.
  58985. * @param {string} uri2 The second URI.
  58986. * @return {boolean} Whether they have the same scheme, domain and port.
  58987. */
  58988. goog.uri.utils.haveSameDomain = function(uri1, uri2) {
  58989. var pieces1 = goog.uri.utils.split(uri1);
  58990. var pieces2 = goog.uri.utils.split(uri2);
  58991. return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
  58992. pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
  58993. pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==
  58994. pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&
  58995. pieces1[goog.uri.utils.ComponentIndex.PORT] ==
  58996. pieces2[goog.uri.utils.ComponentIndex.PORT];
  58997. };
  58998. /**
  58999. * Asserts that there are no fragment or query identifiers, only in uncompiled
  59000. * mode.
  59001. * @param {string} uri The URI to examine.
  59002. * @private
  59003. */
  59004. goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {
  59005. // NOTE: would use goog.asserts here, but jscompiler doesn't know that
  59006. // indexOf has no side effects.
  59007. if (goog.DEBUG && (uri.indexOf('#') >= 0 || uri.indexOf('?') >= 0)) {
  59008. throw Error('goog.uri.utils: Fragment or query identifiers are not ' +
  59009. 'supported: [' + uri + ']');
  59010. }
  59011. };
  59012. /**
  59013. * Supported query parameter values by the parameter serializing utilities.
  59014. *
  59015. * If a value is null or undefined, the key-value pair is skipped, as an easy
  59016. * way to omit parameters conditionally. Non-array parameters are converted
  59017. * to a string and URI encoded. Array values are expanded into multiple
  59018. * &key=value pairs, with each element stringized and URI-encoded.
  59019. *
  59020. * @typedef {*}
  59021. */
  59022. goog.uri.utils.QueryValue;
  59023. /**
  59024. * An array representing a set of query parameters with alternating keys
  59025. * and values.
  59026. *
  59027. * Keys are assumed to be URI encoded already and live at even indices. See
  59028. * goog.uri.utils.QueryValue for details on how parameter values are encoded.
  59029. *
  59030. * Example:
  59031. * <pre>
  59032. * var data = [
  59033. * // Simple param: ?name=BobBarker
  59034. * 'name', 'BobBarker',
  59035. * // Conditional param -- may be omitted entirely.
  59036. * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,
  59037. * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null
  59038. * 'house', ['LosAngeles', 'NewYork', null]
  59039. * ];
  59040. * </pre>
  59041. *
  59042. * @typedef {!Array<string|goog.uri.utils.QueryValue>}
  59043. */
  59044. goog.uri.utils.QueryArray;
  59045. /**
  59046. * Parses encoded query parameters and calls callback function for every
  59047. * parameter found in the string.
  59048. *
  59049. * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an
  59050. * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means
  59051. * that “…&=&…” and “…&&…” will result in an empty key and value.
  59052. *
  59053. * @param {string} encodedQuery Encoded query string excluding question mark at
  59054. * the beginning.
  59055. * @param {function(string, string)} callback Function called for every
  59056. * parameter found in query string. The first argument (name) will not be
  59057. * urldecoded (so the function is consistent with buildQueryData), but the
  59058. * second will. If the parameter has no value (i.e. “=” was not present)
  59059. * the second argument (value) will be an empty string.
  59060. */
  59061. goog.uri.utils.parseQueryData = function(encodedQuery, callback) {
  59062. if (!encodedQuery) {
  59063. return;
  59064. }
  59065. var pairs = encodedQuery.split('&');
  59066. for (var i = 0; i < pairs.length; i++) {
  59067. var indexOfEquals = pairs[i].indexOf('=');
  59068. var name = null;
  59069. var value = null;
  59070. if (indexOfEquals >= 0) {
  59071. name = pairs[i].substring(0, indexOfEquals);
  59072. value = pairs[i].substring(indexOfEquals + 1);
  59073. } else {
  59074. name = pairs[i];
  59075. }
  59076. callback(name, value ? goog.string.urlDecode(value) : '');
  59077. }
  59078. };
  59079. /**
  59080. * Appends a URI and query data in a string buffer with special preconditions.
  59081. *
  59082. * Internal implementation utility, performing very few object allocations.
  59083. *
  59084. * @param {!Array<string|undefined>} buffer A string buffer. The first element
  59085. * must be the base URI, and may have a fragment identifier. If the array
  59086. * contains more than one element, the second element must be an ampersand,
  59087. * and may be overwritten, depending on the base URI. Undefined elements
  59088. * are treated as empty-string.
  59089. * @return {string} The concatenated URI and query data.
  59090. * @private
  59091. */
  59092. goog.uri.utils.appendQueryData_ = function(buffer) {
  59093. if (buffer[1]) {
  59094. // At least one query parameter was added. We need to check the
  59095. // punctuation mark, which is currently an ampersand, and also make sure
  59096. // there aren't any interfering fragment identifiers.
  59097. var baseUri = /** @type {string} */ (buffer[0]);
  59098. var hashIndex = baseUri.indexOf('#');
  59099. if (hashIndex >= 0) {
  59100. // Move the fragment off the base part of the URI into the end.
  59101. buffer.push(baseUri.substr(hashIndex));
  59102. buffer[0] = baseUri = baseUri.substr(0, hashIndex);
  59103. }
  59104. var questionIndex = baseUri.indexOf('?');
  59105. if (questionIndex < 0) {
  59106. // No question mark, so we need a question mark instead of an ampersand.
  59107. buffer[1] = '?';
  59108. } else if (questionIndex == baseUri.length - 1) {
  59109. // Question mark is the very last character of the existing URI, so don't
  59110. // append an additional delimiter.
  59111. buffer[1] = undefined;
  59112. }
  59113. }
  59114. return buffer.join('');
  59115. };
  59116. /**
  59117. * Appends key=value pairs to an array, supporting multi-valued objects.
  59118. * @param {string} key The key prefix.
  59119. * @param {goog.uri.utils.QueryValue} value The value to serialize.
  59120. * @param {!Array<string>} pairs The array to which the 'key=value' strings
  59121. * should be appended.
  59122. * @private
  59123. */
  59124. goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {
  59125. if (goog.isArray(value)) {
  59126. // Convince the compiler it's an array.
  59127. goog.asserts.assertArray(value);
  59128. for (var j = 0; j < value.length; j++) {
  59129. // Convert to string explicitly, to short circuit the null and array
  59130. // logic in this function -- this ensures that null and undefined get
  59131. // written as literal 'null' and 'undefined', and arrays don't get
  59132. // expanded out but instead encoded in the default way.
  59133. goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);
  59134. }
  59135. } else if (value != null) {
  59136. // Skip a top-level null or undefined entirely.
  59137. pairs.push('&', key,
  59138. // Check for empty string. Zero gets encoded into the url as literal
  59139. // strings. For empty string, skip the equal sign, to be consistent
  59140. // with UriBuilder.java.
  59141. value === '' ? '' : '=',
  59142. goog.string.urlEncode(value));
  59143. }
  59144. };
  59145. /**
  59146. * Builds a buffer of query data from a sequence of alternating keys and values.
  59147. *
  59148. * @param {!Array<string|undefined>} buffer A string buffer to append to. The
  59149. * first element appended will be an '&', and may be replaced by the caller.
  59150. * @param {!goog.uri.utils.QueryArray|!Arguments} keysAndValues An array with
  59151. * alternating keys and values -- see the typedef.
  59152. * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.
  59153. * @return {!Array<string|undefined>} The buffer argument.
  59154. * @private
  59155. */
  59156. goog.uri.utils.buildQueryDataBuffer_ = function(
  59157. buffer, keysAndValues, opt_startIndex) {
  59158. goog.asserts.assert(Math.max(keysAndValues.length - (opt_startIndex || 0),
  59159. 0) % 2 == 0, 'goog.uri.utils: Key/value lists must be even in length.');
  59160. for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {
  59161. goog.uri.utils.appendKeyValuePairs_(
  59162. keysAndValues[i], keysAndValues[i + 1], buffer);
  59163. }
  59164. return buffer;
  59165. };
  59166. /**
  59167. * Builds a query data string from a sequence of alternating keys and values.
  59168. * Currently generates "&key&" for empty args.
  59169. *
  59170. * @param {goog.uri.utils.QueryArray} keysAndValues Alternating keys and
  59171. * values. See the typedef.
  59172. * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.
  59173. * @return {string} The encoded query string, in the form 'a=1&b=2'.
  59174. */
  59175. goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {
  59176. var buffer = goog.uri.utils.buildQueryDataBuffer_(
  59177. [], keysAndValues, opt_startIndex);
  59178. buffer[0] = ''; // Remove the leading ampersand.
  59179. return buffer.join('');
  59180. };
  59181. /**
  59182. * Builds a buffer of query data from a map.
  59183. *
  59184. * @param {!Array<string|undefined>} buffer A string buffer to append to. The
  59185. * first element appended will be an '&', and may be replaced by the caller.
  59186. * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys
  59187. * are URI-encoded parameter keys, and the values conform to the contract
  59188. * specified in the goog.uri.utils.QueryValue typedef.
  59189. * @return {!Array<string|undefined>} The buffer argument.
  59190. * @private
  59191. */
  59192. goog.uri.utils.buildQueryDataBufferFromMap_ = function(buffer, map) {
  59193. for (var key in map) {
  59194. goog.uri.utils.appendKeyValuePairs_(key, map[key], buffer);
  59195. }
  59196. return buffer;
  59197. };
  59198. /**
  59199. * Builds a query data string from a map.
  59200. * Currently generates "&key&" for empty args.
  59201. *
  59202. * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys
  59203. * are URI-encoded parameter keys, and the values are arbitrary types
  59204. * or arrays. Keys with a null value are dropped.
  59205. * @return {string} The encoded query string, in the form 'a=1&b=2'.
  59206. */
  59207. goog.uri.utils.buildQueryDataFromMap = function(map) {
  59208. var buffer = goog.uri.utils.buildQueryDataBufferFromMap_([], map);
  59209. buffer[0] = '';
  59210. return buffer.join('');
  59211. };
  59212. /**
  59213. * Appends URI parameters to an existing URI.
  59214. *
  59215. * The variable arguments may contain alternating keys and values. Keys are
  59216. * assumed to be already URI encoded. The values should not be URI-encoded,
  59217. * and will instead be encoded by this function.
  59218. * <pre>
  59219. * appendParams('http://www.foo.com?existing=true',
  59220. * 'key1', 'value1',
  59221. * 'key2', 'value?willBeEncoded',
  59222. * 'key3', ['valueA', 'valueB', 'valueC'],
  59223. * 'key4', null);
  59224. * result: 'http://www.foo.com?existing=true&' +
  59225. * 'key1=value1&' +
  59226. * 'key2=value%3FwillBeEncoded&' +
  59227. * 'key3=valueA&key3=valueB&key3=valueC'
  59228. * </pre>
  59229. *
  59230. * A single call to this function will not exhibit quadratic behavior in IE,
  59231. * whereas multiple repeated calls may, although the effect is limited by
  59232. * fact that URL's generally can't exceed 2kb.
  59233. *
  59234. * @param {string} uri The original URI, which may already have query data.
  59235. * @param {...(goog.uri.utils.QueryArray|string|goog.uri.utils.QueryValue)} var_args
  59236. * An array or argument list conforming to goog.uri.utils.QueryArray.
  59237. * @return {string} The URI with all query parameters added.
  59238. */
  59239. goog.uri.utils.appendParams = function(uri, var_args) {
  59240. return goog.uri.utils.appendQueryData_(
  59241. arguments.length == 2 ?
  59242. goog.uri.utils.buildQueryDataBuffer_([uri], arguments[1], 0) :
  59243. goog.uri.utils.buildQueryDataBuffer_([uri], arguments, 1));
  59244. };
  59245. /**
  59246. * Appends query parameters from a map.
  59247. *
  59248. * @param {string} uri The original URI, which may already have query data.
  59249. * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are
  59250. * URI-encoded parameter keys, and the values are arbitrary types or arrays.
  59251. * Keys with a null value are dropped.
  59252. * @return {string} The new parameters.
  59253. */
  59254. goog.uri.utils.appendParamsFromMap = function(uri, map) {
  59255. return goog.uri.utils.appendQueryData_(
  59256. goog.uri.utils.buildQueryDataBufferFromMap_([uri], map));
  59257. };
  59258. /**
  59259. * Appends a single URI parameter.
  59260. *
  59261. * Repeated calls to this can exhibit quadratic behavior in IE6 due to the
  59262. * way string append works, though it should be limited given the 2kb limit.
  59263. *
  59264. * @param {string} uri The original URI, which may already have query data.
  59265. * @param {string} key The key, which must already be URI encoded.
  59266. * @param {*=} opt_value The value, which will be stringized and encoded
  59267. * (assumed not already to be encoded). If omitted, undefined, or null, the
  59268. * key will be added as a valueless parameter.
  59269. * @return {string} The URI with the query parameter added.
  59270. */
  59271. goog.uri.utils.appendParam = function(uri, key, opt_value) {
  59272. var paramArr = [uri, '&', key];
  59273. if (goog.isDefAndNotNull(opt_value)) {
  59274. paramArr.push('=', goog.string.urlEncode(opt_value));
  59275. }
  59276. return goog.uri.utils.appendQueryData_(paramArr);
  59277. };
  59278. /**
  59279. * Finds the next instance of a query parameter with the specified name.
  59280. *
  59281. * Does not instantiate any objects.
  59282. *
  59283. * @param {string} uri The URI to search. May contain a fragment identifier
  59284. * if opt_hashIndex is specified.
  59285. * @param {number} startIndex The index to begin searching for the key at. A
  59286. * match may be found even if this is one character after the ampersand.
  59287. * @param {string} keyEncoded The URI-encoded key.
  59288. * @param {number} hashOrEndIndex Index to stop looking at. If a hash
  59289. * mark is present, it should be its index, otherwise it should be the
  59290. * length of the string.
  59291. * @return {number} The position of the first character in the key's name,
  59292. * immediately after either a question mark or a dot.
  59293. * @private
  59294. */
  59295. goog.uri.utils.findParam_ = function(
  59296. uri, startIndex, keyEncoded, hashOrEndIndex) {
  59297. var index = startIndex;
  59298. var keyLength = keyEncoded.length;
  59299. // Search for the key itself and post-filter for surronuding punctuation,
  59300. // rather than expensively building a regexp.
  59301. while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&
  59302. index < hashOrEndIndex) {
  59303. var precedingChar = uri.charCodeAt(index - 1);
  59304. // Ensure that the preceding character is '&' or '?'.
  59305. if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||
  59306. precedingChar == goog.uri.utils.CharCode_.QUESTION) {
  59307. // Ensure the following character is '&', '=', '#', or NaN
  59308. // (end of string).
  59309. var followingChar = uri.charCodeAt(index + keyLength);
  59310. if (!followingChar ||
  59311. followingChar == goog.uri.utils.CharCode_.EQUAL ||
  59312. followingChar == goog.uri.utils.CharCode_.AMPERSAND ||
  59313. followingChar == goog.uri.utils.CharCode_.HASH) {
  59314. return index;
  59315. }
  59316. }
  59317. index += keyLength + 1;
  59318. }
  59319. return -1;
  59320. };
  59321. /**
  59322. * Regular expression for finding a hash mark or end of string.
  59323. * @type {RegExp}
  59324. * @private
  59325. */
  59326. goog.uri.utils.hashOrEndRe_ = /#|$/;
  59327. /**
  59328. * Determines if the URI contains a specific key.
  59329. *
  59330. * Performs no object instantiations.
  59331. *
  59332. * @param {string} uri The URI to process. May contain a fragment
  59333. * identifier.
  59334. * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
  59335. * @return {boolean} Whether the key is present.
  59336. */
  59337. goog.uri.utils.hasParam = function(uri, keyEncoded) {
  59338. return goog.uri.utils.findParam_(uri, 0, keyEncoded,
  59339. uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;
  59340. };
  59341. /**
  59342. * Gets the first value of a query parameter.
  59343. * @param {string} uri The URI to process. May contain a fragment.
  59344. * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
  59345. * @return {?string} The first value of the parameter (URI-decoded), or null
  59346. * if the parameter is not found.
  59347. */
  59348. goog.uri.utils.getParamValue = function(uri, keyEncoded) {
  59349. var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
  59350. var foundIndex = goog.uri.utils.findParam_(
  59351. uri, 0, keyEncoded, hashOrEndIndex);
  59352. if (foundIndex < 0) {
  59353. return null;
  59354. } else {
  59355. var endPosition = uri.indexOf('&', foundIndex);
  59356. if (endPosition < 0 || endPosition > hashOrEndIndex) {
  59357. endPosition = hashOrEndIndex;
  59358. }
  59359. // Progress forth to the end of the "key=" or "key&" substring.
  59360. foundIndex += keyEncoded.length + 1;
  59361. // Use substr, because it (unlike substring) will return empty string
  59362. // if foundIndex > endPosition.
  59363. return goog.string.urlDecode(
  59364. uri.substr(foundIndex, endPosition - foundIndex));
  59365. }
  59366. };
  59367. /**
  59368. * Gets all values of a query parameter.
  59369. * @param {string} uri The URI to process. May contain a fragment.
  59370. * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
  59371. * @return {!Array<string>} All URI-decoded values with the given key.
  59372. * If the key is not found, this will have length 0, but never be null.
  59373. */
  59374. goog.uri.utils.getParamValues = function(uri, keyEncoded) {
  59375. var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
  59376. var position = 0;
  59377. var foundIndex;
  59378. var result = [];
  59379. while ((foundIndex = goog.uri.utils.findParam_(
  59380. uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
  59381. // Find where this parameter ends, either the '&' or the end of the
  59382. // query parameters.
  59383. position = uri.indexOf('&', foundIndex);
  59384. if (position < 0 || position > hashOrEndIndex) {
  59385. position = hashOrEndIndex;
  59386. }
  59387. // Progress forth to the end of the "key=" or "key&" substring.
  59388. foundIndex += keyEncoded.length + 1;
  59389. // Use substr, because it (unlike substring) will return empty string
  59390. // if foundIndex > position.
  59391. result.push(goog.string.urlDecode(uri.substr(
  59392. foundIndex, position - foundIndex)));
  59393. }
  59394. return result;
  59395. };
  59396. /**
  59397. * Regexp to find trailing question marks and ampersands.
  59398. * @type {RegExp}
  59399. * @private
  59400. */
  59401. goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;
  59402. /**
  59403. * Removes all instances of a query parameter.
  59404. * @param {string} uri The URI to process. Must not contain a fragment.
  59405. * @param {string} keyEncoded The URI-encoded key.
  59406. * @return {string} The URI with all instances of the parameter removed.
  59407. */
  59408. goog.uri.utils.removeParam = function(uri, keyEncoded) {
  59409. var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
  59410. var position = 0;
  59411. var foundIndex;
  59412. var buffer = [];
  59413. // Look for a query parameter.
  59414. while ((foundIndex = goog.uri.utils.findParam_(
  59415. uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
  59416. // Get the portion of the query string up to, but not including, the ?
  59417. // or & starting the parameter.
  59418. buffer.push(uri.substring(position, foundIndex));
  59419. // Progress to immediately after the '&'. If not found, go to the end.
  59420. // Avoid including the hash mark.
  59421. position = Math.min((uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex,
  59422. hashOrEndIndex);
  59423. }
  59424. // Append everything that is remaining.
  59425. buffer.push(uri.substr(position));
  59426. // Join the buffer, and remove trailing punctuation that remains.
  59427. return buffer.join('').replace(
  59428. goog.uri.utils.trailingQueryPunctuationRe_, '$1');
  59429. };
  59430. /**
  59431. * Replaces all existing definitions of a parameter with a single definition.
  59432. *
  59433. * Repeated calls to this can exhibit quadratic behavior due to the need to
  59434. * find existing instances and reconstruct the string, though it should be
  59435. * limited given the 2kb limit. Consider using appendParams to append multiple
  59436. * parameters in bulk.
  59437. *
  59438. * @param {string} uri The original URI, which may already have query data.
  59439. * @param {string} keyEncoded The key, which must already be URI encoded.
  59440. * @param {*} value The value, which will be stringized and encoded (assumed
  59441. * not already to be encoded).
  59442. * @return {string} The URI with the query parameter added.
  59443. */
  59444. goog.uri.utils.setParam = function(uri, keyEncoded, value) {
  59445. return goog.uri.utils.appendParam(
  59446. goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);
  59447. };
  59448. /**
  59449. * Generates a URI path using a given URI and a path with checks to
  59450. * prevent consecutive "//". The baseUri passed in must not contain
  59451. * query or fragment identifiers. The path to append may not contain query or
  59452. * fragment identifiers.
  59453. *
  59454. * @param {string} baseUri URI to use as the base.
  59455. * @param {string} path Path to append.
  59456. * @return {string} Updated URI.
  59457. */
  59458. goog.uri.utils.appendPath = function(baseUri, path) {
  59459. goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);
  59460. // Remove any trailing '/'
  59461. if (goog.string.endsWith(baseUri, '/')) {
  59462. baseUri = baseUri.substr(0, baseUri.length - 1);
  59463. }
  59464. // Remove any leading '/'
  59465. if (goog.string.startsWith(path, '/')) {
  59466. path = path.substr(1);
  59467. }
  59468. return goog.string.buildString(baseUri, '/', path);
  59469. };
  59470. /**
  59471. * Replaces the path.
  59472. * @param {string} uri URI to use as the base.
  59473. * @param {string} path New path.
  59474. * @return {string} Updated URI.
  59475. */
  59476. goog.uri.utils.setPath = function(uri, path) {
  59477. // Add any missing '/'.
  59478. if (!goog.string.startsWith(path, '/')) {
  59479. path = '/' + path;
  59480. }
  59481. var parts = goog.uri.utils.split(uri);
  59482. return goog.uri.utils.buildFromEncodedParts(
  59483. parts[goog.uri.utils.ComponentIndex.SCHEME],
  59484. parts[goog.uri.utils.ComponentIndex.USER_INFO],
  59485. parts[goog.uri.utils.ComponentIndex.DOMAIN],
  59486. parts[goog.uri.utils.ComponentIndex.PORT],
  59487. path,
  59488. parts[goog.uri.utils.ComponentIndex.QUERY_DATA],
  59489. parts[goog.uri.utils.ComponentIndex.FRAGMENT]);
  59490. };
  59491. /**
  59492. * Standard supported query parameters.
  59493. * @enum {string}
  59494. */
  59495. goog.uri.utils.StandardQueryParam = {
  59496. /** Unused parameter for unique-ifying. */
  59497. RANDOM: 'zx'
  59498. };
  59499. /**
  59500. * Sets the zx parameter of a URI to a random value.
  59501. * @param {string} uri Any URI.
  59502. * @return {string} That URI with the "zx" parameter added or replaced to
  59503. * contain a random string.
  59504. */
  59505. goog.uri.utils.makeUnique = function(uri) {
  59506. return goog.uri.utils.setParam(uri,
  59507. goog.uri.utils.StandardQueryParam.RANDOM, goog.string.getRandomString());
  59508. };
  59509. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  59510. //
  59511. // Licensed under the Apache License, Version 2.0 (the "License");
  59512. // you may not use this file except in compliance with the License.
  59513. // You may obtain a copy of the License at
  59514. //
  59515. // http://www.apache.org/licenses/LICENSE-2.0
  59516. //
  59517. // Unless required by applicable law or agreed to in writing, software
  59518. // distributed under the License is distributed on an "AS-IS" BASIS,
  59519. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  59520. // See the License for the specific language governing permissions and
  59521. // limitations under the License.
  59522. /**
  59523. * @fileoverview Wrapper class for handling XmlHttpRequests.
  59524. *
  59525. * One off requests can be sent through goog.net.XhrIo.send() or an
  59526. * instance can be created to send multiple requests. Each request uses its
  59527. * own XmlHttpRequest object and handles clearing of the event callback to
  59528. * ensure no leaks.
  59529. *
  59530. * XhrIo is event based, it dispatches events on success, failure, finishing,
  59531. * ready-state change, or progress.
  59532. *
  59533. * The ready-state or timeout event fires first, followed by
  59534. * a generic completed event. Then the abort, error, or success event
  59535. * is fired as appropriate. Progress events are fired as they are
  59536. * received. Lastly, the ready event will fire to indicate that the
  59537. * object may be used to make another request.
  59538. *
  59539. * The error event may also be called before completed and
  59540. * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
  59541. *
  59542. * This class does not support multiple requests, queuing, or prioritization.
  59543. *
  59544. * When progress events are supported by the browser, and progress is
  59545. * enabled via .setProgressEventsEnabled(true), the
  59546. * goog.net.EventType.PROGRESS event will be the re-dispatched browser
  59547. * progress event.
  59548. *
  59549. * Tested = IE6, FF1.5, Safari, Opera 8.5
  59550. *
  59551. * TODO(user): Error cases aren't playing nicely in Safari.
  59552. *
  59553. */
  59554. goog.provide('goog.net.XhrIo');
  59555. goog.provide('goog.net.XhrIo.ResponseType');
  59556. goog.require('goog.Timer');
  59557. goog.require('goog.array');
  59558. goog.require('goog.asserts');
  59559. goog.require('goog.debug.entryPointRegistry');
  59560. goog.require('goog.events.EventTarget');
  59561. goog.require('goog.json');
  59562. goog.require('goog.log');
  59563. goog.require('goog.net.ErrorCode');
  59564. goog.require('goog.net.EventType');
  59565. goog.require('goog.net.HttpStatus');
  59566. goog.require('goog.net.XmlHttp');
  59567. goog.require('goog.object');
  59568. goog.require('goog.string');
  59569. goog.require('goog.structs');
  59570. goog.require('goog.structs.Map');
  59571. goog.require('goog.uri.utils');
  59572. goog.require('goog.userAgent');
  59573. goog.forwardDeclare('goog.Uri');
  59574. /**
  59575. * Basic class for handling XMLHttpRequests.
  59576. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
  59577. * creating XMLHttpRequest objects.
  59578. * @constructor
  59579. * @extends {goog.events.EventTarget}
  59580. */
  59581. goog.net.XhrIo = function(opt_xmlHttpFactory) {
  59582. goog.net.XhrIo.base(this, 'constructor');
  59583. /**
  59584. * Map of default headers to add to every request, use:
  59585. * XhrIo.headers.set(name, value)
  59586. * @type {!goog.structs.Map}
  59587. */
  59588. this.headers = new goog.structs.Map();
  59589. /**
  59590. * Optional XmlHttpFactory
  59591. * @private {goog.net.XmlHttpFactory}
  59592. */
  59593. this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
  59594. /**
  59595. * Whether XMLHttpRequest is active. A request is active from the time send()
  59596. * is called until onReadyStateChange() is complete, or error() or abort()
  59597. * is called.
  59598. * @private {boolean}
  59599. */
  59600. this.active_ = false;
  59601. /**
  59602. * The XMLHttpRequest object that is being used for the transfer.
  59603. * @private {?goog.net.XhrLike.OrNative}
  59604. */
  59605. this.xhr_ = null;
  59606. /**
  59607. * The options to use with the current XMLHttpRequest object.
  59608. * @private {Object}
  59609. */
  59610. this.xhrOptions_ = null;
  59611. /**
  59612. * Last URL that was requested.
  59613. * @private {string|goog.Uri}
  59614. */
  59615. this.lastUri_ = '';
  59616. /**
  59617. * Method for the last request.
  59618. * @private {string}
  59619. */
  59620. this.lastMethod_ = '';
  59621. /**
  59622. * Last error code.
  59623. * @private {!goog.net.ErrorCode}
  59624. */
  59625. this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
  59626. /**
  59627. * Last error message.
  59628. * @private {Error|string}
  59629. */
  59630. this.lastError_ = '';
  59631. /**
  59632. * Used to ensure that we don't dispatch an multiple ERROR events. This can
  59633. * happen in IE when it does a synchronous load and one error is handled in
  59634. * the ready statte change and one is handled due to send() throwing an
  59635. * exception.
  59636. * @private {boolean}
  59637. */
  59638. this.errorDispatched_ = false;
  59639. /**
  59640. * Used to make sure we don't fire the complete event from inside a send call.
  59641. * @private {boolean}
  59642. */
  59643. this.inSend_ = false;
  59644. /**
  59645. * Used in determining if a call to {@link #onReadyStateChange_} is from
  59646. * within a call to this.xhr_.open.
  59647. * @private {boolean}
  59648. */
  59649. this.inOpen_ = false;
  59650. /**
  59651. * Used in determining if a call to {@link #onReadyStateChange_} is from
  59652. * within a call to this.xhr_.abort.
  59653. * @private {boolean}
  59654. */
  59655. this.inAbort_ = false;
  59656. /**
  59657. * Number of milliseconds after which an incomplete request will be aborted
  59658. * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
  59659. * is set.
  59660. * @private {number}
  59661. */
  59662. this.timeoutInterval_ = 0;
  59663. /**
  59664. * Timer to track request timeout.
  59665. * @private {?number}
  59666. */
  59667. this.timeoutId_ = null;
  59668. /**
  59669. * The requested type for the response. The empty string means use the default
  59670. * XHR behavior.
  59671. * @private {goog.net.XhrIo.ResponseType}
  59672. */
  59673. this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT;
  59674. /**
  59675. * Whether a "credentialed" request is to be sent (one that is aware of
  59676. * cookies and authentication). This is applicable only for cross-domain
  59677. * requests and more recent browsers that support this part of the HTTP Access
  59678. * Control standard.
  59679. *
  59680. * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
  59681. *
  59682. * @private {boolean}
  59683. */
  59684. this.withCredentials_ = false;
  59685. /**
  59686. * Whether progress events are enabled for this request. This is
  59687. * disabled by default because setting a progress event handler
  59688. * causes pre-flight OPTIONS requests to be sent for CORS requests,
  59689. * even in cases where a pre-flight request would not otherwise be
  59690. * sent.
  59691. *
  59692. * @see http://xhr.spec.whatwg.org/#security-considerations
  59693. *
  59694. * Note that this can cause problems for Firefox 22 and below, as an
  59695. * older "LSProgressEvent" will be dispatched by the browser. That
  59696. * progress event is no longer supported, and can lead to failures,
  59697. * including throwing exceptions.
  59698. *
  59699. * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
  59700. * @see b/23469793
  59701. *
  59702. * @private {boolean}
  59703. */
  59704. this.progressEventsEnabled_ = false;
  59705. /**
  59706. * True if we can use XMLHttpRequest's timeout directly.
  59707. * @private {boolean}
  59708. */
  59709. this.useXhr2Timeout_ = false;
  59710. };
  59711. goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
  59712. /**
  59713. * Response types that may be requested for XMLHttpRequests.
  59714. * @enum {string}
  59715. * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
  59716. */
  59717. goog.net.XhrIo.ResponseType = {
  59718. DEFAULT: '',
  59719. TEXT: 'text',
  59720. DOCUMENT: 'document',
  59721. // Not supported as of Chrome 10.0.612.1 dev
  59722. BLOB: 'blob',
  59723. ARRAY_BUFFER: 'arraybuffer'
  59724. };
  59725. /**
  59726. * A reference to the XhrIo logger
  59727. * @private {goog.debug.Logger}
  59728. * @const
  59729. */
  59730. goog.net.XhrIo.prototype.logger_ =
  59731. goog.log.getLogger('goog.net.XhrIo');
  59732. /**
  59733. * The Content-Type HTTP header name
  59734. * @type {string}
  59735. */
  59736. goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
  59737. /**
  59738. * The pattern matching the 'http' and 'https' URI schemes
  59739. * @type {!RegExp}
  59740. */
  59741. goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
  59742. /**
  59743. * The methods that typically come along with form data. We set different
  59744. * headers depending on whether the HTTP action is one of these.
  59745. */
  59746. goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
  59747. /**
  59748. * The Content-Type HTTP header value for a url-encoded form
  59749. * @type {string}
  59750. */
  59751. goog.net.XhrIo.FORM_CONTENT_TYPE =
  59752. 'application/x-www-form-urlencoded;charset=utf-8';
  59753. /**
  59754. * The XMLHttpRequest Level two timeout delay ms property name.
  59755. *
  59756. * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
  59757. *
  59758. * @private {string}
  59759. * @const
  59760. */
  59761. goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
  59762. /**
  59763. * The XMLHttpRequest Level two ontimeout handler property name.
  59764. *
  59765. * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
  59766. *
  59767. * @private {string}
  59768. * @const
  59769. */
  59770. goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
  59771. /**
  59772. * All non-disposed instances of goog.net.XhrIo created
  59773. * by {@link goog.net.XhrIo.send} are in this Array.
  59774. * @see goog.net.XhrIo.cleanup
  59775. * @private {!Array<!goog.net.XhrIo>}
  59776. */
  59777. goog.net.XhrIo.sendInstances_ = [];
  59778. /**
  59779. * Static send that creates a short lived instance of XhrIo to send the
  59780. * request.
  59781. * @see goog.net.XhrIo.cleanup
  59782. * @param {string|goog.Uri} url Uri to make request to.
  59783. * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
  59784. * for when request is complete.
  59785. * @param {string=} opt_method Send method, default: GET.
  59786. * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
  59787. * opt_content Body data.
  59788. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
  59789. * request.
  59790. * @param {number=} opt_timeoutInterval Number of milliseconds after which an
  59791. * incomplete request will be aborted; 0 means no timeout is set.
  59792. * @param {boolean=} opt_withCredentials Whether to send credentials with the
  59793. * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
  59794. * @return {!goog.net.XhrIo} The sent XhrIo.
  59795. */
  59796. goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content,
  59797. opt_headers, opt_timeoutInterval,
  59798. opt_withCredentials) {
  59799. var x = new goog.net.XhrIo();
  59800. goog.net.XhrIo.sendInstances_.push(x);
  59801. if (opt_callback) {
  59802. x.listen(goog.net.EventType.COMPLETE, opt_callback);
  59803. }
  59804. x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
  59805. if (opt_timeoutInterval) {
  59806. x.setTimeoutInterval(opt_timeoutInterval);
  59807. }
  59808. if (opt_withCredentials) {
  59809. x.setWithCredentials(opt_withCredentials);
  59810. }
  59811. x.send(url, opt_method, opt_content, opt_headers);
  59812. return x;
  59813. };
  59814. /**
  59815. * Disposes all non-disposed instances of goog.net.XhrIo created by
  59816. * {@link goog.net.XhrIo.send}.
  59817. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
  59818. * it creates when the request completes or fails. However, if
  59819. * the request never completes, then the goog.net.XhrIo is not disposed.
  59820. * This can occur if the window is unloaded before the request completes.
  59821. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
  59822. * it creates and make the client of {@link goog.net.XhrIo.send} be
  59823. * responsible for disposing it in this case. However, this makes things
  59824. * significantly more complicated for the client, and the whole point
  59825. * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
  59826. * Clients of {@link goog.net.XhrIo.send} should call
  59827. * {@link goog.net.XhrIo.cleanup} when doing final
  59828. * cleanup on window unload.
  59829. */
  59830. goog.net.XhrIo.cleanup = function() {
  59831. var instances = goog.net.XhrIo.sendInstances_;
  59832. while (instances.length) {
  59833. instances.pop().dispose();
  59834. }
  59835. };
  59836. /**
  59837. * Installs exception protection for all entry point introduced by
  59838. * goog.net.XhrIo instances which are not protected by
  59839. * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
  59840. * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
  59841. * {@link goog.events.protectBrowserEventEntryPoint}.
  59842. *
  59843. * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
  59844. * protect the entry point(s).
  59845. */
  59846. goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
  59847. goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
  59848. errorHandler.protectEntryPoint(
  59849. goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
  59850. };
  59851. /**
  59852. * Disposes of the specified goog.net.XhrIo created by
  59853. * {@link goog.net.XhrIo.send} and removes it from
  59854. * {@link goog.net.XhrIo.pendingStaticSendInstances_}.
  59855. * @private
  59856. */
  59857. goog.net.XhrIo.prototype.cleanupSend_ = function() {
  59858. this.dispose();
  59859. goog.array.remove(goog.net.XhrIo.sendInstances_, this);
  59860. };
  59861. /**
  59862. * Returns the number of milliseconds after which an incomplete request will be
  59863. * aborted, or 0 if no timeout is set.
  59864. * @return {number} Timeout interval in milliseconds.
  59865. */
  59866. goog.net.XhrIo.prototype.getTimeoutInterval = function() {
  59867. return this.timeoutInterval_;
  59868. };
  59869. /**
  59870. * Sets the number of milliseconds after which an incomplete request will be
  59871. * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
  59872. * timeout is set.
  59873. * @param {number} ms Timeout interval in milliseconds; 0 means none.
  59874. */
  59875. goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
  59876. this.timeoutInterval_ = Math.max(0, ms);
  59877. };
  59878. /**
  59879. * Sets the desired type for the response. At time of writing, this is only
  59880. * supported in very recent versions of WebKit (10.0.612.1 dev and later).
  59881. *
  59882. * If this is used, the response may only be accessed via {@link #getResponse}.
  59883. *
  59884. * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
  59885. */
  59886. goog.net.XhrIo.prototype.setResponseType = function(type) {
  59887. this.responseType_ = type;
  59888. };
  59889. /**
  59890. * Gets the desired type for the response.
  59891. * @return {goog.net.XhrIo.ResponseType} The desired type for the response.
  59892. */
  59893. goog.net.XhrIo.prototype.getResponseType = function() {
  59894. return this.responseType_;
  59895. };
  59896. /**
  59897. * Sets whether a "credentialed" request that is aware of cookie and
  59898. * authentication information should be made. This option is only supported by
  59899. * browsers that support HTTP Access Control. As of this writing, this option
  59900. * is not supported in IE.
  59901. *
  59902. * @param {boolean} withCredentials Whether this should be a "credentialed"
  59903. * request.
  59904. */
  59905. goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
  59906. this.withCredentials_ = withCredentials;
  59907. };
  59908. /**
  59909. * Gets whether a "credentialed" request is to be sent.
  59910. * @return {boolean} The desired type for the response.
  59911. */
  59912. goog.net.XhrIo.prototype.getWithCredentials = function() {
  59913. return this.withCredentials_;
  59914. };
  59915. /**
  59916. * Sets whether progress events are enabled for this request. Note
  59917. * that progress events require pre-flight OPTIONS request handling
  59918. * for CORS requests, and may cause trouble with older browsers. See
  59919. * progressEventsEnabled_ for details.
  59920. * @param {boolean} enabled Whether progress events should be enabled.
  59921. */
  59922. goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
  59923. this.progressEventsEnabled_ = enabled;
  59924. };
  59925. /**
  59926. * Gets whether progress events are enabled.
  59927. * @return {boolean} Whether progress events are enabled for this request.
  59928. */
  59929. goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
  59930. return this.progressEventsEnabled_;
  59931. };
  59932. /**
  59933. * Instance send that actually uses XMLHttpRequest to make a server call.
  59934. * @param {string|goog.Uri} url Uri to make request to.
  59935. * @param {string=} opt_method Send method, default: GET.
  59936. * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
  59937. * opt_content Body data.
  59938. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
  59939. * request.
  59940. */
  59941. goog.net.XhrIo.prototype.send = function(url, opt_method, opt_content,
  59942. opt_headers) {
  59943. if (this.xhr_) {
  59944. throw Error('[goog.net.XhrIo] Object is active with another request=' +
  59945. this.lastUri_ + '; newUri=' + url);
  59946. }
  59947. var method = opt_method ? opt_method.toUpperCase() : 'GET';
  59948. this.lastUri_ = url;
  59949. this.lastError_ = '';
  59950. this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
  59951. this.lastMethod_ = method;
  59952. this.errorDispatched_ = false;
  59953. this.active_ = true;
  59954. // Use the factory to create the XHR object and options
  59955. this.xhr_ = this.createXhr();
  59956. this.xhrOptions_ = this.xmlHttpFactory_ ?
  59957. this.xmlHttpFactory_.getOptions() : goog.net.XmlHttp.getOptions();
  59958. // Set up the onreadystatechange callback
  59959. this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
  59960. // Set up upload/download progress events, if progress events are supported.
  59961. if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
  59962. this.xhr_.onprogress = goog.bind(this.onProgressHandler_, this);
  59963. if (this.xhr_.upload) {
  59964. this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
  59965. }
  59966. }
  59967. /**
  59968. * Try to open the XMLHttpRequest (always async), if an error occurs here it
  59969. * is generally permission denied
  59970. * @preserveTry
  59971. */
  59972. try {
  59973. goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
  59974. this.inOpen_ = true;
  59975. this.xhr_.open(method, String(url), true); // Always async!
  59976. this.inOpen_ = false;
  59977. } catch (err) {
  59978. goog.log.fine(this.logger_,
  59979. this.formatMsg_('Error opening Xhr: ' + err.message));
  59980. this.error_(goog.net.ErrorCode.EXCEPTION, err);
  59981. return;
  59982. }
  59983. // We can't use null since this won't allow requests with form data to have a
  59984. // content length specified which will cause some proxies to return a 411
  59985. // error.
  59986. var content = opt_content || '';
  59987. var headers = this.headers.clone();
  59988. // Add headers specific to this request
  59989. if (opt_headers) {
  59990. goog.structs.forEach(opt_headers, function(value, key) {
  59991. headers.set(key, value);
  59992. });
  59993. }
  59994. // Find whether a content type header is set, ignoring case.
  59995. // HTTP header names are case-insensitive. See:
  59996. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
  59997. var contentTypeKey = goog.array.find(headers.getKeys(),
  59998. goog.net.XhrIo.isContentTypeHeader_);
  59999. var contentIsFormData = (goog.global['FormData'] &&
  60000. (content instanceof goog.global['FormData']));
  60001. if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
  60002. !contentTypeKey && !contentIsFormData) {
  60003. // For requests typically with form data, default to the url-encoded form
  60004. // content type unless this is a FormData request. For FormData,
  60005. // the browser will automatically add a multipart/form-data content type
  60006. // with an appropriate multipart boundary.
  60007. headers.set(goog.net.XhrIo.CONTENT_TYPE_HEADER,
  60008. goog.net.XhrIo.FORM_CONTENT_TYPE);
  60009. }
  60010. // Add the headers to the Xhr object
  60011. headers.forEach(function(value, key) {
  60012. this.xhr_.setRequestHeader(key, value);
  60013. }, this);
  60014. if (this.responseType_) {
  60015. this.xhr_.responseType = this.responseType_;
  60016. }
  60017. if (goog.object.containsKey(this.xhr_, 'withCredentials')) {
  60018. this.xhr_.withCredentials = this.withCredentials_;
  60019. }
  60020. /**
  60021. * Try to send the request, or other wise report an error (404 not found).
  60022. * @preserveTry
  60023. */
  60024. try {
  60025. this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
  60026. if (this.timeoutInterval_ > 0) {
  60027. this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
  60028. goog.log.fine(this.logger_, this.formatMsg_('Will abort after ' +
  60029. this.timeoutInterval_ + 'ms if incomplete, xhr2 ' +
  60030. this.useXhr2Timeout_));
  60031. if (this.useXhr2Timeout_) {
  60032. this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
  60033. this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
  60034. goog.bind(this.timeout_, this);
  60035. } else {
  60036. this.timeoutId_ = goog.Timer.callOnce(this.timeout_,
  60037. this.timeoutInterval_, this);
  60038. }
  60039. }
  60040. goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
  60041. this.inSend_ = true;
  60042. this.xhr_.send(content);
  60043. this.inSend_ = false;
  60044. } catch (err) {
  60045. goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
  60046. this.error_(goog.net.ErrorCode.EXCEPTION, err);
  60047. }
  60048. };
  60049. /**
  60050. * Determines if the argument is an XMLHttpRequest that supports the level 2
  60051. * timeout value and event.
  60052. *
  60053. * Currently, FF 21.0 OS X has the fields but won't actually call the timeout
  60054. * handler. Perhaps the confusion in the bug referenced below hasn't
  60055. * entirely been resolved.
  60056. *
  60057. * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
  60058. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
  60059. *
  60060. * @param {!goog.net.XhrLike.OrNative} xhr The request.
  60061. * @return {boolean} True if the request supports level 2 timeout.
  60062. * @private
  60063. */
  60064. goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
  60065. return goog.userAgent.IE &&
  60066. goog.userAgent.isVersionOrHigher(9) &&
  60067. goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&
  60068. goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);
  60069. };
  60070. /**
  60071. * @param {string} header An HTTP header key.
  60072. * @return {boolean} Whether the key is a content type header (ignoring
  60073. * case.
  60074. * @private
  60075. */
  60076. goog.net.XhrIo.isContentTypeHeader_ = function(header) {
  60077. return goog.string.caseInsensitiveEquals(
  60078. goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
  60079. };
  60080. /**
  60081. * Creates a new XHR object.
  60082. * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
  60083. * @protected
  60084. */
  60085. goog.net.XhrIo.prototype.createXhr = function() {
  60086. return this.xmlHttpFactory_ ?
  60087. this.xmlHttpFactory_.createInstance() : goog.net.XmlHttp();
  60088. };
  60089. /**
  60090. * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
  60091. * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
  60092. * the request.
  60093. * @private
  60094. */
  60095. goog.net.XhrIo.prototype.timeout_ = function() {
  60096. if (typeof goog == 'undefined') {
  60097. // If goog is undefined then the callback has occurred as the application
  60098. // is unloading and will error. Thus we let it silently fail.
  60099. } else if (this.xhr_) {
  60100. this.lastError_ = 'Timed out after ' + this.timeoutInterval_ +
  60101. 'ms, aborting';
  60102. this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
  60103. goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
  60104. this.dispatchEvent(goog.net.EventType.TIMEOUT);
  60105. this.abort(goog.net.ErrorCode.TIMEOUT);
  60106. }
  60107. };
  60108. /**
  60109. * Something errorred, so inactivate, fire error callback and clean up
  60110. * @param {goog.net.ErrorCode} errorCode The error code.
  60111. * @param {Error} err The error object.
  60112. * @private
  60113. */
  60114. goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
  60115. this.active_ = false;
  60116. if (this.xhr_) {
  60117. this.inAbort_ = true;
  60118. this.xhr_.abort(); // Ensures XHR isn't hung (FF)
  60119. this.inAbort_ = false;
  60120. }
  60121. this.lastError_ = err;
  60122. this.lastErrorCode_ = errorCode;
  60123. this.dispatchErrors_();
  60124. this.cleanUpXhr_();
  60125. };
  60126. /**
  60127. * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
  60128. * not dispatch multiple error events.
  60129. * @private
  60130. */
  60131. goog.net.XhrIo.prototype.dispatchErrors_ = function() {
  60132. if (!this.errorDispatched_) {
  60133. this.errorDispatched_ = true;
  60134. this.dispatchEvent(goog.net.EventType.COMPLETE);
  60135. this.dispatchEvent(goog.net.EventType.ERROR);
  60136. }
  60137. };
  60138. /**
  60139. * Abort the current XMLHttpRequest
  60140. * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
  60141. * defaults to ABORT.
  60142. */
  60143. goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
  60144. if (this.xhr_ && this.active_) {
  60145. goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
  60146. this.active_ = false;
  60147. this.inAbort_ = true;
  60148. this.xhr_.abort();
  60149. this.inAbort_ = false;
  60150. this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
  60151. this.dispatchEvent(goog.net.EventType.COMPLETE);
  60152. this.dispatchEvent(goog.net.EventType.ABORT);
  60153. this.cleanUpXhr_();
  60154. }
  60155. };
  60156. /**
  60157. * Nullifies all callbacks to reduce risks of leaks.
  60158. * @override
  60159. * @protected
  60160. */
  60161. goog.net.XhrIo.prototype.disposeInternal = function() {
  60162. if (this.xhr_) {
  60163. // We explicitly do not call xhr_.abort() unless active_ is still true.
  60164. // This is to avoid unnecessarily aborting a successful request when
  60165. // dispose() is called in a callback triggered by a complete response, but
  60166. // in which browser cleanup has not yet finished.
  60167. // (See http://b/issue?id=1684217.)
  60168. if (this.active_) {
  60169. this.active_ = false;
  60170. this.inAbort_ = true;
  60171. this.xhr_.abort();
  60172. this.inAbort_ = false;
  60173. }
  60174. this.cleanUpXhr_(true);
  60175. }
  60176. goog.net.XhrIo.base(this, 'disposeInternal');
  60177. };
  60178. /**
  60179. * Internal handler for the XHR object's readystatechange event. This method
  60180. * checks the status and the readystate and fires the correct callbacks.
  60181. * If the request has ended, the handlers are cleaned up and the XHR object is
  60182. * nullified.
  60183. * @private
  60184. */
  60185. goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
  60186. if (this.isDisposed()) {
  60187. // This method is the target of an untracked goog.Timer.callOnce().
  60188. return;
  60189. }
  60190. if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
  60191. // Were not being called from within a call to this.xhr_.send
  60192. // this.xhr_.abort, or this.xhr_.open, so this is an entry point
  60193. this.onReadyStateChangeEntryPoint_();
  60194. } else {
  60195. this.onReadyStateChangeHelper_();
  60196. }
  60197. };
  60198. /**
  60199. * Used to protect the onreadystatechange handler entry point. Necessary
  60200. * as {#onReadyStateChange_} maybe called from within send or abort, this
  60201. * method is only called when {#onReadyStateChange_} is called as an
  60202. * entry point.
  60203. * {@see #protectEntryPoints}
  60204. * @private
  60205. */
  60206. goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
  60207. this.onReadyStateChangeHelper_();
  60208. };
  60209. /**
  60210. * Helper for {@link #onReadyStateChange_}. This is used so that
  60211. * entry point calls to {@link #onReadyStateChange_} can be routed through
  60212. * {@link #onReadyStateChangeEntryPoint_}.
  60213. * @private
  60214. */
  60215. goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
  60216. if (!this.active_) {
  60217. // can get called inside abort call
  60218. return;
  60219. }
  60220. if (typeof goog == 'undefined') {
  60221. // NOTE(user): If goog is undefined then the callback has occurred as the
  60222. // application is unloading and will error. Thus we let it silently fail.
  60223. } else if (
  60224. this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
  60225. this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
  60226. this.getStatus() == 2) {
  60227. // NOTE(user): In IE if send() errors on a *local* request the readystate
  60228. // is still changed to COMPLETE. We need to ignore it and allow the
  60229. // try/catch around send() to pick up the error.
  60230. goog.log.fine(this.logger_, this.formatMsg_(
  60231. 'Local request error detected and ignored'));
  60232. } else {
  60233. // In IE when the response has been cached we sometimes get the callback
  60234. // from inside the send call and this usually breaks code that assumes that
  60235. // XhrIo is asynchronous. If that is the case we delay the callback
  60236. // using a timer.
  60237. if (this.inSend_ &&
  60238. this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
  60239. goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
  60240. return;
  60241. }
  60242. this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
  60243. // readyState indicates the transfer has finished
  60244. if (this.isComplete()) {
  60245. goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
  60246. this.active_ = false;
  60247. try {
  60248. // Call the specific callbacks for success or failure. Only call the
  60249. // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
  60250. if (this.isSuccess()) {
  60251. this.dispatchEvent(goog.net.EventType.COMPLETE);
  60252. this.dispatchEvent(goog.net.EventType.SUCCESS);
  60253. } else {
  60254. this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
  60255. this.lastError_ =
  60256. this.getStatusText() + ' [' + this.getStatus() + ']';
  60257. this.dispatchErrors_();
  60258. }
  60259. } finally {
  60260. this.cleanUpXhr_();
  60261. }
  60262. }
  60263. }
  60264. };
  60265. /**
  60266. * Internal handler for the XHR object's onprogress event.
  60267. * @param {!ProgressEvent} e XHR progress event.
  60268. * @private
  60269. */
  60270. goog.net.XhrIo.prototype.onProgressHandler_ = function(e) {
  60271. goog.asserts.assert(e.type === goog.net.EventType.PROGRESS,
  60272. 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
  60273. // Redispatch the progress event.
  60274. this.dispatchEvent(e);
  60275. };
  60276. /**
  60277. * Remove the listener to protect against leaks, and nullify the XMLHttpRequest
  60278. * object.
  60279. * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
  60280. * fire any events).
  60281. * @private
  60282. */
  60283. goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
  60284. if (this.xhr_) {
  60285. // Cancel any pending timeout event handler.
  60286. this.cleanUpTimeoutTimer_();
  60287. // Save reference so we can mark it as closed after the READY event. The
  60288. // READY event may trigger another request, thus we must nullify this.xhr_
  60289. var xhr = this.xhr_;
  60290. var clearedOnReadyStateChange =
  60291. this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
  60292. goog.nullFunction : null;
  60293. this.xhr_ = null;
  60294. this.xhrOptions_ = null;
  60295. if (!opt_fromDispose) {
  60296. this.dispatchEvent(goog.net.EventType.READY);
  60297. }
  60298. try {
  60299. // NOTE(user): Not nullifying in FireFox can still leak if the callbacks
  60300. // are defined in the same scope as the instance of XhrIo. But, IE doesn't
  60301. // allow you to set the onreadystatechange to NULL so nullFunction is
  60302. // used.
  60303. xhr.onreadystatechange = clearedOnReadyStateChange;
  60304. } catch (e) {
  60305. // This seems to occur with a Gears HTTP request. Delayed the setting of
  60306. // this onreadystatechange until after READY is sent out and catching the
  60307. // error to see if we can track down the problem.
  60308. goog.log.error(this.logger_,
  60309. 'Problem encountered resetting onreadystatechange: ' + e.message);
  60310. }
  60311. }
  60312. };
  60313. /**
  60314. * Make sure the timeout timer isn't running.
  60315. * @private
  60316. */
  60317. goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
  60318. if (this.xhr_ && this.useXhr2Timeout_) {
  60319. this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
  60320. }
  60321. if (goog.isNumber(this.timeoutId_)) {
  60322. goog.Timer.clear(this.timeoutId_);
  60323. this.timeoutId_ = null;
  60324. }
  60325. };
  60326. /**
  60327. * @return {boolean} Whether there is an active request.
  60328. */
  60329. goog.net.XhrIo.prototype.isActive = function() {
  60330. return !!this.xhr_;
  60331. };
  60332. /**
  60333. * @return {boolean} Whether the request has completed.
  60334. */
  60335. goog.net.XhrIo.prototype.isComplete = function() {
  60336. return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
  60337. };
  60338. /**
  60339. * @return {boolean} Whether the request completed with a success.
  60340. */
  60341. goog.net.XhrIo.prototype.isSuccess = function() {
  60342. var status = this.getStatus();
  60343. // A zero status code is considered successful for local files.
  60344. return goog.net.HttpStatus.isSuccess(status) ||
  60345. status === 0 && !this.isLastUriEffectiveSchemeHttp_();
  60346. };
  60347. /**
  60348. * @return {boolean} whether the effective scheme of the last URI that was
  60349. * fetched was 'http' or 'https'.
  60350. * @private
  60351. */
  60352. goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
  60353. var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
  60354. return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
  60355. };
  60356. /**
  60357. * Get the readystate from the Xhr object
  60358. * Will only return correct result when called from the context of a callback
  60359. * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
  60360. */
  60361. goog.net.XhrIo.prototype.getReadyState = function() {
  60362. return this.xhr_ ?
  60363. /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
  60364. goog.net.XmlHttp.ReadyState.UNINITIALIZED;
  60365. };
  60366. /**
  60367. * Get the status from the Xhr object
  60368. * Will only return correct result when called from the context of a callback
  60369. * @return {number} Http status.
  60370. */
  60371. goog.net.XhrIo.prototype.getStatus = function() {
  60372. /**
  60373. * IE doesn't like you checking status until the readystate is greater than 2
  60374. * (i.e. it is receiving or complete). The try/catch is used for when the
  60375. * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
  60376. * @preserveTry
  60377. */
  60378. try {
  60379. return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
  60380. this.xhr_.status : -1;
  60381. } catch (e) {
  60382. return -1;
  60383. }
  60384. };
  60385. /**
  60386. * Get the status text from the Xhr object
  60387. * Will only return correct result when called from the context of a callback
  60388. * @return {string} Status text.
  60389. */
  60390. goog.net.XhrIo.prototype.getStatusText = function() {
  60391. /**
  60392. * IE doesn't like you checking status until the readystate is greater than 2
  60393. * (i.e. it is recieving or complete). The try/catch is used for when the
  60394. * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
  60395. * @preserveTry
  60396. */
  60397. try {
  60398. return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
  60399. this.xhr_.statusText : '';
  60400. } catch (e) {
  60401. goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
  60402. return '';
  60403. }
  60404. };
  60405. /**
  60406. * Get the last Uri that was requested
  60407. * @return {string} Last Uri.
  60408. */
  60409. goog.net.XhrIo.prototype.getLastUri = function() {
  60410. return String(this.lastUri_);
  60411. };
  60412. /**
  60413. * Get the response text from the Xhr object
  60414. * Will only return correct result when called from the context of a callback.
  60415. * @return {string} Result from the server, or '' if no result available.
  60416. */
  60417. goog.net.XhrIo.prototype.getResponseText = function() {
  60418. /** @preserveTry */
  60419. try {
  60420. return this.xhr_ ? this.xhr_.responseText : '';
  60421. } catch (e) {
  60422. // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
  60423. // states that responseText should return '' (and responseXML null)
  60424. // when the state is not LOADING or DONE. Instead, IE can
  60425. // throw unexpected exceptions, for example when a request is aborted
  60426. // or no data is available yet.
  60427. goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
  60428. return '';
  60429. }
  60430. };
  60431. /**
  60432. * Get the response body from the Xhr object. This property is only available
  60433. * in IE since version 7 according to MSDN:
  60434. * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
  60435. * Will only return correct result when called from the context of a callback.
  60436. *
  60437. * One option is to construct a VBArray from the returned object and convert
  60438. * it to a JavaScript array using the toArray method:
  60439. * {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()}
  60440. * This will result in an array of numbers in the range of [0..255]
  60441. *
  60442. * Another option is to use the VBScript CStr method to convert it into a
  60443. * string as outlined in http://stackoverflow.com/questions/1919972
  60444. *
  60445. * @return {Object} Binary result from the server or null if not available.
  60446. */
  60447. goog.net.XhrIo.prototype.getResponseBody = function() {
  60448. /** @preserveTry */
  60449. try {
  60450. if (this.xhr_ && 'responseBody' in this.xhr_) {
  60451. return this.xhr_['responseBody'];
  60452. }
  60453. } catch (e) {
  60454. // IE can throw unexpected exceptions, for example when a request is aborted
  60455. // or no data is yet available.
  60456. goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
  60457. }
  60458. return null;
  60459. };
  60460. /**
  60461. * Get the response XML from the Xhr object
  60462. * Will only return correct result when called from the context of a callback.
  60463. * @return {Document} The DOM Document representing the XML file, or null
  60464. * if no result available.
  60465. */
  60466. goog.net.XhrIo.prototype.getResponseXml = function() {
  60467. /** @preserveTry */
  60468. try {
  60469. return this.xhr_ ? this.xhr_.responseXML : null;
  60470. } catch (e) {
  60471. goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
  60472. return null;
  60473. }
  60474. };
  60475. /**
  60476. * Get the response and evaluates it as JSON from the Xhr object
  60477. * Will only return correct result when called from the context of a callback
  60478. * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
  60479. * stripping of the response before parsing. This needs to be set only if
  60480. * your backend server prepends the same prefix string to the JSON response.
  60481. * @return {Object|undefined} JavaScript object.
  60482. */
  60483. goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
  60484. if (!this.xhr_) {
  60485. return undefined;
  60486. }
  60487. var responseText = this.xhr_.responseText;
  60488. if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
  60489. responseText = responseText.substring(opt_xssiPrefix.length);
  60490. }
  60491. return goog.json.parse(responseText);
  60492. };
  60493. /**
  60494. * Get the response as the type specificed by {@link #setResponseType}. At time
  60495. * of writing, this is only directly supported in very recent versions of WebKit
  60496. * (10.0.612.1 dev and later). If the field is not supported directly, we will
  60497. * try to emulate it.
  60498. *
  60499. * Emulating the response means following the rules laid out at
  60500. * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
  60501. *
  60502. * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
  60503. * response types of DEFAULT or TEXT may be used, and the response returned will
  60504. * be the text response.
  60505. *
  60506. * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
  60507. * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
  60508. * response returned will be either the text response or the Mozilla
  60509. * implementation of the array buffer response.
  60510. *
  60511. * On browsers will full support, any valid response type supported by the
  60512. * browser may be used, and the response provided by the browser will be
  60513. * returned.
  60514. *
  60515. * @return {*} The response.
  60516. */
  60517. goog.net.XhrIo.prototype.getResponse = function() {
  60518. /** @preserveTry */
  60519. try {
  60520. if (!this.xhr_) {
  60521. return null;
  60522. }
  60523. if ('response' in this.xhr_) {
  60524. return this.xhr_.response;
  60525. }
  60526. switch (this.responseType_) {
  60527. case goog.net.XhrIo.ResponseType.DEFAULT:
  60528. case goog.net.XhrIo.ResponseType.TEXT:
  60529. return this.xhr_.responseText;
  60530. // DOCUMENT and BLOB don't need to be handled here because they are
  60531. // introduced in the same spec that adds the .response field, and would
  60532. // have been caught above.
  60533. // ARRAY_BUFFER needs an implementation for Firefox 4, where it was
  60534. // implemented using a draft spec rather than the final spec.
  60535. case goog.net.XhrIo.ResponseType.ARRAY_BUFFER:
  60536. if ('mozResponseArrayBuffer' in this.xhr_) {
  60537. return this.xhr_.mozResponseArrayBuffer;
  60538. }
  60539. }
  60540. // Fell through to a response type that is not supported on this browser.
  60541. goog.log.error(this.logger_,
  60542. 'Response type ' + this.responseType_ + ' is not ' +
  60543. 'supported on this browser');
  60544. return null;
  60545. } catch (e) {
  60546. goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
  60547. return null;
  60548. }
  60549. };
  60550. /**
  60551. * Get the value of the response-header with the given name from the Xhr object
  60552. * Will only return correct result when called from the context of a callback
  60553. * and the request has completed
  60554. * @param {string} key The name of the response-header to retrieve.
  60555. * @return {string|undefined} The value of the response-header named key.
  60556. */
  60557. goog.net.XhrIo.prototype.getResponseHeader = function(key) {
  60558. return this.xhr_ && this.isComplete() ?
  60559. this.xhr_.getResponseHeader(key) : undefined;
  60560. };
  60561. /**
  60562. * Gets the text of all the headers in the response.
  60563. * Will only return correct result when called from the context of a callback
  60564. * and the request has completed.
  60565. * @return {string} The value of the response headers or empty string.
  60566. */
  60567. goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
  60568. return this.xhr_ && this.isComplete() ?
  60569. this.xhr_.getAllResponseHeaders() : '';
  60570. };
  60571. /**
  60572. * Returns all response headers as a key-value map.
  60573. * Multiple values for the same header key can be combined into one,
  60574. * separated by a comma and a space.
  60575. * Note that the native getResponseHeader method for retrieving a single header
  60576. * does a case insensitive match on the header name. This method does not
  60577. * include any case normalization logic, it will just return a key-value
  60578. * representation of the headers.
  60579. * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
  60580. * @return {!Object<string, string>} An object with the header keys as keys
  60581. * and header values as values.
  60582. */
  60583. goog.net.XhrIo.prototype.getResponseHeaders = function() {
  60584. var headersObject = {};
  60585. var headersArray = this.getAllResponseHeaders().split('\r\n');
  60586. for (var i = 0; i < headersArray.length; i++) {
  60587. if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
  60588. continue;
  60589. }
  60590. var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2);
  60591. if (headersObject[keyValue[0]]) {
  60592. headersObject[keyValue[0]] += ', ' + keyValue[1];
  60593. } else {
  60594. headersObject[keyValue[0]] = keyValue[1];
  60595. }
  60596. }
  60597. return headersObject;
  60598. };
  60599. /**
  60600. * Get the last error message
  60601. * @return {goog.net.ErrorCode} Last error code.
  60602. */
  60603. goog.net.XhrIo.prototype.getLastErrorCode = function() {
  60604. return this.lastErrorCode_;
  60605. };
  60606. /**
  60607. * Get the last error message
  60608. * @return {string} Last error message.
  60609. */
  60610. goog.net.XhrIo.prototype.getLastError = function() {
  60611. return goog.isString(this.lastError_) ? this.lastError_ :
  60612. String(this.lastError_);
  60613. };
  60614. /**
  60615. * Adds the last method, status and URI to the message. This is used to add
  60616. * this information to the logging calls.
  60617. * @param {string} msg The message text that we want to add the extra text to.
  60618. * @return {string} The message with the extra text appended.
  60619. * @private
  60620. */
  60621. goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
  60622. return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
  60623. this.getStatus() + ']';
  60624. };
  60625. // Register the xhr handler as an entry point, so that
  60626. // it can be monitored for exception handling, etc.
  60627. goog.debug.entryPointRegistry.register(
  60628. /**
  60629. * @param {function(!Function): !Function} transformer The transforming
  60630. * function.
  60631. */
  60632. function(transformer) {
  60633. goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
  60634. transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
  60635. });
  60636. goog.provide('ol.format.FormatType');
  60637. /**
  60638. * @enum {string}
  60639. */
  60640. ol.format.FormatType = {
  60641. JSON: 'json',
  60642. TEXT: 'text',
  60643. XML: 'xml'
  60644. };
  60645. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  60646. //
  60647. // Licensed under the Apache License, Version 2.0 (the "License");
  60648. // you may not use this file except in compliance with the License.
  60649. // You may obtain a copy of the License at
  60650. //
  60651. // http://www.apache.org/licenses/LICENSE-2.0
  60652. //
  60653. // Unless required by applicable law or agreed to in writing, software
  60654. // distributed under the License is distributed on an "AS-IS" BASIS,
  60655. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  60656. // See the License for the specific language governing permissions and
  60657. // limitations under the License.
  60658. /**
  60659. * @fileoverview
  60660. * XML utilities.
  60661. *
  60662. */
  60663. goog.provide('goog.dom.xml');
  60664. goog.require('goog.dom');
  60665. goog.require('goog.dom.NodeType');
  60666. goog.require('goog.userAgent');
  60667. /**
  60668. * Max XML size for MSXML2. Used to prevent potential DoS attacks.
  60669. * @type {number}
  60670. */
  60671. goog.dom.xml.MAX_XML_SIZE_KB = 2 * 1024; // In kB
  60672. /**
  60673. * Max XML size for MSXML2. Used to prevent potential DoS attacks.
  60674. * @type {number}
  60675. */
  60676. goog.dom.xml.MAX_ELEMENT_DEPTH = 256; // Same default as MSXML6.
  60677. /**
  60678. * Check for ActiveXObject support by the browser.
  60679. * @return {boolean} true if browser has ActiveXObject support.
  60680. * @private
  60681. */
  60682. goog.dom.xml.hasActiveXObjectSupport_ = function() {
  60683. if (!goog.userAgent.IE) {
  60684. // Avoid raising useless exception in case code is not compiled
  60685. // and browser is not MSIE.
  60686. return false;
  60687. }
  60688. try {
  60689. // Due to lot of changes in IE 9, 10 & 11 behaviour and ActiveX being
  60690. // totally disableable using MSIE's security level, trying to create the
  60691. // ActiveXOjbect is a lot more reliable than testing for the existance of
  60692. // window.ActiveXObject
  60693. new ActiveXObject('MSXML2.DOMDocument');
  60694. return true;
  60695. } catch (e) {
  60696. return false;
  60697. }
  60698. };
  60699. /**
  60700. * True if browser has ActiveXObject support.
  60701. * Possible override if this test become wrong in coming IE versions.
  60702. * @type {boolean}
  60703. */
  60704. goog.dom.xml.ACTIVEX_SUPPORT =
  60705. goog.userAgent.IE && goog.dom.xml.hasActiveXObjectSupport_();
  60706. /**
  60707. * Creates an XML document appropriate for the current JS runtime
  60708. * @param {string=} opt_rootTagName The root tag name.
  60709. * @param {string=} opt_namespaceUri Namespace URI of the document element.
  60710. * @param {boolean=} opt_preferActiveX Whether to default to ActiveXObject to
  60711. * create Document in IE. Use this if you need xpath support in IE (e.g.,
  60712. * selectSingleNode or selectNodes), but be aware that the ActiveXObject does
  60713. * not support various DOM-specific Document methods and attributes.
  60714. * @return {Document} The new document.
  60715. * @throws {Error} if browser does not support creating new documents or
  60716. * namespace is provided without a root tag name.
  60717. */
  60718. goog.dom.xml.createDocument = function(opt_rootTagName, opt_namespaceUri,
  60719. opt_preferActiveX) {
  60720. if (opt_namespaceUri && !opt_rootTagName) {
  60721. throw Error("Can't create document with namespace and no root tag");
  60722. }
  60723. // If document.implementation.createDocument is available and they haven't
  60724. // explicitly opted to use ActiveXObject when possible.
  60725. if (document.implementation && document.implementation.createDocument &&
  60726. !(goog.dom.xml.ACTIVEX_SUPPORT && opt_preferActiveX)) {
  60727. return document.implementation.createDocument(opt_namespaceUri || '',
  60728. opt_rootTagName || '', null);
  60729. } else if (goog.dom.xml.ACTIVEX_SUPPORT) {
  60730. var doc = goog.dom.xml.createMsXmlDocument_();
  60731. if (doc) {
  60732. if (opt_rootTagName) {
  60733. doc.appendChild(doc.createNode(goog.dom.NodeType.ELEMENT,
  60734. opt_rootTagName,
  60735. opt_namespaceUri || ''));
  60736. }
  60737. return doc;
  60738. }
  60739. }
  60740. throw Error('Your browser does not support creating new documents');
  60741. };
  60742. /**
  60743. * Creates an XML document from a string
  60744. * @param {string} xml The text.
  60745. * @param {boolean=} opt_preferActiveX Whether to default to ActiveXObject to
  60746. * create Document in IE. Use this if you need xpath support in IE (e.g.,
  60747. * selectSingleNode or selectNodes), but be aware that the ActiveXObject does
  60748. * not support various DOM-specific Document methods and attributes.
  60749. * @return {Document} XML document from the text.
  60750. * @throws {Error} if browser does not support loading XML documents.
  60751. */
  60752. goog.dom.xml.loadXml = function(xml, opt_preferActiveX) {
  60753. if (typeof DOMParser != 'undefined' &&
  60754. !(goog.dom.xml.ACTIVEX_SUPPORT && opt_preferActiveX)) {
  60755. return new DOMParser().parseFromString(xml, 'application/xml');
  60756. } else if (goog.dom.xml.ACTIVEX_SUPPORT) {
  60757. var doc = goog.dom.xml.createMsXmlDocument_();
  60758. doc.loadXML(xml);
  60759. return doc;
  60760. }
  60761. throw Error('Your browser does not support loading xml documents');
  60762. };
  60763. /**
  60764. * Serializes an XML document or subtree to string.
  60765. * @param {Document|Element} xml The document or the root node of the subtree.
  60766. * @return {string} The serialized XML.
  60767. * @throws {Error} if browser does not support XML serialization.
  60768. */
  60769. goog.dom.xml.serialize = function(xml) {
  60770. // Compatible with IE/ActiveXObject.
  60771. var text = xml.xml;
  60772. if (text) {
  60773. return text;
  60774. }
  60775. // Compatible with Firefox, Opera and WebKit.
  60776. if (typeof XMLSerializer != 'undefined') {
  60777. return new XMLSerializer().serializeToString(xml);
  60778. }
  60779. throw Error('Your browser does not support serializing XML documents');
  60780. };
  60781. /**
  60782. * Selects a single node using an Xpath expression and a root node
  60783. * @param {Node} node The root node.
  60784. * @param {string} path Xpath selector.
  60785. * @return {Node} The selected node, or null if no matching node.
  60786. */
  60787. goog.dom.xml.selectSingleNode = function(node, path) {
  60788. if (typeof node.selectSingleNode != 'undefined') {
  60789. var doc = goog.dom.getOwnerDocument(node);
  60790. if (typeof doc.setProperty != 'undefined') {
  60791. doc.setProperty('SelectionLanguage', 'XPath');
  60792. }
  60793. return node.selectSingleNode(path);
  60794. } else if (document.implementation.hasFeature('XPath', '3.0')) {
  60795. var doc = goog.dom.getOwnerDocument(node);
  60796. var resolver = doc.createNSResolver(doc.documentElement);
  60797. var result = doc.evaluate(path, node, resolver,
  60798. XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  60799. return result.singleNodeValue;
  60800. }
  60801. // This browser does not support xpath for the given node. If IE, ensure XML
  60802. // Document was created using ActiveXObject
  60803. // TODO(joeltine): This should throw instead of return null.
  60804. return null;
  60805. };
  60806. /**
  60807. * Selects multiple nodes using an Xpath expression and a root node
  60808. * @param {Node} node The root node.
  60809. * @param {string} path Xpath selector.
  60810. * @return {(NodeList|Array<Node>)} The selected nodes, or empty array if no
  60811. * matching nodes.
  60812. */
  60813. goog.dom.xml.selectNodes = function(node, path) {
  60814. if (typeof node.selectNodes != 'undefined') {
  60815. var doc = goog.dom.getOwnerDocument(node);
  60816. if (typeof doc.setProperty != 'undefined') {
  60817. doc.setProperty('SelectionLanguage', 'XPath');
  60818. }
  60819. return node.selectNodes(path);
  60820. } else if (document.implementation.hasFeature('XPath', '3.0')) {
  60821. var doc = goog.dom.getOwnerDocument(node);
  60822. var resolver = doc.createNSResolver(doc.documentElement);
  60823. var nodes = doc.evaluate(path, node, resolver,
  60824. XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  60825. var results = [];
  60826. var count = nodes.snapshotLength;
  60827. for (var i = 0; i < count; i++) {
  60828. results.push(nodes.snapshotItem(i));
  60829. }
  60830. return results;
  60831. } else {
  60832. // This browser does not support xpath for the given node. If IE, ensure XML
  60833. // Document was created using ActiveXObject.
  60834. // TODO(joeltine): This should throw instead of return empty array.
  60835. return [];
  60836. }
  60837. };
  60838. /**
  60839. * Sets multiple attributes on an element. Differs from goog.dom.setProperties
  60840. * in that it exclusively uses the element's setAttributes method. Use this
  60841. * when you need to ensure that the exact property is available as an attribute
  60842. * and can be read later by the native getAttribute method.
  60843. * @param {!Element} element XML or DOM element to set attributes on.
  60844. * @param {!Object<string, string>} attributes Map of property:value pairs.
  60845. */
  60846. goog.dom.xml.setAttributes = function(element, attributes) {
  60847. for (var key in attributes) {
  60848. if (attributes.hasOwnProperty(key)) {
  60849. element.setAttribute(key, attributes[key]);
  60850. }
  60851. }
  60852. };
  60853. /**
  60854. * Creates an instance of the MSXML2.DOMDocument.
  60855. * @return {Document} The new document.
  60856. * @private
  60857. */
  60858. goog.dom.xml.createMsXmlDocument_ = function() {
  60859. var doc = new ActiveXObject('MSXML2.DOMDocument');
  60860. if (doc) {
  60861. // Prevent potential vulnerabilities exposed by MSXML2, see
  60862. // http://b/1707300 and http://wiki/Main/ISETeamXMLAttacks for details.
  60863. doc.resolveExternals = false;
  60864. doc.validateOnParse = false;
  60865. // Add a try catch block because accessing these properties will throw an
  60866. // error on unsupported MSXML versions. This affects Windows machines
  60867. // running IE6 or IE7 that are on XP SP2 or earlier without MSXML updates.
  60868. // See http://msdn.microsoft.com/en-us/library/ms766391(VS.85).aspx for
  60869. // specific details on which MSXML versions support these properties.
  60870. try {
  60871. doc.setProperty('ProhibitDTD', true);
  60872. doc.setProperty('MaxXMLSize', goog.dom.xml.MAX_XML_SIZE_KB);
  60873. doc.setProperty('MaxElementDepth', goog.dom.xml.MAX_ELEMENT_DEPTH);
  60874. } catch (e) {
  60875. // No-op.
  60876. }
  60877. }
  60878. return doc;
  60879. };
  60880. goog.provide('ol.xml');
  60881. goog.require('goog.array');
  60882. goog.require('goog.asserts');
  60883. goog.require('goog.dom.NodeType');
  60884. goog.require('goog.dom.xml');
  60885. goog.require('goog.object');
  60886. goog.require('goog.userAgent');
  60887. /**
  60888. * When using {@link ol.xml.makeChildAppender} or
  60889. * {@link ol.xml.makeSimpleNodeFactory}, the top `objectStack` item needs to
  60890. * have this structure.
  60891. * @typedef {{node:Node}}
  60892. */
  60893. ol.xml.NodeStackItem;
  60894. /**
  60895. * @typedef {function(Node, Array.<*>)}
  60896. */
  60897. ol.xml.Parser;
  60898. /**
  60899. * @typedef {function(Node, *, Array.<*>)}
  60900. */
  60901. ol.xml.Serializer;
  60902. /**
  60903. * This document should be used when creating nodes for XML serializations. This
  60904. * document is also used by {@link ol.xml.createElementNS} and
  60905. * {@link ol.xml.setAttributeNS}
  60906. * @const
  60907. * @type {Document}
  60908. */
  60909. ol.xml.DOCUMENT = goog.dom.xml.createDocument();
  60910. /**
  60911. * @param {string} namespaceURI Namespace URI.
  60912. * @param {string} qualifiedName Qualified name.
  60913. * @return {Node} Node.
  60914. * @private
  60915. */
  60916. ol.xml.createElementNS_ = function(namespaceURI, qualifiedName) {
  60917. return ol.xml.DOCUMENT.createElementNS(namespaceURI, qualifiedName);
  60918. };
  60919. /**
  60920. * @param {string} namespaceURI Namespace URI.
  60921. * @param {string} qualifiedName Qualified name.
  60922. * @return {Node} Node.
  60923. * @private
  60924. */
  60925. ol.xml.createElementNSActiveX_ = function(namespaceURI, qualifiedName) {
  60926. if (!namespaceURI) {
  60927. namespaceURI = '';
  60928. }
  60929. return ol.xml.DOCUMENT.createNode(1, qualifiedName, namespaceURI);
  60930. };
  60931. /**
  60932. * @param {string} namespaceURI Namespace URI.
  60933. * @param {string} qualifiedName Qualified name.
  60934. * @return {Node} Node.
  60935. */
  60936. ol.xml.createElementNS =
  60937. (document.implementation && document.implementation.createDocument) ?
  60938. ol.xml.createElementNS_ : ol.xml.createElementNSActiveX_;
  60939. /**
  60940. * Recursively grab all text content of child nodes into a single string.
  60941. * @param {Node} node Node.
  60942. * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line
  60943. * breaks.
  60944. * @return {string} All text content.
  60945. * @api
  60946. */
  60947. ol.xml.getAllTextContent = function(node, normalizeWhitespace) {
  60948. return ol.xml.getAllTextContent_(node, normalizeWhitespace, []).join('');
  60949. };
  60950. /**
  60951. * Recursively grab all text content of child nodes into a single string.
  60952. * @param {Node} node Node.
  60953. * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line
  60954. * breaks.
  60955. * @param {Array.<String|string>} accumulator Accumulator.
  60956. * @private
  60957. * @return {Array.<String|string>} Accumulator.
  60958. */
  60959. ol.xml.getAllTextContent_ = function(node, normalizeWhitespace, accumulator) {
  60960. if (node.nodeType == goog.dom.NodeType.CDATA_SECTION ||
  60961. node.nodeType == goog.dom.NodeType.TEXT) {
  60962. if (normalizeWhitespace) {
  60963. // FIXME understand why goog.dom.getTextContent_ uses String here
  60964. accumulator.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
  60965. } else {
  60966. accumulator.push(node.nodeValue);
  60967. }
  60968. } else {
  60969. var n;
  60970. for (n = node.firstChild; n; n = n.nextSibling) {
  60971. ol.xml.getAllTextContent_(n, normalizeWhitespace, accumulator);
  60972. }
  60973. }
  60974. return accumulator;
  60975. };
  60976. /**
  60977. * @param {Node} node Node.
  60978. * @private
  60979. * @return {string} Local name.
  60980. */
  60981. ol.xml.getLocalName_ = function(node) {
  60982. return node.localName;
  60983. };
  60984. /**
  60985. * @param {Node} node Node.
  60986. * @private
  60987. * @return {string} Local name.
  60988. */
  60989. ol.xml.getLocalNameIE_ = function(node) {
  60990. var localName = node.localName;
  60991. if (localName !== undefined) {
  60992. return localName;
  60993. }
  60994. var baseName = node.baseName;
  60995. goog.asserts.assert(baseName,
  60996. 'Failed to get localName/baseName of node %s', node);
  60997. return baseName;
  60998. };
  60999. /**
  61000. * @param {Node} node Node.
  61001. * @return {string} Local name.
  61002. */
  61003. ol.xml.getLocalName = goog.userAgent.IE ?
  61004. ol.xml.getLocalNameIE_ : ol.xml.getLocalName_;
  61005. /**
  61006. * @param {?} value Value.
  61007. * @private
  61008. * @return {boolean} Is document.
  61009. */
  61010. ol.xml.isDocument_ = function(value) {
  61011. return value instanceof Document;
  61012. };
  61013. /**
  61014. * @param {?} value Value.
  61015. * @private
  61016. * @return {boolean} Is document.
  61017. */
  61018. ol.xml.isDocumentIE_ = function(value) {
  61019. return goog.isObject(value) && value.nodeType == goog.dom.NodeType.DOCUMENT;
  61020. };
  61021. /**
  61022. * @param {?} value Value.
  61023. * @return {boolean} Is document.
  61024. */
  61025. ol.xml.isDocument = goog.userAgent.IE ?
  61026. ol.xml.isDocumentIE_ : ol.xml.isDocument_;
  61027. /**
  61028. * @param {?} value Value.
  61029. * @private
  61030. * @return {boolean} Is node.
  61031. */
  61032. ol.xml.isNode_ = function(value) {
  61033. return value instanceof Node;
  61034. };
  61035. /**
  61036. * @param {?} value Value.
  61037. * @private
  61038. * @return {boolean} Is node.
  61039. */
  61040. ol.xml.isNodeIE_ = function(value) {
  61041. return goog.isObject(value) && value.nodeType !== undefined;
  61042. };
  61043. /**
  61044. * @param {?} value Value.
  61045. * @return {boolean} Is node.
  61046. */
  61047. ol.xml.isNode = goog.userAgent.IE ? ol.xml.isNodeIE_ : ol.xml.isNode_;
  61048. /**
  61049. * @param {Node} node Node.
  61050. * @param {?string} namespaceURI Namespace URI.
  61051. * @param {string} name Attribute name.
  61052. * @return {string} Value
  61053. * @private
  61054. */
  61055. ol.xml.getAttributeNS_ = function(node, namespaceURI, name) {
  61056. return node.getAttributeNS(namespaceURI, name) || '';
  61057. };
  61058. /**
  61059. * @param {Node} node Node.
  61060. * @param {?string} namespaceURI Namespace URI.
  61061. * @param {string} name Attribute name.
  61062. * @return {string} Value
  61063. * @private
  61064. */
  61065. ol.xml.getAttributeNSActiveX_ = function(node, namespaceURI, name) {
  61066. var attributeValue = '';
  61067. var attributeNode = ol.xml.getAttributeNodeNS(node, namespaceURI, name);
  61068. if (attributeNode !== undefined) {
  61069. attributeValue = attributeNode.nodeValue;
  61070. }
  61071. return attributeValue;
  61072. };
  61073. /**
  61074. * @param {Node} node Node.
  61075. * @param {?string} namespaceURI Namespace URI.
  61076. * @param {string} name Attribute name.
  61077. * @return {string} Value
  61078. */
  61079. ol.xml.getAttributeNS =
  61080. (document.implementation && document.implementation.createDocument) ?
  61081. ol.xml.getAttributeNS_ : ol.xml.getAttributeNSActiveX_;
  61082. /**
  61083. * @param {Node} node Node.
  61084. * @param {?string} namespaceURI Namespace URI.
  61085. * @param {string} name Attribute name.
  61086. * @return {?Node} Attribute node or null if none found.
  61087. * @private
  61088. */
  61089. ol.xml.getAttributeNodeNS_ = function(node, namespaceURI, name) {
  61090. return node.getAttributeNodeNS(namespaceURI, name);
  61091. };
  61092. /**
  61093. * @param {Node} node Node.
  61094. * @param {?string} namespaceURI Namespace URI.
  61095. * @param {string} name Attribute name.
  61096. * @return {?Node} Attribute node or null if none found.
  61097. * @private
  61098. */
  61099. ol.xml.getAttributeNodeNSActiveX_ = function(node, namespaceURI, name) {
  61100. var attributeNode = null;
  61101. var attributes = node.attributes;
  61102. var potentialNode, fullName;
  61103. for (var i = 0, len = attributes.length; i < len; ++i) {
  61104. potentialNode = attributes[i];
  61105. if (potentialNode.namespaceURI == namespaceURI) {
  61106. fullName = (potentialNode.prefix) ?
  61107. (potentialNode.prefix + ':' + name) : name;
  61108. if (fullName == potentialNode.nodeName) {
  61109. attributeNode = potentialNode;
  61110. break;
  61111. }
  61112. }
  61113. }
  61114. return attributeNode;
  61115. };
  61116. /**
  61117. * @param {Node} node Node.
  61118. * @param {?string} namespaceURI Namespace URI.
  61119. * @param {string} name Attribute name.
  61120. * @return {?Node} Attribute node or null if none found.
  61121. */
  61122. ol.xml.getAttributeNodeNS =
  61123. (document.implementation && document.implementation.createDocument) ?
  61124. ol.xml.getAttributeNodeNS_ : ol.xml.getAttributeNodeNSActiveX_;
  61125. /**
  61126. * @param {Node} node Node.
  61127. * @param {?string} namespaceURI Namespace URI.
  61128. * @param {string} name Attribute name.
  61129. * @param {string|number} value Value.
  61130. * @private
  61131. */
  61132. ol.xml.setAttributeNS_ = function(node, namespaceURI, name, value) {
  61133. node.setAttributeNS(namespaceURI, name, value);
  61134. };
  61135. /**
  61136. * @param {Node} node Node.
  61137. * @param {?string} namespaceURI Namespace URI.
  61138. * @param {string} name Attribute name.
  61139. * @param {string|number} value Value.
  61140. * @private
  61141. */
  61142. ol.xml.setAttributeNSActiveX_ = function(node, namespaceURI, name, value) {
  61143. if (namespaceURI) {
  61144. var attribute = node.ownerDocument.createNode(2, name, namespaceURI);
  61145. attribute.nodeValue = value;
  61146. node.setAttributeNode(attribute);
  61147. } else {
  61148. node.setAttribute(name, value);
  61149. }
  61150. };
  61151. /**
  61152. * @param {Node} node Node.
  61153. * @param {?string} namespaceURI Namespace URI.
  61154. * @param {string} name Attribute name.
  61155. * @param {string|number} value Value.
  61156. */
  61157. ol.xml.setAttributeNS =
  61158. (document.implementation && document.implementation.createDocument) ?
  61159. ol.xml.setAttributeNS_ : ol.xml.setAttributeNSActiveX_;
  61160. /**
  61161. * Parse an XML string to an XML Document.
  61162. * @param {string} xml XML.
  61163. * @return {Document} Document.
  61164. * @api
  61165. */
  61166. ol.xml.parse = function(xml) {
  61167. return new DOMParser().parseFromString(xml, 'application/xml');
  61168. };
  61169. /**
  61170. * Make an array extender function for extending the array at the top of the
  61171. * object stack.
  61172. * @param {function(this: T, Node, Array.<*>): (Array.<*>|undefined)}
  61173. * valueReader Value reader.
  61174. * @param {T=} opt_this The object to use as `this` in `valueReader`.
  61175. * @return {ol.xml.Parser} Parser.
  61176. * @template T
  61177. */
  61178. ol.xml.makeArrayExtender = function(valueReader, opt_this) {
  61179. return (
  61180. /**
  61181. * @param {Node} node Node.
  61182. * @param {Array.<*>} objectStack Object stack.
  61183. */
  61184. function(node, objectStack) {
  61185. var value = valueReader.call(opt_this, node, objectStack);
  61186. if (value !== undefined) {
  61187. goog.asserts.assert(goog.isArray(value),
  61188. 'valueReader function is expected to return an array of values');
  61189. var array = /** @type {Array.<*>} */
  61190. (objectStack[objectStack.length - 1]);
  61191. goog.asserts.assert(goog.isArray(array),
  61192. 'objectStack is supposed to be an array of arrays');
  61193. goog.array.extend(array, value);
  61194. }
  61195. });
  61196. };
  61197. /**
  61198. * Make an array pusher function for pushing to the array at the top of the
  61199. * object stack.
  61200. * @param {function(this: T, Node, Array.<*>): *} valueReader Value reader.
  61201. * @param {T=} opt_this The object to use as `this` in `valueReader`.
  61202. * @return {ol.xml.Parser} Parser.
  61203. * @template T
  61204. */
  61205. ol.xml.makeArrayPusher = function(valueReader, opt_this) {
  61206. return (
  61207. /**
  61208. * @param {Node} node Node.
  61209. * @param {Array.<*>} objectStack Object stack.
  61210. */
  61211. function(node, objectStack) {
  61212. var value = valueReader.call(opt_this !== undefined ? opt_this : this,
  61213. node, objectStack);
  61214. if (value !== undefined) {
  61215. var array = objectStack[objectStack.length - 1];
  61216. goog.asserts.assert(goog.isArray(array),
  61217. 'objectStack is supposed to be an array of arrays');
  61218. array.push(value);
  61219. }
  61220. });
  61221. };
  61222. /**
  61223. * Make an object stack replacer function for replacing the object at the
  61224. * top of the stack.
  61225. * @param {function(this: T, Node, Array.<*>): *} valueReader Value reader.
  61226. * @param {T=} opt_this The object to use as `this` in `valueReader`.
  61227. * @return {ol.xml.Parser} Parser.
  61228. * @template T
  61229. */
  61230. ol.xml.makeReplacer = function(valueReader, opt_this) {
  61231. return (
  61232. /**
  61233. * @param {Node} node Node.
  61234. * @param {Array.<*>} objectStack Object stack.
  61235. */
  61236. function(node, objectStack) {
  61237. var value = valueReader.call(opt_this !== undefined ? opt_this : this,
  61238. node, objectStack);
  61239. if (value !== undefined) {
  61240. objectStack[objectStack.length - 1] = value;
  61241. }
  61242. });
  61243. };
  61244. /**
  61245. * Make an object property pusher function for adding a property to the
  61246. * object at the top of the stack.
  61247. * @param {function(this: T, Node, Array.<*>): *} valueReader Value reader.
  61248. * @param {string=} opt_property Property.
  61249. * @param {T=} opt_this The object to use as `this` in `valueReader`.
  61250. * @return {ol.xml.Parser} Parser.
  61251. * @template T
  61252. */
  61253. ol.xml.makeObjectPropertyPusher =
  61254. function(valueReader, opt_property, opt_this) {
  61255. goog.asserts.assert(valueReader !== undefined,
  61256. 'undefined valueReader, expected function(this: T, Node, Array.<*>)');
  61257. return (
  61258. /**
  61259. * @param {Node} node Node.
  61260. * @param {Array.<*>} objectStack Object stack.
  61261. */
  61262. function(node, objectStack) {
  61263. var value = valueReader.call(opt_this !== undefined ? opt_this : this,
  61264. node, objectStack);
  61265. if (value !== undefined) {
  61266. var object = /** @type {Object} */
  61267. (objectStack[objectStack.length - 1]);
  61268. var property = opt_property !== undefined ?
  61269. opt_property : node.localName;
  61270. goog.asserts.assert(goog.isObject(object),
  61271. 'entity from stack was not an object');
  61272. var array = goog.object.setIfUndefined(object, property, []);
  61273. array.push(value);
  61274. }
  61275. });
  61276. };
  61277. /**
  61278. * Make an object property setter function.
  61279. * @param {function(this: T, Node, Array.<*>): *} valueReader Value reader.
  61280. * @param {string=} opt_property Property.
  61281. * @param {T=} opt_this The object to use as `this` in `valueReader`.
  61282. * @return {ol.xml.Parser} Parser.
  61283. * @template T
  61284. */
  61285. ol.xml.makeObjectPropertySetter =
  61286. function(valueReader, opt_property, opt_this) {
  61287. goog.asserts.assert(valueReader !== undefined,
  61288. 'undefined valueReader, expected function(this: T, Node, Array.<*>)');
  61289. return (
  61290. /**
  61291. * @param {Node} node Node.
  61292. * @param {Array.<*>} objectStack Object stack.
  61293. */
  61294. function(node, objectStack) {
  61295. var value = valueReader.call(opt_this !== undefined ? opt_this : this,
  61296. node, objectStack);
  61297. if (value !== undefined) {
  61298. var object = /** @type {Object} */
  61299. (objectStack[objectStack.length - 1]);
  61300. var property = opt_property !== undefined ?
  61301. opt_property : node.localName;
  61302. goog.asserts.assert(goog.isObject(object),
  61303. 'entity from stack was not an object');
  61304. object[property] = value;
  61305. }
  61306. });
  61307. };
  61308. /**
  61309. * Create a serializer that appends nodes written by its `nodeWriter` to its
  61310. * designated parent. The parent is the `node` of the
  61311. * {@link ol.xml.NodeStackItem} at the top of the `objectStack`.
  61312. * @param {function(this: T, Node, V, Array.<*>)}
  61313. * nodeWriter Node writer.
  61314. * @param {T=} opt_this The object to use as `this` in `nodeWriter`.
  61315. * @return {ol.xml.Serializer} Serializer.
  61316. * @template T, V
  61317. */
  61318. ol.xml.makeChildAppender = function(nodeWriter, opt_this) {
  61319. return function(node, value, objectStack) {
  61320. nodeWriter.call(opt_this !== undefined ? opt_this : this,
  61321. node, value, objectStack);
  61322. var parent = objectStack[objectStack.length - 1];
  61323. goog.asserts.assert(goog.isObject(parent),
  61324. 'entity from stack was not an object');
  61325. var parentNode = parent.node;
  61326. goog.asserts.assert(ol.xml.isNode(parentNode) ||
  61327. ol.xml.isDocument(parentNode),
  61328. 'expected parentNode %s to be a Node or a Document', parentNode);
  61329. parentNode.appendChild(node);
  61330. };
  61331. };
  61332. /**
  61333. * Create a serializer that calls the provided `nodeWriter` from
  61334. * {@link ol.xml.serialize}. This can be used by the parent writer to have the
  61335. * 'nodeWriter' called with an array of values when the `nodeWriter` was
  61336. * designed to serialize a single item. An example would be a LineString
  61337. * geometry writer, which could be reused for writing MultiLineString
  61338. * geometries.
  61339. * @param {function(this: T, Node, V, Array.<*>)}
  61340. * nodeWriter Node writer.
  61341. * @param {T=} opt_this The object to use as `this` in `nodeWriter`.
  61342. * @return {ol.xml.Serializer} Serializer.
  61343. * @template T, V
  61344. */
  61345. ol.xml.makeArraySerializer = function(nodeWriter, opt_this) {
  61346. var serializersNS, nodeFactory;
  61347. return function(node, value, objectStack) {
  61348. if (serializersNS === undefined) {
  61349. serializersNS = {};
  61350. var serializers = {};
  61351. serializers[node.localName] = nodeWriter;
  61352. serializersNS[node.namespaceURI] = serializers;
  61353. nodeFactory = ol.xml.makeSimpleNodeFactory(node.localName);
  61354. }
  61355. ol.xml.serialize(serializersNS, nodeFactory, value, objectStack);
  61356. };
  61357. };
  61358. /**
  61359. * Create a node factory which can use the `opt_keys` passed to
  61360. * {@link ol.xml.serialize} or {@link ol.xml.pushSerializeAndPop} as node names,
  61361. * or a fixed node name. The namespace of the created nodes can either be fixed,
  61362. * or the parent namespace will be used.
  61363. * @param {string=} opt_nodeName Fixed node name which will be used for all
  61364. * created nodes. If not provided, the 3rd argument to the resulting node
  61365. * factory needs to be provided and will be the nodeName.
  61366. * @param {string=} opt_namespaceURI Fixed namespace URI which will be used for
  61367. * all created nodes. If not provided, the namespace of the parent node will
  61368. * be used.
  61369. * @return {function(*, Array.<*>, string=): (Node|undefined)} Node factory.
  61370. */
  61371. ol.xml.makeSimpleNodeFactory = function(opt_nodeName, opt_namespaceURI) {
  61372. var fixedNodeName = opt_nodeName;
  61373. return (
  61374. /**
  61375. * @param {*} value Value.
  61376. * @param {Array.<*>} objectStack Object stack.
  61377. * @param {string=} opt_nodeName Node name.
  61378. * @return {Node} Node.
  61379. */
  61380. function(value, objectStack, opt_nodeName) {
  61381. var context = objectStack[objectStack.length - 1];
  61382. var node = context.node;
  61383. goog.asserts.assert(ol.xml.isNode(node) || ol.xml.isDocument(node),
  61384. 'expected node %s to be a Node or a Document', node);
  61385. var nodeName = fixedNodeName;
  61386. if (nodeName === undefined) {
  61387. nodeName = opt_nodeName;
  61388. }
  61389. var namespaceURI = opt_namespaceURI;
  61390. if (opt_namespaceURI === undefined) {
  61391. namespaceURI = node.namespaceURI;
  61392. }
  61393. goog.asserts.assert(nodeName !== undefined, 'nodeName was undefined');
  61394. return ol.xml.createElementNS(namespaceURI, nodeName);
  61395. }
  61396. );
  61397. };
  61398. /**
  61399. * A node factory that creates a node using the parent's `namespaceURI` and the
  61400. * `nodeName` passed by {@link ol.xml.serialize} or
  61401. * {@link ol.xml.pushSerializeAndPop} to the node factory.
  61402. * @const
  61403. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  61404. */
  61405. ol.xml.OBJECT_PROPERTY_NODE_FACTORY = ol.xml.makeSimpleNodeFactory();
  61406. /**
  61407. * Create an array of `values` to be used with {@link ol.xml.serialize} or
  61408. * {@link ol.xml.pushSerializeAndPop}, where `orderedKeys` has to be provided as
  61409. * `opt_key` argument.
  61410. * @param {Object.<string, V>} object Key-value pairs for the sequence. Keys can
  61411. * be a subset of the `orderedKeys`.
  61412. * @param {Array.<string>} orderedKeys Keys in the order of the sequence.
  61413. * @return {Array.<V>} Values in the order of the sequence. The resulting array
  61414. * has the same length as the `orderedKeys` array. Values that are not
  61415. * present in `object` will be `undefined` in the resulting array.
  61416. * @template V
  61417. */
  61418. ol.xml.makeSequence = function(object, orderedKeys) {
  61419. var length = orderedKeys.length;
  61420. var sequence = new Array(length);
  61421. for (var i = 0; i < length; ++i) {
  61422. sequence[i] = object[orderedKeys[i]];
  61423. }
  61424. return sequence;
  61425. };
  61426. /**
  61427. * Create a namespaced structure, using the same values for each namespace.
  61428. * This can be used as a starting point for versioned parsers, when only a few
  61429. * values are version specific.
  61430. * @param {Array.<string>} namespaceURIs Namespace URIs.
  61431. * @param {T} structure Structure.
  61432. * @param {Object.<string, T>=} opt_structureNS Namespaced structure to add to.
  61433. * @return {Object.<string, T>} Namespaced structure.
  61434. * @template T
  61435. */
  61436. ol.xml.makeStructureNS = function(namespaceURIs, structure, opt_structureNS) {
  61437. /**
  61438. * @type {Object.<string, *>}
  61439. */
  61440. var structureNS = opt_structureNS !== undefined ? opt_structureNS : {};
  61441. var i, ii;
  61442. for (i = 0, ii = namespaceURIs.length; i < ii; ++i) {
  61443. structureNS[namespaceURIs[i]] = structure;
  61444. }
  61445. return structureNS;
  61446. };
  61447. /**
  61448. * Parse a node using the parsers and object stack.
  61449. * @param {Object.<string, Object.<string, ol.xml.Parser>>} parsersNS
  61450. * Parsers by namespace.
  61451. * @param {Node} node Node.
  61452. * @param {Array.<*>} objectStack Object stack.
  61453. * @param {*=} opt_this The object to use as `this`.
  61454. */
  61455. ol.xml.parseNode = function(parsersNS, node, objectStack, opt_this) {
  61456. var n;
  61457. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  61458. var parsers = parsersNS[n.namespaceURI];
  61459. if (parsers !== undefined) {
  61460. var parser = parsers[n.localName];
  61461. if (parser !== undefined) {
  61462. parser.call(opt_this, n, objectStack);
  61463. }
  61464. }
  61465. }
  61466. };
  61467. /**
  61468. * Push an object on top of the stack, parse and return the popped object.
  61469. * @param {T} object Object.
  61470. * @param {Object.<string, Object.<string, ol.xml.Parser>>} parsersNS
  61471. * Parsers by namespace.
  61472. * @param {Node} node Node.
  61473. * @param {Array.<*>} objectStack Object stack.
  61474. * @param {*=} opt_this The object to use as `this`.
  61475. * @return {T} Object.
  61476. * @template T
  61477. */
  61478. ol.xml.pushParseAndPop = function(
  61479. object, parsersNS, node, objectStack, opt_this) {
  61480. objectStack.push(object);
  61481. ol.xml.parseNode(parsersNS, node, objectStack, opt_this);
  61482. return objectStack.pop();
  61483. };
  61484. /**
  61485. * Walk through an array of `values` and call a serializer for each value.
  61486. * @param {Object.<string, Object.<string, ol.xml.Serializer>>} serializersNS
  61487. * Namespaced serializers.
  61488. * @param {function(this: T, *, Array.<*>, (string|undefined)): (Node|undefined)} nodeFactory
  61489. * Node factory. The `nodeFactory` creates the node whose namespace and name
  61490. * will be used to choose a node writer from `serializersNS`. This
  61491. * separation allows us to decide what kind of node to create, depending on
  61492. * the value we want to serialize. An example for this would be different
  61493. * geometry writers based on the geometry type.
  61494. * @param {Array.<*>} values Values to serialize. An example would be an array
  61495. * of {@link ol.Feature} instances.
  61496. * @param {Array.<*>} objectStack Node stack.
  61497. * @param {Array.<string>=} opt_keys Keys of the `values`. Will be passed to the
  61498. * `nodeFactory`. This is used for serializing object literals where the
  61499. * node name relates to the property key. The array length of `opt_keys` has
  61500. * to match the length of `values`. For serializing a sequence, `opt_keys`
  61501. * determines the order of the sequence.
  61502. * @param {T=} opt_this The object to use as `this` for the node factory and
  61503. * serializers.
  61504. * @template T
  61505. */
  61506. ol.xml.serialize = function(
  61507. serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) {
  61508. var length = (opt_keys !== undefined ? opt_keys : values).length;
  61509. var value, node;
  61510. for (var i = 0; i < length; ++i) {
  61511. value = values[i];
  61512. if (value !== undefined) {
  61513. node = nodeFactory.call(opt_this, value, objectStack,
  61514. opt_keys !== undefined ? opt_keys[i] : undefined);
  61515. if (node !== undefined) {
  61516. serializersNS[node.namespaceURI][node.localName]
  61517. .call(opt_this, node, value, objectStack);
  61518. }
  61519. }
  61520. }
  61521. };
  61522. /**
  61523. * @param {O} object Object.
  61524. * @param {Object.<string, Object.<string, ol.xml.Serializer>>} serializersNS
  61525. * Namespaced serializers.
  61526. * @param {function(this: T, *, Array.<*>, (string|undefined)): (Node|undefined)} nodeFactory
  61527. * Node factory. The `nodeFactory` creates the node whose namespace and name
  61528. * will be used to choose a node writer from `serializersNS`. This
  61529. * separation allows us to decide what kind of node to create, depending on
  61530. * the value we want to serialize. An example for this would be different
  61531. * geometry writers based on the geometry type.
  61532. * @param {Array.<*>} values Values to serialize. An example would be an array
  61533. * of {@link ol.Feature} instances.
  61534. * @param {Array.<*>} objectStack Node stack.
  61535. * @param {Array.<string>=} opt_keys Keys of the `values`. Will be passed to the
  61536. * `nodeFactory`. This is used for serializing object literals where the
  61537. * node name relates to the property key. The array length of `opt_keys` has
  61538. * to match the length of `values`. For serializing a sequence, `opt_keys`
  61539. * determines the order of the sequence.
  61540. * @param {T=} opt_this The object to use as `this` for the node factory and
  61541. * serializers.
  61542. * @return {O|undefined} Object.
  61543. * @template O, T
  61544. */
  61545. ol.xml.pushSerializeAndPop = function(object,
  61546. serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this) {
  61547. objectStack.push(object);
  61548. ol.xml.serialize(
  61549. serializersNS, nodeFactory, values, objectStack, opt_keys, opt_this);
  61550. return objectStack.pop();
  61551. };
  61552. goog.provide('ol.FeatureLoader');
  61553. goog.provide('ol.FeatureUrlFunction');
  61554. goog.provide('ol.featureloader');
  61555. goog.require('goog.asserts');
  61556. goog.require('goog.events');
  61557. goog.require('goog.net.EventType');
  61558. goog.require('goog.net.XhrIo');
  61559. goog.require('goog.net.XhrIo.ResponseType');
  61560. goog.require('ol.format.FormatType');
  61561. goog.require('ol.xml');
  61562. /**
  61563. * {@link ol.source.Vector} sources use a function of this type to load
  61564. * features.
  61565. *
  61566. * This function takes an {@link ol.Extent} representing the area to be loaded,
  61567. * a `{number}` representing the resolution (map units per pixel) and an
  61568. * {@link ol.proj.Projection} for the projection as arguments. `this` within
  61569. * the function is bound to the {@link ol.source.Vector} it's called from.
  61570. *
  61571. * The function is responsible for loading the features and adding them to the
  61572. * source.
  61573. * @api
  61574. * @typedef {function(this:ol.source.Vector, ol.Extent, number,
  61575. * ol.proj.Projection)}
  61576. */
  61577. ol.FeatureLoader;
  61578. /**
  61579. * {@link ol.source.Vector} sources use a function of this type to get the url
  61580. * to load features from.
  61581. *
  61582. * This function takes an {@link ol.Extent} representing the area to be loaded,
  61583. * a `{number}` representing the resolution (map units per pixel) and an
  61584. * {@link ol.proj.Projection} for the projection as arguments and returns a
  61585. * `{string}` representing the URL.
  61586. * @api
  61587. * @typedef {function(ol.Extent, number, ol.proj.Projection) : string}
  61588. */
  61589. ol.FeatureUrlFunction;
  61590. /**
  61591. * @param {string|ol.FeatureUrlFunction} url Feature URL service.
  61592. * @param {ol.format.Feature} format Feature format.
  61593. * @param {function(this:ol.source.Vector, Array.<ol.Feature>)} success
  61594. * Function called with the loaded features. Called with the vector
  61595. * source as `this`.
  61596. * @return {ol.FeatureLoader} The feature loader.
  61597. */
  61598. ol.featureloader.loadFeaturesXhr = function(url, format, success) {
  61599. return (
  61600. /**
  61601. * @param {ol.Extent} extent Extent.
  61602. * @param {number} resolution Resolution.
  61603. * @param {ol.proj.Projection} projection Projection.
  61604. * @this {ol.source.Vector}
  61605. */
  61606. function(extent, resolution, projection) {
  61607. var xhrIo = new goog.net.XhrIo();
  61608. xhrIo.setResponseType(goog.net.XhrIo.ResponseType.TEXT);
  61609. goog.events.listen(xhrIo, goog.net.EventType.COMPLETE,
  61610. /**
  61611. * @param {Event} event Event.
  61612. * @private
  61613. * @this {ol.source.Vector}
  61614. */
  61615. function(event) {
  61616. var xhrIo = event.target;
  61617. goog.asserts.assertInstanceof(xhrIo, goog.net.XhrIo,
  61618. 'event.target/xhrIo is an instance of goog.net.XhrIo');
  61619. if (xhrIo.isSuccess()) {
  61620. var type = format.getType();
  61621. /** @type {Document|Node|Object|string|undefined} */
  61622. var source;
  61623. if (type == ol.format.FormatType.JSON) {
  61624. source = xhrIo.getResponseText();
  61625. } else if (type == ol.format.FormatType.TEXT) {
  61626. source = xhrIo.getResponseText();
  61627. } else if (type == ol.format.FormatType.XML) {
  61628. if (!goog.userAgent.IE) {
  61629. source = xhrIo.getResponseXml();
  61630. }
  61631. if (!source) {
  61632. source = ol.xml.parse(xhrIo.getResponseText());
  61633. }
  61634. } else {
  61635. goog.asserts.fail('unexpected format type');
  61636. }
  61637. if (source) {
  61638. var features = format.readFeatures(source,
  61639. {featureProjection: projection});
  61640. success.call(this, features);
  61641. } else {
  61642. goog.asserts.fail('undefined or null source');
  61643. }
  61644. } else {
  61645. // FIXME
  61646. }
  61647. goog.dispose(xhrIo);
  61648. }, false, this);
  61649. if (goog.isFunction(url)) {
  61650. xhrIo.send(url(extent, resolution, projection));
  61651. } else {
  61652. xhrIo.send(url);
  61653. }
  61654. });
  61655. };
  61656. /**
  61657. * Create an XHR feature loader for a `url` and `format`. The feature loader
  61658. * loads features (with XHR), parses the features, and adds them to the
  61659. * vector source.
  61660. * @param {string|ol.FeatureUrlFunction} url Feature URL service.
  61661. * @param {ol.format.Feature} format Feature format.
  61662. * @return {ol.FeatureLoader} The feature loader.
  61663. * @api
  61664. */
  61665. ol.featureloader.xhr = function(url, format) {
  61666. return ol.featureloader.loadFeaturesXhr(url, format,
  61667. /**
  61668. * @param {Array.<ol.Feature>} features The loaded features.
  61669. * @this {ol.source.Vector}
  61670. */
  61671. function(features) {
  61672. this.addFeatures(features);
  61673. });
  61674. };
  61675. goog.provide('ol.LoadingStrategy');
  61676. goog.provide('ol.loadingstrategy');
  61677. goog.require('ol.TileCoord');
  61678. /**
  61679. * @typedef {function(ol.Extent, number): Array.<ol.Extent>}
  61680. * @api
  61681. */
  61682. ol.LoadingStrategy;
  61683. /**
  61684. * Strategy function for loading all features with a single request.
  61685. * @param {ol.Extent} extent Extent.
  61686. * @param {number} resolution Resolution.
  61687. * @return {Array.<ol.Extent>} Extents.
  61688. * @api
  61689. */
  61690. ol.loadingstrategy.all = function(extent, resolution) {
  61691. return [[-Infinity, -Infinity, Infinity, Infinity]];
  61692. };
  61693. /**
  61694. * Strategy function for loading features based on the view's extent and
  61695. * resolution.
  61696. * @param {ol.Extent} extent Extent.
  61697. * @param {number} resolution Resolution.
  61698. * @return {Array.<ol.Extent>} Extents.
  61699. * @api
  61700. */
  61701. ol.loadingstrategy.bbox = function(extent, resolution) {
  61702. return [extent];
  61703. };
  61704. /**
  61705. * Creates a strategy function for loading features based on a tile grid.
  61706. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  61707. * @return {function(ol.Extent, number): Array.<ol.Extent>} Loading strategy.
  61708. * @api
  61709. */
  61710. ol.loadingstrategy.tile = function(tileGrid) {
  61711. return (
  61712. /**
  61713. * @param {ol.Extent} extent Extent.
  61714. * @param {number} resolution Resolution.
  61715. * @return {Array.<ol.Extent>} Extents.
  61716. */
  61717. function(extent, resolution) {
  61718. var z = tileGrid.getZForResolution(resolution);
  61719. var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  61720. /** @type {Array.<ol.Extent>} */
  61721. var extents = [];
  61722. /** @type {ol.TileCoord} */
  61723. var tileCoord = [z, 0, 0];
  61724. for (tileCoord[1] = tileRange.minX; tileCoord[1] <= tileRange.maxX;
  61725. ++tileCoord[1]) {
  61726. for (tileCoord[2] = tileRange.minY; tileCoord[2] <= tileRange.maxY;
  61727. ++tileCoord[2]) {
  61728. extents.push(tileGrid.getTileCoordExtent(tileCoord));
  61729. }
  61730. }
  61731. return extents;
  61732. });
  61733. };
  61734. goog.provide('ol.ext.rbush');
  61735. /** @typedef {function(*)} */
  61736. ol.ext.rbush;
  61737. (function() {
  61738. var exports = {};
  61739. var module = {exports: exports};
  61740. var define;
  61741. /**
  61742. * @fileoverview
  61743. * @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, uselessCode, visibility}
  61744. */
  61745. /*
  61746. (c) 2013, Vladimir Agafonkin
  61747. RBush, a JavaScript library for high-performance 2D spatial indexing of points and rectangles.
  61748. https://github.com/mourner/rbush
  61749. */
  61750. (function () { 'use strict';
  61751. function rbush(maxEntries, format) {
  61752. // jshint newcap: false, validthis: true
  61753. if (!(this instanceof rbush)) return new rbush(maxEntries, format);
  61754. // max entries in a node is 9 by default; min node fill is 40% for best performance
  61755. this._maxEntries = Math.max(4, maxEntries || 9);
  61756. this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
  61757. if (format) {
  61758. this._initFormat(format);
  61759. }
  61760. this.clear();
  61761. }
  61762. rbush.prototype = {
  61763. all: function () {
  61764. return this._all(this.data, []);
  61765. },
  61766. search: function (bbox) {
  61767. var node = this.data,
  61768. result = [],
  61769. toBBox = this.toBBox;
  61770. if (!intersects(bbox, node.bbox)) return result;
  61771. var nodesToSearch = [],
  61772. i, len, child, childBBox;
  61773. while (node) {
  61774. for (i = 0, len = node.children.length; i < len; i++) {
  61775. child = node.children[i];
  61776. childBBox = node.leaf ? toBBox(child) : child.bbox;
  61777. if (intersects(bbox, childBBox)) {
  61778. if (node.leaf) result.push(child);
  61779. else if (contains(bbox, childBBox)) this._all(child, result);
  61780. else nodesToSearch.push(child);
  61781. }
  61782. }
  61783. node = nodesToSearch.pop();
  61784. }
  61785. return result;
  61786. },
  61787. load: function (data) {
  61788. if (!(data && data.length)) return this;
  61789. if (data.length < this._minEntries) {
  61790. for (var i = 0, len = data.length; i < len; i++) {
  61791. this.insert(data[i]);
  61792. }
  61793. return this;
  61794. }
  61795. // recursively build the tree with the given data from stratch using OMT algorithm
  61796. var node = this._build(data.slice(), 0, data.length - 1, 0);
  61797. if (!this.data.children.length) {
  61798. // save as is if tree is empty
  61799. this.data = node;
  61800. } else if (this.data.height === node.height) {
  61801. // split root if trees have the same height
  61802. this._splitRoot(this.data, node);
  61803. } else {
  61804. if (this.data.height < node.height) {
  61805. // swap trees if inserted one is bigger
  61806. var tmpNode = this.data;
  61807. this.data = node;
  61808. node = tmpNode;
  61809. }
  61810. // insert the small tree into the large tree at appropriate level
  61811. this._insert(node, this.data.height - node.height - 1, true);
  61812. }
  61813. return this;
  61814. },
  61815. insert: function (item) {
  61816. if (item) this._insert(item, this.data.height - 1);
  61817. return this;
  61818. },
  61819. clear: function () {
  61820. this.data = {
  61821. children: [],
  61822. height: 1,
  61823. bbox: empty(),
  61824. leaf: true
  61825. };
  61826. return this;
  61827. },
  61828. remove: function (item) {
  61829. if (!item) return this;
  61830. var node = this.data,
  61831. bbox = this.toBBox(item),
  61832. path = [],
  61833. indexes = [],
  61834. i, parent, index, goingUp;
  61835. // depth-first iterative tree traversal
  61836. while (node || path.length) {
  61837. if (!node) { // go up
  61838. node = path.pop();
  61839. parent = path[path.length - 1];
  61840. i = indexes.pop();
  61841. goingUp = true;
  61842. }
  61843. if (node.leaf) { // check current node
  61844. index = node.children.indexOf(item);
  61845. if (index !== -1) {
  61846. // item found, remove the item and condense tree upwards
  61847. node.children.splice(index, 1);
  61848. path.push(node);
  61849. this._condense(path);
  61850. return this;
  61851. }
  61852. }
  61853. if (!goingUp && !node.leaf && contains(node.bbox, bbox)) { // go down
  61854. path.push(node);
  61855. indexes.push(i);
  61856. i = 0;
  61857. parent = node;
  61858. node = node.children[0];
  61859. } else if (parent) { // go right
  61860. i++;
  61861. node = parent.children[i];
  61862. goingUp = false;
  61863. } else node = null; // nothing found
  61864. }
  61865. return this;
  61866. },
  61867. toBBox: function (item) { return item; },
  61868. compareMinX: function (a, b) { return a[0] - b[0]; },
  61869. compareMinY: function (a, b) { return a[1] - b[1]; },
  61870. toJSON: function () { return this.data; },
  61871. fromJSON: function (data) {
  61872. this.data = data;
  61873. return this;
  61874. },
  61875. _all: function (node, result) {
  61876. var nodesToSearch = [];
  61877. while (node) {
  61878. if (node.leaf) result.push.apply(result, node.children);
  61879. else nodesToSearch.push.apply(nodesToSearch, node.children);
  61880. node = nodesToSearch.pop();
  61881. }
  61882. return result;
  61883. },
  61884. _build: function (items, left, right, height) {
  61885. var N = right - left + 1,
  61886. M = this._maxEntries,
  61887. node;
  61888. if (N <= M) {
  61889. // reached leaf level; return leaf
  61890. node = {
  61891. children: items.slice(left, right + 1),
  61892. height: 1,
  61893. bbox: null,
  61894. leaf: true
  61895. };
  61896. calcBBox(node, this.toBBox);
  61897. return node;
  61898. }
  61899. if (!height) {
  61900. // target height of the bulk-loaded tree
  61901. height = Math.ceil(Math.log(N) / Math.log(M));
  61902. // target number of root entries to maximize storage utilization
  61903. M = Math.ceil(N / Math.pow(M, height - 1));
  61904. }
  61905. // TODO eliminate recursion?
  61906. node = {
  61907. children: [],
  61908. height: height,
  61909. bbox: null
  61910. };
  61911. // split the items into M mostly square tiles
  61912. var N2 = Math.ceil(N / M),
  61913. N1 = N2 * Math.ceil(Math.sqrt(M)),
  61914. i, j, right2, right3;
  61915. multiSelect(items, left, right, N1, this.compareMinX);
  61916. for (i = left; i <= right; i += N1) {
  61917. right2 = Math.min(i + N1 - 1, right);
  61918. multiSelect(items, i, right2, N2, this.compareMinY);
  61919. for (j = i; j <= right2; j += N2) {
  61920. right3 = Math.min(j + N2 - 1, right2);
  61921. // pack each entry recursively
  61922. node.children.push(this._build(items, j, right3, height - 1));
  61923. }
  61924. }
  61925. calcBBox(node, this.toBBox);
  61926. return node;
  61927. },
  61928. _chooseSubtree: function (bbox, node, level, path) {
  61929. var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
  61930. while (true) {
  61931. path.push(node);
  61932. if (node.leaf || path.length - 1 === level) break;
  61933. minArea = minEnlargement = Infinity;
  61934. for (i = 0, len = node.children.length; i < len; i++) {
  61935. child = node.children[i];
  61936. area = bboxArea(child.bbox);
  61937. enlargement = enlargedArea(bbox, child.bbox) - area;
  61938. // choose entry with the least area enlargement
  61939. if (enlargement < minEnlargement) {
  61940. minEnlargement = enlargement;
  61941. minArea = area < minArea ? area : minArea;
  61942. targetNode = child;
  61943. } else if (enlargement === minEnlargement) {
  61944. // otherwise choose one with the smallest area
  61945. if (area < minArea) {
  61946. minArea = area;
  61947. targetNode = child;
  61948. }
  61949. }
  61950. }
  61951. node = targetNode;
  61952. }
  61953. return node;
  61954. },
  61955. _insert: function (item, level, isNode) {
  61956. var toBBox = this.toBBox,
  61957. bbox = isNode ? item.bbox : toBBox(item),
  61958. insertPath = [];
  61959. // find the best node for accommodating the item, saving all nodes along the path too
  61960. var node = this._chooseSubtree(bbox, this.data, level, insertPath);
  61961. // put the item into the node
  61962. node.children.push(item);
  61963. extend(node.bbox, bbox);
  61964. // split on node overflow; propagate upwards if necessary
  61965. while (level >= 0) {
  61966. if (insertPath[level].children.length > this._maxEntries) {
  61967. this._split(insertPath, level);
  61968. level--;
  61969. } else break;
  61970. }
  61971. // adjust bboxes along the insertion path
  61972. this._adjustParentBBoxes(bbox, insertPath, level);
  61973. },
  61974. // split overflowed node into two
  61975. _split: function (insertPath, level) {
  61976. var node = insertPath[level],
  61977. M = node.children.length,
  61978. m = this._minEntries;
  61979. this._chooseSplitAxis(node, m, M);
  61980. var newNode = {
  61981. children: node.children.splice(this._chooseSplitIndex(node, m, M)),
  61982. height: node.height
  61983. };
  61984. if (node.leaf) newNode.leaf = true;
  61985. calcBBox(node, this.toBBox);
  61986. calcBBox(newNode, this.toBBox);
  61987. if (level) insertPath[level - 1].children.push(newNode);
  61988. else this._splitRoot(node, newNode);
  61989. },
  61990. _splitRoot: function (node, newNode) {
  61991. // split root node
  61992. this.data = {
  61993. children: [node, newNode],
  61994. height: node.height + 1
  61995. };
  61996. calcBBox(this.data, this.toBBox);
  61997. },
  61998. _chooseSplitIndex: function (node, m, M) {
  61999. var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
  62000. minOverlap = minArea = Infinity;
  62001. for (i = m; i <= M - m; i++) {
  62002. bbox1 = distBBox(node, 0, i, this.toBBox);
  62003. bbox2 = distBBox(node, i, M, this.toBBox);
  62004. overlap = intersectionArea(bbox1, bbox2);
  62005. area = bboxArea(bbox1) + bboxArea(bbox2);
  62006. // choose distribution with minimum overlap
  62007. if (overlap < minOverlap) {
  62008. minOverlap = overlap;
  62009. index = i;
  62010. minArea = area < minArea ? area : minArea;
  62011. } else if (overlap === minOverlap) {
  62012. // otherwise choose distribution with minimum area
  62013. if (area < minArea) {
  62014. minArea = area;
  62015. index = i;
  62016. }
  62017. }
  62018. }
  62019. return index;
  62020. },
  62021. // sorts node children by the best axis for split
  62022. _chooseSplitAxis: function (node, m, M) {
  62023. var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
  62024. compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
  62025. xMargin = this._allDistMargin(node, m, M, compareMinX),
  62026. yMargin = this._allDistMargin(node, m, M, compareMinY);
  62027. // if total distributions margin value is minimal for x, sort by minX,
  62028. // otherwise it's already sorted by minY
  62029. if (xMargin < yMargin) node.children.sort(compareMinX);
  62030. },
  62031. // total margin of all possible split distributions where each node is at least m full
  62032. _allDistMargin: function (node, m, M, compare) {
  62033. node.children.sort(compare);
  62034. var toBBox = this.toBBox,
  62035. leftBBox = distBBox(node, 0, m, toBBox),
  62036. rightBBox = distBBox(node, M - m, M, toBBox),
  62037. margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
  62038. i, child;
  62039. for (i = m; i < M - m; i++) {
  62040. child = node.children[i];
  62041. extend(leftBBox, node.leaf ? toBBox(child) : child.bbox);
  62042. margin += bboxMargin(leftBBox);
  62043. }
  62044. for (i = M - m - 1; i >= m; i--) {
  62045. child = node.children[i];
  62046. extend(rightBBox, node.leaf ? toBBox(child) : child.bbox);
  62047. margin += bboxMargin(rightBBox);
  62048. }
  62049. return margin;
  62050. },
  62051. _adjustParentBBoxes: function (bbox, path, level) {
  62052. // adjust bboxes along the given tree path
  62053. for (var i = level; i >= 0; i--) {
  62054. extend(path[i].bbox, bbox);
  62055. }
  62056. },
  62057. _condense: function (path) {
  62058. // go through the path, removing empty nodes and updating bboxes
  62059. for (var i = path.length - 1, siblings; i >= 0; i--) {
  62060. if (path[i].children.length === 0) {
  62061. if (i > 0) {
  62062. siblings = path[i - 1].children;
  62063. siblings.splice(siblings.indexOf(path[i]), 1);
  62064. } else this.clear();
  62065. } else calcBBox(path[i], this.toBBox);
  62066. }
  62067. },
  62068. _initFormat: function (format) {
  62069. // data format (minX, minY, maxX, maxY accessors)
  62070. // uses eval-type function compilation instead of just accepting a toBBox function
  62071. // because the algorithms are very sensitive to sorting functions performance,
  62072. // so they should be dead simple and without inner calls
  62073. // jshint evil: true
  62074. var compareArr = ['return a', ' - b', ';'];
  62075. this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
  62076. this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
  62077. this.toBBox = new Function('a', 'return [a' + format.join(', a') + '];');
  62078. }
  62079. };
  62080. // calculate node's bbox from bboxes of its children
  62081. function calcBBox(node, toBBox) {
  62082. node.bbox = distBBox(node, 0, node.children.length, toBBox);
  62083. }
  62084. // min bounding rectangle of node children from k to p-1
  62085. function distBBox(node, k, p, toBBox) {
  62086. var bbox = empty();
  62087. for (var i = k, child; i < p; i++) {
  62088. child = node.children[i];
  62089. extend(bbox, node.leaf ? toBBox(child) : child.bbox);
  62090. }
  62091. return bbox;
  62092. }
  62093. function empty() { return [Infinity, Infinity, -Infinity, -Infinity]; }
  62094. function extend(a, b) {
  62095. a[0] = Math.min(a[0], b[0]);
  62096. a[1] = Math.min(a[1], b[1]);
  62097. a[2] = Math.max(a[2], b[2]);
  62098. a[3] = Math.max(a[3], b[3]);
  62099. return a;
  62100. }
  62101. function compareNodeMinX(a, b) { return a.bbox[0] - b.bbox[0]; }
  62102. function compareNodeMinY(a, b) { return a.bbox[1] - b.bbox[1]; }
  62103. function bboxArea(a) { return (a[2] - a[0]) * (a[3] - a[1]); }
  62104. function bboxMargin(a) { return (a[2] - a[0]) + (a[3] - a[1]); }
  62105. function enlargedArea(a, b) {
  62106. return (Math.max(b[2], a[2]) - Math.min(b[0], a[0])) *
  62107. (Math.max(b[3], a[3]) - Math.min(b[1], a[1]));
  62108. }
  62109. function intersectionArea(a, b) {
  62110. var minX = Math.max(a[0], b[0]),
  62111. minY = Math.max(a[1], b[1]),
  62112. maxX = Math.min(a[2], b[2]),
  62113. maxY = Math.min(a[3], b[3]);
  62114. return Math.max(0, maxX - minX) *
  62115. Math.max(0, maxY - minY);
  62116. }
  62117. function contains(a, b) {
  62118. return a[0] <= b[0] &&
  62119. a[1] <= b[1] &&
  62120. b[2] <= a[2] &&
  62121. b[3] <= a[3];
  62122. }
  62123. function intersects(a, b) {
  62124. return b[0] <= a[2] &&
  62125. b[1] <= a[3] &&
  62126. b[2] >= a[0] &&
  62127. b[3] >= a[1];
  62128. }
  62129. // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  62130. // combines selection algorithm with binary divide & conquer approach
  62131. function multiSelect(arr, left, right, n, compare) {
  62132. var stack = [left, right],
  62133. mid;
  62134. while (stack.length) {
  62135. right = stack.pop();
  62136. left = stack.pop();
  62137. if (right - left <= n) continue;
  62138. mid = left + Math.ceil((right - left) / n / 2) * n;
  62139. select(arr, left, right, mid, compare);
  62140. stack.push(left, mid, mid, right);
  62141. }
  62142. }
  62143. // sort array between left and right (inclusive) so that the smallest k elements come first (unordered)
  62144. function select(arr, left, right, k, compare) {
  62145. var n, i, z, s, sd, newLeft, newRight, t, j;
  62146. while (right > left) {
  62147. if (right - left > 600) {
  62148. n = right - left + 1;
  62149. i = k - left + 1;
  62150. z = Math.log(n);
  62151. s = 0.5 * Math.exp(2 * z / 3);
  62152. sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (i - n / 2 < 0 ? -1 : 1);
  62153. newLeft = Math.max(left, Math.floor(k - i * s / n + sd));
  62154. newRight = Math.min(right, Math.floor(k + (n - i) * s / n + sd));
  62155. select(arr, newLeft, newRight, k, compare);
  62156. }
  62157. t = arr[k];
  62158. i = left;
  62159. j = right;
  62160. swap(arr, left, k);
  62161. if (compare(arr[right], t) > 0) swap(arr, left, right);
  62162. while (i < j) {
  62163. swap(arr, i, j);
  62164. i++;
  62165. j--;
  62166. while (compare(arr[i], t) < 0) i++;
  62167. while (compare(arr[j], t) > 0) j--;
  62168. }
  62169. if (compare(arr[left], t) === 0) swap(arr, left, j);
  62170. else {
  62171. j++;
  62172. swap(arr, j, right);
  62173. }
  62174. if (j <= k) left = j + 1;
  62175. if (k <= j) right = j - 1;
  62176. }
  62177. }
  62178. function swap(arr, i, j) {
  62179. var tmp = arr[i];
  62180. arr[i] = arr[j];
  62181. arr[j] = tmp;
  62182. }
  62183. // export as AMD/CommonJS module or global variable
  62184. if (typeof define === 'function' && define.amd) define('rbush', function() { return rbush; });
  62185. else if (typeof module !== 'undefined') module.exports = rbush;
  62186. else if (typeof self !== 'undefined') self.rbush = rbush;
  62187. else window.rbush = rbush;
  62188. })();
  62189. ol.ext.rbush = module.exports;
  62190. })();
  62191. goog.provide('ol.structs.RBush');
  62192. goog.require('goog.asserts');
  62193. goog.require('goog.object');
  62194. goog.require('ol.ext.rbush');
  62195. goog.require('ol.extent');
  62196. /**
  62197. * Wrapper around the RBush by Vladimir Agafonkin.
  62198. *
  62199. * @constructor
  62200. * @param {number=} opt_maxEntries Max entries.
  62201. * @see https://github.com/mourner/rbush
  62202. * @struct
  62203. * @template T
  62204. */
  62205. ol.structs.RBush = function(opt_maxEntries) {
  62206. /**
  62207. * @private
  62208. */
  62209. this.rbush_ = ol.ext.rbush(opt_maxEntries);
  62210. /**
  62211. * A mapping between the objects added to this rbush wrapper
  62212. * and the objects that are actually added to the internal rbush.
  62213. * @private
  62214. * @type {Object.<number, Object>}
  62215. */
  62216. this.items_ = {};
  62217. if (goog.DEBUG) {
  62218. /**
  62219. * @private
  62220. * @type {number}
  62221. */
  62222. this.readers_ = 0;
  62223. }
  62224. };
  62225. /**
  62226. * Insert a value into the RBush.
  62227. * @param {ol.Extent} extent Extent.
  62228. * @param {T} value Value.
  62229. */
  62230. ol.structs.RBush.prototype.insert = function(extent, value) {
  62231. if (goog.DEBUG && this.readers_) {
  62232. throw new Error('Can not insert value while reading');
  62233. }
  62234. var item = [
  62235. extent[0],
  62236. extent[1],
  62237. extent[2],
  62238. extent[3],
  62239. value
  62240. ];
  62241. this.rbush_.insert(item);
  62242. // remember the object that was added to the internal rbush
  62243. goog.asserts.assert(
  62244. !goog.object.containsKey(this.items_, goog.getUid(value)),
  62245. 'uid (%s) of value (%s) already exists', goog.getUid(value), value);
  62246. this.items_[goog.getUid(value)] = item;
  62247. };
  62248. /**
  62249. * Bulk-insert values into the RBush.
  62250. * @param {Array.<ol.Extent>} extents Extents.
  62251. * @param {Array.<T>} values Values.
  62252. */
  62253. ol.structs.RBush.prototype.load = function(extents, values) {
  62254. if (goog.DEBUG && this.readers_) {
  62255. throw new Error('Can not insert values while reading');
  62256. }
  62257. goog.asserts.assert(extents.length === values.length,
  62258. 'extens and values must have same length (%s === %s)',
  62259. extents.length, values.length);
  62260. var items = new Array(values.length);
  62261. for (var i = 0, l = values.length; i < l; i++) {
  62262. var extent = extents[i];
  62263. var value = values[i];
  62264. var item = [
  62265. extent[0],
  62266. extent[1],
  62267. extent[2],
  62268. extent[3],
  62269. value
  62270. ];
  62271. items[i] = item;
  62272. goog.asserts.assert(
  62273. !goog.object.containsKey(this.items_, goog.getUid(value)),
  62274. 'uid (%s) of value (%s) already exists', goog.getUid(value), value);
  62275. this.items_[goog.getUid(value)] = item;
  62276. }
  62277. this.rbush_.load(items);
  62278. };
  62279. /**
  62280. * Remove a value from the RBush.
  62281. * @param {T} value Value.
  62282. * @return {boolean} Removed.
  62283. */
  62284. ol.structs.RBush.prototype.remove = function(value) {
  62285. if (goog.DEBUG && this.readers_) {
  62286. throw new Error('Can not remove value while reading');
  62287. }
  62288. var uid = goog.getUid(value);
  62289. goog.asserts.assert(goog.object.containsKey(this.items_, uid),
  62290. 'uid (%s) of value (%s) does not exist', uid, value);
  62291. // get the object in which the value was wrapped when adding to the
  62292. // internal rbush. then use that object to do the removal.
  62293. var item = this.items_[uid];
  62294. delete this.items_[uid];
  62295. return this.rbush_.remove(item) !== null;
  62296. };
  62297. /**
  62298. * Update the extent of a value in the RBush.
  62299. * @param {ol.Extent} extent Extent.
  62300. * @param {T} value Value.
  62301. */
  62302. ol.structs.RBush.prototype.update = function(extent, value) {
  62303. var uid = goog.getUid(value);
  62304. goog.asserts.assert(goog.object.containsKey(this.items_, uid),
  62305. 'uid (%s) of value (%s) does not exist', uid, value);
  62306. var item = this.items_[uid];
  62307. if (!ol.extent.equals(item.slice(0, 4), extent)) {
  62308. if (goog.DEBUG && this.readers_) {
  62309. throw new Error('Can not update extent while reading');
  62310. }
  62311. this.remove(value);
  62312. this.insert(extent, value);
  62313. }
  62314. };
  62315. /**
  62316. * Return all values in the RBush.
  62317. * @return {Array.<T>} All.
  62318. */
  62319. ol.structs.RBush.prototype.getAll = function() {
  62320. var items = this.rbush_.all();
  62321. return items.map(function(item) {
  62322. return item[4];
  62323. });
  62324. };
  62325. /**
  62326. * Return all values in the given extent.
  62327. * @param {ol.Extent} extent Extent.
  62328. * @return {Array.<T>} All in extent.
  62329. */
  62330. ol.structs.RBush.prototype.getInExtent = function(extent) {
  62331. var items = this.rbush_.search(extent);
  62332. return items.map(function(item) {
  62333. return item[4];
  62334. });
  62335. };
  62336. /**
  62337. * Calls a callback function with each value in the tree.
  62338. * If the callback returns a truthy value, this value is returned without
  62339. * checking the rest of the tree.
  62340. * @param {function(this: S, T): *} callback Callback.
  62341. * @param {S=} opt_this The object to use as `this` in `callback`.
  62342. * @return {*} Callback return value.
  62343. * @template S
  62344. */
  62345. ol.structs.RBush.prototype.forEach = function(callback, opt_this) {
  62346. if (goog.DEBUG) {
  62347. ++this.readers_;
  62348. try {
  62349. return this.forEach_(this.getAll(), callback, opt_this);
  62350. } finally {
  62351. --this.readers_;
  62352. }
  62353. } else {
  62354. return this.forEach_(this.getAll(), callback, opt_this);
  62355. }
  62356. };
  62357. /**
  62358. * Calls a callback function with each value in the provided extent.
  62359. * @param {ol.Extent} extent Extent.
  62360. * @param {function(this: S, T): *} callback Callback.
  62361. * @param {S=} opt_this The object to use as `this` in `callback`.
  62362. * @return {*} Callback return value.
  62363. * @template S
  62364. */
  62365. ol.structs.RBush.prototype.forEachInExtent =
  62366. function(extent, callback, opt_this) {
  62367. if (goog.DEBUG) {
  62368. ++this.readers_;
  62369. try {
  62370. return this.forEach_(this.getInExtent(extent), callback, opt_this);
  62371. } finally {
  62372. --this.readers_;
  62373. }
  62374. } else {
  62375. return this.forEach_(this.getInExtent(extent), callback, opt_this);
  62376. }
  62377. };
  62378. /**
  62379. * @param {Array.<T>} values Values.
  62380. * @param {function(this: S, T): *} callback Callback.
  62381. * @param {S=} opt_this The object to use as `this` in `callback`.
  62382. * @private
  62383. * @return {*} Callback return value.
  62384. * @template S
  62385. */
  62386. ol.structs.RBush.prototype.forEach_ = function(values, callback, opt_this) {
  62387. var result;
  62388. for (var i = 0, l = values.length; i < l; i++) {
  62389. result = callback.call(opt_this, values[i]);
  62390. if (result) {
  62391. return result;
  62392. }
  62393. }
  62394. return result;
  62395. };
  62396. /**
  62397. * @return {boolean} Is empty.
  62398. */
  62399. ol.structs.RBush.prototype.isEmpty = function() {
  62400. return goog.object.isEmpty(this.items_);
  62401. };
  62402. /**
  62403. * Remove all values from the RBush.
  62404. */
  62405. ol.structs.RBush.prototype.clear = function() {
  62406. this.rbush_.clear();
  62407. this.items_ = {};
  62408. };
  62409. /**
  62410. * @param {ol.Extent=} opt_extent Extent.
  62411. * @return {ol.Extent} Extent.
  62412. */
  62413. ol.structs.RBush.prototype.getExtent = function(opt_extent) {
  62414. // FIXME add getExtent() to rbush
  62415. return this.rbush_.data.bbox;
  62416. };
  62417. // FIXME bulk feature upload - suppress events
  62418. // FIXME make change-detection more refined (notably, geometry hint)
  62419. goog.provide('ol.source.Vector');
  62420. goog.provide('ol.source.VectorEvent');
  62421. goog.provide('ol.source.VectorEventType');
  62422. goog.require('goog.array');
  62423. goog.require('goog.asserts');
  62424. goog.require('goog.events');
  62425. goog.require('goog.events.Event');
  62426. goog.require('goog.events.EventType');
  62427. goog.require('goog.object');
  62428. goog.require('ol');
  62429. goog.require('ol.Collection');
  62430. goog.require('ol.CollectionEventType');
  62431. goog.require('ol.Extent');
  62432. goog.require('ol.Feature');
  62433. goog.require('ol.FeatureLoader');
  62434. goog.require('ol.LoadingStrategy');
  62435. goog.require('ol.ObjectEventType');
  62436. goog.require('ol.extent');
  62437. goog.require('ol.featureloader');
  62438. goog.require('ol.loadingstrategy');
  62439. goog.require('ol.proj');
  62440. goog.require('ol.source.Source');
  62441. goog.require('ol.source.State');
  62442. goog.require('ol.structs.RBush');
  62443. /**
  62444. * @enum {string}
  62445. */
  62446. ol.source.VectorEventType = {
  62447. /**
  62448. * Triggered when a feature is added to the source.
  62449. * @event ol.source.VectorEvent#addfeature
  62450. * @api stable
  62451. */
  62452. ADDFEATURE: 'addfeature',
  62453. /**
  62454. * Triggered when a feature is updated.
  62455. * @event ol.source.VectorEvent#changefeature
  62456. * @api
  62457. */
  62458. CHANGEFEATURE: 'changefeature',
  62459. /**
  62460. * Triggered when the clear method is called on the source.
  62461. * @event ol.source.VectorEvent#clear
  62462. * @api
  62463. */
  62464. CLEAR: 'clear',
  62465. /**
  62466. * Triggered when a feature is removed from the source.
  62467. * See {@link ol.source.Vector#clear source.clear()} for exceptions.
  62468. * @event ol.source.VectorEvent#removefeature
  62469. * @api stable
  62470. */
  62471. REMOVEFEATURE: 'removefeature'
  62472. };
  62473. /**
  62474. * @classdesc
  62475. * Provides a source of features for vector layers.
  62476. *
  62477. * @constructor
  62478. * @extends {ol.source.Source}
  62479. * @fires ol.source.VectorEvent
  62480. * @param {olx.source.VectorOptions=} opt_options Vector source options.
  62481. * @api stable
  62482. */
  62483. ol.source.Vector = function(opt_options) {
  62484. var options = opt_options || {};
  62485. goog.base(this, {
  62486. attributions: options.attributions,
  62487. logo: options.logo,
  62488. projection: undefined,
  62489. state: ol.source.State.READY,
  62490. wrapX: options.wrapX !== undefined ? options.wrapX : true
  62491. });
  62492. /**
  62493. * @private
  62494. * @type {ol.FeatureLoader}
  62495. */
  62496. this.loader_ = ol.nullFunction;
  62497. if (options.loader !== undefined) {
  62498. this.loader_ = options.loader;
  62499. } else if (options.url !== undefined) {
  62500. goog.asserts.assert(options.format !== undefined,
  62501. 'format must be set when url is set');
  62502. // create a XHR feature loader for "url" and "format"
  62503. this.loader_ = ol.featureloader.xhr(options.url, options.format);
  62504. }
  62505. /**
  62506. * @private
  62507. * @type {ol.LoadingStrategy}
  62508. */
  62509. this.strategy_ = options.strategy !== undefined ? options.strategy :
  62510. ol.loadingstrategy.all;
  62511. var useSpatialIndex =
  62512. options.useSpatialIndex !== undefined ? options.useSpatialIndex : true;
  62513. /**
  62514. * @private
  62515. * @type {ol.structs.RBush.<ol.Feature>}
  62516. */
  62517. this.featuresRtree_ = useSpatialIndex ? new ol.structs.RBush() : null;
  62518. /**
  62519. * @private
  62520. * @type {ol.structs.RBush.<{extent: ol.Extent}>}
  62521. */
  62522. this.loadedExtentsRtree_ = new ol.structs.RBush();
  62523. /**
  62524. * @private
  62525. * @type {Object.<string, ol.Feature>}
  62526. */
  62527. this.nullGeometryFeatures_ = {};
  62528. /**
  62529. * A lookup of features by id (the return from feature.getId()).
  62530. * @private
  62531. * @type {Object.<string, ol.Feature>}
  62532. */
  62533. this.idIndex_ = {};
  62534. /**
  62535. * A lookup of features without id (keyed by goog.getUid(feature)).
  62536. * @private
  62537. * @type {Object.<string, ol.Feature>}
  62538. */
  62539. this.undefIdIndex_ = {};
  62540. /**
  62541. * @private
  62542. * @type {Object.<string, Array.<goog.events.Key>>}
  62543. */
  62544. this.featureChangeKeys_ = {};
  62545. /**
  62546. * @private
  62547. * @type {ol.Collection.<ol.Feature>}
  62548. */
  62549. this.featuresCollection_ = null;
  62550. var collection, features;
  62551. if (options.features instanceof ol.Collection) {
  62552. collection = options.features;
  62553. features = collection.getArray();
  62554. } else if (goog.isArray(options.features)) {
  62555. features = options.features;
  62556. }
  62557. if (!useSpatialIndex && collection === undefined) {
  62558. collection = new ol.Collection(features);
  62559. }
  62560. if (features !== undefined) {
  62561. this.addFeaturesInternal(features);
  62562. }
  62563. if (collection !== undefined) {
  62564. this.bindFeaturesCollection_(collection);
  62565. }
  62566. };
  62567. goog.inherits(ol.source.Vector, ol.source.Source);
  62568. /**
  62569. * Add a single feature to the source. If you want to add a batch of features
  62570. * at once, call {@link ol.source.Vector#addFeatures source.addFeatures()}
  62571. * instead.
  62572. * @param {ol.Feature} feature Feature to add.
  62573. * @api stable
  62574. */
  62575. ol.source.Vector.prototype.addFeature = function(feature) {
  62576. this.addFeatureInternal(feature);
  62577. this.changed();
  62578. };
  62579. /**
  62580. * Add a feature without firing a `change` event.
  62581. * @param {ol.Feature} feature Feature.
  62582. * @protected
  62583. */
  62584. ol.source.Vector.prototype.addFeatureInternal = function(feature) {
  62585. var featureKey = goog.getUid(feature).toString();
  62586. if (!this.addToIndex_(featureKey, feature)) {
  62587. return;
  62588. }
  62589. this.setupChangeEvents_(featureKey, feature);
  62590. var geometry = feature.getGeometry();
  62591. if (geometry) {
  62592. var extent = geometry.getExtent();
  62593. if (this.featuresRtree_) {
  62594. this.featuresRtree_.insert(extent, feature);
  62595. }
  62596. } else {
  62597. this.nullGeometryFeatures_[featureKey] = feature;
  62598. }
  62599. this.dispatchEvent(
  62600. new ol.source.VectorEvent(ol.source.VectorEventType.ADDFEATURE, feature));
  62601. };
  62602. /**
  62603. * @param {string} featureKey
  62604. * @param {ol.Feature} feature
  62605. * @private
  62606. */
  62607. ol.source.Vector.prototype.setupChangeEvents_ = function(featureKey, feature) {
  62608. goog.asserts.assert(!(featureKey in this.featureChangeKeys_),
  62609. 'key (%s) not yet registered in featureChangeKey', featureKey);
  62610. this.featureChangeKeys_[featureKey] = [
  62611. goog.events.listen(feature,
  62612. goog.events.EventType.CHANGE,
  62613. this.handleFeatureChange_, false, this),
  62614. goog.events.listen(feature,
  62615. ol.ObjectEventType.PROPERTYCHANGE,
  62616. this.handleFeatureChange_, false, this)
  62617. ];
  62618. };
  62619. /**
  62620. * @param {string} featureKey
  62621. * @param {ol.Feature} feature
  62622. * @return {boolean} `true` if the feature is "valid", in the sense that it is
  62623. * also a candidate for insertion into the Rtree, otherwise `false`.
  62624. * @private
  62625. */
  62626. ol.source.Vector.prototype.addToIndex_ = function(featureKey, feature) {
  62627. var valid = true;
  62628. var id = feature.getId();
  62629. if (id !== undefined) {
  62630. if (!(id.toString() in this.idIndex_)) {
  62631. this.idIndex_[id.toString()] = feature;
  62632. } else {
  62633. valid = false;
  62634. }
  62635. } else {
  62636. goog.asserts.assert(!(featureKey in this.undefIdIndex_),
  62637. 'Feature already added to the source');
  62638. this.undefIdIndex_[featureKey] = feature;
  62639. }
  62640. return valid;
  62641. };
  62642. /**
  62643. * Add a batch of features to the source.
  62644. * @param {Array.<ol.Feature>} features Features to add.
  62645. * @api stable
  62646. */
  62647. ol.source.Vector.prototype.addFeatures = function(features) {
  62648. this.addFeaturesInternal(features);
  62649. this.changed();
  62650. };
  62651. /**
  62652. * Add features without firing a `change` event.
  62653. * @param {Array.<ol.Feature>} features Features.
  62654. * @protected
  62655. */
  62656. ol.source.Vector.prototype.addFeaturesInternal = function(features) {
  62657. var featureKey, i, length, feature;
  62658. var extents = [];
  62659. var newFeatures = [];
  62660. var geometryFeatures = [];
  62661. for (i = 0, length = features.length; i < length; i++) {
  62662. feature = features[i];
  62663. featureKey = goog.getUid(feature).toString();
  62664. if (this.addToIndex_(featureKey, feature)) {
  62665. newFeatures.push(feature);
  62666. }
  62667. }
  62668. for (i = 0, length = newFeatures.length; i < length; i++) {
  62669. feature = newFeatures[i];
  62670. featureKey = goog.getUid(feature).toString();
  62671. this.setupChangeEvents_(featureKey, feature);
  62672. var geometry = feature.getGeometry();
  62673. if (geometry) {
  62674. var extent = geometry.getExtent();
  62675. extents.push(extent);
  62676. geometryFeatures.push(feature);
  62677. } else {
  62678. this.nullGeometryFeatures_[featureKey] = feature;
  62679. }
  62680. }
  62681. if (this.featuresRtree_) {
  62682. this.featuresRtree_.load(extents, geometryFeatures);
  62683. }
  62684. for (i = 0, length = newFeatures.length; i < length; i++) {
  62685. this.dispatchEvent(new ol.source.VectorEvent(
  62686. ol.source.VectorEventType.ADDFEATURE, newFeatures[i]));
  62687. }
  62688. };
  62689. /**
  62690. * @param {!ol.Collection.<ol.Feature>} collection Collection.
  62691. * @private
  62692. */
  62693. ol.source.Vector.prototype.bindFeaturesCollection_ = function(collection) {
  62694. goog.asserts.assert(!this.featuresCollection_,
  62695. 'bindFeaturesCollection can only be called once');
  62696. var modifyingCollection = false;
  62697. goog.events.listen(this, ol.source.VectorEventType.ADDFEATURE,
  62698. function(evt) {
  62699. if (!modifyingCollection) {
  62700. modifyingCollection = true;
  62701. collection.push(evt.feature);
  62702. modifyingCollection = false;
  62703. }
  62704. });
  62705. goog.events.listen(this, ol.source.VectorEventType.REMOVEFEATURE,
  62706. function(evt) {
  62707. if (!modifyingCollection) {
  62708. modifyingCollection = true;
  62709. collection.remove(evt.feature);
  62710. modifyingCollection = false;
  62711. }
  62712. });
  62713. goog.events.listen(collection, ol.CollectionEventType.ADD,
  62714. function(evt) {
  62715. if (!modifyingCollection) {
  62716. var feature = evt.element;
  62717. goog.asserts.assertInstanceof(feature, ol.Feature);
  62718. modifyingCollection = true;
  62719. this.addFeature(feature);
  62720. modifyingCollection = false;
  62721. }
  62722. }, false, this);
  62723. goog.events.listen(collection, ol.CollectionEventType.REMOVE,
  62724. function(evt) {
  62725. if (!modifyingCollection) {
  62726. var feature = evt.element;
  62727. goog.asserts.assertInstanceof(feature, ol.Feature);
  62728. modifyingCollection = true;
  62729. this.removeFeature(feature);
  62730. modifyingCollection = false;
  62731. }
  62732. }, false, this);
  62733. this.featuresCollection_ = collection;
  62734. };
  62735. /**
  62736. * Remove all features from the source.
  62737. * @param {boolean=} opt_fast Skip dispatching of {@link removefeature} events.
  62738. * @api stable
  62739. */
  62740. ol.source.Vector.prototype.clear = function(opt_fast) {
  62741. if (opt_fast) {
  62742. for (var featureId in this.featureChangeKeys_) {
  62743. var keys = this.featureChangeKeys_[featureId];
  62744. keys.forEach(goog.events.unlistenByKey);
  62745. }
  62746. if (!this.featuresCollection_) {
  62747. this.featureChangeKeys_ = {};
  62748. this.idIndex_ = {};
  62749. this.undefIdIndex_ = {};
  62750. }
  62751. } else {
  62752. var rmFeatureInternal = this.removeFeatureInternal;
  62753. if (this.featuresRtree_) {
  62754. this.featuresRtree_.forEach(rmFeatureInternal, this);
  62755. goog.object.forEach(this.nullGeometryFeatures_, rmFeatureInternal, this);
  62756. }
  62757. }
  62758. if (this.featuresCollection_) {
  62759. this.featuresCollection_.clear();
  62760. }
  62761. goog.asserts.assert(goog.object.isEmpty(this.featureChangeKeys_),
  62762. 'featureChangeKeys is an empty object now');
  62763. goog.asserts.assert(goog.object.isEmpty(this.idIndex_),
  62764. 'idIndex is an empty object now');
  62765. goog.asserts.assert(goog.object.isEmpty(this.undefIdIndex_),
  62766. 'undefIdIndex is an empty object now');
  62767. if (this.featuresRtree_) {
  62768. this.featuresRtree_.clear();
  62769. }
  62770. this.loadedExtentsRtree_.clear();
  62771. this.nullGeometryFeatures_ = {};
  62772. var clearEvent = new ol.source.VectorEvent(ol.source.VectorEventType.CLEAR);
  62773. this.dispatchEvent(clearEvent);
  62774. this.changed();
  62775. };
  62776. /**
  62777. * Iterate through all features on the source, calling the provided callback
  62778. * with each one. If the callback returns any "truthy" value, iteration will
  62779. * stop and the function will return the same value.
  62780. *
  62781. * @param {function(this: T, ol.Feature): S} callback Called with each feature
  62782. * on the source. Return a truthy value to stop iteration.
  62783. * @param {T=} opt_this The object to use as `this` in the callback.
  62784. * @return {S|undefined} The return value from the last call to the callback.
  62785. * @template T,S
  62786. * @api stable
  62787. */
  62788. ol.source.Vector.prototype.forEachFeature = function(callback, opt_this) {
  62789. if (this.featuresRtree_) {
  62790. return this.featuresRtree_.forEach(callback, opt_this);
  62791. } else if (this.featuresCollection_) {
  62792. return this.featuresCollection_.forEach(callback, opt_this);
  62793. }
  62794. };
  62795. /**
  62796. * Iterate through all features whose geometries contain the provided
  62797. * coordinate, calling the callback with each feature. If the callback returns
  62798. * a "truthy" value, iteration will stop and the function will return the same
  62799. * value.
  62800. *
  62801. * @param {ol.Coordinate} coordinate Coordinate.
  62802. * @param {function(this: T, ol.Feature): S} callback Called with each feature
  62803. * whose goemetry contains the provided coordinate.
  62804. * @param {T=} opt_this The object to use as `this` in the callback.
  62805. * @return {S|undefined} The return value from the last call to the callback.
  62806. * @template T,S
  62807. */
  62808. ol.source.Vector.prototype.forEachFeatureAtCoordinateDirect =
  62809. function(coordinate, callback, opt_this) {
  62810. var extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]];
  62811. return this.forEachFeatureInExtent(extent, function(feature) {
  62812. var geometry = feature.getGeometry();
  62813. goog.asserts.assert(geometry, 'feature geometry is defined and not null');
  62814. if (geometry.containsCoordinate(coordinate)) {
  62815. return callback.call(opt_this, feature);
  62816. } else {
  62817. return undefined;
  62818. }
  62819. });
  62820. };
  62821. /**
  62822. * Iterate through all features whose bounding box intersects the provided
  62823. * extent (note that the feature's geometry may not intersect the extent),
  62824. * calling the callback with each feature. If the callback returns a "truthy"
  62825. * value, iteration will stop and the function will return the same value.
  62826. *
  62827. * If you are interested in features whose geometry intersects an extent, call
  62828. * the {@link ol.source.Vector#forEachFeatureIntersectingExtent
  62829. * source.forEachFeatureIntersectingExtent()} method instead.
  62830. *
  62831. * When `useSpatialIndex` is set to false, this method will loop through all
  62832. * features, equivalent to {@link ol.source.Vector#forEachFeature}.
  62833. *
  62834. * @param {ol.Extent} extent Extent.
  62835. * @param {function(this: T, ol.Feature): S} callback Called with each feature
  62836. * whose bounding box intersects the provided extent.
  62837. * @param {T=} opt_this The object to use as `this` in the callback.
  62838. * @return {S|undefined} The return value from the last call to the callback.
  62839. * @template T,S
  62840. * @api
  62841. */
  62842. ol.source.Vector.prototype.forEachFeatureInExtent =
  62843. function(extent, callback, opt_this) {
  62844. if (this.featuresRtree_) {
  62845. return this.featuresRtree_.forEachInExtent(extent, callback, opt_this);
  62846. } else if (this.featuresCollection_) {
  62847. return this.featuresCollection_.forEach(callback, opt_this);
  62848. }
  62849. };
  62850. /**
  62851. * @param {ol.Extent} extent Extent.
  62852. * @param {number} resolution Resolution.
  62853. * @param {function(this: T, ol.Feature): S} f Callback.
  62854. * @param {T=} opt_this The object to use as `this` in `f`.
  62855. * @return {S|undefined}
  62856. * @template T,S
  62857. */
  62858. ol.source.Vector.prototype.forEachFeatureInExtentAtResolution =
  62859. function(extent, resolution, f, opt_this) {
  62860. return this.forEachFeatureInExtent(extent, f, opt_this);
  62861. };
  62862. /**
  62863. * Iterate through all features whose geometry intersects the provided extent,
  62864. * calling the callback with each feature. If the callback returns a "truthy"
  62865. * value, iteration will stop and the function will return the same value.
  62866. *
  62867. * If you only want to test for bounding box intersection, call the
  62868. * {@link ol.source.Vector#forEachFeatureInExtent
  62869. * source.forEachFeatureInExtent()} method instead.
  62870. *
  62871. * @param {ol.Extent} extent Extent.
  62872. * @param {function(this: T, ol.Feature): S} callback Called with each feature
  62873. * whose geometry intersects the provided extent.
  62874. * @param {T=} opt_this The object to use as `this` in the callback.
  62875. * @return {S|undefined} The return value from the last call to the callback.
  62876. * @template T,S
  62877. * @api
  62878. */
  62879. ol.source.Vector.prototype.forEachFeatureIntersectingExtent =
  62880. function(extent, callback, opt_this) {
  62881. return this.forEachFeatureInExtent(extent,
  62882. /**
  62883. * @param {ol.Feature} feature Feature.
  62884. * @return {S|undefined}
  62885. * @template S
  62886. */
  62887. function(feature) {
  62888. var geometry = feature.getGeometry();
  62889. goog.asserts.assert(geometry,
  62890. 'feature geometry is defined and not null');
  62891. if (geometry.intersectsExtent(extent)) {
  62892. var result = callback.call(opt_this, feature);
  62893. if (result) {
  62894. return result;
  62895. }
  62896. }
  62897. });
  62898. };
  62899. /**
  62900. * Get the features collection associated with this source. Will be `null`
  62901. * unless the source was configured with `useSpatialIndex` set to `false`, or
  62902. * with an {@link ol.Collection} as `features`.
  62903. * @return {ol.Collection.<ol.Feature>}
  62904. * @api
  62905. */
  62906. ol.source.Vector.prototype.getFeaturesCollection = function() {
  62907. return this.featuresCollection_;
  62908. };
  62909. /**
  62910. * Get all features on the source.
  62911. * @return {Array.<ol.Feature>} Features.
  62912. * @api stable
  62913. */
  62914. ol.source.Vector.prototype.getFeatures = function() {
  62915. var features;
  62916. if (this.featuresCollection_) {
  62917. features = this.featuresCollection_.getArray();
  62918. } else if (this.featuresRtree_) {
  62919. features = this.featuresRtree_.getAll();
  62920. if (!goog.object.isEmpty(this.nullGeometryFeatures_)) {
  62921. goog.array.extend(
  62922. features, goog.object.getValues(this.nullGeometryFeatures_));
  62923. }
  62924. }
  62925. goog.asserts.assert(features !== undefined,
  62926. 'Neither featuresRtree_ nor featuresCollection_ are available');
  62927. return features;
  62928. };
  62929. /**
  62930. * Get all features whose geometry intersects the provided coordinate.
  62931. * @param {ol.Coordinate} coordinate Coordinate.
  62932. * @return {Array.<ol.Feature>} Features.
  62933. * @api stable
  62934. */
  62935. ol.source.Vector.prototype.getFeaturesAtCoordinate = function(coordinate) {
  62936. var features = [];
  62937. this.forEachFeatureAtCoordinateDirect(coordinate, function(feature) {
  62938. features.push(feature);
  62939. });
  62940. return features;
  62941. };
  62942. /**
  62943. * Get all features in the provided extent. Note that this returns all features
  62944. * whose bounding boxes intersect the given extent (so it may include features
  62945. * whose geometries do not intersect the extent).
  62946. *
  62947. * This method is not available when the source is configured with
  62948. * `useSpatialIndex` set to `false`.
  62949. * @param {ol.Extent} extent Extent.
  62950. * @return {Array.<ol.Feature>} Features.
  62951. * @api
  62952. */
  62953. ol.source.Vector.prototype.getFeaturesInExtent = function(extent) {
  62954. goog.asserts.assert(this.featuresRtree_,
  62955. 'getFeaturesInExtent does not work when useSpatialIndex is set to false');
  62956. return this.featuresRtree_.getInExtent(extent);
  62957. };
  62958. /**
  62959. * Get the closest feature to the provided coordinate.
  62960. *
  62961. * This method is not available when the source is configured with
  62962. * `useSpatialIndex` set to `false`.
  62963. * @param {ol.Coordinate} coordinate Coordinate.
  62964. * @return {ol.Feature} Closest feature.
  62965. * @api stable
  62966. */
  62967. ol.source.Vector.prototype.getClosestFeatureToCoordinate =
  62968. function(coordinate) {
  62969. // Find the closest feature using branch and bound. We start searching an
  62970. // infinite extent, and find the distance from the first feature found. This
  62971. // becomes the closest feature. We then compute a smaller extent which any
  62972. // closer feature must intersect. We continue searching with this smaller
  62973. // extent, trying to find a closer feature. Every time we find a closer
  62974. // feature, we update the extent being searched so that any even closer
  62975. // feature must intersect it. We continue until we run out of features.
  62976. var x = coordinate[0];
  62977. var y = coordinate[1];
  62978. var closestFeature = null;
  62979. var closestPoint = [NaN, NaN];
  62980. var minSquaredDistance = Infinity;
  62981. var extent = [-Infinity, -Infinity, Infinity, Infinity];
  62982. goog.asserts.assert(this.featuresRtree_,
  62983. 'getClosestFeatureToCoordinate does not work with useSpatialIndex set ' +
  62984. 'to false');
  62985. this.featuresRtree_.forEachInExtent(extent,
  62986. /**
  62987. * @param {ol.Feature} feature Feature.
  62988. */
  62989. function(feature) {
  62990. var geometry = feature.getGeometry();
  62991. goog.asserts.assert(geometry,
  62992. 'feature geometry is defined and not null');
  62993. var previousMinSquaredDistance = minSquaredDistance;
  62994. minSquaredDistance = geometry.closestPointXY(
  62995. x, y, closestPoint, minSquaredDistance);
  62996. if (minSquaredDistance < previousMinSquaredDistance) {
  62997. closestFeature = feature;
  62998. // This is sneaky. Reduce the extent that it is currently being
  62999. // searched while the R-Tree traversal using this same extent object
  63000. // is still in progress. This is safe because the new extent is
  63001. // strictly contained by the old extent.
  63002. var minDistance = Math.sqrt(minSquaredDistance);
  63003. extent[0] = x - minDistance;
  63004. extent[1] = y - minDistance;
  63005. extent[2] = x + minDistance;
  63006. extent[3] = y + minDistance;
  63007. }
  63008. });
  63009. return closestFeature;
  63010. };
  63011. /**
  63012. * Get the extent of the features currently in the source.
  63013. *
  63014. * This method is not available when the source is configured with
  63015. * `useSpatialIndex` set to `false`.
  63016. * @return {ol.Extent} Extent.
  63017. * @api stable
  63018. */
  63019. ol.source.Vector.prototype.getExtent = function() {
  63020. goog.asserts.assert(this.featuresRtree_,
  63021. 'getExtent does not work when useSpatialIndex is set to false');
  63022. return this.featuresRtree_.getExtent();
  63023. };
  63024. /**
  63025. * Get a feature by its identifier (the value returned by feature.getId()).
  63026. * Note that the index treats string and numeric identifiers as the same. So
  63027. * `source.getFeatureById(2)` will return a feature with id `'2'` or `2`.
  63028. *
  63029. * @param {string|number} id Feature identifier.
  63030. * @return {ol.Feature} The feature (or `null` if not found).
  63031. * @api stable
  63032. */
  63033. ol.source.Vector.prototype.getFeatureById = function(id) {
  63034. var feature = this.idIndex_[id.toString()];
  63035. return feature !== undefined ? feature : null;
  63036. };
  63037. /**
  63038. * @param {goog.events.Event} event Event.
  63039. * @private
  63040. */
  63041. ol.source.Vector.prototype.handleFeatureChange_ = function(event) {
  63042. var feature = /** @type {ol.Feature} */ (event.target);
  63043. var featureKey = goog.getUid(feature).toString();
  63044. var geometry = feature.getGeometry();
  63045. if (!geometry) {
  63046. if (!(featureKey in this.nullGeometryFeatures_)) {
  63047. if (this.featuresRtree_) {
  63048. this.featuresRtree_.remove(feature);
  63049. }
  63050. this.nullGeometryFeatures_[featureKey] = feature;
  63051. }
  63052. } else {
  63053. var extent = geometry.getExtent();
  63054. if (featureKey in this.nullGeometryFeatures_) {
  63055. delete this.nullGeometryFeatures_[featureKey];
  63056. if (this.featuresRtree_) {
  63057. this.featuresRtree_.insert(extent, feature);
  63058. }
  63059. } else {
  63060. if (this.featuresRtree_) {
  63061. this.featuresRtree_.update(extent, feature);
  63062. }
  63063. }
  63064. }
  63065. var id = feature.getId();
  63066. var removed;
  63067. if (id !== undefined) {
  63068. var sid = id.toString();
  63069. if (featureKey in this.undefIdIndex_) {
  63070. delete this.undefIdIndex_[featureKey];
  63071. this.idIndex_[sid] = feature;
  63072. } else {
  63073. if (this.idIndex_[sid] !== feature) {
  63074. removed = this.removeFromIdIndex_(feature);
  63075. goog.asserts.assert(removed,
  63076. 'Expected feature to be removed from index');
  63077. this.idIndex_[sid] = feature;
  63078. }
  63079. }
  63080. } else {
  63081. if (!(featureKey in this.undefIdIndex_)) {
  63082. removed = this.removeFromIdIndex_(feature);
  63083. goog.asserts.assert(removed,
  63084. 'Expected feature to be removed from index');
  63085. this.undefIdIndex_[featureKey] = feature;
  63086. } else {
  63087. goog.asserts.assert(this.undefIdIndex_[featureKey] === feature,
  63088. 'feature keyed under %s in undefIdKeys', featureKey);
  63089. }
  63090. }
  63091. this.changed();
  63092. this.dispatchEvent(new ol.source.VectorEvent(
  63093. ol.source.VectorEventType.CHANGEFEATURE, feature));
  63094. };
  63095. /**
  63096. * @return {boolean} Is empty.
  63097. */
  63098. ol.source.Vector.prototype.isEmpty = function() {
  63099. return this.featuresRtree_.isEmpty() &&
  63100. goog.object.isEmpty(this.nullGeometryFeatures_);
  63101. };
  63102. /**
  63103. * @param {ol.Extent} extent Extent.
  63104. * @param {number} resolution Resolution.
  63105. * @param {ol.proj.Projection} projection Projection.
  63106. */
  63107. ol.source.Vector.prototype.loadFeatures = function(
  63108. extent, resolution, projection) {
  63109. var loadedExtentsRtree = this.loadedExtentsRtree_;
  63110. var extentsToLoad = this.strategy_(extent, resolution);
  63111. var i, ii;
  63112. for (i = 0, ii = extentsToLoad.length; i < ii; ++i) {
  63113. var extentToLoad = extentsToLoad[i];
  63114. var alreadyLoaded = loadedExtentsRtree.forEachInExtent(extentToLoad,
  63115. /**
  63116. * @param {{extent: ol.Extent}} object Object.
  63117. * @return {boolean} Contains.
  63118. */
  63119. function(object) {
  63120. return ol.extent.containsExtent(object.extent, extentToLoad);
  63121. });
  63122. if (!alreadyLoaded) {
  63123. this.loader_.call(this, extentToLoad, resolution, projection);
  63124. loadedExtentsRtree.insert(extentToLoad, {extent: extentToLoad.slice()});
  63125. }
  63126. }
  63127. };
  63128. /**
  63129. * Remove a single feature from the source. If you want to remove all features
  63130. * at once, use the {@link ol.source.Vector#clear source.clear()} method
  63131. * instead.
  63132. * @param {ol.Feature} feature Feature to remove.
  63133. * @api stable
  63134. */
  63135. ol.source.Vector.prototype.removeFeature = function(feature) {
  63136. var featureKey = goog.getUid(feature).toString();
  63137. if (featureKey in this.nullGeometryFeatures_) {
  63138. delete this.nullGeometryFeatures_[featureKey];
  63139. } else {
  63140. if (this.featuresRtree_) {
  63141. this.featuresRtree_.remove(feature);
  63142. }
  63143. }
  63144. this.removeFeatureInternal(feature);
  63145. this.changed();
  63146. };
  63147. /**
  63148. * Remove feature without firing a `change` event.
  63149. * @param {ol.Feature} feature Feature.
  63150. * @protected
  63151. */
  63152. ol.source.Vector.prototype.removeFeatureInternal = function(feature) {
  63153. var featureKey = goog.getUid(feature).toString();
  63154. goog.asserts.assert(featureKey in this.featureChangeKeys_,
  63155. 'featureKey exists in featureChangeKeys');
  63156. this.featureChangeKeys_[featureKey].forEach(goog.events.unlistenByKey);
  63157. delete this.featureChangeKeys_[featureKey];
  63158. var id = feature.getId();
  63159. if (id !== undefined) {
  63160. delete this.idIndex_[id.toString()];
  63161. } else {
  63162. delete this.undefIdIndex_[featureKey];
  63163. }
  63164. this.dispatchEvent(new ol.source.VectorEvent(
  63165. ol.source.VectorEventType.REMOVEFEATURE, feature));
  63166. };
  63167. /**
  63168. * Remove a feature from the id index. Called internally when the feature id
  63169. * may have changed.
  63170. * @param {ol.Feature} feature The feature.
  63171. * @return {boolean} Removed the feature from the index.
  63172. * @private
  63173. */
  63174. ol.source.Vector.prototype.removeFromIdIndex_ = function(feature) {
  63175. var removed = false;
  63176. for (var id in this.idIndex_) {
  63177. if (this.idIndex_[id] === feature) {
  63178. delete this.idIndex_[id];
  63179. removed = true;
  63180. break;
  63181. }
  63182. }
  63183. return removed;
  63184. };
  63185. /**
  63186. * @classdesc
  63187. * Events emitted by {@link ol.source.Vector} instances are instances of this
  63188. * type.
  63189. *
  63190. * @constructor
  63191. * @extends {goog.events.Event}
  63192. * @implements {oli.source.VectorEvent}
  63193. * @param {string} type Type.
  63194. * @param {ol.Feature=} opt_feature Feature.
  63195. */
  63196. ol.source.VectorEvent = function(type, opt_feature) {
  63197. goog.base(this, type);
  63198. /**
  63199. * The feature being added or removed.
  63200. * @type {ol.Feature|undefined}
  63201. * @api stable
  63202. */
  63203. this.feature = opt_feature;
  63204. };
  63205. goog.inherits(ol.source.VectorEvent, goog.events.Event);
  63206. goog.provide('ol.source.ImageVector');
  63207. goog.require('goog.asserts');
  63208. goog.require('goog.events');
  63209. goog.require('goog.events.EventType');
  63210. goog.require('goog.vec.Mat4');
  63211. goog.require('ol.dom');
  63212. goog.require('ol.extent');
  63213. goog.require('ol.render.canvas.ReplayGroup');
  63214. goog.require('ol.renderer.vector');
  63215. goog.require('ol.source.ImageCanvas');
  63216. goog.require('ol.source.Vector');
  63217. goog.require('ol.style.Style');
  63218. goog.require('ol.vec.Mat4');
  63219. /**
  63220. * @classdesc
  63221. * An image source whose images are canvas elements into which vector features
  63222. * read from a vector source (`ol.source.Vector`) are drawn. An
  63223. * `ol.source.ImageVector` object is to be used as the `source` of an image
  63224. * layer (`ol.layer.Image`). Image layers are rotated, scaled, and translated,
  63225. * as opposed to being re-rendered, during animations and interactions. So, like
  63226. * any other image layer, an image layer configured with an
  63227. * `ol.source.ImageVector` will exhibit this behaviour. This is in contrast to a
  63228. * vector layer, where vector features are re-drawn during animations and
  63229. * interactions.
  63230. *
  63231. * @constructor
  63232. * @extends {ol.source.ImageCanvas}
  63233. * @param {olx.source.ImageVectorOptions} options Options.
  63234. * @api
  63235. */
  63236. ol.source.ImageVector = function(options) {
  63237. /**
  63238. * @private
  63239. * @type {ol.source.Vector}
  63240. */
  63241. this.source_ = options.source;
  63242. /**
  63243. * @private
  63244. * @type {!goog.vec.Mat4.Number}
  63245. */
  63246. this.transform_ = goog.vec.Mat4.createNumber();
  63247. /**
  63248. * @private
  63249. * @type {CanvasRenderingContext2D}
  63250. */
  63251. this.canvasContext_ = ol.dom.createCanvasContext2D();
  63252. /**
  63253. * @private
  63254. * @type {ol.Size}
  63255. */
  63256. this.canvasSize_ = [0, 0];
  63257. /**
  63258. * @private
  63259. * @type {ol.render.canvas.ReplayGroup}
  63260. */
  63261. this.replayGroup_ = null;
  63262. goog.base(this, {
  63263. attributions: options.attributions,
  63264. canvasFunction: goog.bind(this.canvasFunctionInternal_, this),
  63265. logo: options.logo,
  63266. projection: options.projection,
  63267. ratio: options.ratio,
  63268. resolutions: options.resolutions,
  63269. state: this.source_.getState()
  63270. });
  63271. /**
  63272. * User provided style.
  63273. * @type {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
  63274. * @private
  63275. */
  63276. this.style_ = null;
  63277. /**
  63278. * Style function for use within the library.
  63279. * @type {ol.style.StyleFunction|undefined}
  63280. * @private
  63281. */
  63282. this.styleFunction_ = undefined;
  63283. this.setStyle(options.style);
  63284. goog.events.listen(this.source_, goog.events.EventType.CHANGE,
  63285. this.handleSourceChange_, undefined, this);
  63286. };
  63287. goog.inherits(ol.source.ImageVector, ol.source.ImageCanvas);
  63288. /**
  63289. * @param {ol.Extent} extent Extent.
  63290. * @param {number} resolution Resolution.
  63291. * @param {number} pixelRatio Pixel ratio.
  63292. * @param {ol.Size} size Size.
  63293. * @param {ol.proj.Projection} projection Projection;
  63294. * @return {HTMLCanvasElement} Canvas element.
  63295. * @private
  63296. */
  63297. ol.source.ImageVector.prototype.canvasFunctionInternal_ =
  63298. function(extent, resolution, pixelRatio, size, projection) {
  63299. var replayGroup = new ol.render.canvas.ReplayGroup(
  63300. ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
  63301. resolution);
  63302. this.source_.loadFeatures(extent, resolution, projection);
  63303. var loading = false;
  63304. this.source_.forEachFeatureInExtentAtResolution(extent, resolution,
  63305. /**
  63306. * @param {ol.Feature} feature Feature.
  63307. */
  63308. function(feature) {
  63309. loading = loading ||
  63310. this.renderFeature_(feature, resolution, pixelRatio, replayGroup);
  63311. }, this);
  63312. replayGroup.finish();
  63313. if (loading) {
  63314. return null;
  63315. }
  63316. if (this.canvasSize_[0] != size[0] || this.canvasSize_[1] != size[1]) {
  63317. this.canvasContext_.canvas.width = size[0];
  63318. this.canvasContext_.canvas.height = size[1];
  63319. this.canvasSize_[0] = size[0];
  63320. this.canvasSize_[1] = size[1];
  63321. } else {
  63322. this.canvasContext_.clearRect(0, 0, size[0], size[1]);
  63323. }
  63324. var transform = this.getTransform_(ol.extent.getCenter(extent),
  63325. resolution, pixelRatio, size);
  63326. replayGroup.replay(this.canvasContext_, pixelRatio, transform, 0, {});
  63327. this.replayGroup_ = replayGroup;
  63328. return this.canvasContext_.canvas;
  63329. };
  63330. /**
  63331. * @inheritDoc
  63332. */
  63333. ol.source.ImageVector.prototype.forEachFeatureAtCoordinate = function(
  63334. coordinate, resolution, rotation, skippedFeatureUids, callback) {
  63335. if (!this.replayGroup_) {
  63336. return undefined;
  63337. } else {
  63338. /** @type {Object.<string, boolean>} */
  63339. var features = {};
  63340. return this.replayGroup_.forEachFeatureAtCoordinate(
  63341. coordinate, resolution, 0, skippedFeatureUids,
  63342. /**
  63343. * @param {ol.Feature} feature Feature.
  63344. * @return {?} Callback result.
  63345. */
  63346. function(feature) {
  63347. goog.asserts.assert(feature !== undefined, 'passed a feature');
  63348. var key = goog.getUid(feature).toString();
  63349. if (!(key in features)) {
  63350. features[key] = true;
  63351. return callback(feature);
  63352. }
  63353. });
  63354. }
  63355. };
  63356. /**
  63357. * Get a reference to the wrapped source.
  63358. * @return {ol.source.Vector} Source.
  63359. * @api
  63360. */
  63361. ol.source.ImageVector.prototype.getSource = function() {
  63362. return this.source_;
  63363. };
  63364. /**
  63365. * Get the style for features. This returns whatever was passed to the `style`
  63366. * option at construction or to the `setStyle` method.
  63367. * @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
  63368. * Layer style.
  63369. * @api stable
  63370. */
  63371. ol.source.ImageVector.prototype.getStyle = function() {
  63372. return this.style_;
  63373. };
  63374. /**
  63375. * Get the style function.
  63376. * @return {ol.style.StyleFunction|undefined} Layer style function.
  63377. * @api stable
  63378. */
  63379. ol.source.ImageVector.prototype.getStyleFunction = function() {
  63380. return this.styleFunction_;
  63381. };
  63382. /**
  63383. * @param {ol.Coordinate} center Center.
  63384. * @param {number} resolution Resolution.
  63385. * @param {number} pixelRatio Pixel ratio.
  63386. * @param {ol.Size} size Size.
  63387. * @return {!goog.vec.Mat4.Number} Transform.
  63388. * @private
  63389. */
  63390. ol.source.ImageVector.prototype.getTransform_ =
  63391. function(center, resolution, pixelRatio, size) {
  63392. return ol.vec.Mat4.makeTransform2D(this.transform_,
  63393. size[0] / 2, size[1] / 2,
  63394. pixelRatio / resolution, -pixelRatio / resolution,
  63395. 0,
  63396. -center[0], -center[1]);
  63397. };
  63398. /**
  63399. * Handle changes in image style state.
  63400. * @param {goog.events.Event} event Image style change event.
  63401. * @private
  63402. */
  63403. ol.source.ImageVector.prototype.handleImageChange_ =
  63404. function(event) {
  63405. this.changed();
  63406. };
  63407. /**
  63408. * @private
  63409. */
  63410. ol.source.ImageVector.prototype.handleSourceChange_ = function() {
  63411. // setState will trigger a CHANGE event, so we always rely
  63412. // change events by calling setState.
  63413. this.setState(this.source_.getState());
  63414. };
  63415. /**
  63416. * @param {ol.Feature} feature Feature.
  63417. * @param {number} resolution Resolution.
  63418. * @param {number} pixelRatio Pixel ratio.
  63419. * @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
  63420. * @return {boolean} `true` if an image is loading.
  63421. * @private
  63422. */
  63423. ol.source.ImageVector.prototype.renderFeature_ =
  63424. function(feature, resolution, pixelRatio, replayGroup) {
  63425. var styles;
  63426. var styleFunction = feature.getStyleFunction();
  63427. if (styleFunction) {
  63428. styles = styleFunction.call(feature, resolution);
  63429. } else if (this.styleFunction_) {
  63430. styles = this.styleFunction_(feature, resolution);
  63431. }
  63432. if (!styles) {
  63433. return false;
  63434. }
  63435. var i, ii, loading = false;
  63436. for (i = 0, ii = styles.length; i < ii; ++i) {
  63437. loading = ol.renderer.vector.renderFeature(
  63438. replayGroup, feature, styles[i],
  63439. ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
  63440. this.handleImageChange_, this) || loading;
  63441. }
  63442. return loading;
  63443. };
  63444. /**
  63445. * Set the style for features. This can be a single style object, an array
  63446. * of styles, or a function that takes a feature and resolution and returns
  63447. * an array of styles. If it is `undefined` the default style is used. If
  63448. * it is `null` the layer has no style (a `null` style), so only features
  63449. * that have their own styles will be rendered in the layer. See
  63450. * {@link ol.style} for information on the default style.
  63451. * @param {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction|undefined}
  63452. * style Layer style.
  63453. * @api stable
  63454. */
  63455. ol.source.ImageVector.prototype.setStyle = function(style) {
  63456. this.style_ = style !== undefined ? style : ol.style.defaultStyleFunction;
  63457. this.styleFunction_ = !style ?
  63458. undefined : ol.style.createStyleFunction(this.style_);
  63459. this.changed();
  63460. };
  63461. goog.provide('ol.renderer.canvas.ImageLayer');
  63462. goog.require('goog.asserts');
  63463. goog.require('goog.functions');
  63464. goog.require('goog.vec.Mat4');
  63465. goog.require('ol.ImageBase');
  63466. goog.require('ol.ViewHint');
  63467. goog.require('ol.dom');
  63468. goog.require('ol.extent');
  63469. goog.require('ol.layer.Image');
  63470. goog.require('ol.proj');
  63471. goog.require('ol.renderer.canvas.Layer');
  63472. goog.require('ol.source.ImageVector');
  63473. goog.require('ol.vec.Mat4');
  63474. /**
  63475. * @constructor
  63476. * @extends {ol.renderer.canvas.Layer}
  63477. * @param {ol.layer.Image} imageLayer Single image layer.
  63478. */
  63479. ol.renderer.canvas.ImageLayer = function(imageLayer) {
  63480. goog.base(this, imageLayer);
  63481. /**
  63482. * @private
  63483. * @type {?ol.ImageBase}
  63484. */
  63485. this.image_ = null;
  63486. /**
  63487. * @private
  63488. * @type {!goog.vec.Mat4.Number}
  63489. */
  63490. this.imageTransform_ = goog.vec.Mat4.createNumber();
  63491. /**
  63492. * @private
  63493. * @type {?goog.vec.Mat4.Number}
  63494. */
  63495. this.imageTransformInv_ = null;
  63496. /**
  63497. * @private
  63498. * @type {CanvasRenderingContext2D}
  63499. */
  63500. this.hitCanvasContext_ = null;
  63501. };
  63502. goog.inherits(ol.renderer.canvas.ImageLayer, ol.renderer.canvas.Layer);
  63503. /**
  63504. * @inheritDoc
  63505. */
  63506. ol.renderer.canvas.ImageLayer.prototype.forEachFeatureAtCoordinate =
  63507. function(coordinate, frameState, callback, thisArg) {
  63508. var layer = this.getLayer();
  63509. var source = layer.getSource();
  63510. var resolution = frameState.viewState.resolution;
  63511. var rotation = frameState.viewState.rotation;
  63512. var skippedFeatureUids = frameState.skippedFeatureUids;
  63513. return source.forEachFeatureAtCoordinate(
  63514. coordinate, resolution, rotation, skippedFeatureUids,
  63515. /**
  63516. * @param {ol.Feature} feature Feature.
  63517. * @return {?} Callback result.
  63518. */
  63519. function(feature) {
  63520. return callback.call(thisArg, feature, layer);
  63521. });
  63522. };
  63523. /**
  63524. * @inheritDoc
  63525. */
  63526. ol.renderer.canvas.ImageLayer.prototype.forEachLayerAtPixel =
  63527. function(pixel, frameState, callback, thisArg) {
  63528. if (!this.getImage()) {
  63529. return undefined;
  63530. }
  63531. if (this.getLayer().getSource() instanceof ol.source.ImageVector) {
  63532. // for ImageVector sources use the original hit-detection logic,
  63533. // so that for example also transparent polygons are detected
  63534. var coordinate = pixel.slice();
  63535. ol.vec.Mat4.multVec2(
  63536. frameState.pixelToCoordinateMatrix, coordinate, coordinate);
  63537. var hasFeature = this.forEachFeatureAtCoordinate(
  63538. coordinate, frameState, goog.functions.TRUE, this);
  63539. if (hasFeature) {
  63540. return callback.call(thisArg, this.getLayer());
  63541. } else {
  63542. return undefined;
  63543. }
  63544. } else {
  63545. // for all other image sources directly check the image
  63546. if (!this.imageTransformInv_) {
  63547. this.imageTransformInv_ = goog.vec.Mat4.createNumber();
  63548. goog.vec.Mat4.invert(this.imageTransform_, this.imageTransformInv_);
  63549. }
  63550. var pixelOnCanvas =
  63551. this.getPixelOnCanvas(pixel, this.imageTransformInv_);
  63552. if (!this.hitCanvasContext_) {
  63553. this.hitCanvasContext_ = ol.dom.createCanvasContext2D(1, 1);
  63554. }
  63555. this.hitCanvasContext_.clearRect(0, 0, 1, 1);
  63556. this.hitCanvasContext_.drawImage(
  63557. this.getImage(), pixelOnCanvas[0], pixelOnCanvas[1], 1, 1, 0, 0, 1, 1);
  63558. var imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data;
  63559. if (imageData[3] > 0) {
  63560. return callback.call(thisArg, this.getLayer());
  63561. } else {
  63562. return undefined;
  63563. }
  63564. }
  63565. };
  63566. /**
  63567. * @inheritDoc
  63568. */
  63569. ol.renderer.canvas.ImageLayer.prototype.getImage = function() {
  63570. return !this.image_ ? null : this.image_.getImage();
  63571. };
  63572. /**
  63573. * @inheritDoc
  63574. */
  63575. ol.renderer.canvas.ImageLayer.prototype.getImageTransform = function() {
  63576. return this.imageTransform_;
  63577. };
  63578. /**
  63579. * @inheritDoc
  63580. */
  63581. ol.renderer.canvas.ImageLayer.prototype.prepareFrame =
  63582. function(frameState, layerState) {
  63583. var pixelRatio = frameState.pixelRatio;
  63584. var viewState = frameState.viewState;
  63585. var viewCenter = viewState.center;
  63586. var viewResolution = viewState.resolution;
  63587. var viewRotation = viewState.rotation;
  63588. var image;
  63589. var imageLayer = this.getLayer();
  63590. goog.asserts.assertInstanceof(imageLayer, ol.layer.Image,
  63591. 'layer is an instance of ol.layer.Image');
  63592. var imageSource = imageLayer.getSource();
  63593. var hints = frameState.viewHints;
  63594. var renderedExtent = frameState.extent;
  63595. if (layerState.extent !== undefined) {
  63596. renderedExtent = ol.extent.getIntersection(
  63597. renderedExtent, layerState.extent);
  63598. }
  63599. if (!hints[ol.ViewHint.ANIMATING] && !hints[ol.ViewHint.INTERACTING] &&
  63600. !ol.extent.isEmpty(renderedExtent)) {
  63601. var projection = viewState.projection;
  63602. var sourceProjection = imageSource.getProjection();
  63603. if (sourceProjection) {
  63604. goog.asserts.assert(ol.proj.equivalent(projection, sourceProjection),
  63605. 'projection and sourceProjection are equivalent');
  63606. projection = sourceProjection;
  63607. }
  63608. image = imageSource.getImage(
  63609. renderedExtent, viewResolution, pixelRatio, projection);
  63610. if (image) {
  63611. var loaded = this.loadImage(image);
  63612. if (loaded) {
  63613. this.image_ = image;
  63614. }
  63615. }
  63616. }
  63617. if (this.image_) {
  63618. image = this.image_;
  63619. var imageExtent = image.getExtent();
  63620. var imageResolution = image.getResolution();
  63621. var imagePixelRatio = image.getPixelRatio();
  63622. var scale = pixelRatio * imageResolution /
  63623. (viewResolution * imagePixelRatio);
  63624. ol.vec.Mat4.makeTransform2D(this.imageTransform_,
  63625. pixelRatio * frameState.size[0] / 2,
  63626. pixelRatio * frameState.size[1] / 2,
  63627. scale, scale,
  63628. viewRotation,
  63629. imagePixelRatio * (imageExtent[0] - viewCenter[0]) / imageResolution,
  63630. imagePixelRatio * (viewCenter[1] - imageExtent[3]) / imageResolution);
  63631. this.imageTransformInv_ = null;
  63632. this.updateAttributions(frameState.attributions, image.getAttributions());
  63633. this.updateLogos(frameState, imageSource);
  63634. }
  63635. return true;
  63636. };
  63637. // FIXME find correct globalCompositeOperation
  63638. // FIXME optimize :-)
  63639. goog.provide('ol.renderer.canvas.TileLayer');
  63640. goog.require('goog.array');
  63641. goog.require('goog.asserts');
  63642. goog.require('goog.vec.Mat4');
  63643. goog.require('ol.Size');
  63644. goog.require('ol.TileRange');
  63645. goog.require('ol.TileState');
  63646. goog.require('ol.dom');
  63647. goog.require('ol.extent');
  63648. goog.require('ol.layer.Tile');
  63649. goog.require('ol.renderer.canvas.Layer');
  63650. goog.require('ol.size');
  63651. goog.require('ol.tilecoord');
  63652. goog.require('ol.vec.Mat4');
  63653. /**
  63654. * @constructor
  63655. * @extends {ol.renderer.canvas.Layer}
  63656. * @param {ol.layer.Tile} tileLayer Tile layer.
  63657. */
  63658. ol.renderer.canvas.TileLayer = function(tileLayer) {
  63659. goog.base(this, tileLayer);
  63660. /**
  63661. * @private
  63662. * @type {HTMLCanvasElement}
  63663. */
  63664. this.canvas_ = null;
  63665. /**
  63666. * @private
  63667. * @type {ol.Size}
  63668. */
  63669. this.canvasSize_ = null;
  63670. /**
  63671. * @private
  63672. * @type {boolean}
  63673. */
  63674. this.canvasTooBig_ = false;
  63675. /**
  63676. * @private
  63677. * @type {CanvasRenderingContext2D}
  63678. */
  63679. this.context_ = null;
  63680. /**
  63681. * @private
  63682. * @type {!goog.vec.Mat4.Number}
  63683. */
  63684. this.imageTransform_ = goog.vec.Mat4.createNumber();
  63685. /**
  63686. * @private
  63687. * @type {?goog.vec.Mat4.Number}
  63688. */
  63689. this.imageTransformInv_ = null;
  63690. /**
  63691. * @private
  63692. * @type {number}
  63693. */
  63694. this.renderedCanvasZ_ = NaN;
  63695. /**
  63696. * @private
  63697. * @type {number}
  63698. */
  63699. this.renderedTileWidth_ = NaN;
  63700. /**
  63701. * @private
  63702. * @type {number}
  63703. */
  63704. this.renderedTileHeight_ = NaN;
  63705. /**
  63706. * @private
  63707. * @type {ol.TileRange}
  63708. */
  63709. this.renderedCanvasTileRange_ = null;
  63710. /**
  63711. * @private
  63712. * @type {Array.<ol.Tile|undefined>}
  63713. */
  63714. this.renderedTiles_ = null;
  63715. /**
  63716. * @private
  63717. * @type {ol.Size}
  63718. */
  63719. this.tmpSize_ = [0, 0];
  63720. };
  63721. goog.inherits(ol.renderer.canvas.TileLayer, ol.renderer.canvas.Layer);
  63722. /**
  63723. * @inheritDoc
  63724. */
  63725. ol.renderer.canvas.TileLayer.prototype.getImage = function() {
  63726. return this.canvas_;
  63727. };
  63728. /**
  63729. * @inheritDoc
  63730. */
  63731. ol.renderer.canvas.TileLayer.prototype.getImageTransform = function() {
  63732. return this.imageTransform_;
  63733. };
  63734. /**
  63735. * @inheritDoc
  63736. */
  63737. ol.renderer.canvas.TileLayer.prototype.prepareFrame =
  63738. function(frameState, layerState) {
  63739. //
  63740. // Warning! You're entering a dangerous zone!
  63741. //
  63742. // The canvas tile layer renderering is highly optimized, hence
  63743. // the complexity of this function. For best performance we try
  63744. // to minimize the number of pixels to update on the canvas. This
  63745. // includes:
  63746. //
  63747. // - Only drawing pixels that will be visible.
  63748. // - Not re-drawing pixels/tiles that are already correct.
  63749. // - Minimizing calls to clearRect.
  63750. // - Never shrink the canvas. Just make it bigger when necessary.
  63751. // Re-sizing the canvas also clears it, which further means
  63752. // re-creating it (expensive).
  63753. //
  63754. // The various steps performed by this functions:
  63755. //
  63756. // - Create a canvas element if none has been created yet.
  63757. //
  63758. // - Make the canvas bigger if it's too small. Note that we never shrink
  63759. // the canvas, we just make it bigger when necessary, when rotating for
  63760. // example. Note also that the canvas always contains a whole number
  63761. // of tiles.
  63762. //
  63763. // - Invalidate the canvas tile range (renderedCanvasTileRange_ = null)
  63764. // if (1) the canvas has been enlarged, or (2) the zoom level changes,
  63765. // or (3) the canvas tile range doesn't contain the required tile
  63766. // range. This canvas tile range invalidation thing is related to
  63767. // an optimization where we attempt to redraw as few pixels as
  63768. // possible on each prepareFrame call.
  63769. //
  63770. // - If the canvas tile range has been invalidated we reset
  63771. // renderedCanvasTileRange_ and reset the renderedTiles_ array.
  63772. // The renderedTiles_ array is the structure used to determine
  63773. // the canvas pixels that need not be redrawn from one prepareFrame
  63774. // call to another. It records while tile has been rendered at
  63775. // which position in the canvas.
  63776. //
  63777. // - We then determine the tiles to draw on the canvas. Tiles for
  63778. // the target resolution may not be loaded yet. In that case we
  63779. // use low-resolution/interim tiles if loaded already. And, if
  63780. // for a non-yet-loaded tile we haven't found a corresponding
  63781. // low-resolution tile we indicate that the pixels for that
  63782. // tile must be cleared on the canvas. Note: determining the
  63783. // interim tiles is based on tile extents instead of tile
  63784. // coords, this is to be able to handler irregular tile grids.
  63785. //
  63786. // - We're now ready to render. We start by calling clearRect
  63787. // for the tiles that aren't loaded yet and are not fully covered
  63788. // by a low-resolution tile (if they're loaded, we'll draw them;
  63789. // if they're fully covered by a low-resolution tile then there's
  63790. // no need to clear). We then render the tiles "back to front",
  63791. // i.e. starting with the low-resolution tiles.
  63792. //
  63793. // - After rendering some bookkeeping is performed (updateUsedTiles,
  63794. // etc.). manageTilePyramid is what enqueue tiles in the tile
  63795. // queue for loading.
  63796. //
  63797. // - The last step involves updating the image transform matrix,
  63798. // which will be used by the map renderer for the final
  63799. // composition and positioning.
  63800. //
  63801. var pixelRatio = frameState.pixelRatio;
  63802. var viewState = frameState.viewState;
  63803. var projection = viewState.projection;
  63804. var tileLayer = this.getLayer();
  63805. goog.asserts.assertInstanceof(tileLayer, ol.layer.Tile,
  63806. 'layer is an instance of ol.layer.Tile');
  63807. var tileSource = tileLayer.getSource();
  63808. var tileGrid = tileSource.getTileGridForProjection(projection);
  63809. var tileGutter = tileSource.getGutter();
  63810. var z = tileGrid.getZForResolution(viewState.resolution);
  63811. var tilePixelSize =
  63812. tileSource.getTilePixelSize(z, frameState.pixelRatio, projection);
  63813. var tilePixelRatio = tilePixelSize[0] /
  63814. ol.size.toSize(tileGrid.getTileSize(z), this.tmpSize_)[0];
  63815. var tileResolution = tileGrid.getResolution(z);
  63816. var tilePixelResolution = tileResolution / tilePixelRatio;
  63817. var center = viewState.center;
  63818. var extent;
  63819. if (tileResolution == viewState.resolution) {
  63820. center = this.snapCenterToPixel(center, tileResolution, frameState.size);
  63821. extent = ol.extent.getForViewAndSize(
  63822. center, tileResolution, viewState.rotation, frameState.size);
  63823. } else {
  63824. extent = frameState.extent;
  63825. }
  63826. if (layerState.extent !== undefined) {
  63827. extent = ol.extent.getIntersection(extent, layerState.extent);
  63828. }
  63829. if (ol.extent.isEmpty(extent)) {
  63830. // Return false to prevent the rendering of the layer.
  63831. return false;
  63832. }
  63833. var tileRange = tileGrid.getTileRangeForExtentAndResolution(
  63834. extent, tileResolution);
  63835. var canvasWidth = tilePixelSize[0] * tileRange.getWidth();
  63836. var canvasHeight = tilePixelSize[1] * tileRange.getHeight();
  63837. var canvas, context;
  63838. if (!this.canvas_) {
  63839. goog.asserts.assert(!this.canvasSize_,
  63840. 'canvasSize is null (because canvas is null)');
  63841. goog.asserts.assert(!this.context_,
  63842. 'context is null (because canvas is null)');
  63843. goog.asserts.assert(!this.renderedCanvasTileRange_,
  63844. 'renderedCanvasTileRange is null (because canvas is null)');
  63845. context = ol.dom.createCanvasContext2D(canvasWidth, canvasHeight);
  63846. this.canvas_ = context.canvas;
  63847. this.canvasSize_ = [canvasWidth, canvasHeight];
  63848. this.context_ = context;
  63849. this.canvasTooBig_ =
  63850. !ol.renderer.canvas.Layer.testCanvasSize(this.canvasSize_);
  63851. } else {
  63852. goog.asserts.assert(this.canvasSize_,
  63853. 'non-null canvasSize (because canvas is not null)');
  63854. goog.asserts.assert(this.context_,
  63855. 'non-null context (because canvas is not null)');
  63856. canvas = this.canvas_;
  63857. context = this.context_;
  63858. if (this.canvasSize_[0] < canvasWidth ||
  63859. this.canvasSize_[1] < canvasHeight ||
  63860. this.renderedTileWidth_ !== tilePixelSize[0] ||
  63861. this.renderedTileHeight_ !== tilePixelSize[1] ||
  63862. (this.canvasTooBig_ && (this.canvasSize_[0] > canvasWidth ||
  63863. this.canvasSize_[1] > canvasHeight))) {
  63864. // Canvas is too small or tileSize has changed, resize it.
  63865. // We never shrink the canvas, unless
  63866. // we know that the current canvas size exceeds the maximum size
  63867. canvas.width = canvasWidth;
  63868. canvas.height = canvasHeight;
  63869. this.canvasSize_ = [canvasWidth, canvasHeight];
  63870. this.canvasTooBig_ =
  63871. !ol.renderer.canvas.Layer.testCanvasSize(this.canvasSize_);
  63872. this.renderedCanvasTileRange_ = null;
  63873. } else {
  63874. canvasWidth = this.canvasSize_[0];
  63875. canvasHeight = this.canvasSize_[1];
  63876. if (z != this.renderedCanvasZ_ ||
  63877. !this.renderedCanvasTileRange_.containsTileRange(tileRange)) {
  63878. this.renderedCanvasTileRange_ = null;
  63879. }
  63880. }
  63881. }
  63882. var canvasTileRange, canvasTileRangeWidth, minX, minY;
  63883. if (!this.renderedCanvasTileRange_) {
  63884. canvasTileRangeWidth = canvasWidth / tilePixelSize[0];
  63885. var canvasTileRangeHeight = canvasHeight / tilePixelSize[1];
  63886. minX = tileRange.minX -
  63887. Math.floor((canvasTileRangeWidth - tileRange.getWidth()) / 2);
  63888. minY = tileRange.minY -
  63889. Math.floor((canvasTileRangeHeight - tileRange.getHeight()) / 2);
  63890. this.renderedCanvasZ_ = z;
  63891. this.renderedTileWidth_ = tilePixelSize[0];
  63892. this.renderedTileHeight_ = tilePixelSize[1];
  63893. this.renderedCanvasTileRange_ = new ol.TileRange(
  63894. minX, minX + canvasTileRangeWidth - 1,
  63895. minY, minY + canvasTileRangeHeight - 1);
  63896. this.renderedTiles_ =
  63897. new Array(canvasTileRangeWidth * canvasTileRangeHeight);
  63898. canvasTileRange = this.renderedCanvasTileRange_;
  63899. } else {
  63900. canvasTileRange = this.renderedCanvasTileRange_;
  63901. canvasTileRangeWidth = canvasTileRange.getWidth();
  63902. }
  63903. goog.asserts.assert(canvasTileRange.containsTileRange(tileRange),
  63904. 'tileRange is contained in canvasTileRange');
  63905. /**
  63906. * @type {Object.<number, Object.<string, ol.Tile>>}
  63907. */
  63908. var tilesToDrawByZ = {};
  63909. tilesToDrawByZ[z] = {};
  63910. /** @type {Array.<ol.Tile>} */
  63911. var tilesToClear = [];
  63912. var findLoadedTiles = this.createLoadedTileFinder(tileSource, tilesToDrawByZ);
  63913. var useInterimTilesOnError = tileLayer.getUseInterimTilesOnError();
  63914. var tmpExtent = ol.extent.createEmpty();
  63915. var tmpTileRange = new ol.TileRange(0, 0, 0, 0);
  63916. var childTileRange, fullyLoaded, tile, tileState, x, y;
  63917. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  63918. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  63919. tile = tileSource.getTile(z, x, y, pixelRatio, projection);
  63920. tileState = tile.getState();
  63921. if (tileState == ol.TileState.LOADED ||
  63922. tileState == ol.TileState.EMPTY ||
  63923. (tileState == ol.TileState.ERROR && !useInterimTilesOnError)) {
  63924. tilesToDrawByZ[z][ol.tilecoord.toString(tile.tileCoord)] = tile;
  63925. continue;
  63926. }
  63927. fullyLoaded = tileGrid.forEachTileCoordParentTileRange(
  63928. tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent);
  63929. if (!fullyLoaded) {
  63930. // FIXME we do not need to clear the tile if it is fully covered by its
  63931. // children
  63932. tilesToClear.push(tile);
  63933. childTileRange = tileGrid.getTileCoordChildTileRange(
  63934. tile.tileCoord, tmpTileRange, tmpExtent);
  63935. if (childTileRange) {
  63936. findLoadedTiles(z + 1, childTileRange);
  63937. }
  63938. }
  63939. }
  63940. }
  63941. var i, ii;
  63942. for (i = 0, ii = tilesToClear.length; i < ii; ++i) {
  63943. tile = tilesToClear[i];
  63944. x = tilePixelSize[0] * (tile.tileCoord[1] - canvasTileRange.minX);
  63945. y = tilePixelSize[1] * (canvasTileRange.maxY - tile.tileCoord[2]);
  63946. context.clearRect(x, y, tilePixelSize[0], tilePixelSize[1]);
  63947. }
  63948. /** @type {Array.<number>} */
  63949. var zs = Object.keys(tilesToDrawByZ).map(Number);
  63950. goog.array.sort(zs);
  63951. var opaque = tileSource.getOpaque();
  63952. var origin = ol.extent.getTopLeft(tileGrid.getTileCoordExtent(
  63953. [z, canvasTileRange.minX, canvasTileRange.maxY],
  63954. tmpExtent));
  63955. var currentZ, index, scale, tileCoordKey, tileExtent, tilesToDraw;
  63956. var ix, iy, interimTileRange, maxX, maxY;
  63957. var height, width;
  63958. for (i = 0, ii = zs.length; i < ii; ++i) {
  63959. currentZ = zs[i];
  63960. tilePixelSize =
  63961. tileSource.getTilePixelSize(currentZ, pixelRatio, projection);
  63962. tilesToDraw = tilesToDrawByZ[currentZ];
  63963. if (currentZ == z) {
  63964. for (tileCoordKey in tilesToDraw) {
  63965. tile = tilesToDraw[tileCoordKey];
  63966. index =
  63967. (tile.tileCoord[2] - canvasTileRange.minY) * canvasTileRangeWidth +
  63968. (tile.tileCoord[1] - canvasTileRange.minX);
  63969. if (this.renderedTiles_[index] != tile) {
  63970. x = tilePixelSize[0] * (tile.tileCoord[1] - canvasTileRange.minX);
  63971. y = tilePixelSize[1] * (canvasTileRange.maxY - tile.tileCoord[2]);
  63972. tileState = tile.getState();
  63973. if (tileState == ol.TileState.EMPTY ||
  63974. (tileState == ol.TileState.ERROR && !useInterimTilesOnError) ||
  63975. !opaque) {
  63976. context.clearRect(x, y, tilePixelSize[0], tilePixelSize[1]);
  63977. }
  63978. if (tileState == ol.TileState.LOADED) {
  63979. context.drawImage(tile.getImage(),
  63980. tileGutter, tileGutter, tilePixelSize[0], tilePixelSize[1],
  63981. x, y, tilePixelSize[0], tilePixelSize[1]);
  63982. }
  63983. this.renderedTiles_[index] = tile;
  63984. }
  63985. }
  63986. } else {
  63987. scale = tileGrid.getResolution(currentZ) / tileResolution;
  63988. for (tileCoordKey in tilesToDraw) {
  63989. tile = tilesToDraw[tileCoordKey];
  63990. tileExtent = tileGrid.getTileCoordExtent(tile.tileCoord, tmpExtent);
  63991. x = (tileExtent[0] - origin[0]) / tilePixelResolution;
  63992. y = (origin[1] - tileExtent[3]) / tilePixelResolution;
  63993. width = scale * tilePixelSize[0];
  63994. height = scale * tilePixelSize[1];
  63995. tileState = tile.getState();
  63996. if (tileState == ol.TileState.EMPTY || !opaque) {
  63997. context.clearRect(x, y, width, height);
  63998. }
  63999. if (tileState == ol.TileState.LOADED) {
  64000. context.drawImage(tile.getImage(),
  64001. tileGutter, tileGutter, tilePixelSize[0], tilePixelSize[1],
  64002. x, y, width, height);
  64003. }
  64004. interimTileRange =
  64005. tileGrid.getTileRangeForExtentAndZ(tileExtent, z, tmpTileRange);
  64006. minX = Math.max(interimTileRange.minX, canvasTileRange.minX);
  64007. maxX = Math.min(interimTileRange.maxX, canvasTileRange.maxX);
  64008. minY = Math.max(interimTileRange.minY, canvasTileRange.minY);
  64009. maxY = Math.min(interimTileRange.maxY, canvasTileRange.maxY);
  64010. for (ix = minX; ix <= maxX; ++ix) {
  64011. for (iy = minY; iy <= maxY; ++iy) {
  64012. index = (iy - canvasTileRange.minY) * canvasTileRangeWidth +
  64013. (ix - canvasTileRange.minX);
  64014. this.renderedTiles_[index] = undefined;
  64015. }
  64016. }
  64017. }
  64018. }
  64019. }
  64020. this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange);
  64021. this.manageTilePyramid(frameState, tileSource, tileGrid, pixelRatio,
  64022. projection, extent, z, tileLayer.getPreload());
  64023. this.scheduleExpireCache(frameState, tileSource);
  64024. this.updateLogos(frameState, tileSource);
  64025. ol.vec.Mat4.makeTransform2D(this.imageTransform_,
  64026. pixelRatio * frameState.size[0] / 2,
  64027. pixelRatio * frameState.size[1] / 2,
  64028. pixelRatio * tilePixelResolution / viewState.resolution,
  64029. pixelRatio * tilePixelResolution / viewState.resolution,
  64030. viewState.rotation,
  64031. (origin[0] - center[0]) / tilePixelResolution,
  64032. (center[1] - origin[1]) / tilePixelResolution);
  64033. this.imageTransformInv_ = null;
  64034. return true;
  64035. };
  64036. /**
  64037. * @inheritDoc
  64038. */
  64039. ol.renderer.canvas.TileLayer.prototype.forEachLayerAtPixel =
  64040. function(pixel, frameState, callback, thisArg) {
  64041. if (!this.context_) {
  64042. return undefined;
  64043. }
  64044. if (!this.imageTransformInv_) {
  64045. this.imageTransformInv_ = goog.vec.Mat4.createNumber();
  64046. goog.vec.Mat4.invert(this.imageTransform_, this.imageTransformInv_);
  64047. }
  64048. var pixelOnCanvas =
  64049. this.getPixelOnCanvas(pixel, this.imageTransformInv_);
  64050. var imageData = this.context_.getImageData(
  64051. pixelOnCanvas[0], pixelOnCanvas[1], 1, 1).data;
  64052. if (imageData[3] > 0) {
  64053. return callback.call(thisArg, this.getLayer());
  64054. } else {
  64055. return undefined;
  64056. }
  64057. };
  64058. goog.provide('ol.renderer.canvas.VectorLayer');
  64059. goog.require('goog.array');
  64060. goog.require('goog.asserts');
  64061. goog.require('goog.events');
  64062. goog.require('ol.ViewHint');
  64063. goog.require('ol.dom');
  64064. goog.require('ol.extent');
  64065. goog.require('ol.layer.Vector');
  64066. goog.require('ol.render.EventType');
  64067. goog.require('ol.render.canvas.ReplayGroup');
  64068. goog.require('ol.renderer.canvas.Layer');
  64069. goog.require('ol.renderer.vector');
  64070. goog.require('ol.source.Vector');
  64071. /**
  64072. * @constructor
  64073. * @extends {ol.renderer.canvas.Layer}
  64074. * @param {ol.layer.Vector} vectorLayer Vector layer.
  64075. */
  64076. ol.renderer.canvas.VectorLayer = function(vectorLayer) {
  64077. goog.base(this, vectorLayer);
  64078. /**
  64079. * @private
  64080. * @type {boolean}
  64081. */
  64082. this.dirty_ = false;
  64083. /**
  64084. * @private
  64085. * @type {number}
  64086. */
  64087. this.renderedRevision_ = -1;
  64088. /**
  64089. * @private
  64090. * @type {number}
  64091. */
  64092. this.renderedResolution_ = NaN;
  64093. /**
  64094. * @private
  64095. * @type {ol.Extent}
  64096. */
  64097. this.renderedExtent_ = ol.extent.createEmpty();
  64098. /**
  64099. * @private
  64100. * @type {function(ol.Feature, ol.Feature): number|null}
  64101. */
  64102. this.renderedRenderOrder_ = null;
  64103. /**
  64104. * @private
  64105. * @type {ol.render.canvas.ReplayGroup}
  64106. */
  64107. this.replayGroup_ = null;
  64108. /**
  64109. * @private
  64110. * @type {CanvasRenderingContext2D}
  64111. */
  64112. this.context_ = ol.dom.createCanvasContext2D();
  64113. };
  64114. goog.inherits(ol.renderer.canvas.VectorLayer, ol.renderer.canvas.Layer);
  64115. /**
  64116. * @inheritDoc
  64117. */
  64118. ol.renderer.canvas.VectorLayer.prototype.composeFrame =
  64119. function(frameState, layerState, context) {
  64120. var extent = frameState.extent;
  64121. var pixelRatio = frameState.pixelRatio;
  64122. var skippedFeatureUids = layerState.managed ?
  64123. frameState.skippedFeatureUids : {};
  64124. var viewState = frameState.viewState;
  64125. var projection = viewState.projection;
  64126. var rotation = viewState.rotation;
  64127. var projectionExtent = projection.getExtent();
  64128. var vectorSource = this.getLayer().getSource();
  64129. goog.asserts.assertInstanceof(vectorSource, ol.source.Vector);
  64130. var transform = this.getTransform(frameState, 0);
  64131. this.dispatchPreComposeEvent(context, frameState, transform);
  64132. var replayGroup = this.replayGroup_;
  64133. if (replayGroup && !replayGroup.isEmpty()) {
  64134. var layer = this.getLayer();
  64135. var replayContext;
  64136. if (layer.hasListener(ol.render.EventType.RENDER)) {
  64137. // resize and clear
  64138. this.context_.canvas.width = context.canvas.width;
  64139. this.context_.canvas.height = context.canvas.height;
  64140. replayContext = this.context_;
  64141. } else {
  64142. replayContext = context;
  64143. }
  64144. // for performance reasons, context.save / context.restore is not used
  64145. // to save and restore the transformation matrix and the opacity.
  64146. // see http://jsperf.com/context-save-restore-versus-variable
  64147. var alpha = replayContext.globalAlpha;
  64148. replayContext.globalAlpha = layerState.opacity;
  64149. replayGroup.replay(replayContext, pixelRatio, transform, rotation,
  64150. skippedFeatureUids);
  64151. if (vectorSource.getWrapX() && projection.canWrapX() &&
  64152. !ol.extent.containsExtent(projectionExtent, extent)) {
  64153. var startX = extent[0];
  64154. var worldWidth = ol.extent.getWidth(projectionExtent);
  64155. var world = 0;
  64156. var offsetX;
  64157. while (startX < projectionExtent[0]) {
  64158. --world;
  64159. offsetX = worldWidth * world;
  64160. transform = this.getTransform(frameState, offsetX);
  64161. replayGroup.replay(replayContext, pixelRatio, transform, rotation,
  64162. skippedFeatureUids);
  64163. startX += worldWidth;
  64164. }
  64165. world = 0;
  64166. startX = extent[2];
  64167. while (startX > projectionExtent[2]) {
  64168. ++world;
  64169. offsetX = worldWidth * world;
  64170. transform = this.getTransform(frameState, offsetX);
  64171. replayGroup.replay(replayContext, pixelRatio, transform, rotation,
  64172. skippedFeatureUids);
  64173. startX -= worldWidth;
  64174. }
  64175. // restore original transform for render and compose events
  64176. transform = this.getTransform(frameState, 0);
  64177. }
  64178. if (replayContext != context) {
  64179. this.dispatchRenderEvent(replayContext, frameState, transform);
  64180. context.drawImage(replayContext.canvas, 0, 0);
  64181. }
  64182. replayContext.globalAlpha = alpha;
  64183. }
  64184. this.dispatchPostComposeEvent(context, frameState, transform);
  64185. };
  64186. /**
  64187. * @inheritDoc
  64188. */
  64189. ol.renderer.canvas.VectorLayer.prototype.forEachFeatureAtCoordinate =
  64190. function(coordinate, frameState, callback, thisArg) {
  64191. if (!this.replayGroup_) {
  64192. return undefined;
  64193. } else {
  64194. var resolution = frameState.viewState.resolution;
  64195. var rotation = frameState.viewState.rotation;
  64196. var layer = this.getLayer();
  64197. var layerState = frameState.layerStates[goog.getUid(layer)];
  64198. /** @type {Object.<string, boolean>} */
  64199. var features = {};
  64200. return this.replayGroup_.forEachFeatureAtCoordinate(coordinate, resolution,
  64201. rotation, layerState.managed ? frameState.skippedFeatureUids : {},
  64202. /**
  64203. * @param {ol.Feature} feature Feature.
  64204. * @return {?} Callback result.
  64205. */
  64206. function(feature) {
  64207. goog.asserts.assert(feature !== undefined, 'received a feature');
  64208. var key = goog.getUid(feature).toString();
  64209. if (!(key in features)) {
  64210. features[key] = true;
  64211. return callback.call(thisArg, feature, layer);
  64212. }
  64213. });
  64214. }
  64215. };
  64216. /**
  64217. * Handle changes in image style state.
  64218. * @param {goog.events.Event} event Image style change event.
  64219. * @private
  64220. */
  64221. ol.renderer.canvas.VectorLayer.prototype.handleStyleImageChange_ =
  64222. function(event) {
  64223. this.renderIfReadyAndVisible();
  64224. };
  64225. /**
  64226. * @inheritDoc
  64227. */
  64228. ol.renderer.canvas.VectorLayer.prototype.prepareFrame =
  64229. function(frameState, layerState) {
  64230. var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  64231. goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector,
  64232. 'layer is an instance of ol.layer.Vector');
  64233. var vectorSource = vectorLayer.getSource();
  64234. this.updateAttributions(
  64235. frameState.attributions, vectorSource.getAttributions());
  64236. this.updateLogos(frameState, vectorSource);
  64237. var animating = frameState.viewHints[ol.ViewHint.ANIMATING];
  64238. var interacting = frameState.viewHints[ol.ViewHint.INTERACTING];
  64239. var updateWhileAnimating = vectorLayer.getUpdateWhileAnimating();
  64240. var updateWhileInteracting = vectorLayer.getUpdateWhileInteracting();
  64241. if (!this.dirty_ && (!updateWhileAnimating && animating) ||
  64242. (!updateWhileInteracting && interacting)) {
  64243. return true;
  64244. }
  64245. var frameStateExtent = frameState.extent;
  64246. var viewState = frameState.viewState;
  64247. var projection = viewState.projection;
  64248. var resolution = viewState.resolution;
  64249. var pixelRatio = frameState.pixelRatio;
  64250. var vectorLayerRevision = vectorLayer.getRevision();
  64251. var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();
  64252. var vectorLayerRenderOrder = vectorLayer.getRenderOrder();
  64253. if (vectorLayerRenderOrder === undefined) {
  64254. vectorLayerRenderOrder = ol.renderer.vector.defaultOrder;
  64255. }
  64256. var extent = ol.extent.buffer(frameStateExtent,
  64257. vectorLayerRenderBuffer * resolution);
  64258. var projectionExtent = viewState.projection.getExtent();
  64259. if (vectorSource.getWrapX() && viewState.projection.canWrapX() &&
  64260. !ol.extent.containsExtent(projectionExtent, frameState.extent)) {
  64261. // For the replay group, we need an extent that intersects the real world
  64262. // (-180° to +180°). To support geometries in a coordinate range from -540°
  64263. // to +540°, we add at least 1 world width on each side of the projection
  64264. // extent. If the viewport is wider than the world, we need to add half of
  64265. // the viewport width to make sure we cover the whole viewport.
  64266. var worldWidth = ol.extent.getWidth(projectionExtent);
  64267. var buffer = Math.max(ol.extent.getWidth(extent) / 2, worldWidth);
  64268. extent[0] = projectionExtent[0] - buffer;
  64269. extent[2] = projectionExtent[2] + buffer;
  64270. }
  64271. if (!this.dirty_ &&
  64272. this.renderedResolution_ == resolution &&
  64273. this.renderedRevision_ == vectorLayerRevision &&
  64274. this.renderedRenderOrder_ == vectorLayerRenderOrder &&
  64275. ol.extent.containsExtent(this.renderedExtent_, extent)) {
  64276. return true;
  64277. }
  64278. // FIXME dispose of old replayGroup in post render
  64279. goog.dispose(this.replayGroup_);
  64280. this.replayGroup_ = null;
  64281. this.dirty_ = false;
  64282. var replayGroup =
  64283. new ol.render.canvas.ReplayGroup(
  64284. ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
  64285. resolution, vectorLayer.getRenderBuffer());
  64286. vectorSource.loadFeatures(extent, resolution, projection);
  64287. var renderFeature =
  64288. /**
  64289. * @param {ol.Feature} feature Feature.
  64290. * @this {ol.renderer.canvas.VectorLayer}
  64291. */
  64292. function(feature) {
  64293. var styles;
  64294. var styleFunction = feature.getStyleFunction();
  64295. if (styleFunction) {
  64296. styles = styleFunction.call(feature, resolution);
  64297. } else {
  64298. styleFunction = vectorLayer.getStyleFunction();
  64299. if (styleFunction) {
  64300. styles = styleFunction(feature, resolution);
  64301. }
  64302. }
  64303. if (styles) {
  64304. var dirty = this.renderFeature(
  64305. feature, resolution, pixelRatio, styles, replayGroup);
  64306. this.dirty_ = this.dirty_ || dirty;
  64307. }
  64308. };
  64309. if (vectorLayerRenderOrder) {
  64310. /** @type {Array.<ol.Feature>} */
  64311. var features = [];
  64312. vectorSource.forEachFeatureInExtentAtResolution(extent, resolution,
  64313. /**
  64314. * @param {ol.Feature} feature Feature.
  64315. */
  64316. function(feature) {
  64317. features.push(feature);
  64318. }, this);
  64319. goog.array.sort(features, vectorLayerRenderOrder);
  64320. features.forEach(renderFeature, this);
  64321. } else {
  64322. vectorSource.forEachFeatureInExtentAtResolution(
  64323. extent, resolution, renderFeature, this);
  64324. }
  64325. replayGroup.finish();
  64326. this.renderedResolution_ = resolution;
  64327. this.renderedRevision_ = vectorLayerRevision;
  64328. this.renderedRenderOrder_ = vectorLayerRenderOrder;
  64329. this.renderedExtent_ = extent;
  64330. this.replayGroup_ = replayGroup;
  64331. return true;
  64332. };
  64333. /**
  64334. * @param {ol.Feature} feature Feature.
  64335. * @param {number} resolution Resolution.
  64336. * @param {number} pixelRatio Pixel ratio.
  64337. * @param {Array.<ol.style.Style>} styles Array of styles
  64338. * @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
  64339. * @return {boolean} `true` if an image is loading.
  64340. */
  64341. ol.renderer.canvas.VectorLayer.prototype.renderFeature =
  64342. function(feature, resolution, pixelRatio, styles, replayGroup) {
  64343. if (!styles) {
  64344. return false;
  64345. }
  64346. var i, ii, loading = false;
  64347. for (i = 0, ii = styles.length; i < ii; ++i) {
  64348. loading = ol.renderer.vector.renderFeature(
  64349. replayGroup, feature, styles[i],
  64350. ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
  64351. this.handleStyleImageChange_, this) || loading;
  64352. }
  64353. return loading;
  64354. };
  64355. // FIXME offset panning
  64356. goog.provide('ol.renderer.canvas.Map');
  64357. goog.require('goog.array');
  64358. goog.require('goog.asserts');
  64359. goog.require('goog.dom');
  64360. goog.require('goog.style');
  64361. goog.require('goog.vec.Mat4');
  64362. goog.require('ol');
  64363. goog.require('ol.RendererType');
  64364. goog.require('ol.css');
  64365. goog.require('ol.dom');
  64366. goog.require('ol.layer.Image');
  64367. goog.require('ol.layer.Layer');
  64368. goog.require('ol.layer.Tile');
  64369. goog.require('ol.layer.Vector');
  64370. goog.require('ol.render.Event');
  64371. goog.require('ol.render.EventType');
  64372. goog.require('ol.render.canvas.Immediate');
  64373. goog.require('ol.renderer.Map');
  64374. goog.require('ol.renderer.canvas.ImageLayer');
  64375. goog.require('ol.renderer.canvas.Layer');
  64376. goog.require('ol.renderer.canvas.TileLayer');
  64377. goog.require('ol.renderer.canvas.VectorLayer');
  64378. goog.require('ol.source.State');
  64379. goog.require('ol.vec.Mat4');
  64380. /**
  64381. * @constructor
  64382. * @extends {ol.renderer.Map}
  64383. * @param {Element} container Container.
  64384. * @param {ol.Map} map Map.
  64385. */
  64386. ol.renderer.canvas.Map = function(container, map) {
  64387. goog.base(this, container, map);
  64388. /**
  64389. * @private
  64390. * @type {CanvasRenderingContext2D}
  64391. */
  64392. this.context_ = ol.dom.createCanvasContext2D();
  64393. /**
  64394. * @private
  64395. * @type {HTMLCanvasElement}
  64396. */
  64397. this.canvas_ = this.context_.canvas;
  64398. this.canvas_.style.width = '100%';
  64399. this.canvas_.style.height = '100%';
  64400. this.canvas_.className = ol.css.CLASS_UNSELECTABLE;
  64401. goog.dom.insertChildAt(container, this.canvas_, 0);
  64402. /**
  64403. * @private
  64404. * @type {boolean}
  64405. */
  64406. this.renderedVisible_ = true;
  64407. /**
  64408. * @private
  64409. * @type {!goog.vec.Mat4.Number}
  64410. */
  64411. this.transform_ = goog.vec.Mat4.createNumber();
  64412. };
  64413. goog.inherits(ol.renderer.canvas.Map, ol.renderer.Map);
  64414. /**
  64415. * @inheritDoc
  64416. */
  64417. ol.renderer.canvas.Map.prototype.createLayerRenderer = function(layer) {
  64418. if (ol.ENABLE_IMAGE && layer instanceof ol.layer.Image) {
  64419. return new ol.renderer.canvas.ImageLayer(layer);
  64420. } else if (ol.ENABLE_TILE && layer instanceof ol.layer.Tile) {
  64421. return new ol.renderer.canvas.TileLayer(layer);
  64422. } else if (ol.ENABLE_VECTOR && layer instanceof ol.layer.Vector) {
  64423. return new ol.renderer.canvas.VectorLayer(layer);
  64424. } else {
  64425. goog.asserts.fail('unexpected layer configuration');
  64426. return null;
  64427. }
  64428. };
  64429. /**
  64430. * @param {ol.render.EventType} type Event type.
  64431. * @param {olx.FrameState} frameState Frame state.
  64432. * @private
  64433. */
  64434. ol.renderer.canvas.Map.prototype.dispatchComposeEvent_ =
  64435. function(type, frameState) {
  64436. var map = this.getMap();
  64437. var context = this.context_;
  64438. if (map.hasListener(type)) {
  64439. var extent = frameState.extent;
  64440. var pixelRatio = frameState.pixelRatio;
  64441. var viewState = frameState.viewState;
  64442. var rotation = viewState.rotation;
  64443. var transform = this.getTransform(frameState);
  64444. var vectorContext = new ol.render.canvas.Immediate(context, pixelRatio,
  64445. extent, transform, rotation);
  64446. var composeEvent = new ol.render.Event(type, map, vectorContext,
  64447. frameState, context, null);
  64448. map.dispatchEvent(composeEvent);
  64449. vectorContext.flush();
  64450. }
  64451. };
  64452. /**
  64453. * @param {olx.FrameState} frameState Frame state.
  64454. * @protected
  64455. * @return {!goog.vec.Mat4.Number} Transform.
  64456. */
  64457. ol.renderer.canvas.Map.prototype.getTransform = function(frameState) {
  64458. var pixelRatio = frameState.pixelRatio;
  64459. var viewState = frameState.viewState;
  64460. var resolution = viewState.resolution;
  64461. return ol.vec.Mat4.makeTransform2D(this.transform_,
  64462. this.canvas_.width / 2, this.canvas_.height / 2,
  64463. pixelRatio / resolution, -pixelRatio / resolution,
  64464. -viewState.rotation,
  64465. -viewState.center[0], -viewState.center[1]);
  64466. };
  64467. /**
  64468. * @inheritDoc
  64469. */
  64470. ol.renderer.canvas.Map.prototype.getType = function() {
  64471. return ol.RendererType.CANVAS;
  64472. };
  64473. /**
  64474. * @inheritDoc
  64475. */
  64476. ol.renderer.canvas.Map.prototype.renderFrame = function(frameState) {
  64477. if (!frameState) {
  64478. if (this.renderedVisible_) {
  64479. goog.style.setElementShown(this.canvas_, false);
  64480. this.renderedVisible_ = false;
  64481. }
  64482. return;
  64483. }
  64484. var context = this.context_;
  64485. var width = frameState.size[0] * frameState.pixelRatio;
  64486. var height = frameState.size[1] * frameState.pixelRatio;
  64487. if (this.canvas_.width != width || this.canvas_.height != height) {
  64488. this.canvas_.width = width;
  64489. this.canvas_.height = height;
  64490. } else {
  64491. context.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
  64492. }
  64493. this.calculateMatrices2D(frameState);
  64494. this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE, frameState);
  64495. var layerStatesArray = frameState.layerStatesArray;
  64496. goog.array.stableSort(layerStatesArray, ol.renderer.Map.sortByZIndex);
  64497. var viewResolution = frameState.viewState.resolution;
  64498. var i, ii, layer, layerRenderer, layerState;
  64499. for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
  64500. layerState = layerStatesArray[i];
  64501. layer = layerState.layer;
  64502. layerRenderer = this.getLayerRenderer(layer);
  64503. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.canvas.Layer,
  64504. 'layerRenderer is an instance of ol.renderer.canvas.Layer');
  64505. if (!ol.layer.Layer.visibleAtResolution(layerState, viewResolution) ||
  64506. layerState.sourceState != ol.source.State.READY) {
  64507. continue;
  64508. }
  64509. if (layerRenderer.prepareFrame(frameState, layerState)) {
  64510. layerRenderer.composeFrame(frameState, layerState, context);
  64511. }
  64512. }
  64513. this.dispatchComposeEvent_(
  64514. ol.render.EventType.POSTCOMPOSE, frameState);
  64515. if (!this.renderedVisible_) {
  64516. goog.style.setElementShown(this.canvas_, true);
  64517. this.renderedVisible_ = true;
  64518. }
  64519. this.scheduleRemoveUnusedLayerRenderers(frameState);
  64520. this.scheduleExpireIconCache(frameState);
  64521. };
  64522. goog.provide('ol.renderer.dom.Layer');
  64523. goog.require('ol');
  64524. goog.require('ol.layer.Layer');
  64525. goog.require('ol.renderer.Layer');
  64526. /**
  64527. * @constructor
  64528. * @extends {ol.renderer.Layer}
  64529. * @param {ol.layer.Layer} layer Layer.
  64530. * @param {!Element} target Target.
  64531. */
  64532. ol.renderer.dom.Layer = function(layer, target) {
  64533. goog.base(this, layer);
  64534. /**
  64535. * @type {!Element}
  64536. * @protected
  64537. */
  64538. this.target = target;
  64539. };
  64540. goog.inherits(ol.renderer.dom.Layer, ol.renderer.Layer);
  64541. /**
  64542. * Clear rendered elements.
  64543. */
  64544. ol.renderer.dom.Layer.prototype.clearFrame = ol.nullFunction;
  64545. /**
  64546. * @param {olx.FrameState} frameState Frame state.
  64547. * @param {ol.layer.LayerState} layerState Layer state.
  64548. */
  64549. ol.renderer.dom.Layer.prototype.composeFrame = ol.nullFunction;
  64550. /**
  64551. * @return {!Element} Target.
  64552. */
  64553. ol.renderer.dom.Layer.prototype.getTarget = function() {
  64554. return this.target;
  64555. };
  64556. /**
  64557. * @param {olx.FrameState} frameState Frame state.
  64558. * @param {ol.layer.LayerState} layerState Layer state.
  64559. * @return {boolean} whether composeFrame should be called.
  64560. */
  64561. ol.renderer.dom.Layer.prototype.prepareFrame = goog.abstractMethod;
  64562. goog.provide('ol.renderer.dom.ImageLayer');
  64563. goog.require('goog.asserts');
  64564. goog.require('goog.dom');
  64565. goog.require('goog.dom.TagName');
  64566. goog.require('goog.vec.Mat4');
  64567. goog.require('ol.ImageBase');
  64568. goog.require('ol.ViewHint');
  64569. goog.require('ol.dom');
  64570. goog.require('ol.extent');
  64571. goog.require('ol.layer.Image');
  64572. goog.require('ol.proj');
  64573. goog.require('ol.renderer.dom.Layer');
  64574. goog.require('ol.vec.Mat4');
  64575. /**
  64576. * @constructor
  64577. * @extends {ol.renderer.dom.Layer}
  64578. * @param {ol.layer.Image} imageLayer Image layer.
  64579. */
  64580. ol.renderer.dom.ImageLayer = function(imageLayer) {
  64581. var target = goog.dom.createElement(goog.dom.TagName.DIV);
  64582. target.style.position = 'absolute';
  64583. goog.base(this, imageLayer, target);
  64584. /**
  64585. * The last rendered image.
  64586. * @private
  64587. * @type {?ol.ImageBase}
  64588. */
  64589. this.image_ = null;
  64590. /**
  64591. * @private
  64592. * @type {goog.vec.Mat4.Number}
  64593. */
  64594. this.transform_ = goog.vec.Mat4.createNumberIdentity();
  64595. };
  64596. goog.inherits(ol.renderer.dom.ImageLayer, ol.renderer.dom.Layer);
  64597. /**
  64598. * @inheritDoc
  64599. */
  64600. ol.renderer.dom.ImageLayer.prototype.forEachFeatureAtCoordinate =
  64601. function(coordinate, frameState, callback, thisArg) {
  64602. var layer = this.getLayer();
  64603. var source = layer.getSource();
  64604. var resolution = frameState.viewState.resolution;
  64605. var rotation = frameState.viewState.rotation;
  64606. var skippedFeatureUids = frameState.skippedFeatureUids;
  64607. return source.forEachFeatureAtCoordinate(
  64608. coordinate, resolution, rotation, skippedFeatureUids,
  64609. /**
  64610. * @param {ol.Feature} feature Feature.
  64611. * @return {?} Callback result.
  64612. */
  64613. function(feature) {
  64614. return callback.call(thisArg, feature, layer);
  64615. });
  64616. };
  64617. /**
  64618. * @inheritDoc
  64619. */
  64620. ol.renderer.dom.ImageLayer.prototype.clearFrame = function() {
  64621. goog.dom.removeChildren(this.target);
  64622. this.image_ = null;
  64623. };
  64624. /**
  64625. * @inheritDoc
  64626. */
  64627. ol.renderer.dom.ImageLayer.prototype.prepareFrame =
  64628. function(frameState, layerState) {
  64629. var viewState = frameState.viewState;
  64630. var viewCenter = viewState.center;
  64631. var viewResolution = viewState.resolution;
  64632. var viewRotation = viewState.rotation;
  64633. var image = this.image_;
  64634. var imageLayer = this.getLayer();
  64635. goog.asserts.assertInstanceof(imageLayer, ol.layer.Image,
  64636. 'layer is an instance of ol.layer.Image');
  64637. var imageSource = imageLayer.getSource();
  64638. var hints = frameState.viewHints;
  64639. var renderedExtent = frameState.extent;
  64640. if (layerState.extent !== undefined) {
  64641. renderedExtent = ol.extent.getIntersection(
  64642. renderedExtent, layerState.extent);
  64643. }
  64644. if (!hints[ol.ViewHint.ANIMATING] && !hints[ol.ViewHint.INTERACTING] &&
  64645. !ol.extent.isEmpty(renderedExtent)) {
  64646. var projection = viewState.projection;
  64647. var sourceProjection = imageSource.getProjection();
  64648. if (sourceProjection) {
  64649. goog.asserts.assert(ol.proj.equivalent(projection, sourceProjection),
  64650. 'projection and sourceProjection are equivalent');
  64651. projection = sourceProjection;
  64652. }
  64653. var image_ = imageSource.getImage(renderedExtent, viewResolution,
  64654. frameState.pixelRatio, projection);
  64655. if (image_) {
  64656. var loaded = this.loadImage(image_);
  64657. if (loaded) {
  64658. image = image_;
  64659. }
  64660. }
  64661. }
  64662. if (image) {
  64663. var imageExtent = image.getExtent();
  64664. var imageResolution = image.getResolution();
  64665. var transform = goog.vec.Mat4.createNumber();
  64666. ol.vec.Mat4.makeTransform2D(transform,
  64667. frameState.size[0] / 2, frameState.size[1] / 2,
  64668. imageResolution / viewResolution, imageResolution / viewResolution,
  64669. viewRotation,
  64670. (imageExtent[0] - viewCenter[0]) / imageResolution,
  64671. (viewCenter[1] - imageExtent[3]) / imageResolution);
  64672. if (image != this.image_) {
  64673. var imageElement = image.getImage(this);
  64674. // Bootstrap sets the style max-width: 100% for all images, which breaks
  64675. // prevents the image from being displayed in FireFox. Workaround by
  64676. // overriding the max-width style.
  64677. imageElement.style.maxWidth = 'none';
  64678. imageElement.style.position = 'absolute';
  64679. goog.dom.removeChildren(this.target);
  64680. this.target.appendChild(imageElement);
  64681. this.image_ = image;
  64682. }
  64683. this.setTransform_(transform);
  64684. this.updateAttributions(frameState.attributions, image.getAttributions());
  64685. this.updateLogos(frameState, imageSource);
  64686. }
  64687. return true;
  64688. };
  64689. /**
  64690. * @param {goog.vec.Mat4.Number} transform Transform.
  64691. * @private
  64692. */
  64693. ol.renderer.dom.ImageLayer.prototype.setTransform_ = function(transform) {
  64694. if (!ol.vec.Mat4.equals2D(transform, this.transform_)) {
  64695. ol.dom.transformElement2D(this.target, transform, 6);
  64696. goog.vec.Mat4.setFromArray(this.transform_, transform);
  64697. }
  64698. };
  64699. // FIXME probably need to reset TileLayerZ if offsets get too large
  64700. // FIXME when zooming out, preserve higher Z divs to avoid white flash
  64701. goog.provide('ol.renderer.dom.TileLayer');
  64702. goog.require('goog.array');
  64703. goog.require('goog.asserts');
  64704. goog.require('goog.dom');
  64705. goog.require('goog.dom.TagName');
  64706. goog.require('goog.style');
  64707. goog.require('goog.vec.Mat4');
  64708. goog.require('ol');
  64709. goog.require('ol.Coordinate');
  64710. goog.require('ol.TileCoord');
  64711. goog.require('ol.TileRange');
  64712. goog.require('ol.TileState');
  64713. goog.require('ol.ViewHint');
  64714. goog.require('ol.dom');
  64715. goog.require('ol.extent');
  64716. goog.require('ol.layer.Tile');
  64717. goog.require('ol.renderer.dom.Layer');
  64718. goog.require('ol.size');
  64719. goog.require('ol.tilecoord');
  64720. goog.require('ol.tilegrid.TileGrid');
  64721. goog.require('ol.vec.Mat4');
  64722. /**
  64723. * @constructor
  64724. * @extends {ol.renderer.dom.Layer}
  64725. * @param {ol.layer.Tile} tileLayer Tile layer.
  64726. */
  64727. ol.renderer.dom.TileLayer = function(tileLayer) {
  64728. var target = goog.dom.createElement(goog.dom.TagName.DIV);
  64729. target.style.position = 'absolute';
  64730. goog.base(this, tileLayer, target);
  64731. /**
  64732. * @private
  64733. * @type {boolean}
  64734. */
  64735. this.renderedVisible_ = true;
  64736. /**
  64737. * @private
  64738. * @type {number}
  64739. */
  64740. this.renderedOpacity_ = 1;
  64741. /**
  64742. * @private
  64743. * @type {number}
  64744. */
  64745. this.renderedRevision_ = 0;
  64746. /**
  64747. * @private
  64748. * @type {!Object.<number, ol.renderer.dom.TileLayerZ_>}
  64749. */
  64750. this.tileLayerZs_ = {};
  64751. };
  64752. goog.inherits(ol.renderer.dom.TileLayer, ol.renderer.dom.Layer);
  64753. /**
  64754. * @inheritDoc
  64755. */
  64756. ol.renderer.dom.TileLayer.prototype.clearFrame = function() {
  64757. goog.dom.removeChildren(this.target);
  64758. this.renderedRevision_ = 0;
  64759. };
  64760. /**
  64761. * @inheritDoc
  64762. */
  64763. ol.renderer.dom.TileLayer.prototype.prepareFrame =
  64764. function(frameState, layerState) {
  64765. if (!layerState.visible) {
  64766. if (this.renderedVisible_) {
  64767. goog.style.setElementShown(this.target, false);
  64768. this.renderedVisible_ = false;
  64769. }
  64770. return true;
  64771. }
  64772. var pixelRatio = frameState.pixelRatio;
  64773. var viewState = frameState.viewState;
  64774. var projection = viewState.projection;
  64775. var tileLayer = this.getLayer();
  64776. goog.asserts.assertInstanceof(tileLayer, ol.layer.Tile,
  64777. 'layer is an instance of ol.layer.Tile');
  64778. var tileSource = tileLayer.getSource();
  64779. var tileGrid = tileSource.getTileGridForProjection(projection);
  64780. var tileGutter = tileSource.getGutter();
  64781. var z = tileGrid.getZForResolution(viewState.resolution);
  64782. var tileResolution = tileGrid.getResolution(z);
  64783. var center = viewState.center;
  64784. var extent;
  64785. if (tileResolution == viewState.resolution) {
  64786. center = this.snapCenterToPixel(center, tileResolution, frameState.size);
  64787. extent = ol.extent.getForViewAndSize(
  64788. center, tileResolution, viewState.rotation, frameState.size);
  64789. } else {
  64790. extent = frameState.extent;
  64791. }
  64792. if (layerState.extent !== undefined) {
  64793. extent = ol.extent.getIntersection(extent, layerState.extent);
  64794. }
  64795. var tileRange = tileGrid.getTileRangeForExtentAndResolution(
  64796. extent, tileResolution);
  64797. /** @type {Object.<number, Object.<string, ol.Tile>>} */
  64798. var tilesToDrawByZ = {};
  64799. tilesToDrawByZ[z] = {};
  64800. var findLoadedTiles = this.createLoadedTileFinder(tileSource, tilesToDrawByZ);
  64801. var useInterimTilesOnError = tileLayer.getUseInterimTilesOnError();
  64802. var tmpExtent = ol.extent.createEmpty();
  64803. var tmpTileRange = new ol.TileRange(0, 0, 0, 0);
  64804. var childTileRange, fullyLoaded, tile, tileState, x, y;
  64805. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  64806. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  64807. tile = tileSource.getTile(z, x, y, pixelRatio, projection);
  64808. tileState = tile.getState();
  64809. if (tileState == ol.TileState.LOADED) {
  64810. tilesToDrawByZ[z][ol.tilecoord.toString(tile.tileCoord)] = tile;
  64811. continue;
  64812. } else if (tileState == ol.TileState.EMPTY ||
  64813. (tileState == ol.TileState.ERROR &&
  64814. !useInterimTilesOnError)) {
  64815. continue;
  64816. }
  64817. fullyLoaded = tileGrid.forEachTileCoordParentTileRange(
  64818. tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent);
  64819. if (!fullyLoaded) {
  64820. childTileRange = tileGrid.getTileCoordChildTileRange(
  64821. tile.tileCoord, tmpTileRange, tmpExtent);
  64822. if (childTileRange) {
  64823. findLoadedTiles(z + 1, childTileRange);
  64824. }
  64825. }
  64826. }
  64827. }
  64828. // If the tile source revision changes, we destroy the existing DOM structure
  64829. // so that a new one will be created. It would be more efficient to modify
  64830. // the existing structure.
  64831. var tileLayerZ, tileLayerZKey;
  64832. if (this.renderedRevision_ != tileSource.getRevision()) {
  64833. for (tileLayerZKey in this.tileLayerZs_) {
  64834. tileLayerZ = this.tileLayerZs_[+tileLayerZKey];
  64835. goog.dom.removeNode(tileLayerZ.target);
  64836. }
  64837. this.tileLayerZs_ = {};
  64838. this.renderedRevision_ = tileSource.getRevision();
  64839. }
  64840. /** @type {Array.<number>} */
  64841. var zs = Object.keys(tilesToDrawByZ).map(Number);
  64842. goog.array.sort(zs);
  64843. /** @type {Object.<number, boolean>} */
  64844. var newTileLayerZKeys = {};
  64845. var iz, iziz, tileCoordKey, tileCoordOrigin, tilesToDraw;
  64846. for (iz = 0, iziz = zs.length; iz < iziz; ++iz) {
  64847. tileLayerZKey = zs[iz];
  64848. if (tileLayerZKey in this.tileLayerZs_) {
  64849. tileLayerZ = this.tileLayerZs_[tileLayerZKey];
  64850. } else {
  64851. tileCoordOrigin =
  64852. tileGrid.getTileCoordForCoordAndZ(center, tileLayerZKey);
  64853. tileLayerZ = new ol.renderer.dom.TileLayerZ_(tileGrid, tileCoordOrigin);
  64854. newTileLayerZKeys[tileLayerZKey] = true;
  64855. this.tileLayerZs_[tileLayerZKey] = tileLayerZ;
  64856. }
  64857. tilesToDraw = tilesToDrawByZ[tileLayerZKey];
  64858. for (tileCoordKey in tilesToDraw) {
  64859. tileLayerZ.addTile(tilesToDraw[tileCoordKey], tileGutter);
  64860. }
  64861. tileLayerZ.finalizeAddTiles();
  64862. }
  64863. /** @type {Array.<number>} */
  64864. var tileLayerZKeys = Object.keys(this.tileLayerZs_).map(Number);
  64865. goog.array.sort(tileLayerZKeys);
  64866. var i, ii, j, origin, resolution;
  64867. var transform = goog.vec.Mat4.createNumber();
  64868. for (i = 0, ii = tileLayerZKeys.length; i < ii; ++i) {
  64869. tileLayerZKey = tileLayerZKeys[i];
  64870. tileLayerZ = this.tileLayerZs_[tileLayerZKey];
  64871. if (!(tileLayerZKey in tilesToDrawByZ)) {
  64872. goog.dom.removeNode(tileLayerZ.target);
  64873. delete this.tileLayerZs_[tileLayerZKey];
  64874. continue;
  64875. }
  64876. resolution = tileLayerZ.getResolution();
  64877. origin = tileLayerZ.getOrigin();
  64878. ol.vec.Mat4.makeTransform2D(transform,
  64879. frameState.size[0] / 2, frameState.size[1] / 2,
  64880. resolution / viewState.resolution,
  64881. resolution / viewState.resolution,
  64882. viewState.rotation,
  64883. (origin[0] - center[0]) / resolution,
  64884. (center[1] - origin[1]) / resolution);
  64885. tileLayerZ.setTransform(transform);
  64886. if (tileLayerZKey in newTileLayerZKeys) {
  64887. for (j = tileLayerZKey - 1; j >= 0; --j) {
  64888. if (j in this.tileLayerZs_) {
  64889. goog.dom.insertSiblingAfter(
  64890. tileLayerZ.target, this.tileLayerZs_[j].target);
  64891. break;
  64892. }
  64893. }
  64894. if (j < 0) {
  64895. goog.dom.insertChildAt(this.target, tileLayerZ.target, 0);
  64896. }
  64897. } else {
  64898. if (!frameState.viewHints[ol.ViewHint.ANIMATING] &&
  64899. !frameState.viewHints[ol.ViewHint.INTERACTING]) {
  64900. tileLayerZ.removeTilesOutsideExtent(extent, tmpTileRange);
  64901. }
  64902. }
  64903. }
  64904. if (layerState.opacity != this.renderedOpacity_) {
  64905. this.target.style.opacity = layerState.opacity;
  64906. this.renderedOpacity_ = layerState.opacity;
  64907. }
  64908. if (layerState.visible && !this.renderedVisible_) {
  64909. goog.style.setElementShown(this.target, true);
  64910. this.renderedVisible_ = true;
  64911. }
  64912. this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange);
  64913. this.manageTilePyramid(frameState, tileSource, tileGrid, pixelRatio,
  64914. projection, extent, z, tileLayer.getPreload());
  64915. this.scheduleExpireCache(frameState, tileSource);
  64916. this.updateLogos(frameState, tileSource);
  64917. return true;
  64918. };
  64919. /**
  64920. * @constructor
  64921. * @private
  64922. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  64923. * @param {ol.TileCoord} tileCoordOrigin Tile coord origin.
  64924. */
  64925. ol.renderer.dom.TileLayerZ_ = function(tileGrid, tileCoordOrigin) {
  64926. /**
  64927. * @type {!Element}
  64928. */
  64929. this.target = goog.dom.createElement(goog.dom.TagName.DIV);
  64930. this.target.style.position = 'absolute';
  64931. this.target.style.width = '100%';
  64932. this.target.style.height = '100%';
  64933. /**
  64934. * @private
  64935. * @type {ol.tilegrid.TileGrid}
  64936. */
  64937. this.tileGrid_ = tileGrid;
  64938. /**
  64939. * @private
  64940. * @type {ol.TileCoord}
  64941. */
  64942. this.tileCoordOrigin_ = tileCoordOrigin;
  64943. /**
  64944. * @private
  64945. * @type {ol.Coordinate}
  64946. */
  64947. this.origin_ =
  64948. ol.extent.getTopLeft(tileGrid.getTileCoordExtent(tileCoordOrigin));
  64949. /**
  64950. * @private
  64951. * @type {number}
  64952. */
  64953. this.resolution_ = tileGrid.getResolution(tileCoordOrigin[0]);
  64954. /**
  64955. * @private
  64956. * @type {Object.<string, ol.Tile>}
  64957. */
  64958. this.tiles_ = {};
  64959. /**
  64960. * @private
  64961. * @type {DocumentFragment}
  64962. */
  64963. this.documentFragment_ = null;
  64964. /**
  64965. * @private
  64966. * @type {goog.vec.Mat4.Number}
  64967. */
  64968. this.transform_ = goog.vec.Mat4.createNumberIdentity();
  64969. /**
  64970. * @private
  64971. * @type {ol.Size}
  64972. */
  64973. this.tmpSize_ = [0, 0];
  64974. };
  64975. /**
  64976. * @param {ol.Tile} tile Tile.
  64977. * @param {number} tileGutter Tile gutter.
  64978. */
  64979. ol.renderer.dom.TileLayerZ_.prototype.addTile = function(tile, tileGutter) {
  64980. var tileCoord = tile.tileCoord;
  64981. var tileCoordZ = tileCoord[0];
  64982. var tileCoordX = tileCoord[1];
  64983. var tileCoordY = tileCoord[2];
  64984. goog.asserts.assert(tileCoordZ == this.tileCoordOrigin_[0],
  64985. 'tileCoordZ matches z of tileCoordOrigin');
  64986. var tileCoordKey = ol.tilecoord.toString(tileCoord);
  64987. if (tileCoordKey in this.tiles_) {
  64988. return;
  64989. }
  64990. var tileSize = ol.size.toSize(
  64991. this.tileGrid_.getTileSize(tileCoordZ), this.tmpSize_);
  64992. var image = tile.getImage(this);
  64993. var imageStyle = image.style;
  64994. // Bootstrap sets the style max-width: 100% for all images, which
  64995. // prevents the tile from being displayed in FireFox. Workaround
  64996. // by overriding the max-width style.
  64997. imageStyle.maxWidth = 'none';
  64998. var tileElement;
  64999. var tileElementStyle;
  65000. if (tileGutter > 0) {
  65001. tileElement = goog.dom.createElement(goog.dom.TagName.DIV);
  65002. tileElementStyle = tileElement.style;
  65003. tileElementStyle.overflow = 'hidden';
  65004. tileElementStyle.width = tileSize[0] + 'px';
  65005. tileElementStyle.height = tileSize[1] + 'px';
  65006. imageStyle.position = 'absolute';
  65007. imageStyle.left = -tileGutter + 'px';
  65008. imageStyle.top = -tileGutter + 'px';
  65009. imageStyle.width = (tileSize[0] + 2 * tileGutter) + 'px';
  65010. imageStyle.height = (tileSize[1] + 2 * tileGutter) + 'px';
  65011. tileElement.appendChild(image);
  65012. } else {
  65013. imageStyle.width = tileSize[0] + 'px';
  65014. imageStyle.height = tileSize[1] + 'px';
  65015. tileElement = image;
  65016. tileElementStyle = imageStyle;
  65017. }
  65018. tileElementStyle.position = 'absolute';
  65019. tileElementStyle.left =
  65020. ((tileCoordX - this.tileCoordOrigin_[1]) * tileSize[0]) + 'px';
  65021. tileElementStyle.top =
  65022. ((this.tileCoordOrigin_[2] - tileCoordY) * tileSize[1]) + 'px';
  65023. if (!this.documentFragment_) {
  65024. this.documentFragment_ = document.createDocumentFragment();
  65025. }
  65026. this.documentFragment_.appendChild(tileElement);
  65027. this.tiles_[tileCoordKey] = tile;
  65028. };
  65029. /**
  65030. * FIXME empty description for jsdoc
  65031. */
  65032. ol.renderer.dom.TileLayerZ_.prototype.finalizeAddTiles = function() {
  65033. if (this.documentFragment_) {
  65034. this.target.appendChild(this.documentFragment_);
  65035. this.documentFragment_ = null;
  65036. }
  65037. };
  65038. /**
  65039. * @return {ol.Coordinate} Origin.
  65040. */
  65041. ol.renderer.dom.TileLayerZ_.prototype.getOrigin = function() {
  65042. return this.origin_;
  65043. };
  65044. /**
  65045. * @return {number} Resolution.
  65046. */
  65047. ol.renderer.dom.TileLayerZ_.prototype.getResolution = function() {
  65048. return this.resolution_;
  65049. };
  65050. /**
  65051. * @param {ol.Extent} extent Extent.
  65052. * @param {ol.TileRange=} opt_tileRange Temporary ol.TileRange object.
  65053. */
  65054. ol.renderer.dom.TileLayerZ_.prototype.removeTilesOutsideExtent =
  65055. function(extent, opt_tileRange) {
  65056. var tileRange = this.tileGrid_.getTileRangeForExtentAndZ(
  65057. extent, this.tileCoordOrigin_[0], opt_tileRange);
  65058. /** @type {Array.<ol.Tile>} */
  65059. var tilesToRemove = [];
  65060. var tile, tileCoordKey;
  65061. for (tileCoordKey in this.tiles_) {
  65062. tile = this.tiles_[tileCoordKey];
  65063. if (!tileRange.contains(tile.tileCoord)) {
  65064. tilesToRemove.push(tile);
  65065. }
  65066. }
  65067. var i, ii;
  65068. for (i = 0, ii = tilesToRemove.length; i < ii; ++i) {
  65069. tile = tilesToRemove[i];
  65070. tileCoordKey = ol.tilecoord.toString(tile.tileCoord);
  65071. goog.dom.removeNode(tile.getImage(this));
  65072. delete this.tiles_[tileCoordKey];
  65073. }
  65074. };
  65075. /**
  65076. * @param {goog.vec.Mat4.Number} transform Transform.
  65077. */
  65078. ol.renderer.dom.TileLayerZ_.prototype.setTransform = function(transform) {
  65079. if (!ol.vec.Mat4.equals2D(transform, this.transform_)) {
  65080. ol.dom.transformElement2D(this.target, transform, 6);
  65081. goog.vec.Mat4.setFromArray(this.transform_, transform);
  65082. }
  65083. };
  65084. goog.provide('ol.renderer.dom.VectorLayer');
  65085. goog.require('goog.array');
  65086. goog.require('goog.asserts');
  65087. goog.require('goog.events');
  65088. goog.require('goog.vec.Mat4');
  65089. goog.require('ol.ViewHint');
  65090. goog.require('ol.dom');
  65091. goog.require('ol.extent');
  65092. goog.require('ol.layer.Vector');
  65093. goog.require('ol.render.Event');
  65094. goog.require('ol.render.EventType');
  65095. goog.require('ol.render.canvas.Immediate');
  65096. goog.require('ol.render.canvas.ReplayGroup');
  65097. goog.require('ol.renderer.dom.Layer');
  65098. goog.require('ol.renderer.vector');
  65099. goog.require('ol.vec.Mat4');
  65100. /**
  65101. * @constructor
  65102. * @extends {ol.renderer.dom.Layer}
  65103. * @param {ol.layer.Vector} vectorLayer Vector layer.
  65104. */
  65105. ol.renderer.dom.VectorLayer = function(vectorLayer) {
  65106. /**
  65107. * @private
  65108. * @type {CanvasRenderingContext2D}
  65109. */
  65110. this.context_ = ol.dom.createCanvasContext2D();
  65111. var target = this.context_.canvas;
  65112. // Bootstrap sets the style max-width: 100% for all images, which breaks
  65113. // prevents the image from being displayed in FireFox. Workaround by
  65114. // overriding the max-width style.
  65115. target.style.maxWidth = 'none';
  65116. target.style.position = 'absolute';
  65117. goog.base(this, vectorLayer, target);
  65118. /**
  65119. * @private
  65120. * @type {boolean}
  65121. */
  65122. this.dirty_ = false;
  65123. /**
  65124. * @private
  65125. * @type {number}
  65126. */
  65127. this.renderedRevision_ = -1;
  65128. /**
  65129. * @private
  65130. * @type {number}
  65131. */
  65132. this.renderedResolution_ = NaN;
  65133. /**
  65134. * @private
  65135. * @type {ol.Extent}
  65136. */
  65137. this.renderedExtent_ = ol.extent.createEmpty();
  65138. /**
  65139. * @private
  65140. * @type {function(ol.Feature, ol.Feature): number|null}
  65141. */
  65142. this.renderedRenderOrder_ = null;
  65143. /**
  65144. * @private
  65145. * @type {ol.render.canvas.ReplayGroup}
  65146. */
  65147. this.replayGroup_ = null;
  65148. /**
  65149. * @private
  65150. * @type {goog.vec.Mat4.Number}
  65151. */
  65152. this.transform_ = goog.vec.Mat4.createNumber();
  65153. /**
  65154. * @private
  65155. * @type {goog.vec.Mat4.Number}
  65156. */
  65157. this.elementTransform_ = goog.vec.Mat4.createNumber();
  65158. };
  65159. goog.inherits(ol.renderer.dom.VectorLayer, ol.renderer.dom.Layer);
  65160. /**
  65161. * @inheritDoc
  65162. */
  65163. ol.renderer.dom.VectorLayer.prototype.composeFrame =
  65164. function(frameState, layerState) {
  65165. var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  65166. goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector,
  65167. 'layer is an instance of ol.layer.Vector');
  65168. var viewState = frameState.viewState;
  65169. var viewCenter = viewState.center;
  65170. var viewRotation = viewState.rotation;
  65171. var viewResolution = viewState.resolution;
  65172. var pixelRatio = frameState.pixelRatio;
  65173. var viewWidth = frameState.size[0];
  65174. var viewHeight = frameState.size[1];
  65175. var imageWidth = viewWidth * pixelRatio;
  65176. var imageHeight = viewHeight * pixelRatio;
  65177. var transform = ol.vec.Mat4.makeTransform2D(this.transform_,
  65178. pixelRatio * viewWidth / 2,
  65179. pixelRatio * viewHeight / 2,
  65180. pixelRatio / viewResolution,
  65181. -pixelRatio / viewResolution,
  65182. -viewRotation,
  65183. -viewCenter[0], -viewCenter[1]);
  65184. var context = this.context_;
  65185. // Clear the canvas and set the correct size
  65186. context.canvas.width = imageWidth;
  65187. context.canvas.height = imageHeight;
  65188. var elementTransform = ol.vec.Mat4.makeTransform2D(this.elementTransform_,
  65189. 0, 0,
  65190. 1 / pixelRatio, 1 / pixelRatio,
  65191. 0,
  65192. -(imageWidth - viewWidth) / 2 * pixelRatio,
  65193. -(imageHeight - viewHeight) / 2 * pixelRatio);
  65194. ol.dom.transformElement2D(context.canvas, elementTransform, 6);
  65195. this.dispatchEvent_(ol.render.EventType.PRECOMPOSE, frameState, transform);
  65196. var replayGroup = this.replayGroup_;
  65197. if (replayGroup && !replayGroup.isEmpty()) {
  65198. context.globalAlpha = layerState.opacity;
  65199. replayGroup.replay(context, pixelRatio, transform, viewRotation,
  65200. layerState.managed ? frameState.skippedFeatureUids : {});
  65201. this.dispatchEvent_(ol.render.EventType.RENDER, frameState, transform);
  65202. }
  65203. this.dispatchEvent_(ol.render.EventType.POSTCOMPOSE, frameState, transform);
  65204. };
  65205. /**
  65206. * @param {ol.render.EventType} type Event type.
  65207. * @param {olx.FrameState} frameState Frame state.
  65208. * @param {goog.vec.Mat4.Number} transform Transform.
  65209. * @private
  65210. */
  65211. ol.renderer.dom.VectorLayer.prototype.dispatchEvent_ =
  65212. function(type, frameState, transform) {
  65213. var context = this.context_;
  65214. var layer = this.getLayer();
  65215. if (layer.hasListener(type)) {
  65216. var render = new ol.render.canvas.Immediate(
  65217. context, frameState.pixelRatio, frameState.extent, transform,
  65218. frameState.viewState.rotation);
  65219. var event = new ol.render.Event(type, layer, render, frameState,
  65220. context, null);
  65221. layer.dispatchEvent(event);
  65222. render.flush();
  65223. }
  65224. };
  65225. /**
  65226. * @inheritDoc
  65227. */
  65228. ol.renderer.dom.VectorLayer.prototype.forEachFeatureAtCoordinate =
  65229. function(coordinate, frameState, callback, thisArg) {
  65230. if (!this.replayGroup_) {
  65231. return undefined;
  65232. } else {
  65233. var resolution = frameState.viewState.resolution;
  65234. var rotation = frameState.viewState.rotation;
  65235. var layer = this.getLayer();
  65236. var layerState = frameState.layerStates[goog.getUid(layer)];
  65237. /** @type {Object.<string, boolean>} */
  65238. var features = {};
  65239. return this.replayGroup_.forEachFeatureAtCoordinate(coordinate, resolution,
  65240. rotation, layerState.managed ? frameState.skippedFeatureUids : {},
  65241. /**
  65242. * @param {ol.Feature} feature Feature.
  65243. * @return {?} Callback result.
  65244. */
  65245. function(feature) {
  65246. goog.asserts.assert(feature !== undefined, 'received a feature');
  65247. var key = goog.getUid(feature).toString();
  65248. if (!(key in features)) {
  65249. features[key] = true;
  65250. return callback.call(thisArg, feature, layer);
  65251. }
  65252. });
  65253. }
  65254. };
  65255. /**
  65256. * Handle changes in image style state.
  65257. * @param {goog.events.Event} event Image style change event.
  65258. * @private
  65259. */
  65260. ol.renderer.dom.VectorLayer.prototype.handleStyleImageChange_ =
  65261. function(event) {
  65262. this.renderIfReadyAndVisible();
  65263. };
  65264. /**
  65265. * @inheritDoc
  65266. */
  65267. ol.renderer.dom.VectorLayer.prototype.prepareFrame =
  65268. function(frameState, layerState) {
  65269. var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  65270. goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector,
  65271. 'layer is an instance of ol.layer.Vector');
  65272. var vectorSource = vectorLayer.getSource();
  65273. this.updateAttributions(
  65274. frameState.attributions, vectorSource.getAttributions());
  65275. this.updateLogos(frameState, vectorSource);
  65276. var animating = frameState.viewHints[ol.ViewHint.ANIMATING];
  65277. var interacting = frameState.viewHints[ol.ViewHint.INTERACTING];
  65278. var updateWhileAnimating = vectorLayer.getUpdateWhileAnimating();
  65279. var updateWhileInteracting = vectorLayer.getUpdateWhileInteracting();
  65280. if (!this.dirty_ && (!updateWhileAnimating && animating) ||
  65281. (!updateWhileInteracting && interacting)) {
  65282. return true;
  65283. }
  65284. var frameStateExtent = frameState.extent;
  65285. var viewState = frameState.viewState;
  65286. var projection = viewState.projection;
  65287. var resolution = viewState.resolution;
  65288. var pixelRatio = frameState.pixelRatio;
  65289. var vectorLayerRevision = vectorLayer.getRevision();
  65290. var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();
  65291. var vectorLayerRenderOrder = vectorLayer.getRenderOrder();
  65292. if (vectorLayerRenderOrder === undefined) {
  65293. vectorLayerRenderOrder = ol.renderer.vector.defaultOrder;
  65294. }
  65295. var extent = ol.extent.buffer(frameStateExtent,
  65296. vectorLayerRenderBuffer * resolution);
  65297. if (!this.dirty_ &&
  65298. this.renderedResolution_ == resolution &&
  65299. this.renderedRevision_ == vectorLayerRevision &&
  65300. this.renderedRenderOrder_ == vectorLayerRenderOrder &&
  65301. ol.extent.containsExtent(this.renderedExtent_, extent)) {
  65302. return true;
  65303. }
  65304. // FIXME dispose of old replayGroup in post render
  65305. goog.dispose(this.replayGroup_);
  65306. this.replayGroup_ = null;
  65307. this.dirty_ = false;
  65308. var replayGroup =
  65309. new ol.render.canvas.ReplayGroup(
  65310. ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
  65311. resolution, vectorLayer.getRenderBuffer());
  65312. vectorSource.loadFeatures(extent, resolution, projection);
  65313. var renderFeature =
  65314. /**
  65315. * @param {ol.Feature} feature Feature.
  65316. * @this {ol.renderer.dom.VectorLayer}
  65317. */
  65318. function(feature) {
  65319. var styles;
  65320. var styleFunction = feature.getStyleFunction();
  65321. if (styleFunction) {
  65322. styles = styleFunction.call(feature, resolution);
  65323. } else {
  65324. styleFunction = vectorLayer.getStyleFunction();
  65325. if (styleFunction) {
  65326. styles = styleFunction(feature, resolution);
  65327. }
  65328. }
  65329. if (styles) {
  65330. var dirty = this.renderFeature(
  65331. feature, resolution, pixelRatio, styles, replayGroup);
  65332. this.dirty_ = this.dirty_ || dirty;
  65333. }
  65334. };
  65335. if (vectorLayerRenderOrder) {
  65336. /** @type {Array.<ol.Feature>} */
  65337. var features = [];
  65338. vectorSource.forEachFeatureInExtentAtResolution(extent, resolution,
  65339. /**
  65340. * @param {ol.Feature} feature Feature.
  65341. */
  65342. function(feature) {
  65343. features.push(feature);
  65344. }, this);
  65345. goog.array.sort(features, vectorLayerRenderOrder);
  65346. features.forEach(renderFeature, this);
  65347. } else {
  65348. vectorSource.forEachFeatureInExtentAtResolution(
  65349. extent, resolution, renderFeature, this);
  65350. }
  65351. replayGroup.finish();
  65352. this.renderedResolution_ = resolution;
  65353. this.renderedRevision_ = vectorLayerRevision;
  65354. this.renderedRenderOrder_ = vectorLayerRenderOrder;
  65355. this.renderedExtent_ = extent;
  65356. this.replayGroup_ = replayGroup;
  65357. return true;
  65358. };
  65359. /**
  65360. * @param {ol.Feature} feature Feature.
  65361. * @param {number} resolution Resolution.
  65362. * @param {number} pixelRatio Pixel ratio.
  65363. * @param {Array.<ol.style.Style>} styles Array of styles
  65364. * @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
  65365. * @return {boolean} `true` if an image is loading.
  65366. */
  65367. ol.renderer.dom.VectorLayer.prototype.renderFeature =
  65368. function(feature, resolution, pixelRatio, styles, replayGroup) {
  65369. if (!styles) {
  65370. return false;
  65371. }
  65372. var i, ii, loading = false;
  65373. for (i = 0, ii = styles.length; i < ii; ++i) {
  65374. loading = ol.renderer.vector.renderFeature(
  65375. replayGroup, feature, styles[i],
  65376. ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
  65377. this.handleStyleImageChange_, this) || loading;
  65378. }
  65379. return loading;
  65380. };
  65381. goog.provide('ol.renderer.dom.Map');
  65382. goog.require('goog.array');
  65383. goog.require('goog.asserts');
  65384. goog.require('goog.dom');
  65385. goog.require('goog.dom.TagName');
  65386. goog.require('goog.events');
  65387. goog.require('goog.events.Event');
  65388. goog.require('goog.events.EventType');
  65389. goog.require('goog.style');
  65390. goog.require('goog.vec.Mat4');
  65391. goog.require('ol');
  65392. goog.require('ol.RendererType');
  65393. goog.require('ol.css');
  65394. goog.require('ol.dom');
  65395. goog.require('ol.layer.Image');
  65396. goog.require('ol.layer.Layer');
  65397. goog.require('ol.layer.Tile');
  65398. goog.require('ol.layer.Vector');
  65399. goog.require('ol.render.Event');
  65400. goog.require('ol.render.EventType');
  65401. goog.require('ol.render.canvas.Immediate');
  65402. goog.require('ol.renderer.Map');
  65403. goog.require('ol.renderer.dom.ImageLayer');
  65404. goog.require('ol.renderer.dom.Layer');
  65405. goog.require('ol.renderer.dom.TileLayer');
  65406. goog.require('ol.renderer.dom.VectorLayer');
  65407. goog.require('ol.source.State');
  65408. goog.require('ol.vec.Mat4');
  65409. /**
  65410. * @constructor
  65411. * @extends {ol.renderer.Map}
  65412. * @param {Element} container Container.
  65413. * @param {ol.Map} map Map.
  65414. */
  65415. ol.renderer.dom.Map = function(container, map) {
  65416. goog.base(this, container, map);
  65417. /**
  65418. * @private
  65419. * @type {CanvasRenderingContext2D}
  65420. */
  65421. this.context_ = ol.dom.createCanvasContext2D();
  65422. var canvas = this.context_.canvas;
  65423. canvas.style.position = 'absolute';
  65424. canvas.style.width = '100%';
  65425. canvas.style.height = '100%';
  65426. canvas.className = ol.css.CLASS_UNSELECTABLE;
  65427. goog.dom.insertChildAt(container, canvas, 0);
  65428. /**
  65429. * @private
  65430. * @type {!goog.vec.Mat4.Number}
  65431. */
  65432. this.transform_ = goog.vec.Mat4.createNumber();
  65433. /**
  65434. * @type {!Element}
  65435. * @private
  65436. */
  65437. this.layersPane_ = goog.dom.createElement(goog.dom.TagName.DIV);
  65438. this.layersPane_.className = ol.css.CLASS_UNSELECTABLE;
  65439. var style = this.layersPane_.style;
  65440. style.position = 'absolute';
  65441. style.width = '100%';
  65442. style.height = '100%';
  65443. // prevent the img context menu on mobile devices
  65444. goog.events.listen(this.layersPane_, goog.events.EventType.TOUCHSTART,
  65445. goog.events.Event.preventDefault);
  65446. goog.dom.insertChildAt(container, this.layersPane_, 0);
  65447. /**
  65448. * @private
  65449. * @type {boolean}
  65450. */
  65451. this.renderedVisible_ = true;
  65452. };
  65453. goog.inherits(ol.renderer.dom.Map, ol.renderer.Map);
  65454. /**
  65455. * @inheritDoc
  65456. */
  65457. ol.renderer.dom.Map.prototype.disposeInternal = function() {
  65458. goog.dom.removeNode(this.layersPane_);
  65459. goog.base(this, 'disposeInternal');
  65460. };
  65461. /**
  65462. * @inheritDoc
  65463. */
  65464. ol.renderer.dom.Map.prototype.createLayerRenderer = function(layer) {
  65465. var layerRenderer;
  65466. if (ol.ENABLE_IMAGE && layer instanceof ol.layer.Image) {
  65467. layerRenderer = new ol.renderer.dom.ImageLayer(layer);
  65468. } else if (ol.ENABLE_TILE && layer instanceof ol.layer.Tile) {
  65469. layerRenderer = new ol.renderer.dom.TileLayer(layer);
  65470. } else if (ol.ENABLE_VECTOR && layer instanceof ol.layer.Vector) {
  65471. layerRenderer = new ol.renderer.dom.VectorLayer(layer);
  65472. } else {
  65473. goog.asserts.fail('unexpected layer configuration');
  65474. return null;
  65475. }
  65476. return layerRenderer;
  65477. };
  65478. /**
  65479. * @param {ol.render.EventType} type Event type.
  65480. * @param {olx.FrameState} frameState Frame state.
  65481. * @private
  65482. */
  65483. ol.renderer.dom.Map.prototype.dispatchComposeEvent_ =
  65484. function(type, frameState) {
  65485. var map = this.getMap();
  65486. if (map.hasListener(type)) {
  65487. var extent = frameState.extent;
  65488. var pixelRatio = frameState.pixelRatio;
  65489. var viewState = frameState.viewState;
  65490. var rotation = viewState.rotation;
  65491. var context = this.context_;
  65492. var canvas = context.canvas;
  65493. ol.vec.Mat4.makeTransform2D(this.transform_,
  65494. canvas.width / 2,
  65495. canvas.height / 2,
  65496. pixelRatio / viewState.resolution,
  65497. -pixelRatio / viewState.resolution,
  65498. -viewState.rotation,
  65499. -viewState.center[0], -viewState.center[1]);
  65500. var vectorContext = new ol.render.canvas.Immediate(context, pixelRatio,
  65501. extent, this.transform_, rotation);
  65502. var composeEvent = new ol.render.Event(type, map, vectorContext,
  65503. frameState, context, null);
  65504. map.dispatchEvent(composeEvent);
  65505. vectorContext.flush();
  65506. }
  65507. };
  65508. /**
  65509. * @inheritDoc
  65510. */
  65511. ol.renderer.dom.Map.prototype.getType = function() {
  65512. return ol.RendererType.DOM;
  65513. };
  65514. /**
  65515. * @inheritDoc
  65516. */
  65517. ol.renderer.dom.Map.prototype.renderFrame = function(frameState) {
  65518. if (!frameState) {
  65519. if (this.renderedVisible_) {
  65520. goog.style.setElementShown(this.layersPane_, false);
  65521. this.renderedVisible_ = false;
  65522. }
  65523. return;
  65524. }
  65525. var map = this.getMap();
  65526. if (map.hasListener(ol.render.EventType.PRECOMPOSE) ||
  65527. map.hasListener(ol.render.EventType.POSTCOMPOSE)) {
  65528. var canvas = this.context_.canvas;
  65529. var pixelRatio = frameState.pixelRatio;
  65530. canvas.width = frameState.size[0] * pixelRatio;
  65531. canvas.height = frameState.size[1] * pixelRatio;
  65532. }
  65533. this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE, frameState);
  65534. var layerStatesArray = frameState.layerStatesArray;
  65535. goog.array.stableSort(layerStatesArray, ol.renderer.Map.sortByZIndex);
  65536. var viewResolution = frameState.viewState.resolution;
  65537. var i, ii, layer, layerRenderer, layerState;
  65538. for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
  65539. layerState = layerStatesArray[i];
  65540. layer = layerState.layer;
  65541. layerRenderer = /** @type {ol.renderer.dom.Layer} */ (
  65542. this.getLayerRenderer(layer));
  65543. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.dom.Layer,
  65544. 'renderer is an instance of ol.renderer.dom.Layer');
  65545. goog.dom.insertChildAt(this.layersPane_, layerRenderer.getTarget(), i);
  65546. if (ol.layer.Layer.visibleAtResolution(layerState, viewResolution) &&
  65547. layerState.sourceState == ol.source.State.READY) {
  65548. if (layerRenderer.prepareFrame(frameState, layerState)) {
  65549. layerRenderer.composeFrame(frameState, layerState);
  65550. }
  65551. } else {
  65552. layerRenderer.clearFrame();
  65553. }
  65554. }
  65555. var layerStates = frameState.layerStates;
  65556. var layerKey;
  65557. for (layerKey in this.getLayerRenderers()) {
  65558. if (!(layerKey in layerStates)) {
  65559. layerRenderer = this.getLayerRendererByKey(layerKey);
  65560. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.dom.Layer,
  65561. 'renderer is an instance of ol.renderer.dom.Layer');
  65562. goog.dom.removeNode(layerRenderer.getTarget());
  65563. }
  65564. }
  65565. if (!this.renderedVisible_) {
  65566. goog.style.setElementShown(this.layersPane_, true);
  65567. this.renderedVisible_ = true;
  65568. }
  65569. this.calculateMatrices2D(frameState);
  65570. this.scheduleRemoveUnusedLayerRenderers(frameState);
  65571. this.scheduleExpireIconCache(frameState);
  65572. this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE, frameState);
  65573. };
  65574. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  65575. //
  65576. // Licensed under the Apache License, Version 2.0 (the "License");
  65577. // you may not use this file except in compliance with the License.
  65578. // You may obtain a copy of the License at
  65579. //
  65580. // http://www.apache.org/licenses/LICENSE-2.0
  65581. //
  65582. // Unless required by applicable law or agreed to in writing, software
  65583. // distributed under the License is distributed on an "AS-IS" BASIS,
  65584. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65585. // See the License for the specific language governing permissions and
  65586. // limitations under the License.
  65587. /**
  65588. * @fileoverview Constants used by the WebGL rendering, including all of the
  65589. * constants used from the WebGL context. For example, instead of using
  65590. * context.ARRAY_BUFFER, your code can use
  65591. * goog.webgl.ARRAY_BUFFER. The benefits for doing this include allowing
  65592. * the compiler to optimize your code so that the compiled code does not have to
  65593. * contain large strings to reference these properties, and reducing runtime
  65594. * property access.
  65595. *
  65596. * Values are taken from the WebGL Spec:
  65597. * https://www.khronos.org/registry/webgl/specs/1.0/#WEBGLRENDERINGCONTEXT
  65598. */
  65599. goog.provide('goog.webgl');
  65600. /**
  65601. * @const
  65602. * @type {number}
  65603. */
  65604. goog.webgl.DEPTH_BUFFER_BIT = 0x00000100;
  65605. /**
  65606. * @const
  65607. * @type {number}
  65608. */
  65609. goog.webgl.STENCIL_BUFFER_BIT = 0x00000400;
  65610. /**
  65611. * @const
  65612. * @type {number}
  65613. */
  65614. goog.webgl.COLOR_BUFFER_BIT = 0x00004000;
  65615. /**
  65616. * @const
  65617. * @type {number}
  65618. */
  65619. goog.webgl.POINTS = 0x0000;
  65620. /**
  65621. * @const
  65622. * @type {number}
  65623. */
  65624. goog.webgl.LINES = 0x0001;
  65625. /**
  65626. * @const
  65627. * @type {number}
  65628. */
  65629. goog.webgl.LINE_LOOP = 0x0002;
  65630. /**
  65631. * @const
  65632. * @type {number}
  65633. */
  65634. goog.webgl.LINE_STRIP = 0x0003;
  65635. /**
  65636. * @const
  65637. * @type {number}
  65638. */
  65639. goog.webgl.TRIANGLES = 0x0004;
  65640. /**
  65641. * @const
  65642. * @type {number}
  65643. */
  65644. goog.webgl.TRIANGLE_STRIP = 0x0005;
  65645. /**
  65646. * @const
  65647. * @type {number}
  65648. */
  65649. goog.webgl.TRIANGLE_FAN = 0x0006;
  65650. /**
  65651. * @const
  65652. * @type {number}
  65653. */
  65654. goog.webgl.ZERO = 0;
  65655. /**
  65656. * @const
  65657. * @type {number}
  65658. */
  65659. goog.webgl.ONE = 1;
  65660. /**
  65661. * @const
  65662. * @type {number}
  65663. */
  65664. goog.webgl.SRC_COLOR = 0x0300;
  65665. /**
  65666. * @const
  65667. * @type {number}
  65668. */
  65669. goog.webgl.ONE_MINUS_SRC_COLOR = 0x0301;
  65670. /**
  65671. * @const
  65672. * @type {number}
  65673. */
  65674. goog.webgl.SRC_ALPHA = 0x0302;
  65675. /**
  65676. * @const
  65677. * @type {number}
  65678. */
  65679. goog.webgl.ONE_MINUS_SRC_ALPHA = 0x0303;
  65680. /**
  65681. * @const
  65682. * @type {number}
  65683. */
  65684. goog.webgl.DST_ALPHA = 0x0304;
  65685. /**
  65686. * @const
  65687. * @type {number}
  65688. */
  65689. goog.webgl.ONE_MINUS_DST_ALPHA = 0x0305;
  65690. /**
  65691. * @const
  65692. * @type {number}
  65693. */
  65694. goog.webgl.DST_COLOR = 0x0306;
  65695. /**
  65696. * @const
  65697. * @type {number}
  65698. */
  65699. goog.webgl.ONE_MINUS_DST_COLOR = 0x0307;
  65700. /**
  65701. * @const
  65702. * @type {number}
  65703. */
  65704. goog.webgl.SRC_ALPHA_SATURATE = 0x0308;
  65705. /**
  65706. * @const
  65707. * @type {number}
  65708. */
  65709. goog.webgl.FUNC_ADD = 0x8006;
  65710. /**
  65711. * @const
  65712. * @type {number}
  65713. */
  65714. goog.webgl.BLEND_EQUATION = 0x8009;
  65715. /**
  65716. * Same as BLEND_EQUATION
  65717. * @const
  65718. * @type {number}
  65719. */
  65720. goog.webgl.BLEND_EQUATION_RGB = 0x8009;
  65721. /**
  65722. * @const
  65723. * @type {number}
  65724. */
  65725. goog.webgl.BLEND_EQUATION_ALPHA = 0x883D;
  65726. /**
  65727. * @const
  65728. * @type {number}
  65729. */
  65730. goog.webgl.FUNC_SUBTRACT = 0x800A;
  65731. /**
  65732. * @const
  65733. * @type {number}
  65734. */
  65735. goog.webgl.FUNC_REVERSE_SUBTRACT = 0x800B;
  65736. /**
  65737. * @const
  65738. * @type {number}
  65739. */
  65740. goog.webgl.BLEND_DST_RGB = 0x80C8;
  65741. /**
  65742. * @const
  65743. * @type {number}
  65744. */
  65745. goog.webgl.BLEND_SRC_RGB = 0x80C9;
  65746. /**
  65747. * @const
  65748. * @type {number}
  65749. */
  65750. goog.webgl.BLEND_DST_ALPHA = 0x80CA;
  65751. /**
  65752. * @const
  65753. * @type {number}
  65754. */
  65755. goog.webgl.BLEND_SRC_ALPHA = 0x80CB;
  65756. /**
  65757. * @const
  65758. * @type {number}
  65759. */
  65760. goog.webgl.CONSTANT_COLOR = 0x8001;
  65761. /**
  65762. * @const
  65763. * @type {number}
  65764. */
  65765. goog.webgl.ONE_MINUS_CONSTANT_COLOR = 0x8002;
  65766. /**
  65767. * @const
  65768. * @type {number}
  65769. */
  65770. goog.webgl.CONSTANT_ALPHA = 0x8003;
  65771. /**
  65772. * @const
  65773. * @type {number}
  65774. */
  65775. goog.webgl.ONE_MINUS_CONSTANT_ALPHA = 0x8004;
  65776. /**
  65777. * @const
  65778. * @type {number}
  65779. */
  65780. goog.webgl.BLEND_COLOR = 0x8005;
  65781. /**
  65782. * @const
  65783. * @type {number}
  65784. */
  65785. goog.webgl.ARRAY_BUFFER = 0x8892;
  65786. /**
  65787. * @const
  65788. * @type {number}
  65789. */
  65790. goog.webgl.ELEMENT_ARRAY_BUFFER = 0x8893;
  65791. /**
  65792. * @const
  65793. * @type {number}
  65794. */
  65795. goog.webgl.ARRAY_BUFFER_BINDING = 0x8894;
  65796. /**
  65797. * @const
  65798. * @type {number}
  65799. */
  65800. goog.webgl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
  65801. /**
  65802. * @const
  65803. * @type {number}
  65804. */
  65805. goog.webgl.STREAM_DRAW = 0x88E0;
  65806. /**
  65807. * @const
  65808. * @type {number}
  65809. */
  65810. goog.webgl.STATIC_DRAW = 0x88E4;
  65811. /**
  65812. * @const
  65813. * @type {number}
  65814. */
  65815. goog.webgl.DYNAMIC_DRAW = 0x88E8;
  65816. /**
  65817. * @const
  65818. * @type {number}
  65819. */
  65820. goog.webgl.BUFFER_SIZE = 0x8764;
  65821. /**
  65822. * @const
  65823. * @type {number}
  65824. */
  65825. goog.webgl.BUFFER_USAGE = 0x8765;
  65826. /**
  65827. * @const
  65828. * @type {number}
  65829. */
  65830. goog.webgl.CURRENT_VERTEX_ATTRIB = 0x8626;
  65831. /**
  65832. * @const
  65833. * @type {number}
  65834. */
  65835. goog.webgl.FRONT = 0x0404;
  65836. /**
  65837. * @const
  65838. * @type {number}
  65839. */
  65840. goog.webgl.BACK = 0x0405;
  65841. /**
  65842. * @const
  65843. * @type {number}
  65844. */
  65845. goog.webgl.FRONT_AND_BACK = 0x0408;
  65846. /**
  65847. * @const
  65848. * @type {number}
  65849. */
  65850. goog.webgl.CULL_FACE = 0x0B44;
  65851. /**
  65852. * @const
  65853. * @type {number}
  65854. */
  65855. goog.webgl.BLEND = 0x0BE2;
  65856. /**
  65857. * @const
  65858. * @type {number}
  65859. */
  65860. goog.webgl.DITHER = 0x0BD0;
  65861. /**
  65862. * @const
  65863. * @type {number}
  65864. */
  65865. goog.webgl.STENCIL_TEST = 0x0B90;
  65866. /**
  65867. * @const
  65868. * @type {number}
  65869. */
  65870. goog.webgl.DEPTH_TEST = 0x0B71;
  65871. /**
  65872. * @const
  65873. * @type {number}
  65874. */
  65875. goog.webgl.SCISSOR_TEST = 0x0C11;
  65876. /**
  65877. * @const
  65878. * @type {number}
  65879. */
  65880. goog.webgl.POLYGON_OFFSET_FILL = 0x8037;
  65881. /**
  65882. * @const
  65883. * @type {number}
  65884. */
  65885. goog.webgl.SAMPLE_ALPHA_TO_COVERAGE = 0x809E;
  65886. /**
  65887. * @const
  65888. * @type {number}
  65889. */
  65890. goog.webgl.SAMPLE_COVERAGE = 0x80A0;
  65891. /**
  65892. * @const
  65893. * @type {number}
  65894. */
  65895. goog.webgl.NO_ERROR = 0;
  65896. /**
  65897. * @const
  65898. * @type {number}
  65899. */
  65900. goog.webgl.INVALID_ENUM = 0x0500;
  65901. /**
  65902. * @const
  65903. * @type {number}
  65904. */
  65905. goog.webgl.INVALID_VALUE = 0x0501;
  65906. /**
  65907. * @const
  65908. * @type {number}
  65909. */
  65910. goog.webgl.INVALID_OPERATION = 0x0502;
  65911. /**
  65912. * @const
  65913. * @type {number}
  65914. */
  65915. goog.webgl.OUT_OF_MEMORY = 0x0505;
  65916. /**
  65917. * @const
  65918. * @type {number}
  65919. */
  65920. goog.webgl.CW = 0x0900;
  65921. /**
  65922. * @const
  65923. * @type {number}
  65924. */
  65925. goog.webgl.CCW = 0x0901;
  65926. /**
  65927. * @const
  65928. * @type {number}
  65929. */
  65930. goog.webgl.LINE_WIDTH = 0x0B21;
  65931. /**
  65932. * @const
  65933. * @type {number}
  65934. */
  65935. goog.webgl.ALIASED_POINT_SIZE_RANGE = 0x846D;
  65936. /**
  65937. * @const
  65938. * @type {number}
  65939. */
  65940. goog.webgl.ALIASED_LINE_WIDTH_RANGE = 0x846E;
  65941. /**
  65942. * @const
  65943. * @type {number}
  65944. */
  65945. goog.webgl.CULL_FACE_MODE = 0x0B45;
  65946. /**
  65947. * @const
  65948. * @type {number}
  65949. */
  65950. goog.webgl.FRONT_FACE = 0x0B46;
  65951. /**
  65952. * @const
  65953. * @type {number}
  65954. */
  65955. goog.webgl.DEPTH_RANGE = 0x0B70;
  65956. /**
  65957. * @const
  65958. * @type {number}
  65959. */
  65960. goog.webgl.DEPTH_WRITEMASK = 0x0B72;
  65961. /**
  65962. * @const
  65963. * @type {number}
  65964. */
  65965. goog.webgl.DEPTH_CLEAR_VALUE = 0x0B73;
  65966. /**
  65967. * @const
  65968. * @type {number}
  65969. */
  65970. goog.webgl.DEPTH_FUNC = 0x0B74;
  65971. /**
  65972. * @const
  65973. * @type {number}
  65974. */
  65975. goog.webgl.STENCIL_CLEAR_VALUE = 0x0B91;
  65976. /**
  65977. * @const
  65978. * @type {number}
  65979. */
  65980. goog.webgl.STENCIL_FUNC = 0x0B92;
  65981. /**
  65982. * @const
  65983. * @type {number}
  65984. */
  65985. goog.webgl.STENCIL_FAIL = 0x0B94;
  65986. /**
  65987. * @const
  65988. * @type {number}
  65989. */
  65990. goog.webgl.STENCIL_PASS_DEPTH_FAIL = 0x0B95;
  65991. /**
  65992. * @const
  65993. * @type {number}
  65994. */
  65995. goog.webgl.STENCIL_PASS_DEPTH_PASS = 0x0B96;
  65996. /**
  65997. * @const
  65998. * @type {number}
  65999. */
  66000. goog.webgl.STENCIL_REF = 0x0B97;
  66001. /**
  66002. * @const
  66003. * @type {number}
  66004. */
  66005. goog.webgl.STENCIL_VALUE_MASK = 0x0B93;
  66006. /**
  66007. * @const
  66008. * @type {number}
  66009. */
  66010. goog.webgl.STENCIL_WRITEMASK = 0x0B98;
  66011. /**
  66012. * @const
  66013. * @type {number}
  66014. */
  66015. goog.webgl.STENCIL_BACK_FUNC = 0x8800;
  66016. /**
  66017. * @const
  66018. * @type {number}
  66019. */
  66020. goog.webgl.STENCIL_BACK_FAIL = 0x8801;
  66021. /**
  66022. * @const
  66023. * @type {number}
  66024. */
  66025. goog.webgl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
  66026. /**
  66027. * @const
  66028. * @type {number}
  66029. */
  66030. goog.webgl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
  66031. /**
  66032. * @const
  66033. * @type {number}
  66034. */
  66035. goog.webgl.STENCIL_BACK_REF = 0x8CA3;
  66036. /**
  66037. * @const
  66038. * @type {number}
  66039. */
  66040. goog.webgl.STENCIL_BACK_VALUE_MASK = 0x8CA4;
  66041. /**
  66042. * @const
  66043. * @type {number}
  66044. */
  66045. goog.webgl.STENCIL_BACK_WRITEMASK = 0x8CA5;
  66046. /**
  66047. * @const
  66048. * @type {number}
  66049. */
  66050. goog.webgl.VIEWPORT = 0x0BA2;
  66051. /**
  66052. * @const
  66053. * @type {number}
  66054. */
  66055. goog.webgl.SCISSOR_BOX = 0x0C10;
  66056. /**
  66057. * @const
  66058. * @type {number}
  66059. */
  66060. goog.webgl.COLOR_CLEAR_VALUE = 0x0C22;
  66061. /**
  66062. * @const
  66063. * @type {number}
  66064. */
  66065. goog.webgl.COLOR_WRITEMASK = 0x0C23;
  66066. /**
  66067. * @const
  66068. * @type {number}
  66069. */
  66070. goog.webgl.UNPACK_ALIGNMENT = 0x0CF5;
  66071. /**
  66072. * @const
  66073. * @type {number}
  66074. */
  66075. goog.webgl.PACK_ALIGNMENT = 0x0D05;
  66076. /**
  66077. * @const
  66078. * @type {number}
  66079. */
  66080. goog.webgl.MAX_TEXTURE_SIZE = 0x0D33;
  66081. /**
  66082. * @const
  66083. * @type {number}
  66084. */
  66085. goog.webgl.MAX_VIEWPORT_DIMS = 0x0D3A;
  66086. /**
  66087. * @const
  66088. * @type {number}
  66089. */
  66090. goog.webgl.SUBPIXEL_BITS = 0x0D50;
  66091. /**
  66092. * @const
  66093. * @type {number}
  66094. */
  66095. goog.webgl.RED_BITS = 0x0D52;
  66096. /**
  66097. * @const
  66098. * @type {number}
  66099. */
  66100. goog.webgl.GREEN_BITS = 0x0D53;
  66101. /**
  66102. * @const
  66103. * @type {number}
  66104. */
  66105. goog.webgl.BLUE_BITS = 0x0D54;
  66106. /**
  66107. * @const
  66108. * @type {number}
  66109. */
  66110. goog.webgl.ALPHA_BITS = 0x0D55;
  66111. /**
  66112. * @const
  66113. * @type {number}
  66114. */
  66115. goog.webgl.DEPTH_BITS = 0x0D56;
  66116. /**
  66117. * @const
  66118. * @type {number}
  66119. */
  66120. goog.webgl.STENCIL_BITS = 0x0D57;
  66121. /**
  66122. * @const
  66123. * @type {number}
  66124. */
  66125. goog.webgl.POLYGON_OFFSET_UNITS = 0x2A00;
  66126. /**
  66127. * @const
  66128. * @type {number}
  66129. */
  66130. goog.webgl.POLYGON_OFFSET_FACTOR = 0x8038;
  66131. /**
  66132. * @const
  66133. * @type {number}
  66134. */
  66135. goog.webgl.TEXTURE_BINDING_2D = 0x8069;
  66136. /**
  66137. * @const
  66138. * @type {number}
  66139. */
  66140. goog.webgl.SAMPLE_BUFFERS = 0x80A8;
  66141. /**
  66142. * @const
  66143. * @type {number}
  66144. */
  66145. goog.webgl.SAMPLES = 0x80A9;
  66146. /**
  66147. * @const
  66148. * @type {number}
  66149. */
  66150. goog.webgl.SAMPLE_COVERAGE_VALUE = 0x80AA;
  66151. /**
  66152. * @const
  66153. * @type {number}
  66154. */
  66155. goog.webgl.SAMPLE_COVERAGE_INVERT = 0x80AB;
  66156. /**
  66157. * @const
  66158. * @type {number}
  66159. */
  66160. goog.webgl.COMPRESSED_TEXTURE_FORMATS = 0x86A3;
  66161. /**
  66162. * @const
  66163. * @type {number}
  66164. */
  66165. goog.webgl.DONT_CARE = 0x1100;
  66166. /**
  66167. * @const
  66168. * @type {number}
  66169. */
  66170. goog.webgl.FASTEST = 0x1101;
  66171. /**
  66172. * @const
  66173. * @type {number}
  66174. */
  66175. goog.webgl.NICEST = 0x1102;
  66176. /**
  66177. * @const
  66178. * @type {number}
  66179. */
  66180. goog.webgl.GENERATE_MIPMAP_HINT = 0x8192;
  66181. /**
  66182. * @const
  66183. * @type {number}
  66184. */
  66185. goog.webgl.BYTE = 0x1400;
  66186. /**
  66187. * @const
  66188. * @type {number}
  66189. */
  66190. goog.webgl.UNSIGNED_BYTE = 0x1401;
  66191. /**
  66192. * @const
  66193. * @type {number}
  66194. */
  66195. goog.webgl.SHORT = 0x1402;
  66196. /**
  66197. * @const
  66198. * @type {number}
  66199. */
  66200. goog.webgl.UNSIGNED_SHORT = 0x1403;
  66201. /**
  66202. * @const
  66203. * @type {number}
  66204. */
  66205. goog.webgl.INT = 0x1404;
  66206. /**
  66207. * @const
  66208. * @type {number}
  66209. */
  66210. goog.webgl.UNSIGNED_INT = 0x1405;
  66211. /**
  66212. * @const
  66213. * @type {number}
  66214. */
  66215. goog.webgl.FLOAT = 0x1406;
  66216. /**
  66217. * @const
  66218. * @type {number}
  66219. */
  66220. goog.webgl.DEPTH_COMPONENT = 0x1902;
  66221. /**
  66222. * @const
  66223. * @type {number}
  66224. */
  66225. goog.webgl.ALPHA = 0x1906;
  66226. /**
  66227. * @const
  66228. * @type {number}
  66229. */
  66230. goog.webgl.RGB = 0x1907;
  66231. /**
  66232. * @const
  66233. * @type {number}
  66234. */
  66235. goog.webgl.RGBA = 0x1908;
  66236. /**
  66237. * @const
  66238. * @type {number}
  66239. */
  66240. goog.webgl.LUMINANCE = 0x1909;
  66241. /**
  66242. * @const
  66243. * @type {number}
  66244. */
  66245. goog.webgl.LUMINANCE_ALPHA = 0x190A;
  66246. /**
  66247. * @const
  66248. * @type {number}
  66249. */
  66250. goog.webgl.UNSIGNED_SHORT_4_4_4_4 = 0x8033;
  66251. /**
  66252. * @const
  66253. * @type {number}
  66254. */
  66255. goog.webgl.UNSIGNED_SHORT_5_5_5_1 = 0x8034;
  66256. /**
  66257. * @const
  66258. * @type {number}
  66259. */
  66260. goog.webgl.UNSIGNED_SHORT_5_6_5 = 0x8363;
  66261. /**
  66262. * @const
  66263. * @type {number}
  66264. */
  66265. goog.webgl.FRAGMENT_SHADER = 0x8B30;
  66266. /**
  66267. * @const
  66268. * @type {number}
  66269. */
  66270. goog.webgl.VERTEX_SHADER = 0x8B31;
  66271. /**
  66272. * @const
  66273. * @type {number}
  66274. */
  66275. goog.webgl.MAX_VERTEX_ATTRIBS = 0x8869;
  66276. /**
  66277. * @const
  66278. * @type {number}
  66279. */
  66280. goog.webgl.MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB;
  66281. /**
  66282. * @const
  66283. * @type {number}
  66284. */
  66285. goog.webgl.MAX_VARYING_VECTORS = 0x8DFC;
  66286. /**
  66287. * @const
  66288. * @type {number}
  66289. */
  66290. goog.webgl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
  66291. /**
  66292. * @const
  66293. * @type {number}
  66294. */
  66295. goog.webgl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
  66296. /**
  66297. * @const
  66298. * @type {number}
  66299. */
  66300. goog.webgl.MAX_TEXTURE_IMAGE_UNITS = 0x8872;
  66301. /**
  66302. * @const
  66303. * @type {number}
  66304. */
  66305. goog.webgl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD;
  66306. /**
  66307. * @const
  66308. * @type {number}
  66309. */
  66310. goog.webgl.SHADER_TYPE = 0x8B4F;
  66311. /**
  66312. * @const
  66313. * @type {number}
  66314. */
  66315. goog.webgl.DELETE_STATUS = 0x8B80;
  66316. /**
  66317. * @const
  66318. * @type {number}
  66319. */
  66320. goog.webgl.LINK_STATUS = 0x8B82;
  66321. /**
  66322. * @const
  66323. * @type {number}
  66324. */
  66325. goog.webgl.VALIDATE_STATUS = 0x8B83;
  66326. /**
  66327. * @const
  66328. * @type {number}
  66329. */
  66330. goog.webgl.ATTACHED_SHADERS = 0x8B85;
  66331. /**
  66332. * @const
  66333. * @type {number}
  66334. */
  66335. goog.webgl.ACTIVE_UNIFORMS = 0x8B86;
  66336. /**
  66337. * @const
  66338. * @type {number}
  66339. */
  66340. goog.webgl.ACTIVE_ATTRIBUTES = 0x8B89;
  66341. /**
  66342. * @const
  66343. * @type {number}
  66344. */
  66345. goog.webgl.SHADING_LANGUAGE_VERSION = 0x8B8C;
  66346. /**
  66347. * @const
  66348. * @type {number}
  66349. */
  66350. goog.webgl.CURRENT_PROGRAM = 0x8B8D;
  66351. /**
  66352. * @const
  66353. * @type {number}
  66354. */
  66355. goog.webgl.NEVER = 0x0200;
  66356. /**
  66357. * @const
  66358. * @type {number}
  66359. */
  66360. goog.webgl.LESS = 0x0201;
  66361. /**
  66362. * @const
  66363. * @type {number}
  66364. */
  66365. goog.webgl.EQUAL = 0x0202;
  66366. /**
  66367. * @const
  66368. * @type {number}
  66369. */
  66370. goog.webgl.LEQUAL = 0x0203;
  66371. /**
  66372. * @const
  66373. * @type {number}
  66374. */
  66375. goog.webgl.GREATER = 0x0204;
  66376. /**
  66377. * @const
  66378. * @type {number}
  66379. */
  66380. goog.webgl.NOTEQUAL = 0x0205;
  66381. /**
  66382. * @const
  66383. * @type {number}
  66384. */
  66385. goog.webgl.GEQUAL = 0x0206;
  66386. /**
  66387. * @const
  66388. * @type {number}
  66389. */
  66390. goog.webgl.ALWAYS = 0x0207;
  66391. /**
  66392. * @const
  66393. * @type {number}
  66394. */
  66395. goog.webgl.KEEP = 0x1E00;
  66396. /**
  66397. * @const
  66398. * @type {number}
  66399. */
  66400. goog.webgl.REPLACE = 0x1E01;
  66401. /**
  66402. * @const
  66403. * @type {number}
  66404. */
  66405. goog.webgl.INCR = 0x1E02;
  66406. /**
  66407. * @const
  66408. * @type {number}
  66409. */
  66410. goog.webgl.DECR = 0x1E03;
  66411. /**
  66412. * @const
  66413. * @type {number}
  66414. */
  66415. goog.webgl.INVERT = 0x150A;
  66416. /**
  66417. * @const
  66418. * @type {number}
  66419. */
  66420. goog.webgl.INCR_WRAP = 0x8507;
  66421. /**
  66422. * @const
  66423. * @type {number}
  66424. */
  66425. goog.webgl.DECR_WRAP = 0x8508;
  66426. /**
  66427. * @const
  66428. * @type {number}
  66429. */
  66430. goog.webgl.VENDOR = 0x1F00;
  66431. /**
  66432. * @const
  66433. * @type {number}
  66434. */
  66435. goog.webgl.RENDERER = 0x1F01;
  66436. /**
  66437. * @const
  66438. * @type {number}
  66439. */
  66440. goog.webgl.VERSION = 0x1F02;
  66441. /**
  66442. * @const
  66443. * @type {number}
  66444. */
  66445. goog.webgl.NEAREST = 0x2600;
  66446. /**
  66447. * @const
  66448. * @type {number}
  66449. */
  66450. goog.webgl.LINEAR = 0x2601;
  66451. /**
  66452. * @const
  66453. * @type {number}
  66454. */
  66455. goog.webgl.NEAREST_MIPMAP_NEAREST = 0x2700;
  66456. /**
  66457. * @const
  66458. * @type {number}
  66459. */
  66460. goog.webgl.LINEAR_MIPMAP_NEAREST = 0x2701;
  66461. /**
  66462. * @const
  66463. * @type {number}
  66464. */
  66465. goog.webgl.NEAREST_MIPMAP_LINEAR = 0x2702;
  66466. /**
  66467. * @const
  66468. * @type {number}
  66469. */
  66470. goog.webgl.LINEAR_MIPMAP_LINEAR = 0x2703;
  66471. /**
  66472. * @const
  66473. * @type {number}
  66474. */
  66475. goog.webgl.TEXTURE_MAG_FILTER = 0x2800;
  66476. /**
  66477. * @const
  66478. * @type {number}
  66479. */
  66480. goog.webgl.TEXTURE_MIN_FILTER = 0x2801;
  66481. /**
  66482. * @const
  66483. * @type {number}
  66484. */
  66485. goog.webgl.TEXTURE_WRAP_S = 0x2802;
  66486. /**
  66487. * @const
  66488. * @type {number}
  66489. */
  66490. goog.webgl.TEXTURE_WRAP_T = 0x2803;
  66491. /**
  66492. * @const
  66493. * @type {number}
  66494. */
  66495. goog.webgl.TEXTURE_2D = 0x0DE1;
  66496. /**
  66497. * @const
  66498. * @type {number}
  66499. */
  66500. goog.webgl.TEXTURE = 0x1702;
  66501. /**
  66502. * @const
  66503. * @type {number}
  66504. */
  66505. goog.webgl.TEXTURE_CUBE_MAP = 0x8513;
  66506. /**
  66507. * @const
  66508. * @type {number}
  66509. */
  66510. goog.webgl.TEXTURE_BINDING_CUBE_MAP = 0x8514;
  66511. /**
  66512. * @const
  66513. * @type {number}
  66514. */
  66515. goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;
  66516. /**
  66517. * @const
  66518. * @type {number}
  66519. */
  66520. goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;
  66521. /**
  66522. * @const
  66523. * @type {number}
  66524. */
  66525. goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;
  66526. /**
  66527. * @const
  66528. * @type {number}
  66529. */
  66530. goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;
  66531. /**
  66532. * @const
  66533. * @type {number}
  66534. */
  66535. goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;
  66536. /**
  66537. * @const
  66538. * @type {number}
  66539. */
  66540. goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A;
  66541. /**
  66542. * @const
  66543. * @type {number}
  66544. */
  66545. goog.webgl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C;
  66546. /**
  66547. * @const
  66548. * @type {number}
  66549. */
  66550. goog.webgl.TEXTURE0 = 0x84C0;
  66551. /**
  66552. * @const
  66553. * @type {number}
  66554. */
  66555. goog.webgl.TEXTURE1 = 0x84C1;
  66556. /**
  66557. * @const
  66558. * @type {number}
  66559. */
  66560. goog.webgl.TEXTURE2 = 0x84C2;
  66561. /**
  66562. * @const
  66563. * @type {number}
  66564. */
  66565. goog.webgl.TEXTURE3 = 0x84C3;
  66566. /**
  66567. * @const
  66568. * @type {number}
  66569. */
  66570. goog.webgl.TEXTURE4 = 0x84C4;
  66571. /**
  66572. * @const
  66573. * @type {number}
  66574. */
  66575. goog.webgl.TEXTURE5 = 0x84C5;
  66576. /**
  66577. * @const
  66578. * @type {number}
  66579. */
  66580. goog.webgl.TEXTURE6 = 0x84C6;
  66581. /**
  66582. * @const
  66583. * @type {number}
  66584. */
  66585. goog.webgl.TEXTURE7 = 0x84C7;
  66586. /**
  66587. * @const
  66588. * @type {number}
  66589. */
  66590. goog.webgl.TEXTURE8 = 0x84C8;
  66591. /**
  66592. * @const
  66593. * @type {number}
  66594. */
  66595. goog.webgl.TEXTURE9 = 0x84C9;
  66596. /**
  66597. * @const
  66598. * @type {number}
  66599. */
  66600. goog.webgl.TEXTURE10 = 0x84CA;
  66601. /**
  66602. * @const
  66603. * @type {number}
  66604. */
  66605. goog.webgl.TEXTURE11 = 0x84CB;
  66606. /**
  66607. * @const
  66608. * @type {number}
  66609. */
  66610. goog.webgl.TEXTURE12 = 0x84CC;
  66611. /**
  66612. * @const
  66613. * @type {number}
  66614. */
  66615. goog.webgl.TEXTURE13 = 0x84CD;
  66616. /**
  66617. * @const
  66618. * @type {number}
  66619. */
  66620. goog.webgl.TEXTURE14 = 0x84CE;
  66621. /**
  66622. * @const
  66623. * @type {number}
  66624. */
  66625. goog.webgl.TEXTURE15 = 0x84CF;
  66626. /**
  66627. * @const
  66628. * @type {number}
  66629. */
  66630. goog.webgl.TEXTURE16 = 0x84D0;
  66631. /**
  66632. * @const
  66633. * @type {number}
  66634. */
  66635. goog.webgl.TEXTURE17 = 0x84D1;
  66636. /**
  66637. * @const
  66638. * @type {number}
  66639. */
  66640. goog.webgl.TEXTURE18 = 0x84D2;
  66641. /**
  66642. * @const
  66643. * @type {number}
  66644. */
  66645. goog.webgl.TEXTURE19 = 0x84D3;
  66646. /**
  66647. * @const
  66648. * @type {number}
  66649. */
  66650. goog.webgl.TEXTURE20 = 0x84D4;
  66651. /**
  66652. * @const
  66653. * @type {number}
  66654. */
  66655. goog.webgl.TEXTURE21 = 0x84D5;
  66656. /**
  66657. * @const
  66658. * @type {number}
  66659. */
  66660. goog.webgl.TEXTURE22 = 0x84D6;
  66661. /**
  66662. * @const
  66663. * @type {number}
  66664. */
  66665. goog.webgl.TEXTURE23 = 0x84D7;
  66666. /**
  66667. * @const
  66668. * @type {number}
  66669. */
  66670. goog.webgl.TEXTURE24 = 0x84D8;
  66671. /**
  66672. * @const
  66673. * @type {number}
  66674. */
  66675. goog.webgl.TEXTURE25 = 0x84D9;
  66676. /**
  66677. * @const
  66678. * @type {number}
  66679. */
  66680. goog.webgl.TEXTURE26 = 0x84DA;
  66681. /**
  66682. * @const
  66683. * @type {number}
  66684. */
  66685. goog.webgl.TEXTURE27 = 0x84DB;
  66686. /**
  66687. * @const
  66688. * @type {number}
  66689. */
  66690. goog.webgl.TEXTURE28 = 0x84DC;
  66691. /**
  66692. * @const
  66693. * @type {number}
  66694. */
  66695. goog.webgl.TEXTURE29 = 0x84DD;
  66696. /**
  66697. * @const
  66698. * @type {number}
  66699. */
  66700. goog.webgl.TEXTURE30 = 0x84DE;
  66701. /**
  66702. * @const
  66703. * @type {number}
  66704. */
  66705. goog.webgl.TEXTURE31 = 0x84DF;
  66706. /**
  66707. * @const
  66708. * @type {number}
  66709. */
  66710. goog.webgl.ACTIVE_TEXTURE = 0x84E0;
  66711. /**
  66712. * @const
  66713. * @type {number}
  66714. */
  66715. goog.webgl.REPEAT = 0x2901;
  66716. /**
  66717. * @const
  66718. * @type {number}
  66719. */
  66720. goog.webgl.CLAMP_TO_EDGE = 0x812F;
  66721. /**
  66722. * @const
  66723. * @type {number}
  66724. */
  66725. goog.webgl.MIRRORED_REPEAT = 0x8370;
  66726. /**
  66727. * @const
  66728. * @type {number}
  66729. */
  66730. goog.webgl.FLOAT_VEC2 = 0x8B50;
  66731. /**
  66732. * @const
  66733. * @type {number}
  66734. */
  66735. goog.webgl.FLOAT_VEC3 = 0x8B51;
  66736. /**
  66737. * @const
  66738. * @type {number}
  66739. */
  66740. goog.webgl.FLOAT_VEC4 = 0x8B52;
  66741. /**
  66742. * @const
  66743. * @type {number}
  66744. */
  66745. goog.webgl.INT_VEC2 = 0x8B53;
  66746. /**
  66747. * @const
  66748. * @type {number}
  66749. */
  66750. goog.webgl.INT_VEC3 = 0x8B54;
  66751. /**
  66752. * @const
  66753. * @type {number}
  66754. */
  66755. goog.webgl.INT_VEC4 = 0x8B55;
  66756. /**
  66757. * @const
  66758. * @type {number}
  66759. */
  66760. goog.webgl.BOOL = 0x8B56;
  66761. /**
  66762. * @const
  66763. * @type {number}
  66764. */
  66765. goog.webgl.BOOL_VEC2 = 0x8B57;
  66766. /**
  66767. * @const
  66768. * @type {number}
  66769. */
  66770. goog.webgl.BOOL_VEC3 = 0x8B58;
  66771. /**
  66772. * @const
  66773. * @type {number}
  66774. */
  66775. goog.webgl.BOOL_VEC4 = 0x8B59;
  66776. /**
  66777. * @const
  66778. * @type {number}
  66779. */
  66780. goog.webgl.FLOAT_MAT2 = 0x8B5A;
  66781. /**
  66782. * @const
  66783. * @type {number}
  66784. */
  66785. goog.webgl.FLOAT_MAT3 = 0x8B5B;
  66786. /**
  66787. * @const
  66788. * @type {number}
  66789. */
  66790. goog.webgl.FLOAT_MAT4 = 0x8B5C;
  66791. /**
  66792. * @const
  66793. * @type {number}
  66794. */
  66795. goog.webgl.SAMPLER_2D = 0x8B5E;
  66796. /**
  66797. * @const
  66798. * @type {number}
  66799. */
  66800. goog.webgl.SAMPLER_CUBE = 0x8B60;
  66801. /**
  66802. * @const
  66803. * @type {number}
  66804. */
  66805. goog.webgl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
  66806. /**
  66807. * @const
  66808. * @type {number}
  66809. */
  66810. goog.webgl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
  66811. /**
  66812. * @const
  66813. * @type {number}
  66814. */
  66815. goog.webgl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
  66816. /**
  66817. * @const
  66818. * @type {number}
  66819. */
  66820. goog.webgl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
  66821. /**
  66822. * @const
  66823. * @type {number}
  66824. */
  66825. goog.webgl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
  66826. /**
  66827. * @const
  66828. * @type {number}
  66829. */
  66830. goog.webgl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
  66831. /**
  66832. * @const
  66833. * @type {number}
  66834. */
  66835. goog.webgl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F;
  66836. /**
  66837. * @const
  66838. * @type {number}
  66839. */
  66840. goog.webgl.COMPILE_STATUS = 0x8B81;
  66841. /**
  66842. * @const
  66843. * @type {number}
  66844. */
  66845. goog.webgl.LOW_FLOAT = 0x8DF0;
  66846. /**
  66847. * @const
  66848. * @type {number}
  66849. */
  66850. goog.webgl.MEDIUM_FLOAT = 0x8DF1;
  66851. /**
  66852. * @const
  66853. * @type {number}
  66854. */
  66855. goog.webgl.HIGH_FLOAT = 0x8DF2;
  66856. /**
  66857. * @const
  66858. * @type {number}
  66859. */
  66860. goog.webgl.LOW_INT = 0x8DF3;
  66861. /**
  66862. * @const
  66863. * @type {number}
  66864. */
  66865. goog.webgl.MEDIUM_INT = 0x8DF4;
  66866. /**
  66867. * @const
  66868. * @type {number}
  66869. */
  66870. goog.webgl.HIGH_INT = 0x8DF5;
  66871. /**
  66872. * @const
  66873. * @type {number}
  66874. */
  66875. goog.webgl.FRAMEBUFFER = 0x8D40;
  66876. /**
  66877. * @const
  66878. * @type {number}
  66879. */
  66880. goog.webgl.RENDERBUFFER = 0x8D41;
  66881. /**
  66882. * @const
  66883. * @type {number}
  66884. */
  66885. goog.webgl.RGBA4 = 0x8056;
  66886. /**
  66887. * @const
  66888. * @type {number}
  66889. */
  66890. goog.webgl.RGB5_A1 = 0x8057;
  66891. /**
  66892. * @const
  66893. * @type {number}
  66894. */
  66895. goog.webgl.RGB565 = 0x8D62;
  66896. /**
  66897. * @const
  66898. * @type {number}
  66899. */
  66900. goog.webgl.DEPTH_COMPONENT16 = 0x81A5;
  66901. /**
  66902. * @const
  66903. * @type {number}
  66904. */
  66905. goog.webgl.STENCIL_INDEX = 0x1901;
  66906. /**
  66907. * @const
  66908. * @type {number}
  66909. */
  66910. goog.webgl.STENCIL_INDEX8 = 0x8D48;
  66911. /**
  66912. * @const
  66913. * @type {number}
  66914. */
  66915. goog.webgl.DEPTH_STENCIL = 0x84F9;
  66916. /**
  66917. * @const
  66918. * @type {number}
  66919. */
  66920. goog.webgl.RENDERBUFFER_WIDTH = 0x8D42;
  66921. /**
  66922. * @const
  66923. * @type {number}
  66924. */
  66925. goog.webgl.RENDERBUFFER_HEIGHT = 0x8D43;
  66926. /**
  66927. * @const
  66928. * @type {number}
  66929. */
  66930. goog.webgl.RENDERBUFFER_INTERNAL_FORMAT = 0x8D44;
  66931. /**
  66932. * @const
  66933. * @type {number}
  66934. */
  66935. goog.webgl.RENDERBUFFER_RED_SIZE = 0x8D50;
  66936. /**
  66937. * @const
  66938. * @type {number}
  66939. */
  66940. goog.webgl.RENDERBUFFER_GREEN_SIZE = 0x8D51;
  66941. /**
  66942. * @const
  66943. * @type {number}
  66944. */
  66945. goog.webgl.RENDERBUFFER_BLUE_SIZE = 0x8D52;
  66946. /**
  66947. * @const
  66948. * @type {number}
  66949. */
  66950. goog.webgl.RENDERBUFFER_ALPHA_SIZE = 0x8D53;
  66951. /**
  66952. * @const
  66953. * @type {number}
  66954. */
  66955. goog.webgl.RENDERBUFFER_DEPTH_SIZE = 0x8D54;
  66956. /**
  66957. * @const
  66958. * @type {number}
  66959. */
  66960. goog.webgl.RENDERBUFFER_STENCIL_SIZE = 0x8D55;
  66961. /**
  66962. * @const
  66963. * @type {number}
  66964. */
  66965. goog.webgl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0;
  66966. /**
  66967. * @const
  66968. * @type {number}
  66969. */
  66970. goog.webgl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1;
  66971. /**
  66972. * @const
  66973. * @type {number}
  66974. */
  66975. goog.webgl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2;
  66976. /**
  66977. * @const
  66978. * @type {number}
  66979. */
  66980. goog.webgl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3;
  66981. /**
  66982. * @const
  66983. * @type {number}
  66984. */
  66985. goog.webgl.COLOR_ATTACHMENT0 = 0x8CE0;
  66986. /**
  66987. * @const
  66988. * @type {number}
  66989. */
  66990. goog.webgl.DEPTH_ATTACHMENT = 0x8D00;
  66991. /**
  66992. * @const
  66993. * @type {number}
  66994. */
  66995. goog.webgl.STENCIL_ATTACHMENT = 0x8D20;
  66996. /**
  66997. * @const
  66998. * @type {number}
  66999. */
  67000. goog.webgl.DEPTH_STENCIL_ATTACHMENT = 0x821A;
  67001. /**
  67002. * @const
  67003. * @type {number}
  67004. */
  67005. goog.webgl.NONE = 0;
  67006. /**
  67007. * @const
  67008. * @type {number}
  67009. */
  67010. goog.webgl.FRAMEBUFFER_COMPLETE = 0x8CD5;
  67011. /**
  67012. * @const
  67013. * @type {number}
  67014. */
  67015. goog.webgl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6;
  67016. /**
  67017. * @const
  67018. * @type {number}
  67019. */
  67020. goog.webgl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7;
  67021. /**
  67022. * @const
  67023. * @type {number}
  67024. */
  67025. goog.webgl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9;
  67026. /**
  67027. * @const
  67028. * @type {number}
  67029. */
  67030. goog.webgl.FRAMEBUFFER_UNSUPPORTED = 0x8CDD;
  67031. /**
  67032. * @const
  67033. * @type {number}
  67034. */
  67035. goog.webgl.FRAMEBUFFER_BINDING = 0x8CA6;
  67036. /**
  67037. * @const
  67038. * @type {number}
  67039. */
  67040. goog.webgl.RENDERBUFFER_BINDING = 0x8CA7;
  67041. /**
  67042. * @const
  67043. * @type {number}
  67044. */
  67045. goog.webgl.MAX_RENDERBUFFER_SIZE = 0x84E8;
  67046. /**
  67047. * @const
  67048. * @type {number}
  67049. */
  67050. goog.webgl.INVALID_FRAMEBUFFER_OPERATION = 0x0506;
  67051. /**
  67052. * @const
  67053. * @type {number}
  67054. */
  67055. goog.webgl.UNPACK_FLIP_Y_WEBGL = 0x9240;
  67056. /**
  67057. * @const
  67058. * @type {number}
  67059. */
  67060. goog.webgl.UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;
  67061. /**
  67062. * @const
  67063. * @type {number}
  67064. */
  67065. goog.webgl.CONTEXT_LOST_WEBGL = 0x9242;
  67066. /**
  67067. * @const
  67068. * @type {number}
  67069. */
  67070. goog.webgl.UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;
  67071. /**
  67072. * @const
  67073. * @type {number}
  67074. */
  67075. goog.webgl.BROWSER_DEFAULT_WEBGL = 0x9244;
  67076. /**
  67077. * From the OES_texture_half_float extension.
  67078. * http://www.khronos.org/registry/webgl/extensions/OES_texture_half_float/
  67079. * @const
  67080. * @type {number}
  67081. */
  67082. goog.webgl.HALF_FLOAT_OES = 0x8D61;
  67083. /**
  67084. * From the OES_standard_derivatives extension.
  67085. * http://www.khronos.org/registry/webgl/extensions/OES_standard_derivatives/
  67086. * @const
  67087. * @type {number}
  67088. */
  67089. goog.webgl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8B8B;
  67090. /**
  67091. * From the OES_vertex_array_object extension.
  67092. * http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/
  67093. * @const
  67094. * @type {number}
  67095. */
  67096. goog.webgl.VERTEX_ARRAY_BINDING_OES = 0x85B5;
  67097. /**
  67098. * From the WEBGL_debug_renderer_info extension.
  67099. * http://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/
  67100. * @const
  67101. * @type {number}
  67102. */
  67103. goog.webgl.UNMASKED_VENDOR_WEBGL = 0x9245;
  67104. /**
  67105. * From the WEBGL_debug_renderer_info extension.
  67106. * http://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/
  67107. * @const
  67108. * @type {number}
  67109. */
  67110. goog.webgl.UNMASKED_RENDERER_WEBGL = 0x9246;
  67111. /**
  67112. * From the WEBGL_compressed_texture_s3tc extension.
  67113. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  67114. * @const
  67115. * @type {number}
  67116. */
  67117. goog.webgl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0;
  67118. /**
  67119. * From the WEBGL_compressed_texture_s3tc extension.
  67120. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  67121. * @const
  67122. * @type {number}
  67123. */
  67124. goog.webgl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1;
  67125. /**
  67126. * From the WEBGL_compressed_texture_s3tc extension.
  67127. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  67128. * @const
  67129. * @type {number}
  67130. */
  67131. goog.webgl.COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2;
  67132. /**
  67133. * From the WEBGL_compressed_texture_s3tc extension.
  67134. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  67135. * @const
  67136. * @type {number}
  67137. */
  67138. goog.webgl.COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3;
  67139. /**
  67140. * From the EXT_texture_filter_anisotropic extension.
  67141. * http://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/
  67142. * @const
  67143. * @type {number}
  67144. */
  67145. goog.webgl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;
  67146. /**
  67147. * From the EXT_texture_filter_anisotropic extension.
  67148. * http://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/
  67149. * @const
  67150. * @type {number}
  67151. */
  67152. goog.webgl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF;
  67153. goog.provide('ol.webgl.Fragment');
  67154. goog.provide('ol.webgl.Shader');
  67155. goog.provide('ol.webgl.Vertex');
  67156. goog.provide('ol.webgl.shader');
  67157. goog.require('goog.functions');
  67158. goog.require('goog.webgl');
  67159. goog.require('ol.webgl');
  67160. /**
  67161. * @constructor
  67162. * @param {string} source Source.
  67163. * @struct
  67164. */
  67165. ol.webgl.Shader = function(source) {
  67166. /**
  67167. * @private
  67168. * @type {string}
  67169. */
  67170. this.source_ = source;
  67171. };
  67172. /**
  67173. * @return {number} Type.
  67174. */
  67175. ol.webgl.Shader.prototype.getType = goog.abstractMethod;
  67176. /**
  67177. * @return {string} Source.
  67178. */
  67179. ol.webgl.Shader.prototype.getSource = function() {
  67180. return this.source_;
  67181. };
  67182. /**
  67183. * @return {boolean} Is animated?
  67184. */
  67185. ol.webgl.Shader.prototype.isAnimated = goog.functions.FALSE;
  67186. /**
  67187. * @constructor
  67188. * @extends {ol.webgl.Shader}
  67189. * @param {string} source Source.
  67190. * @struct
  67191. */
  67192. ol.webgl.shader.Fragment = function(source) {
  67193. goog.base(this, source);
  67194. };
  67195. goog.inherits(ol.webgl.shader.Fragment, ol.webgl.Shader);
  67196. /**
  67197. * @inheritDoc
  67198. */
  67199. ol.webgl.shader.Fragment.prototype.getType = function() {
  67200. return goog.webgl.FRAGMENT_SHADER;
  67201. };
  67202. /**
  67203. * @constructor
  67204. * @extends {ol.webgl.Shader}
  67205. * @param {string} source Source.
  67206. * @struct
  67207. */
  67208. ol.webgl.shader.Vertex = function(source) {
  67209. goog.base(this, source);
  67210. };
  67211. goog.inherits(ol.webgl.shader.Vertex, ol.webgl.Shader);
  67212. /**
  67213. * @inheritDoc
  67214. */
  67215. ol.webgl.shader.Vertex.prototype.getType = function() {
  67216. return goog.webgl.VERTEX_SHADER;
  67217. };
  67218. // This file is automatically generated, do not edit
  67219. goog.provide('ol.render.webgl.imagereplay.shader.Default');
  67220. goog.provide('ol.render.webgl.imagereplay.shader.Default.Locations');
  67221. goog.provide('ol.render.webgl.imagereplay.shader.DefaultFragment');
  67222. goog.provide('ol.render.webgl.imagereplay.shader.DefaultVertex');
  67223. goog.require('ol.webgl.shader');
  67224. /**
  67225. * @constructor
  67226. * @extends {ol.webgl.shader.Fragment}
  67227. * @struct
  67228. */
  67229. ol.render.webgl.imagereplay.shader.DefaultFragment = function() {
  67230. goog.base(this, ol.render.webgl.imagereplay.shader.DefaultFragment.SOURCE);
  67231. };
  67232. goog.inherits(ol.render.webgl.imagereplay.shader.DefaultFragment, ol.webgl.shader.Fragment);
  67233. goog.addSingletonGetter(ol.render.webgl.imagereplay.shader.DefaultFragment);
  67234. /**
  67235. * @const
  67236. * @type {string}
  67237. */
  67238. ol.render.webgl.imagereplay.shader.DefaultFragment.DEBUG_SOURCE = 'precision mediump float;\nvarying vec2 v_texCoord;\nvarying float v_opacity;\n\nuniform float u_opacity;\nuniform sampler2D u_image;\n\nvoid main(void) {\n vec4 texColor = texture2D(u_image, v_texCoord);\n gl_FragColor.rgb = texColor.rgb;\n float alpha = texColor.a * v_opacity * u_opacity;\n if (alpha == 0.0) {\n discard;\n }\n gl_FragColor.a = alpha;\n}\n';
  67239. /**
  67240. * @const
  67241. * @type {string}
  67242. */
  67243. ol.render.webgl.imagereplay.shader.DefaultFragment.OPTIMIZED_SOURCE = 'precision mediump float;varying vec2 a;varying float b;uniform float k;uniform sampler2D l;void main(void){vec4 texColor=texture2D(l,a);gl_FragColor.rgb=texColor.rgb;float alpha=texColor.a*b*k;if(alpha==0.0){discard;}gl_FragColor.a=alpha;}';
  67244. /**
  67245. * @const
  67246. * @type {string}
  67247. */
  67248. ol.render.webgl.imagereplay.shader.DefaultFragment.SOURCE = goog.DEBUG ?
  67249. ol.render.webgl.imagereplay.shader.DefaultFragment.DEBUG_SOURCE :
  67250. ol.render.webgl.imagereplay.shader.DefaultFragment.OPTIMIZED_SOURCE;
  67251. /**
  67252. * @constructor
  67253. * @extends {ol.webgl.shader.Vertex}
  67254. * @struct
  67255. */
  67256. ol.render.webgl.imagereplay.shader.DefaultVertex = function() {
  67257. goog.base(this, ol.render.webgl.imagereplay.shader.DefaultVertex.SOURCE);
  67258. };
  67259. goog.inherits(ol.render.webgl.imagereplay.shader.DefaultVertex, ol.webgl.shader.Vertex);
  67260. goog.addSingletonGetter(ol.render.webgl.imagereplay.shader.DefaultVertex);
  67261. /**
  67262. * @const
  67263. * @type {string}
  67264. */
  67265. ol.render.webgl.imagereplay.shader.DefaultVertex.DEBUG_SOURCE = 'varying vec2 v_texCoord;\nvarying float v_opacity;\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nattribute vec2 a_offsets;\nattribute float a_opacity;\nattribute float a_rotateWithView;\n\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\n\nvoid main(void) {\n mat4 offsetMatrix = u_offsetScaleMatrix;\n if (a_rotateWithView == 1.0) {\n offsetMatrix = u_offsetScaleMatrix * u_offsetRotateMatrix;\n }\n vec4 offsets = offsetMatrix * vec4(a_offsets, 0., 0.);\n gl_Position = u_projectionMatrix * vec4(a_position, 0., 1.) + offsets;\n v_texCoord = a_texCoord;\n v_opacity = a_opacity;\n}\n\n\n';
  67266. /**
  67267. * @const
  67268. * @type {string}
  67269. */
  67270. ol.render.webgl.imagereplay.shader.DefaultVertex.OPTIMIZED_SOURCE = 'varying vec2 a;varying float b;attribute vec2 c;attribute vec2 d;attribute vec2 e;attribute float f;attribute float g;uniform mat4 h;uniform mat4 i;uniform mat4 j;void main(void){mat4 offsetMatrix=i;if(g==1.0){offsetMatrix=i*j;}vec4 offsets=offsetMatrix*vec4(e,0.,0.);gl_Position=h*vec4(c,0.,1.)+offsets;a=d;b=f;}';
  67271. /**
  67272. * @const
  67273. * @type {string}
  67274. */
  67275. ol.render.webgl.imagereplay.shader.DefaultVertex.SOURCE = goog.DEBUG ?
  67276. ol.render.webgl.imagereplay.shader.DefaultVertex.DEBUG_SOURCE :
  67277. ol.render.webgl.imagereplay.shader.DefaultVertex.OPTIMIZED_SOURCE;
  67278. /**
  67279. * @constructor
  67280. * @param {WebGLRenderingContext} gl GL.
  67281. * @param {WebGLProgram} program Program.
  67282. * @struct
  67283. */
  67284. ol.render.webgl.imagereplay.shader.Default.Locations = function(gl, program) {
  67285. /**
  67286. * @type {WebGLUniformLocation}
  67287. */
  67288. this.u_image = gl.getUniformLocation(
  67289. program, goog.DEBUG ? 'u_image' : 'l');
  67290. /**
  67291. * @type {WebGLUniformLocation}
  67292. */
  67293. this.u_offsetRotateMatrix = gl.getUniformLocation(
  67294. program, goog.DEBUG ? 'u_offsetRotateMatrix' : 'j');
  67295. /**
  67296. * @type {WebGLUniformLocation}
  67297. */
  67298. this.u_offsetScaleMatrix = gl.getUniformLocation(
  67299. program, goog.DEBUG ? 'u_offsetScaleMatrix' : 'i');
  67300. /**
  67301. * @type {WebGLUniformLocation}
  67302. */
  67303. this.u_opacity = gl.getUniformLocation(
  67304. program, goog.DEBUG ? 'u_opacity' : 'k');
  67305. /**
  67306. * @type {WebGLUniformLocation}
  67307. */
  67308. this.u_projectionMatrix = gl.getUniformLocation(
  67309. program, goog.DEBUG ? 'u_projectionMatrix' : 'h');
  67310. /**
  67311. * @type {number}
  67312. */
  67313. this.a_offsets = gl.getAttribLocation(
  67314. program, goog.DEBUG ? 'a_offsets' : 'e');
  67315. /**
  67316. * @type {number}
  67317. */
  67318. this.a_opacity = gl.getAttribLocation(
  67319. program, goog.DEBUG ? 'a_opacity' : 'f');
  67320. /**
  67321. * @type {number}
  67322. */
  67323. this.a_position = gl.getAttribLocation(
  67324. program, goog.DEBUG ? 'a_position' : 'c');
  67325. /**
  67326. * @type {number}
  67327. */
  67328. this.a_rotateWithView = gl.getAttribLocation(
  67329. program, goog.DEBUG ? 'a_rotateWithView' : 'g');
  67330. /**
  67331. * @type {number}
  67332. */
  67333. this.a_texCoord = gl.getAttribLocation(
  67334. program, goog.DEBUG ? 'a_texCoord' : 'd');
  67335. };
  67336. goog.provide('ol.webgl.Buffer');
  67337. goog.require('goog.webgl');
  67338. goog.require('ol');
  67339. /**
  67340. * @enum {number}
  67341. */
  67342. ol.webgl.BufferUsage = {
  67343. STATIC_DRAW: goog.webgl.STATIC_DRAW,
  67344. STREAM_DRAW: goog.webgl.STREAM_DRAW,
  67345. DYNAMIC_DRAW: goog.webgl.DYNAMIC_DRAW
  67346. };
  67347. /**
  67348. * @constructor
  67349. * @param {Array.<number>=} opt_arr Array.
  67350. * @param {number=} opt_usage Usage.
  67351. * @struct
  67352. */
  67353. ol.webgl.Buffer = function(opt_arr, opt_usage) {
  67354. /**
  67355. * @private
  67356. * @type {Array.<number>}
  67357. */
  67358. this.arr_ = opt_arr !== undefined ? opt_arr : [];
  67359. /**
  67360. * @private
  67361. * @type {number}
  67362. */
  67363. this.usage_ = opt_usage !== undefined ?
  67364. opt_usage : ol.webgl.BufferUsage.STATIC_DRAW;
  67365. };
  67366. /**
  67367. * @return {Array.<number>} Array.
  67368. */
  67369. ol.webgl.Buffer.prototype.getArray = function() {
  67370. return this.arr_;
  67371. };
  67372. /**
  67373. * @return {number} Usage.
  67374. */
  67375. ol.webgl.Buffer.prototype.getUsage = function() {
  67376. return this.usage_;
  67377. };
  67378. goog.provide('ol.webgl.Context');
  67379. goog.require('goog.asserts');
  67380. goog.require('goog.events');
  67381. goog.require('goog.log');
  67382. goog.require('goog.object');
  67383. goog.require('ol');
  67384. goog.require('ol.array');
  67385. goog.require('ol.webgl.Buffer');
  67386. goog.require('ol.webgl.WebGLContextEventType');
  67387. /**
  67388. * @typedef {{buf: ol.webgl.Buffer,
  67389. * buffer: WebGLBuffer}}
  67390. */
  67391. ol.webgl.BufferCacheEntry;
  67392. /**
  67393. * @classdesc
  67394. * A WebGL context for accessing low-level WebGL capabilities.
  67395. *
  67396. * @constructor
  67397. * @extends {goog.events.EventTarget}
  67398. * @param {HTMLCanvasElement} canvas Canvas.
  67399. * @param {WebGLRenderingContext} gl GL.
  67400. * @api
  67401. */
  67402. ol.webgl.Context = function(canvas, gl) {
  67403. /**
  67404. * @private
  67405. * @type {HTMLCanvasElement}
  67406. */
  67407. this.canvas_ = canvas;
  67408. /**
  67409. * @private
  67410. * @type {WebGLRenderingContext}
  67411. */
  67412. this.gl_ = gl;
  67413. /**
  67414. * @private
  67415. * @type {Object.<number, ol.webgl.BufferCacheEntry>}
  67416. */
  67417. this.bufferCache_ = {};
  67418. /**
  67419. * @private
  67420. * @type {Object.<number, WebGLShader>}
  67421. */
  67422. this.shaderCache_ = {};
  67423. /**
  67424. * @private
  67425. * @type {Object.<string, WebGLProgram>}
  67426. */
  67427. this.programCache_ = {};
  67428. /**
  67429. * @private
  67430. * @type {WebGLProgram}
  67431. */
  67432. this.currentProgram_ = null;
  67433. /**
  67434. * @private
  67435. * @type {WebGLFramebuffer}
  67436. */
  67437. this.hitDetectionFramebuffer_ = null;
  67438. /**
  67439. * @private
  67440. * @type {WebGLTexture}
  67441. */
  67442. this.hitDetectionTexture_ = null;
  67443. /**
  67444. * @private
  67445. * @type {WebGLRenderbuffer}
  67446. */
  67447. this.hitDetectionRenderbuffer_ = null;
  67448. /**
  67449. * @type {boolean}
  67450. */
  67451. this.hasOESElementIndexUint = ol.array.includes(
  67452. ol.WEBGL_EXTENSIONS, 'OES_element_index_uint');
  67453. // use the OES_element_index_uint extension if available
  67454. if (this.hasOESElementIndexUint) {
  67455. var ext = gl.getExtension('OES_element_index_uint');
  67456. goog.asserts.assert(ext,
  67457. 'Failed to get extension "OES_element_index_uint"');
  67458. }
  67459. goog.events.listen(this.canvas_, ol.webgl.WebGLContextEventType.LOST,
  67460. this.handleWebGLContextLost, false, this);
  67461. goog.events.listen(this.canvas_, ol.webgl.WebGLContextEventType.RESTORED,
  67462. this.handleWebGLContextRestored, false, this);
  67463. };
  67464. /**
  67465. * Just bind the buffer if it's in the cache. Otherwise create
  67466. * the WebGL buffer, bind it, populate it, and add an entry to
  67467. * the cache.
  67468. * @param {number} target Target.
  67469. * @param {ol.webgl.Buffer} buf Buffer.
  67470. */
  67471. ol.webgl.Context.prototype.bindBuffer = function(target, buf) {
  67472. var gl = this.getGL();
  67473. var arr = buf.getArray();
  67474. var bufferKey = goog.getUid(buf);
  67475. if (bufferKey in this.bufferCache_) {
  67476. var bufferCacheEntry = this.bufferCache_[bufferKey];
  67477. gl.bindBuffer(target, bufferCacheEntry.buffer);
  67478. } else {
  67479. var buffer = gl.createBuffer();
  67480. gl.bindBuffer(target, buffer);
  67481. goog.asserts.assert(target == goog.webgl.ARRAY_BUFFER ||
  67482. target == goog.webgl.ELEMENT_ARRAY_BUFFER,
  67483. 'target is supposed to be an ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER');
  67484. var /** @type {ArrayBufferView} */ arrayBuffer;
  67485. if (target == goog.webgl.ARRAY_BUFFER) {
  67486. arrayBuffer = new Float32Array(arr);
  67487. } else if (target == goog.webgl.ELEMENT_ARRAY_BUFFER) {
  67488. arrayBuffer = this.hasOESElementIndexUint ?
  67489. new Uint32Array(arr) : new Uint16Array(arr);
  67490. } else {
  67491. goog.asserts.fail();
  67492. }
  67493. gl.bufferData(target, arrayBuffer, buf.getUsage());
  67494. this.bufferCache_[bufferKey] = {
  67495. buf: buf,
  67496. buffer: buffer
  67497. };
  67498. }
  67499. };
  67500. /**
  67501. * @param {ol.webgl.Buffer} buf Buffer.
  67502. */
  67503. ol.webgl.Context.prototype.deleteBuffer = function(buf) {
  67504. var gl = this.getGL();
  67505. var bufferKey = goog.getUid(buf);
  67506. goog.asserts.assert(bufferKey in this.bufferCache_,
  67507. 'attempted to delete uncached buffer');
  67508. var bufferCacheEntry = this.bufferCache_[bufferKey];
  67509. if (!gl.isContextLost()) {
  67510. gl.deleteBuffer(bufferCacheEntry.buffer);
  67511. }
  67512. delete this.bufferCache_[bufferKey];
  67513. };
  67514. /**
  67515. * @inheritDoc
  67516. */
  67517. ol.webgl.Context.prototype.disposeInternal = function() {
  67518. var gl = this.getGL();
  67519. if (!gl.isContextLost()) {
  67520. goog.object.forEach(this.bufferCache_, function(bufferCacheEntry) {
  67521. gl.deleteBuffer(bufferCacheEntry.buffer);
  67522. });
  67523. goog.object.forEach(this.programCache_, function(program) {
  67524. gl.deleteProgram(program);
  67525. });
  67526. goog.object.forEach(this.shaderCache_, function(shader) {
  67527. gl.deleteShader(shader);
  67528. });
  67529. // delete objects for hit-detection
  67530. gl.deleteFramebuffer(this.hitDetectionFramebuffer_);
  67531. gl.deleteRenderbuffer(this.hitDetectionRenderbuffer_);
  67532. gl.deleteTexture(this.hitDetectionTexture_);
  67533. }
  67534. };
  67535. /**
  67536. * @return {HTMLCanvasElement} Canvas.
  67537. */
  67538. ol.webgl.Context.prototype.getCanvas = function() {
  67539. return this.canvas_;
  67540. };
  67541. /**
  67542. * Get the WebGL rendering context
  67543. * @return {WebGLRenderingContext} The rendering context.
  67544. * @api
  67545. */
  67546. ol.webgl.Context.prototype.getGL = function() {
  67547. return this.gl_;
  67548. };
  67549. /**
  67550. * Get the frame buffer for hit detection.
  67551. * @return {WebGLFramebuffer} The hit detection frame buffer.
  67552. */
  67553. ol.webgl.Context.prototype.getHitDetectionFramebuffer = function() {
  67554. if (!this.hitDetectionFramebuffer_) {
  67555. this.initHitDetectionFramebuffer_();
  67556. }
  67557. return this.hitDetectionFramebuffer_;
  67558. };
  67559. /**
  67560. * Get shader from the cache if it's in the cache. Otherwise, create
  67561. * the WebGL shader, compile it, and add entry to cache.
  67562. * @param {ol.webgl.Shader} shaderObject Shader object.
  67563. * @return {WebGLShader} Shader.
  67564. */
  67565. ol.webgl.Context.prototype.getShader = function(shaderObject) {
  67566. var shaderKey = goog.getUid(shaderObject);
  67567. if (shaderKey in this.shaderCache_) {
  67568. return this.shaderCache_[shaderKey];
  67569. } else {
  67570. var gl = this.getGL();
  67571. var shader = gl.createShader(shaderObject.getType());
  67572. gl.shaderSource(shader, shaderObject.getSource());
  67573. gl.compileShader(shader);
  67574. if (goog.DEBUG) {
  67575. if (!gl.getShaderParameter(shader, goog.webgl.COMPILE_STATUS) &&
  67576. !gl.isContextLost()) {
  67577. goog.log.error(this.logger_, gl.getShaderInfoLog(shader));
  67578. }
  67579. }
  67580. goog.asserts.assert(
  67581. gl.getShaderParameter(shader, goog.webgl.COMPILE_STATUS) ||
  67582. gl.isContextLost(),
  67583. 'illegal state, shader not compiled or context lost');
  67584. this.shaderCache_[shaderKey] = shader;
  67585. return shader;
  67586. }
  67587. };
  67588. /**
  67589. * Get the program from the cache if it's in the cache. Otherwise create
  67590. * the WebGL program, attach the shaders to it, and add an entry to the
  67591. * cache.
  67592. * @param {ol.webgl.shader.Fragment} fragmentShaderObject Fragment shader.
  67593. * @param {ol.webgl.shader.Vertex} vertexShaderObject Vertex shader.
  67594. * @return {WebGLProgram} Program.
  67595. */
  67596. ol.webgl.Context.prototype.getProgram = function(
  67597. fragmentShaderObject, vertexShaderObject) {
  67598. var programKey =
  67599. goog.getUid(fragmentShaderObject) + '/' + goog.getUid(vertexShaderObject);
  67600. if (programKey in this.programCache_) {
  67601. return this.programCache_[programKey];
  67602. } else {
  67603. var gl = this.getGL();
  67604. var program = gl.createProgram();
  67605. gl.attachShader(program, this.getShader(fragmentShaderObject));
  67606. gl.attachShader(program, this.getShader(vertexShaderObject));
  67607. gl.linkProgram(program);
  67608. if (goog.DEBUG) {
  67609. if (!gl.getProgramParameter(program, goog.webgl.LINK_STATUS) &&
  67610. !gl.isContextLost()) {
  67611. goog.log.error(this.logger_, gl.getProgramInfoLog(program));
  67612. }
  67613. }
  67614. goog.asserts.assert(
  67615. gl.getProgramParameter(program, goog.webgl.LINK_STATUS) ||
  67616. gl.isContextLost(),
  67617. 'illegal state, shader not linked or context lost');
  67618. this.programCache_[programKey] = program;
  67619. return program;
  67620. }
  67621. };
  67622. /**
  67623. * FIXME empy description for jsdoc
  67624. */
  67625. ol.webgl.Context.prototype.handleWebGLContextLost = function() {
  67626. goog.object.clear(this.bufferCache_);
  67627. goog.object.clear(this.shaderCache_);
  67628. goog.object.clear(this.programCache_);
  67629. this.currentProgram_ = null;
  67630. this.hitDetectionFramebuffer_ = null;
  67631. this.hitDetectionTexture_ = null;
  67632. this.hitDetectionRenderbuffer_ = null;
  67633. };
  67634. /**
  67635. * FIXME empy description for jsdoc
  67636. */
  67637. ol.webgl.Context.prototype.handleWebGLContextRestored = function() {
  67638. };
  67639. /**
  67640. * Creates a 1x1 pixel framebuffer for the hit-detection.
  67641. * @private
  67642. */
  67643. ol.webgl.Context.prototype.initHitDetectionFramebuffer_ = function() {
  67644. var gl = this.gl_;
  67645. var framebuffer = gl.createFramebuffer();
  67646. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  67647. var texture = ol.webgl.Context.createEmptyTexture(gl, 1, 1);
  67648. var renderbuffer = gl.createRenderbuffer();
  67649. gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);
  67650. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, 1, 1);
  67651. gl.framebufferTexture2D(
  67652. gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  67653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  67654. gl.RENDERBUFFER, renderbuffer);
  67655. gl.bindTexture(gl.TEXTURE_2D, null);
  67656. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  67657. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  67658. this.hitDetectionFramebuffer_ = framebuffer;
  67659. this.hitDetectionTexture_ = texture;
  67660. this.hitDetectionRenderbuffer_ = renderbuffer;
  67661. };
  67662. /**
  67663. * Use a program. If the program is already in use, this will return `false`.
  67664. * @param {WebGLProgram} program Program.
  67665. * @return {boolean} Changed.
  67666. * @api
  67667. */
  67668. ol.webgl.Context.prototype.useProgram = function(program) {
  67669. if (program == this.currentProgram_) {
  67670. return false;
  67671. } else {
  67672. var gl = this.getGL();
  67673. gl.useProgram(program);
  67674. this.currentProgram_ = program;
  67675. return true;
  67676. }
  67677. };
  67678. /**
  67679. * @private
  67680. * @type {goog.log.Logger}
  67681. */
  67682. ol.webgl.Context.prototype.logger_ = goog.log.getLogger('ol.webgl.Context');
  67683. /**
  67684. * @param {WebGLRenderingContext} gl WebGL rendering context.
  67685. * @param {number=} opt_wrapS wrapS.
  67686. * @param {number=} opt_wrapT wrapT.
  67687. * @return {WebGLTexture}
  67688. * @private
  67689. */
  67690. ol.webgl.Context.createTexture_ = function(gl, opt_wrapS, opt_wrapT) {
  67691. var texture = gl.createTexture();
  67692. gl.bindTexture(gl.TEXTURE_2D, texture);
  67693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  67694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  67695. if (opt_wrapS !== undefined) {
  67696. gl.texParameteri(
  67697. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_WRAP_S, opt_wrapS);
  67698. }
  67699. if (opt_wrapT !== undefined) {
  67700. gl.texParameteri(
  67701. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_WRAP_T, opt_wrapT);
  67702. }
  67703. return texture;
  67704. };
  67705. /**
  67706. * @param {WebGLRenderingContext} gl WebGL rendering context.
  67707. * @param {number} width Width.
  67708. * @param {number} height Height.
  67709. * @param {number=} opt_wrapS wrapS.
  67710. * @param {number=} opt_wrapT wrapT.
  67711. * @return {WebGLTexture}
  67712. */
  67713. ol.webgl.Context.createEmptyTexture = function(
  67714. gl, width, height, opt_wrapS, opt_wrapT) {
  67715. var texture = ol.webgl.Context.createTexture_(gl, opt_wrapS, opt_wrapT);
  67716. gl.texImage2D(
  67717. gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE,
  67718. null);
  67719. return texture;
  67720. };
  67721. /**
  67722. * @param {WebGLRenderingContext} gl WebGL rendering context.
  67723. * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image Image.
  67724. * @param {number=} opt_wrapS wrapS.
  67725. * @param {number=} opt_wrapT wrapT.
  67726. * @return {WebGLTexture}
  67727. */
  67728. ol.webgl.Context.createTexture = function(gl, image, opt_wrapS, opt_wrapT) {
  67729. var texture = ol.webgl.Context.createTexture_(gl, opt_wrapS, opt_wrapT);
  67730. gl.texImage2D(
  67731. gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  67732. return texture;
  67733. };
  67734. goog.provide('ol.render.webgl.ImageReplay');
  67735. goog.provide('ol.render.webgl.ReplayGroup');
  67736. goog.require('goog.asserts');
  67737. goog.require('goog.functions');
  67738. goog.require('goog.object');
  67739. goog.require('goog.vec.Mat4');
  67740. goog.require('ol.extent');
  67741. goog.require('ol.render.IReplayGroup');
  67742. goog.require('ol.render.VectorContext');
  67743. goog.require('ol.render.webgl.imagereplay.shader.Default');
  67744. goog.require('ol.render.webgl.imagereplay.shader.Default.Locations');
  67745. goog.require('ol.render.webgl.imagereplay.shader.DefaultFragment');
  67746. goog.require('ol.render.webgl.imagereplay.shader.DefaultVertex');
  67747. goog.require('ol.vec.Mat4');
  67748. goog.require('ol.webgl.Buffer');
  67749. goog.require('ol.webgl.Context');
  67750. /**
  67751. * @constructor
  67752. * @extends {ol.render.VectorContext}
  67753. * @param {number} tolerance Tolerance.
  67754. * @param {ol.Extent} maxExtent Max extent.
  67755. * @protected
  67756. * @struct
  67757. */
  67758. ol.render.webgl.ImageReplay = function(tolerance, maxExtent) {
  67759. goog.base(this);
  67760. /**
  67761. * @type {number|undefined}
  67762. * @private
  67763. */
  67764. this.anchorX_ = undefined;
  67765. /**
  67766. * @type {number|undefined}
  67767. * @private
  67768. */
  67769. this.anchorY_ = undefined;
  67770. /**
  67771. * The origin of the coordinate system for the point coordinates sent to
  67772. * the GPU. To eliminate jitter caused by precision problems in the GPU
  67773. * we use the "Rendering Relative to Eye" technique described in the "3D
  67774. * Engine Design for Virtual Globes" book.
  67775. * @private
  67776. * @type {ol.Coordinate}
  67777. */
  67778. this.origin_ = ol.extent.getCenter(maxExtent);
  67779. /**
  67780. * @type {Array.<number>}
  67781. * @private
  67782. */
  67783. this.groupIndices_ = [];
  67784. /**
  67785. * @type {Array.<number>}
  67786. * @private
  67787. */
  67788. this.hitDetectionGroupIndices_ = [];
  67789. /**
  67790. * @type {number|undefined}
  67791. * @private
  67792. */
  67793. this.height_ = undefined;
  67794. /**
  67795. * @type {Array.<HTMLCanvasElement|HTMLImageElement|HTMLVideoElement>}
  67796. * @private
  67797. */
  67798. this.images_ = [];
  67799. /**
  67800. * @type {Array.<HTMLCanvasElement|HTMLImageElement|HTMLVideoElement>}
  67801. * @private
  67802. */
  67803. this.hitDetectionImages_ = [];
  67804. /**
  67805. * @type {number|undefined}
  67806. * @private
  67807. */
  67808. this.imageHeight_ = undefined;
  67809. /**
  67810. * @type {number|undefined}
  67811. * @private
  67812. */
  67813. this.imageWidth_ = undefined;
  67814. /**
  67815. * @type {Array.<number>}
  67816. * @private
  67817. */
  67818. this.indices_ = [];
  67819. /**
  67820. * @type {ol.webgl.Buffer}
  67821. * @private
  67822. */
  67823. this.indicesBuffer_ = null;
  67824. /**
  67825. * @private
  67826. * @type {ol.render.webgl.imagereplay.shader.Default.Locations}
  67827. */
  67828. this.defaultLocations_ = null;
  67829. /**
  67830. * @private
  67831. * @type {number|undefined}
  67832. */
  67833. this.opacity_ = undefined;
  67834. /**
  67835. * @type {!goog.vec.Mat4.Number}
  67836. * @private
  67837. */
  67838. this.offsetRotateMatrix_ = goog.vec.Mat4.createNumberIdentity();
  67839. /**
  67840. * @type {!goog.vec.Mat4.Number}
  67841. * @private
  67842. */
  67843. this.offsetScaleMatrix_ = goog.vec.Mat4.createNumberIdentity();
  67844. /**
  67845. * @type {number|undefined}
  67846. * @private
  67847. */
  67848. this.originX_ = undefined;
  67849. /**
  67850. * @type {number|undefined}
  67851. * @private
  67852. */
  67853. this.originY_ = undefined;
  67854. /**
  67855. * @type {!goog.vec.Mat4.Number}
  67856. * @private
  67857. */
  67858. this.projectionMatrix_ = goog.vec.Mat4.createNumberIdentity();
  67859. /**
  67860. * @private
  67861. * @type {boolean|undefined}
  67862. */
  67863. this.rotateWithView_ = undefined;
  67864. /**
  67865. * @private
  67866. * @type {number|undefined}
  67867. */
  67868. this.rotation_ = undefined;
  67869. /**
  67870. * @private
  67871. * @type {number|undefined}
  67872. */
  67873. this.scale_ = undefined;
  67874. /**
  67875. * @type {Array.<WebGLTexture>}
  67876. * @private
  67877. */
  67878. this.textures_ = [];
  67879. /**
  67880. * @type {Array.<WebGLTexture>}
  67881. * @private
  67882. */
  67883. this.hitDetectionTextures_ = [];
  67884. /**
  67885. * @type {Array.<number>}
  67886. * @private
  67887. */
  67888. this.vertices_ = [];
  67889. /**
  67890. * @type {ol.webgl.Buffer}
  67891. * @private
  67892. */
  67893. this.verticesBuffer_ = null;
  67894. /**
  67895. * Start index per feature (the index).
  67896. * @type {Array.<number>}
  67897. * @private
  67898. */
  67899. this.startIndices_ = [];
  67900. /**
  67901. * Start index per feature (the feature).
  67902. * @type {Array.<ol.Feature>}
  67903. * @private
  67904. */
  67905. this.startIndicesFeature_ = [];
  67906. /**
  67907. * @type {number|undefined}
  67908. * @private
  67909. */
  67910. this.width_ = undefined;
  67911. };
  67912. goog.inherits(ol.render.webgl.ImageReplay, ol.render.VectorContext);
  67913. /**
  67914. * @param {ol.webgl.Context} context WebGL context.
  67915. * @return {function()} Delete resources function.
  67916. */
  67917. ol.render.webgl.ImageReplay.prototype.getDeleteResourcesFunction =
  67918. function(context) {
  67919. // We only delete our stuff here. The shaders and the program may
  67920. // be used by other ImageReplay instances (for other layers). And
  67921. // they will be deleted when disposing of the ol.webgl.Context
  67922. // object.
  67923. goog.asserts.assert(this.verticesBuffer_,
  67924. 'verticesBuffer must not be null');
  67925. goog.asserts.assert(this.indicesBuffer_,
  67926. 'indicesBuffer must not be null');
  67927. var verticesBuffer = this.verticesBuffer_;
  67928. var indicesBuffer = this.indicesBuffer_;
  67929. var textures = this.textures_;
  67930. var hitDetectionTextures = this.hitDetectionTextures_;
  67931. var gl = context.getGL();
  67932. return function() {
  67933. if (!gl.isContextLost()) {
  67934. var i, ii;
  67935. for (i = 0, ii = textures.length; i < ii; ++i) {
  67936. gl.deleteTexture(textures[i]);
  67937. }
  67938. for (i = 0, ii = hitDetectionTextures.length; i < ii; ++i) {
  67939. gl.deleteTexture(hitDetectionTextures[i]);
  67940. }
  67941. }
  67942. context.deleteBuffer(verticesBuffer);
  67943. context.deleteBuffer(indicesBuffer);
  67944. };
  67945. };
  67946. /**
  67947. * @inheritDoc
  67948. */
  67949. ol.render.webgl.ImageReplay.prototype.drawAsync = goog.abstractMethod;
  67950. /**
  67951. * @param {Array.<number>} flatCoordinates Flat coordinates.
  67952. * @param {number} offset Offset.
  67953. * @param {number} end End.
  67954. * @param {number} stride Stride.
  67955. * @return {number} My end.
  67956. * @private
  67957. */
  67958. ol.render.webgl.ImageReplay.prototype.drawCoordinates_ =
  67959. function(flatCoordinates, offset, end, stride) {
  67960. goog.asserts.assert(this.anchorX_ !== undefined, 'anchorX is defined');
  67961. goog.asserts.assert(this.anchorY_ !== undefined, 'anchorY is defined');
  67962. goog.asserts.assert(this.height_ !== undefined, 'height is defined');
  67963. goog.asserts.assert(this.imageHeight_ !== undefined,
  67964. 'imageHeight is defined');
  67965. goog.asserts.assert(this.imageWidth_ !== undefined, 'imageWidth is defined');
  67966. goog.asserts.assert(this.opacity_ !== undefined, 'opacity is defined');
  67967. goog.asserts.assert(this.originX_ !== undefined, 'originX is defined');
  67968. goog.asserts.assert(this.originY_ !== undefined, 'originY is defined');
  67969. goog.asserts.assert(this.rotateWithView_ !== undefined,
  67970. 'rotateWithView is defined');
  67971. goog.asserts.assert(this.rotation_ !== undefined, 'rotation is defined');
  67972. goog.asserts.assert(this.scale_ !== undefined, 'scale is defined');
  67973. goog.asserts.assert(this.width_ !== undefined, 'width is defined');
  67974. var anchorX = this.anchorX_;
  67975. var anchorY = this.anchorY_;
  67976. var height = this.height_;
  67977. var imageHeight = this.imageHeight_;
  67978. var imageWidth = this.imageWidth_;
  67979. var opacity = this.opacity_;
  67980. var originX = this.originX_;
  67981. var originY = this.originY_;
  67982. var rotateWithView = this.rotateWithView_ ? 1.0 : 0.0;
  67983. var rotation = this.rotation_;
  67984. var scale = this.scale_;
  67985. var width = this.width_;
  67986. var cos = Math.cos(rotation);
  67987. var sin = Math.sin(rotation);
  67988. var numIndices = this.indices_.length;
  67989. var numVertices = this.vertices_.length;
  67990. var i, n, offsetX, offsetY, x, y;
  67991. for (i = offset; i < end; i += stride) {
  67992. x = flatCoordinates[i] - this.origin_[0];
  67993. y = flatCoordinates[i + 1] - this.origin_[1];
  67994. // There are 4 vertices per [x, y] point, one for each corner of the
  67995. // rectangle we're going to draw. We'd use 1 vertex per [x, y] point if
  67996. // WebGL supported Geometry Shaders (which can emit new vertices), but that
  67997. // is not currently the case.
  67998. //
  67999. // And each vertex includes 8 values: the x and y coordinates, the x and
  68000. // y offsets used to calculate the position of the corner, the u and
  68001. // v texture coordinates for the corner, the opacity, and whether the
  68002. // the image should be rotated with the view (rotateWithView).
  68003. n = numVertices / 8;
  68004. // bottom-left corner
  68005. offsetX = -scale * anchorX;
  68006. offsetY = -scale * (height - anchorY);
  68007. this.vertices_[numVertices++] = x;
  68008. this.vertices_[numVertices++] = y;
  68009. this.vertices_[numVertices++] = offsetX * cos - offsetY * sin;
  68010. this.vertices_[numVertices++] = offsetX * sin + offsetY * cos;
  68011. this.vertices_[numVertices++] = originX / imageWidth;
  68012. this.vertices_[numVertices++] = (originY + height) / imageHeight;
  68013. this.vertices_[numVertices++] = opacity;
  68014. this.vertices_[numVertices++] = rotateWithView;
  68015. // bottom-right corner
  68016. offsetX = scale * (width - anchorX);
  68017. offsetY = -scale * (height - anchorY);
  68018. this.vertices_[numVertices++] = x;
  68019. this.vertices_[numVertices++] = y;
  68020. this.vertices_[numVertices++] = offsetX * cos - offsetY * sin;
  68021. this.vertices_[numVertices++] = offsetX * sin + offsetY * cos;
  68022. this.vertices_[numVertices++] = (originX + width) / imageWidth;
  68023. this.vertices_[numVertices++] = (originY + height) / imageHeight;
  68024. this.vertices_[numVertices++] = opacity;
  68025. this.vertices_[numVertices++] = rotateWithView;
  68026. // top-right corner
  68027. offsetX = scale * (width - anchorX);
  68028. offsetY = scale * anchorY;
  68029. this.vertices_[numVertices++] = x;
  68030. this.vertices_[numVertices++] = y;
  68031. this.vertices_[numVertices++] = offsetX * cos - offsetY * sin;
  68032. this.vertices_[numVertices++] = offsetX * sin + offsetY * cos;
  68033. this.vertices_[numVertices++] = (originX + width) / imageWidth;
  68034. this.vertices_[numVertices++] = originY / imageHeight;
  68035. this.vertices_[numVertices++] = opacity;
  68036. this.vertices_[numVertices++] = rotateWithView;
  68037. // top-left corner
  68038. offsetX = -scale * anchorX;
  68039. offsetY = scale * anchorY;
  68040. this.vertices_[numVertices++] = x;
  68041. this.vertices_[numVertices++] = y;
  68042. this.vertices_[numVertices++] = offsetX * cos - offsetY * sin;
  68043. this.vertices_[numVertices++] = offsetX * sin + offsetY * cos;
  68044. this.vertices_[numVertices++] = originX / imageWidth;
  68045. this.vertices_[numVertices++] = originY / imageHeight;
  68046. this.vertices_[numVertices++] = opacity;
  68047. this.vertices_[numVertices++] = rotateWithView;
  68048. this.indices_[numIndices++] = n;
  68049. this.indices_[numIndices++] = n + 1;
  68050. this.indices_[numIndices++] = n + 2;
  68051. this.indices_[numIndices++] = n;
  68052. this.indices_[numIndices++] = n + 2;
  68053. this.indices_[numIndices++] = n + 3;
  68054. }
  68055. return numVertices;
  68056. };
  68057. /**
  68058. * @inheritDoc
  68059. */
  68060. ol.render.webgl.ImageReplay.prototype.drawMultiPointGeometry =
  68061. function(multiPointGeometry, feature) {
  68062. this.startIndices_.push(this.indices_.length);
  68063. this.startIndicesFeature_.push(feature);
  68064. var flatCoordinates = multiPointGeometry.getFlatCoordinates();
  68065. var stride = multiPointGeometry.getStride();
  68066. this.drawCoordinates_(
  68067. flatCoordinates, 0, flatCoordinates.length, stride);
  68068. };
  68069. /**
  68070. * @inheritDoc
  68071. */
  68072. ol.render.webgl.ImageReplay.prototype.drawPointGeometry =
  68073. function(pointGeometry, feature) {
  68074. this.startIndices_.push(this.indices_.length);
  68075. this.startIndicesFeature_.push(feature);
  68076. var flatCoordinates = pointGeometry.getFlatCoordinates();
  68077. var stride = pointGeometry.getStride();
  68078. this.drawCoordinates_(
  68079. flatCoordinates, 0, flatCoordinates.length, stride);
  68080. };
  68081. /**
  68082. * @param {ol.webgl.Context} context Context.
  68083. */
  68084. ol.render.webgl.ImageReplay.prototype.finish = function(context) {
  68085. var gl = context.getGL();
  68086. this.groupIndices_.push(this.indices_.length);
  68087. goog.asserts.assert(this.images_.length === this.groupIndices_.length,
  68088. 'number of images and groupIndices match');
  68089. this.hitDetectionGroupIndices_.push(this.indices_.length);
  68090. goog.asserts.assert(this.hitDetectionImages_.length ===
  68091. this.hitDetectionGroupIndices_.length,
  68092. 'number of hitDetectionImages and hitDetectionGroupIndices match');
  68093. // create, bind, and populate the vertices buffer
  68094. this.verticesBuffer_ = new ol.webgl.Buffer(this.vertices_);
  68095. context.bindBuffer(goog.webgl.ARRAY_BUFFER, this.verticesBuffer_);
  68096. var indices = this.indices_;
  68097. var bits = context.hasOESElementIndexUint ? 32 : 16;
  68098. goog.asserts.assert(indices[indices.length - 1] < Math.pow(2, bits),
  68099. 'Too large element index detected [%s] (OES_element_index_uint "%s")',
  68100. indices[indices.length - 1], context.hasOESElementIndexUint);
  68101. // create, bind, and populate the indices buffer
  68102. this.indicesBuffer_ = new ol.webgl.Buffer(indices);
  68103. context.bindBuffer(goog.webgl.ELEMENT_ARRAY_BUFFER, this.indicesBuffer_);
  68104. // create textures
  68105. /** @type {Object.<string, WebGLTexture>} */
  68106. var texturePerImage = {};
  68107. this.createTextures_(this.textures_, this.images_, texturePerImage, gl);
  68108. goog.asserts.assert(this.textures_.length === this.groupIndices_.length,
  68109. 'number of textures and groupIndices match');
  68110. this.createTextures_(this.hitDetectionTextures_, this.hitDetectionImages_,
  68111. texturePerImage, gl);
  68112. goog.asserts.assert(this.hitDetectionTextures_.length ===
  68113. this.hitDetectionGroupIndices_.length,
  68114. 'number of hitDetectionTextures and hitDetectionGroupIndices match');
  68115. this.anchorX_ = undefined;
  68116. this.anchorY_ = undefined;
  68117. this.height_ = undefined;
  68118. this.images_ = null;
  68119. this.hitDetectionImages_ = null;
  68120. this.imageHeight_ = undefined;
  68121. this.imageWidth_ = undefined;
  68122. this.indices_ = null;
  68123. this.opacity_ = undefined;
  68124. this.originX_ = undefined;
  68125. this.originY_ = undefined;
  68126. this.rotateWithView_ = undefined;
  68127. this.rotation_ = undefined;
  68128. this.scale_ = undefined;
  68129. this.vertices_ = null;
  68130. this.width_ = undefined;
  68131. };
  68132. /**
  68133. * @private
  68134. * @param {Array.<WebGLTexture>} textures Textures.
  68135. * @param {Array.<HTMLCanvasElement|HTMLImageElement|HTMLVideoElement>} images
  68136. * Images.
  68137. * @param {Object.<string, WebGLTexture>} texturePerImage Texture cache.
  68138. * @param {WebGLRenderingContext} gl Gl.
  68139. */
  68140. ol.render.webgl.ImageReplay.prototype.createTextures_ =
  68141. function(textures, images, texturePerImage, gl) {
  68142. goog.asserts.assert(textures.length === 0,
  68143. 'upon creation, textures is empty');
  68144. var texture, image, uid, i;
  68145. var ii = images.length;
  68146. for (i = 0; i < ii; ++i) {
  68147. image = images[i];
  68148. uid = goog.getUid(image).toString();
  68149. if (goog.object.containsKey(texturePerImage, uid)) {
  68150. texture = texturePerImage[uid];
  68151. } else {
  68152. texture = ol.webgl.Context.createTexture(
  68153. gl, image, goog.webgl.CLAMP_TO_EDGE, goog.webgl.CLAMP_TO_EDGE);
  68154. texturePerImage[uid] = texture;
  68155. }
  68156. textures[i] = texture;
  68157. }
  68158. };
  68159. /**
  68160. * @param {ol.webgl.Context} context Context.
  68161. * @param {ol.Coordinate} center Center.
  68162. * @param {number} resolution Resolution.
  68163. * @param {number} rotation Rotation.
  68164. * @param {ol.Size} size Size.
  68165. * @param {number} pixelRatio Pixel ratio.
  68166. * @param {number} opacity Global opacity.
  68167. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68168. * to skip.
  68169. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  68170. * @param {boolean} oneByOne Draw features one-by-one for the hit-detecion.
  68171. * @param {ol.Extent=} opt_hitExtent Hit extent: Only features intersecting
  68172. * this extent are checked.
  68173. * @return {T|undefined} Callback result.
  68174. * @template T
  68175. */
  68176. ol.render.webgl.ImageReplay.prototype.replay = function(context,
  68177. center, resolution, rotation, size, pixelRatio,
  68178. opacity, skippedFeaturesHash,
  68179. featureCallback, oneByOne, opt_hitExtent) {
  68180. var gl = context.getGL();
  68181. // bind the vertices buffer
  68182. goog.asserts.assert(this.verticesBuffer_,
  68183. 'verticesBuffer must not be null');
  68184. context.bindBuffer(goog.webgl.ARRAY_BUFFER, this.verticesBuffer_);
  68185. // bind the indices buffer
  68186. goog.asserts.assert(this.indicesBuffer_,
  68187. 'indecesBuffer must not be null');
  68188. context.bindBuffer(goog.webgl.ELEMENT_ARRAY_BUFFER, this.indicesBuffer_);
  68189. // get the program
  68190. var fragmentShader =
  68191. ol.render.webgl.imagereplay.shader.DefaultFragment.getInstance();
  68192. var vertexShader =
  68193. ol.render.webgl.imagereplay.shader.DefaultVertex.getInstance();
  68194. var program = context.getProgram(fragmentShader, vertexShader);
  68195. // get the locations
  68196. var locations;
  68197. if (!this.defaultLocations_) {
  68198. locations =
  68199. new ol.render.webgl.imagereplay.shader.Default.Locations(gl, program);
  68200. this.defaultLocations_ = locations;
  68201. } else {
  68202. locations = this.defaultLocations_;
  68203. }
  68204. // use the program (FIXME: use the return value)
  68205. context.useProgram(program);
  68206. // enable the vertex attrib arrays
  68207. gl.enableVertexAttribArray(locations.a_position);
  68208. gl.vertexAttribPointer(locations.a_position, 2, goog.webgl.FLOAT,
  68209. false, 32, 0);
  68210. gl.enableVertexAttribArray(locations.a_offsets);
  68211. gl.vertexAttribPointer(locations.a_offsets, 2, goog.webgl.FLOAT,
  68212. false, 32, 8);
  68213. gl.enableVertexAttribArray(locations.a_texCoord);
  68214. gl.vertexAttribPointer(locations.a_texCoord, 2, goog.webgl.FLOAT,
  68215. false, 32, 16);
  68216. gl.enableVertexAttribArray(locations.a_opacity);
  68217. gl.vertexAttribPointer(locations.a_opacity, 1, goog.webgl.FLOAT,
  68218. false, 32, 24);
  68219. gl.enableVertexAttribArray(locations.a_rotateWithView);
  68220. gl.vertexAttribPointer(locations.a_rotateWithView, 1, goog.webgl.FLOAT,
  68221. false, 32, 28);
  68222. // set the "uniform" values
  68223. var projectionMatrix = this.projectionMatrix_;
  68224. ol.vec.Mat4.makeTransform2D(projectionMatrix,
  68225. 0.0, 0.0,
  68226. 2 / (resolution * size[0]),
  68227. 2 / (resolution * size[1]),
  68228. -rotation,
  68229. -(center[0] - this.origin_[0]), -(center[1] - this.origin_[1]));
  68230. var offsetScaleMatrix = this.offsetScaleMatrix_;
  68231. goog.vec.Mat4.makeScale(offsetScaleMatrix, 2 / size[0], 2 / size[1], 1);
  68232. var offsetRotateMatrix = this.offsetRotateMatrix_;
  68233. goog.vec.Mat4.makeIdentity(offsetRotateMatrix);
  68234. if (rotation !== 0) {
  68235. goog.vec.Mat4.rotateZ(offsetRotateMatrix, -rotation);
  68236. }
  68237. gl.uniformMatrix4fv(locations.u_projectionMatrix, false, projectionMatrix);
  68238. gl.uniformMatrix4fv(locations.u_offsetScaleMatrix, false, offsetScaleMatrix);
  68239. gl.uniformMatrix4fv(locations.u_offsetRotateMatrix, false,
  68240. offsetRotateMatrix);
  68241. gl.uniform1f(locations.u_opacity, opacity);
  68242. // draw!
  68243. var result;
  68244. if (featureCallback === undefined) {
  68245. this.drawReplay_(gl, context, skippedFeaturesHash,
  68246. this.textures_, this.groupIndices_);
  68247. } else {
  68248. // draw feature by feature for the hit-detection
  68249. result = this.drawHitDetectionReplay_(gl, context, skippedFeaturesHash,
  68250. featureCallback, oneByOne, opt_hitExtent);
  68251. }
  68252. // disable the vertex attrib arrays
  68253. gl.disableVertexAttribArray(locations.a_position);
  68254. gl.disableVertexAttribArray(locations.a_offsets);
  68255. gl.disableVertexAttribArray(locations.a_texCoord);
  68256. gl.disableVertexAttribArray(locations.a_opacity);
  68257. gl.disableVertexAttribArray(locations.a_rotateWithView);
  68258. return result;
  68259. };
  68260. /**
  68261. * @private
  68262. * @param {WebGLRenderingContext} gl gl.
  68263. * @param {ol.webgl.Context} context Context.
  68264. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68265. * to skip.
  68266. * @param {Array.<WebGLTexture>} textures Textures.
  68267. * @param {Array.<number>} groupIndices Texture group indices.
  68268. */
  68269. ol.render.webgl.ImageReplay.prototype.drawReplay_ =
  68270. function(gl, context, skippedFeaturesHash, textures, groupIndices) {
  68271. goog.asserts.assert(textures.length === groupIndices.length,
  68272. 'number of textures and groupIndeces match');
  68273. var elementType = context.hasOESElementIndexUint ?
  68274. goog.webgl.UNSIGNED_INT : goog.webgl.UNSIGNED_SHORT;
  68275. var elementSize = context.hasOESElementIndexUint ? 4 : 2;
  68276. if (!goog.object.isEmpty(skippedFeaturesHash)) {
  68277. this.drawReplaySkipping_(
  68278. gl, skippedFeaturesHash, textures, groupIndices,
  68279. elementType, elementSize);
  68280. } else {
  68281. var i, ii, start;
  68282. for (i = 0, ii = textures.length, start = 0; i < ii; ++i) {
  68283. gl.bindTexture(goog.webgl.TEXTURE_2D, textures[i]);
  68284. var end = groupIndices[i];
  68285. this.drawElements_(gl, start, end, elementType, elementSize);
  68286. start = end;
  68287. }
  68288. }
  68289. };
  68290. /**
  68291. * Draw the replay while paying attention to skipped features.
  68292. *
  68293. * This functions creates groups of features that can be drawn to together,
  68294. * so that the number of `drawElements` calls is minimized.
  68295. *
  68296. * For example given the following texture groups:
  68297. *
  68298. * Group 1: A B C
  68299. * Group 2: D [E] F G
  68300. *
  68301. * If feature E should be skipped, the following `drawElements` calls will be
  68302. * made:
  68303. *
  68304. * drawElements with feature A, B and C
  68305. * drawElements with feature D
  68306. * drawElements with feature F and G
  68307. *
  68308. * @private
  68309. * @param {WebGLRenderingContext} gl gl.
  68310. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68311. * to skip.
  68312. * @param {Array.<WebGLTexture>} textures Textures.
  68313. * @param {Array.<number>} groupIndices Texture group indices.
  68314. * @param {number} elementType Element type.
  68315. * @param {number} elementSize Element Size.
  68316. */
  68317. ol.render.webgl.ImageReplay.prototype.drawReplaySkipping_ =
  68318. function(gl, skippedFeaturesHash, textures, groupIndices,
  68319. elementType, elementSize) {
  68320. var featureIndex = 0;
  68321. var i, ii;
  68322. for (i = 0, ii = textures.length; i < ii; ++i) {
  68323. gl.bindTexture(goog.webgl.TEXTURE_2D, textures[i]);
  68324. var groupStart = (i > 0) ? groupIndices[i - 1] : 0;
  68325. var groupEnd = groupIndices[i];
  68326. var start = groupStart;
  68327. var end = groupStart;
  68328. while (featureIndex < this.startIndices_.length &&
  68329. this.startIndices_[featureIndex] <= groupEnd) {
  68330. var feature = this.startIndicesFeature_[featureIndex];
  68331. var featureUid = goog.getUid(feature).toString();
  68332. if (skippedFeaturesHash[featureUid] !== undefined) {
  68333. // feature should be skipped
  68334. if (start !== end) {
  68335. // draw the features so far
  68336. this.drawElements_(gl, start, end, elementType, elementSize);
  68337. }
  68338. // continue with the next feature
  68339. start = (featureIndex === this.startIndices_.length - 1) ?
  68340. groupEnd : this.startIndices_[featureIndex + 1];
  68341. end = start;
  68342. } else {
  68343. // the feature is not skipped, augment the end index
  68344. end = (featureIndex === this.startIndices_.length - 1) ?
  68345. groupEnd : this.startIndices_[featureIndex + 1];
  68346. }
  68347. featureIndex++;
  68348. }
  68349. if (start !== end) {
  68350. // draw the remaining features (in case there was no skipped feature
  68351. // in this texture group, all features of a group are drawn together)
  68352. this.drawElements_(gl, start, end, elementType, elementSize);
  68353. }
  68354. }
  68355. };
  68356. /**
  68357. * @private
  68358. * @param {WebGLRenderingContext} gl gl.
  68359. * @param {number} start Start index.
  68360. * @param {number} end End index.
  68361. * @param {number} elementType Element type.
  68362. * @param {number} elementSize Element Size.
  68363. */
  68364. ol.render.webgl.ImageReplay.prototype.drawElements_ = function(
  68365. gl, start, end, elementType, elementSize) {
  68366. var numItems = end - start;
  68367. var offsetInBytes = start * elementSize;
  68368. gl.drawElements(goog.webgl.TRIANGLES, numItems, elementType, offsetInBytes);
  68369. };
  68370. /**
  68371. * @private
  68372. * @param {WebGLRenderingContext} gl gl.
  68373. * @param {ol.webgl.Context} context Context.
  68374. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68375. * to skip.
  68376. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  68377. * @param {boolean} oneByOne Draw features one-by-one for the hit-detecion.
  68378. * @param {ol.Extent=} opt_hitExtent Hit extent: Only features intersecting
  68379. * this extent are checked.
  68380. * @return {T|undefined} Callback result.
  68381. * @template T
  68382. */
  68383. ol.render.webgl.ImageReplay.prototype.drawHitDetectionReplay_ =
  68384. function(gl, context, skippedFeaturesHash, featureCallback, oneByOne,
  68385. opt_hitExtent) {
  68386. if (!oneByOne) {
  68387. // draw all hit-detection features in "once" (by texture group)
  68388. return this.drawHitDetectionReplayAll_(gl, context,
  68389. skippedFeaturesHash, featureCallback);
  68390. } else {
  68391. // draw hit-detection features one by one
  68392. return this.drawHitDetectionReplayOneByOne_(gl, context,
  68393. skippedFeaturesHash, featureCallback, opt_hitExtent);
  68394. }
  68395. };
  68396. /**
  68397. * @private
  68398. * @param {WebGLRenderingContext} gl gl.
  68399. * @param {ol.webgl.Context} context Context.
  68400. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68401. * to skip.
  68402. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  68403. * @return {T|undefined} Callback result.
  68404. * @template T
  68405. */
  68406. ol.render.webgl.ImageReplay.prototype.drawHitDetectionReplayAll_ =
  68407. function(gl, context, skippedFeaturesHash, featureCallback) {
  68408. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  68409. this.drawReplay_(gl, context, skippedFeaturesHash,
  68410. this.hitDetectionTextures_, this.hitDetectionGroupIndices_);
  68411. var result = featureCallback(null);
  68412. if (result) {
  68413. return result;
  68414. } else {
  68415. return undefined;
  68416. }
  68417. };
  68418. /**
  68419. * @private
  68420. * @param {WebGLRenderingContext} gl gl.
  68421. * @param {ol.webgl.Context} context Context.
  68422. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68423. * to skip.
  68424. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  68425. * @param {ol.Extent=} opt_hitExtent Hit extent: Only features intersecting
  68426. * this extent are checked.
  68427. * @return {T|undefined} Callback result.
  68428. * @template T
  68429. */
  68430. ol.render.webgl.ImageReplay.prototype.drawHitDetectionReplayOneByOne_ =
  68431. function(gl, context, skippedFeaturesHash, featureCallback,
  68432. opt_hitExtent) {
  68433. goog.asserts.assert(this.hitDetectionTextures_.length ===
  68434. this.hitDetectionGroupIndices_.length,
  68435. 'number of hitDetectionTextures and hitDetectionGroupIndices match');
  68436. var elementType = context.hasOESElementIndexUint ?
  68437. goog.webgl.UNSIGNED_INT : goog.webgl.UNSIGNED_SHORT;
  68438. var elementSize = context.hasOESElementIndexUint ? 4 : 2;
  68439. var i, groupStart, start, end, feature, featureUid;
  68440. var featureIndex = this.startIndices_.length - 1;
  68441. for (i = this.hitDetectionTextures_.length - 1; i >= 0; --i) {
  68442. gl.bindTexture(goog.webgl.TEXTURE_2D, this.hitDetectionTextures_[i]);
  68443. groupStart = (i > 0) ? this.hitDetectionGroupIndices_[i - 1] : 0;
  68444. end = this.hitDetectionGroupIndices_[i];
  68445. // draw all features for this texture group
  68446. while (featureIndex >= 0 &&
  68447. this.startIndices_[featureIndex] >= groupStart) {
  68448. start = this.startIndices_[featureIndex];
  68449. feature = this.startIndicesFeature_[featureIndex];
  68450. featureUid = goog.getUid(feature).toString();
  68451. if (skippedFeaturesHash[featureUid] === undefined &&
  68452. feature.getGeometry() &&
  68453. (opt_hitExtent === undefined || ol.extent.intersects(
  68454. /** @type {Array<number>} */ (opt_hitExtent),
  68455. feature.getGeometry().getExtent()))) {
  68456. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  68457. this.drawElements_(gl, start, end, elementType, elementSize);
  68458. var result = featureCallback(feature);
  68459. if (result) {
  68460. return result;
  68461. }
  68462. }
  68463. end = start;
  68464. featureIndex--;
  68465. }
  68466. }
  68467. return undefined;
  68468. };
  68469. /**
  68470. * @inheritDoc
  68471. */
  68472. ol.render.webgl.ImageReplay.prototype.setFillStrokeStyle = goog.abstractMethod;
  68473. /**
  68474. * @inheritDoc
  68475. */
  68476. ol.render.webgl.ImageReplay.prototype.setImageStyle = function(imageStyle) {
  68477. var anchor = imageStyle.getAnchor();
  68478. var image = imageStyle.getImage(1);
  68479. var imageSize = imageStyle.getImageSize();
  68480. var hitDetectionImage = imageStyle.getHitDetectionImage(1);
  68481. var hitDetectionImageSize = imageStyle.getHitDetectionImageSize();
  68482. var opacity = imageStyle.getOpacity();
  68483. var origin = imageStyle.getOrigin();
  68484. var rotateWithView = imageStyle.getRotateWithView();
  68485. var rotation = imageStyle.getRotation();
  68486. var size = imageStyle.getSize();
  68487. var scale = imageStyle.getScale();
  68488. goog.asserts.assert(anchor, 'imageStyle anchor is not null');
  68489. goog.asserts.assert(image, 'imageStyle image is not null');
  68490. goog.asserts.assert(imageSize,
  68491. 'imageStyle imageSize is not null');
  68492. goog.asserts.assert(hitDetectionImage,
  68493. 'imageStyle hitDetectionImage is not null');
  68494. goog.asserts.assert(hitDetectionImageSize,
  68495. 'imageStyle hitDetectionImageSize is not null');
  68496. goog.asserts.assert(opacity !== undefined, 'imageStyle opacity is defined');
  68497. goog.asserts.assert(origin, 'imageStyle origin is not null');
  68498. goog.asserts.assert(rotateWithView !== undefined,
  68499. 'imageStyle rotateWithView is defined');
  68500. goog.asserts.assert(rotation !== undefined, 'imageStyle rotation is defined');
  68501. goog.asserts.assert(size, 'imageStyle size is not null');
  68502. goog.asserts.assert(scale !== undefined, 'imageStyle scale is defined');
  68503. var currentImage;
  68504. if (this.images_.length === 0) {
  68505. this.images_.push(image);
  68506. } else {
  68507. currentImage = this.images_[this.images_.length - 1];
  68508. if (goog.getUid(currentImage) != goog.getUid(image)) {
  68509. this.groupIndices_.push(this.indices_.length);
  68510. goog.asserts.assert(this.groupIndices_.length === this.images_.length,
  68511. 'number of groupIndices and images match');
  68512. this.images_.push(image);
  68513. }
  68514. }
  68515. if (this.hitDetectionImages_.length === 0) {
  68516. this.hitDetectionImages_.push(hitDetectionImage);
  68517. } else {
  68518. currentImage =
  68519. this.hitDetectionImages_[this.hitDetectionImages_.length - 1];
  68520. if (goog.getUid(currentImage) != goog.getUid(hitDetectionImage)) {
  68521. this.hitDetectionGroupIndices_.push(this.indices_.length);
  68522. goog.asserts.assert(this.hitDetectionGroupIndices_.length ===
  68523. this.hitDetectionImages_.length,
  68524. 'number of hitDetectionGroupIndices and hitDetectionImages match');
  68525. this.hitDetectionImages_.push(hitDetectionImage);
  68526. }
  68527. }
  68528. this.anchorX_ = anchor[0];
  68529. this.anchorY_ = anchor[1];
  68530. this.height_ = size[1];
  68531. this.imageHeight_ = imageSize[1];
  68532. this.imageWidth_ = imageSize[0];
  68533. this.opacity_ = opacity;
  68534. this.originX_ = origin[0];
  68535. this.originY_ = origin[1];
  68536. this.rotation_ = rotation;
  68537. this.rotateWithView_ = rotateWithView;
  68538. this.scale_ = scale;
  68539. this.width_ = size[0];
  68540. };
  68541. /**
  68542. * @constructor
  68543. * @implements {ol.render.IReplayGroup}
  68544. * @param {number} tolerance Tolerance.
  68545. * @param {ol.Extent} maxExtent Max extent.
  68546. * @param {number=} opt_renderBuffer Render buffer.
  68547. * @struct
  68548. */
  68549. ol.render.webgl.ReplayGroup = function(
  68550. tolerance, maxExtent, opt_renderBuffer) {
  68551. /**
  68552. * @type {ol.Extent}
  68553. * @private
  68554. */
  68555. this.maxExtent_ = maxExtent;
  68556. /**
  68557. * @type {number}
  68558. * @private
  68559. */
  68560. this.tolerance_ = tolerance;
  68561. /**
  68562. * @type {number|undefined}
  68563. * @private
  68564. */
  68565. this.renderBuffer_ = opt_renderBuffer;
  68566. /**
  68567. * ImageReplay only is supported at this point.
  68568. * @type {Object.<ol.render.ReplayType, ol.render.webgl.ImageReplay>}
  68569. * @private
  68570. */
  68571. this.replays_ = {};
  68572. };
  68573. /**
  68574. * @param {ol.webgl.Context} context WebGL context.
  68575. * @return {function()} Delete resources function.
  68576. */
  68577. ol.render.webgl.ReplayGroup.prototype.getDeleteResourcesFunction =
  68578. function(context) {
  68579. var functions = [];
  68580. var replayKey;
  68581. for (replayKey in this.replays_) {
  68582. functions.push(
  68583. this.replays_[replayKey].getDeleteResourcesFunction(context));
  68584. }
  68585. return goog.functions.sequence.apply(null, functions);
  68586. };
  68587. /**
  68588. * @param {ol.webgl.Context} context Context.
  68589. */
  68590. ol.render.webgl.ReplayGroup.prototype.finish = function(context) {
  68591. var replayKey;
  68592. for (replayKey in this.replays_) {
  68593. this.replays_[replayKey].finish(context);
  68594. }
  68595. };
  68596. /**
  68597. * @inheritDoc
  68598. */
  68599. ol.render.webgl.ReplayGroup.prototype.getReplay =
  68600. function(zIndex, replayType) {
  68601. var replay = this.replays_[replayType];
  68602. if (replay === undefined) {
  68603. var constructor = ol.render.webgl.BATCH_CONSTRUCTORS_[replayType];
  68604. goog.asserts.assert(constructor !== undefined,
  68605. replayType +
  68606. ' constructor missing from ol.render.webgl.BATCH_CONSTRUCTORS_');
  68607. replay = new constructor(this.tolerance_, this.maxExtent_);
  68608. this.replays_[replayType] = replay;
  68609. }
  68610. return replay;
  68611. };
  68612. /**
  68613. * @inheritDoc
  68614. */
  68615. ol.render.webgl.ReplayGroup.prototype.isEmpty = function() {
  68616. return goog.object.isEmpty(this.replays_);
  68617. };
  68618. /**
  68619. * @param {ol.webgl.Context} context Context.
  68620. * @param {ol.Coordinate} center Center.
  68621. * @param {number} resolution Resolution.
  68622. * @param {number} rotation Rotation.
  68623. * @param {ol.Size} size Size.
  68624. * @param {number} pixelRatio Pixel ratio.
  68625. * @param {number} opacity Global opacity.
  68626. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68627. * to skip.
  68628. */
  68629. ol.render.webgl.ReplayGroup.prototype.replay = function(context,
  68630. center, resolution, rotation, size, pixelRatio,
  68631. opacity, skippedFeaturesHash) {
  68632. var i, ii, replay;
  68633. for (i = 0, ii = ol.render.REPLAY_ORDER.length; i < ii; ++i) {
  68634. replay = this.replays_[ol.render.REPLAY_ORDER[i]];
  68635. if (replay !== undefined) {
  68636. replay.replay(context,
  68637. center, resolution, rotation, size, pixelRatio,
  68638. opacity, skippedFeaturesHash,
  68639. undefined, false);
  68640. }
  68641. }
  68642. };
  68643. /**
  68644. * @private
  68645. * @param {ol.webgl.Context} context Context.
  68646. * @param {ol.Coordinate} center Center.
  68647. * @param {number} resolution Resolution.
  68648. * @param {number} rotation Rotation.
  68649. * @param {ol.Size} size Size.
  68650. * @param {number} pixelRatio Pixel ratio.
  68651. * @param {number} opacity Global opacity.
  68652. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68653. * to skip.
  68654. * @param {function(ol.Feature): T|undefined} featureCallback Feature callback.
  68655. * @param {boolean} oneByOne Draw features one-by-one for the hit-detecion.
  68656. * @param {ol.Extent=} opt_hitExtent Hit extent: Only features intersecting
  68657. * this extent are checked.
  68658. * @return {T|undefined} Callback result.
  68659. * @template T
  68660. */
  68661. ol.render.webgl.ReplayGroup.prototype.replayHitDetection_ = function(context,
  68662. center, resolution, rotation, size, pixelRatio, opacity,
  68663. skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent) {
  68664. var i, replay, result;
  68665. for (i = ol.render.REPLAY_ORDER.length - 1; i >= 0; --i) {
  68666. replay = this.replays_[ol.render.REPLAY_ORDER[i]];
  68667. if (replay !== undefined) {
  68668. result = replay.replay(context,
  68669. center, resolution, rotation, size, pixelRatio, opacity,
  68670. skippedFeaturesHash, featureCallback, oneByOne, opt_hitExtent);
  68671. if (result) {
  68672. return result;
  68673. }
  68674. }
  68675. }
  68676. return undefined;
  68677. };
  68678. /**
  68679. * @param {ol.Coordinate} coordinate Coordinate.
  68680. * @param {ol.webgl.Context} context Context.
  68681. * @param {ol.Coordinate} center Center.
  68682. * @param {number} resolution Resolution.
  68683. * @param {number} rotation Rotation.
  68684. * @param {ol.Size} size Size.
  68685. * @param {number} pixelRatio Pixel ratio.
  68686. * @param {number} opacity Global opacity.
  68687. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68688. * to skip.
  68689. * @param {function(ol.Feature): T|undefined} callback Feature callback.
  68690. * @return {T|undefined} Callback result.
  68691. * @template T
  68692. */
  68693. ol.render.webgl.ReplayGroup.prototype.forEachFeatureAtCoordinate = function(
  68694. coordinate, context, center, resolution, rotation, size, pixelRatio,
  68695. opacity, skippedFeaturesHash,
  68696. callback) {
  68697. var gl = context.getGL();
  68698. gl.bindFramebuffer(
  68699. gl.FRAMEBUFFER, context.getHitDetectionFramebuffer());
  68700. /**
  68701. * @type {ol.Extent}
  68702. */
  68703. var hitExtent;
  68704. if (this.renderBuffer_ !== undefined) {
  68705. // build an extent around the coordinate, so that only features that
  68706. // intersect this extent are checked
  68707. hitExtent = ol.extent.buffer(
  68708. ol.extent.createOrUpdateFromCoordinate(coordinate),
  68709. resolution * this.renderBuffer_);
  68710. }
  68711. return this.replayHitDetection_(context,
  68712. coordinate, resolution, rotation, ol.render.webgl.HIT_DETECTION_SIZE_,
  68713. pixelRatio, opacity, skippedFeaturesHash,
  68714. /**
  68715. * @param {ol.Feature} feature Feature.
  68716. * @return {?} Callback result.
  68717. */
  68718. function(feature) {
  68719. var imageData = new Uint8Array(4);
  68720. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68721. if (imageData[3] > 0) {
  68722. var result = callback(feature);
  68723. if (result) {
  68724. return result;
  68725. }
  68726. }
  68727. }, true, hitExtent);
  68728. };
  68729. /**
  68730. * @param {ol.Coordinate} coordinate Coordinate.
  68731. * @param {ol.webgl.Context} context Context.
  68732. * @param {ol.Coordinate} center Center.
  68733. * @param {number} resolution Resolution.
  68734. * @param {number} rotation Rotation.
  68735. * @param {ol.Size} size Size.
  68736. * @param {number} pixelRatio Pixel ratio.
  68737. * @param {number} opacity Global opacity.
  68738. * @param {Object.<string, boolean>} skippedFeaturesHash Ids of features
  68739. * to skip.
  68740. * @return {boolean} Is there a feature at the given coordinate?
  68741. */
  68742. ol.render.webgl.ReplayGroup.prototype.hasFeatureAtCoordinate = function(
  68743. coordinate, context, center, resolution, rotation, size, pixelRatio,
  68744. opacity, skippedFeaturesHash) {
  68745. var gl = context.getGL();
  68746. gl.bindFramebuffer(
  68747. gl.FRAMEBUFFER, context.getHitDetectionFramebuffer());
  68748. var hasFeature = this.replayHitDetection_(context,
  68749. coordinate, resolution, rotation, ol.render.webgl.HIT_DETECTION_SIZE_,
  68750. pixelRatio, opacity, skippedFeaturesHash,
  68751. /**
  68752. * @param {ol.Feature} feature Feature.
  68753. * @return {boolean} Is there a feature?
  68754. */
  68755. function(feature) {
  68756. var imageData = new Uint8Array(4);
  68757. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68758. return imageData[3] > 0;
  68759. }, false);
  68760. return hasFeature !== undefined;
  68761. };
  68762. /**
  68763. * @const
  68764. * @private
  68765. * @type {Object.<ol.render.ReplayType,
  68766. * function(new: ol.render.webgl.ImageReplay, number,
  68767. * ol.Extent)>}
  68768. */
  68769. ol.render.webgl.BATCH_CONSTRUCTORS_ = {
  68770. 'Image': ol.render.webgl.ImageReplay
  68771. };
  68772. /**
  68773. * @const
  68774. * @private
  68775. * @type {Array.<number>}
  68776. */
  68777. ol.render.webgl.HIT_DETECTION_SIZE_ = [1, 1];
  68778. goog.provide('ol.render.webgl.Immediate');
  68779. goog.require('goog.array');
  68780. goog.require('ol.extent');
  68781. goog.require('ol.render.VectorContext');
  68782. goog.require('ol.render.webgl.ImageReplay');
  68783. goog.require('ol.render.webgl.ReplayGroup');
  68784. /**
  68785. * @constructor
  68786. * @extends {ol.render.VectorContext}
  68787. * @param {ol.webgl.Context} context Context.
  68788. * @param {ol.Coordinate} center Center.
  68789. * @param {number} resolution Resolution.
  68790. * @param {number} rotation Rotation.
  68791. * @param {ol.Size} size Size.
  68792. * @param {ol.Extent} extent Extent.
  68793. * @param {number} pixelRatio Pixel ratio.
  68794. * @struct
  68795. */
  68796. ol.render.webgl.Immediate = function(context,
  68797. center, resolution, rotation, size, extent, pixelRatio) {
  68798. goog.base(this);
  68799. /**
  68800. * @private
  68801. */
  68802. this.context_ = context;
  68803. /**
  68804. * @private
  68805. */
  68806. this.center_ = center;
  68807. /**
  68808. * @private
  68809. */
  68810. this.extent_ = extent;
  68811. /**
  68812. * @private
  68813. */
  68814. this.pixelRatio_ = pixelRatio;
  68815. /**
  68816. * @private
  68817. */
  68818. this.size_ = size;
  68819. /**
  68820. * @private
  68821. */
  68822. this.rotation_ = rotation;
  68823. /**
  68824. * @private
  68825. */
  68826. this.resolution_ = resolution;
  68827. /**
  68828. * @private
  68829. * @type {ol.style.Image}
  68830. */
  68831. this.imageStyle_ = null;
  68832. /**
  68833. * @private
  68834. * @type {!Object.<string,
  68835. * Array.<function(ol.render.webgl.Immediate)>>}
  68836. */
  68837. this.callbacksByZIndex_ = {};
  68838. };
  68839. goog.inherits(ol.render.webgl.Immediate, ol.render.VectorContext);
  68840. /**
  68841. * FIXME: empty description for jsdoc
  68842. */
  68843. ol.render.webgl.Immediate.prototype.flush = function() {
  68844. /** @type {Array.<number>} */
  68845. var zs = Object.keys(this.callbacksByZIndex_).map(Number);
  68846. goog.array.sort(zs);
  68847. var i, ii, callbacks, j, jj;
  68848. for (i = 0, ii = zs.length; i < ii; ++i) {
  68849. callbacks = this.callbacksByZIndex_[zs[i].toString()];
  68850. for (j = 0, jj = callbacks.length; j < jj; ++j) {
  68851. callbacks[j](this);
  68852. }
  68853. }
  68854. };
  68855. /**
  68856. * Register a function to be called for rendering at a given zIndex. The
  68857. * function will be called asynchronously. The callback will receive a
  68858. * reference to {@link ol.render.canvas.Immediate} context for drawing.
  68859. * @param {number} zIndex Z index.
  68860. * @param {function(ol.render.webgl.Immediate)} callback Callback.
  68861. * @api
  68862. */
  68863. ol.render.webgl.Immediate.prototype.drawAsync = function(zIndex, callback) {
  68864. var zIndexKey = zIndex.toString();
  68865. var callbacks = this.callbacksByZIndex_[zIndexKey];
  68866. if (callbacks !== undefined) {
  68867. callbacks.push(callback);
  68868. } else {
  68869. this.callbacksByZIndex_[zIndexKey] = [callback];
  68870. }
  68871. };
  68872. /**
  68873. * @inheritDoc
  68874. * @api
  68875. */
  68876. ol.render.webgl.Immediate.prototype.drawCircleGeometry =
  68877. function(circleGeometry, data) {
  68878. };
  68879. /**
  68880. * @inheritDoc
  68881. * @api
  68882. */
  68883. ol.render.webgl.Immediate.prototype.drawFeature = function(feature, style) {
  68884. var geometry = style.getGeometryFunction()(feature);
  68885. if (!geometry ||
  68886. !ol.extent.intersects(this.extent_, geometry.getExtent())) {
  68887. return;
  68888. }
  68889. var zIndex = style.getZIndex();
  68890. if (zIndex === undefined) {
  68891. zIndex = 0;
  68892. }
  68893. this.drawAsync(zIndex, function(render) {
  68894. render.setFillStrokeStyle(style.getFill(), style.getStroke());
  68895. render.setImageStyle(style.getImage());
  68896. render.setTextStyle(style.getText());
  68897. var type = geometry.getType();
  68898. var renderGeometry = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_[type];
  68899. // Do not assert since all kinds of geometries are not handled yet.
  68900. // In spite, render what we support.
  68901. if (renderGeometry) {
  68902. renderGeometry.call(render, geometry, null);
  68903. }
  68904. });
  68905. };
  68906. /**
  68907. * @inheritDoc
  68908. * @api
  68909. */
  68910. ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry =
  68911. function(geometryCollectionGeometry, data) {
  68912. var geometries = geometryCollectionGeometry.getGeometriesArray();
  68913. var renderers = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_;
  68914. var i, ii;
  68915. for (i = 0, ii = geometries.length; i < ii; ++i) {
  68916. var geometry = geometries[i];
  68917. var geometryRenderer = renderers[geometry.getType()];
  68918. // Do not assert since all kinds of geometries are not handled yet.
  68919. // In order to support hierarchies, delegate instead what we can to
  68920. // valid renderers.
  68921. if (geometryRenderer) {
  68922. geometryRenderer.call(this, geometry, data);
  68923. }
  68924. }
  68925. };
  68926. /**
  68927. * @inheritDoc
  68928. * @api
  68929. */
  68930. ol.render.webgl.Immediate.prototype.drawPointGeometry =
  68931. function(pointGeometry, data) {
  68932. var context = this.context_;
  68933. var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  68934. var replay = /** @type {ol.render.webgl.ImageReplay} */ (
  68935. replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  68936. replay.setImageStyle(this.imageStyle_);
  68937. replay.drawPointGeometry(pointGeometry, data);
  68938. replay.finish(context);
  68939. // default colors
  68940. var opacity = 1;
  68941. var skippedFeatures = {};
  68942. var featureCallback;
  68943. var oneByOne = false;
  68944. replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
  68945. this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
  68946. oneByOne);
  68947. replay.getDeleteResourcesFunction(context)();
  68948. };
  68949. /**
  68950. * @inheritDoc
  68951. * @api
  68952. */
  68953. ol.render.webgl.Immediate.prototype.drawLineStringGeometry =
  68954. function(lineStringGeometry, data) {
  68955. };
  68956. /**
  68957. * @inheritDoc
  68958. * @api
  68959. */
  68960. ol.render.webgl.Immediate.prototype.drawMultiLineStringGeometry =
  68961. function(multiLineStringGeometry, data) {
  68962. };
  68963. /**
  68964. * @inheritDoc
  68965. * @api
  68966. */
  68967. ol.render.webgl.Immediate.prototype.drawMultiPointGeometry =
  68968. function(multiPointGeometry, data) {
  68969. var context = this.context_;
  68970. var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  68971. var replay = /** @type {ol.render.webgl.ImageReplay} */ (
  68972. replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  68973. replay.setImageStyle(this.imageStyle_);
  68974. replay.drawMultiPointGeometry(multiPointGeometry, data);
  68975. replay.finish(context);
  68976. var opacity = 1;
  68977. var skippedFeatures = {};
  68978. var featureCallback;
  68979. var oneByOne = false;
  68980. replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
  68981. this.size_, this.pixelRatio_, opacity, skippedFeatures, featureCallback,
  68982. oneByOne);
  68983. replay.getDeleteResourcesFunction(context)();
  68984. };
  68985. /**
  68986. * @inheritDoc
  68987. * @api
  68988. */
  68989. ol.render.webgl.Immediate.prototype.drawMultiPolygonGeometry =
  68990. function(multiPolygonGeometry, data) {
  68991. };
  68992. /**
  68993. * @inheritDoc
  68994. * @api
  68995. */
  68996. ol.render.webgl.Immediate.prototype.drawPolygonGeometry =
  68997. function(polygonGeometry, data) {
  68998. };
  68999. /**
  69000. * @inheritDoc
  69001. * @api
  69002. */
  69003. ol.render.webgl.Immediate.prototype.drawText =
  69004. function(flatCoordinates, offset, end, stride, geometry, data) {
  69005. };
  69006. /**
  69007. * @inheritDoc
  69008. * @api
  69009. */
  69010. ol.render.webgl.Immediate.prototype.setFillStrokeStyle =
  69011. function(fillStyle, strokeStyle) {
  69012. };
  69013. /**
  69014. * @inheritDoc
  69015. * @api
  69016. */
  69017. ol.render.webgl.Immediate.prototype.setImageStyle = function(imageStyle) {
  69018. this.imageStyle_ = imageStyle;
  69019. };
  69020. /**
  69021. * @inheritDoc
  69022. * @api
  69023. */
  69024. ol.render.webgl.Immediate.prototype.setTextStyle = function(textStyle) {
  69025. };
  69026. /**
  69027. * @const
  69028. * @private
  69029. * @type {Object.<ol.geom.GeometryType,
  69030. * function(this: ol.render.webgl.Immediate, ol.geom.Geometry,
  69031. * Object)>}
  69032. */
  69033. ol.render.webgl.Immediate.GEOMETRY_RENDERERS_ = {
  69034. 'Point': ol.render.webgl.Immediate.prototype.drawPointGeometry,
  69035. 'MultiPoint': ol.render.webgl.Immediate.prototype.drawMultiPointGeometry,
  69036. 'GeometryCollection':
  69037. ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry
  69038. };
  69039. // This file is automatically generated, do not edit
  69040. goog.provide('ol.renderer.webgl.map.shader.Default');
  69041. goog.provide('ol.renderer.webgl.map.shader.Default.Locations');
  69042. goog.provide('ol.renderer.webgl.map.shader.DefaultFragment');
  69043. goog.provide('ol.renderer.webgl.map.shader.DefaultVertex');
  69044. goog.require('ol.webgl.shader');
  69045. /**
  69046. * @constructor
  69047. * @extends {ol.webgl.shader.Fragment}
  69048. * @struct
  69049. */
  69050. ol.renderer.webgl.map.shader.DefaultFragment = function() {
  69051. goog.base(this, ol.renderer.webgl.map.shader.DefaultFragment.SOURCE);
  69052. };
  69053. goog.inherits(ol.renderer.webgl.map.shader.DefaultFragment, ol.webgl.shader.Fragment);
  69054. goog.addSingletonGetter(ol.renderer.webgl.map.shader.DefaultFragment);
  69055. /**
  69056. * @const
  69057. * @type {string}
  69058. */
  69059. ol.renderer.webgl.map.shader.DefaultFragment.DEBUG_SOURCE = 'precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform float u_opacity;\nuniform sampler2D u_texture;\n\nvoid main(void) {\n vec4 texColor = texture2D(u_texture, v_texCoord);\n gl_FragColor.rgb = texColor.rgb;\n gl_FragColor.a = texColor.a * u_opacity;\n}\n';
  69060. /**
  69061. * @const
  69062. * @type {string}
  69063. */
  69064. ol.renderer.webgl.map.shader.DefaultFragment.OPTIMIZED_SOURCE = 'precision mediump float;varying vec2 a;uniform float f;uniform sampler2D g;void main(void){vec4 texColor=texture2D(g,a);gl_FragColor.rgb=texColor.rgb;gl_FragColor.a=texColor.a*f;}';
  69065. /**
  69066. * @const
  69067. * @type {string}
  69068. */
  69069. ol.renderer.webgl.map.shader.DefaultFragment.SOURCE = goog.DEBUG ?
  69070. ol.renderer.webgl.map.shader.DefaultFragment.DEBUG_SOURCE :
  69071. ol.renderer.webgl.map.shader.DefaultFragment.OPTIMIZED_SOURCE;
  69072. /**
  69073. * @constructor
  69074. * @extends {ol.webgl.shader.Vertex}
  69075. * @struct
  69076. */
  69077. ol.renderer.webgl.map.shader.DefaultVertex = function() {
  69078. goog.base(this, ol.renderer.webgl.map.shader.DefaultVertex.SOURCE);
  69079. };
  69080. goog.inherits(ol.renderer.webgl.map.shader.DefaultVertex, ol.webgl.shader.Vertex);
  69081. goog.addSingletonGetter(ol.renderer.webgl.map.shader.DefaultVertex);
  69082. /**
  69083. * @const
  69084. * @type {string}
  69085. */
  69086. ol.renderer.webgl.map.shader.DefaultVertex.DEBUG_SOURCE = 'varying vec2 v_texCoord;\n\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat4 u_texCoordMatrix;\nuniform mat4 u_projectionMatrix;\n\nvoid main(void) {\n gl_Position = u_projectionMatrix * vec4(a_position, 0., 1.);\n v_texCoord = (u_texCoordMatrix * vec4(a_texCoord, 0., 1.)).st;\n}\n\n\n';
  69087. /**
  69088. * @const
  69089. * @type {string}
  69090. */
  69091. ol.renderer.webgl.map.shader.DefaultVertex.OPTIMIZED_SOURCE = 'varying vec2 a;attribute vec2 b;attribute vec2 c;uniform mat4 d;uniform mat4 e;void main(void){gl_Position=e*vec4(b,0.,1.);a=(d*vec4(c,0.,1.)).st;}';
  69092. /**
  69093. * @const
  69094. * @type {string}
  69095. */
  69096. ol.renderer.webgl.map.shader.DefaultVertex.SOURCE = goog.DEBUG ?
  69097. ol.renderer.webgl.map.shader.DefaultVertex.DEBUG_SOURCE :
  69098. ol.renderer.webgl.map.shader.DefaultVertex.OPTIMIZED_SOURCE;
  69099. /**
  69100. * @constructor
  69101. * @param {WebGLRenderingContext} gl GL.
  69102. * @param {WebGLProgram} program Program.
  69103. * @struct
  69104. */
  69105. ol.renderer.webgl.map.shader.Default.Locations = function(gl, program) {
  69106. /**
  69107. * @type {WebGLUniformLocation}
  69108. */
  69109. this.u_opacity = gl.getUniformLocation(
  69110. program, goog.DEBUG ? 'u_opacity' : 'f');
  69111. /**
  69112. * @type {WebGLUniformLocation}
  69113. */
  69114. this.u_projectionMatrix = gl.getUniformLocation(
  69115. program, goog.DEBUG ? 'u_projectionMatrix' : 'e');
  69116. /**
  69117. * @type {WebGLUniformLocation}
  69118. */
  69119. this.u_texCoordMatrix = gl.getUniformLocation(
  69120. program, goog.DEBUG ? 'u_texCoordMatrix' : 'd');
  69121. /**
  69122. * @type {WebGLUniformLocation}
  69123. */
  69124. this.u_texture = gl.getUniformLocation(
  69125. program, goog.DEBUG ? 'u_texture' : 'g');
  69126. /**
  69127. * @type {number}
  69128. */
  69129. this.a_position = gl.getAttribLocation(
  69130. program, goog.DEBUG ? 'a_position' : 'b');
  69131. /**
  69132. * @type {number}
  69133. */
  69134. this.a_texCoord = gl.getAttribLocation(
  69135. program, goog.DEBUG ? 'a_texCoord' : 'c');
  69136. };
  69137. goog.provide('ol.renderer.webgl.Layer');
  69138. goog.require('goog.vec.Mat4');
  69139. goog.require('goog.webgl');
  69140. goog.require('ol.layer.Layer');
  69141. goog.require('ol.render.Event');
  69142. goog.require('ol.render.EventType');
  69143. goog.require('ol.render.webgl.Immediate');
  69144. goog.require('ol.renderer.Layer');
  69145. goog.require('ol.renderer.webgl.map.shader.Default');
  69146. goog.require('ol.renderer.webgl.map.shader.Default.Locations');
  69147. goog.require('ol.renderer.webgl.map.shader.DefaultFragment');
  69148. goog.require('ol.renderer.webgl.map.shader.DefaultVertex');
  69149. goog.require('ol.webgl.Buffer');
  69150. goog.require('ol.webgl.Context');
  69151. /**
  69152. * @constructor
  69153. * @extends {ol.renderer.Layer}
  69154. * @param {ol.renderer.webgl.Map} mapRenderer Map renderer.
  69155. * @param {ol.layer.Layer} layer Layer.
  69156. */
  69157. ol.renderer.webgl.Layer = function(mapRenderer, layer) {
  69158. goog.base(this, layer);
  69159. /**
  69160. * @protected
  69161. * @type {ol.renderer.webgl.Map}
  69162. */
  69163. this.mapRenderer = mapRenderer;
  69164. /**
  69165. * @private
  69166. * @type {ol.webgl.Buffer}
  69167. */
  69168. this.arrayBuffer_ = new ol.webgl.Buffer([
  69169. -1, -1, 0, 0,
  69170. 1, -1, 1, 0,
  69171. -1, 1, 0, 1,
  69172. 1, 1, 1, 1
  69173. ]);
  69174. /**
  69175. * @protected
  69176. * @type {WebGLTexture}
  69177. */
  69178. this.texture = null;
  69179. /**
  69180. * @protected
  69181. * @type {WebGLFramebuffer}
  69182. */
  69183. this.framebuffer = null;
  69184. /**
  69185. * @protected
  69186. * @type {number|undefined}
  69187. */
  69188. this.framebufferDimension = undefined;
  69189. /**
  69190. * @protected
  69191. * @type {!goog.vec.Mat4.Number}
  69192. */
  69193. this.texCoordMatrix = goog.vec.Mat4.createNumber();
  69194. /**
  69195. * @protected
  69196. * @type {!goog.vec.Mat4.Number}
  69197. */
  69198. this.projectionMatrix = goog.vec.Mat4.createNumberIdentity();
  69199. /**
  69200. * @private
  69201. * @type {ol.renderer.webgl.map.shader.Default.Locations}
  69202. */
  69203. this.defaultLocations_ = null;
  69204. };
  69205. goog.inherits(ol.renderer.webgl.Layer, ol.renderer.Layer);
  69206. /**
  69207. * @param {olx.FrameState} frameState Frame state.
  69208. * @param {number} framebufferDimension Framebuffer dimension.
  69209. * @protected
  69210. */
  69211. ol.renderer.webgl.Layer.prototype.bindFramebuffer =
  69212. function(frameState, framebufferDimension) {
  69213. var gl = this.mapRenderer.getGL();
  69214. if (this.framebufferDimension === undefined ||
  69215. this.framebufferDimension != framebufferDimension) {
  69216. frameState.postRenderFunctions.push(
  69217. goog.partial(
  69218. /**
  69219. * @param {WebGLRenderingContext} gl GL.
  69220. * @param {WebGLFramebuffer} framebuffer Framebuffer.
  69221. * @param {WebGLTexture} texture Texture.
  69222. */
  69223. function(gl, framebuffer, texture) {
  69224. if (!gl.isContextLost()) {
  69225. gl.deleteFramebuffer(framebuffer);
  69226. gl.deleteTexture(texture);
  69227. }
  69228. }, gl, this.framebuffer, this.texture));
  69229. var texture = ol.webgl.Context.createEmptyTexture(
  69230. gl, framebufferDimension, framebufferDimension);
  69231. var framebuffer = gl.createFramebuffer();
  69232. gl.bindFramebuffer(goog.webgl.FRAMEBUFFER, framebuffer);
  69233. gl.framebufferTexture2D(goog.webgl.FRAMEBUFFER,
  69234. goog.webgl.COLOR_ATTACHMENT0, goog.webgl.TEXTURE_2D, texture, 0);
  69235. this.texture = texture;
  69236. this.framebuffer = framebuffer;
  69237. this.framebufferDimension = framebufferDimension;
  69238. } else {
  69239. gl.bindFramebuffer(goog.webgl.FRAMEBUFFER, this.framebuffer);
  69240. }
  69241. };
  69242. /**
  69243. * @param {olx.FrameState} frameState Frame state.
  69244. * @param {ol.layer.LayerState} layerState Layer state.
  69245. * @param {ol.webgl.Context} context Context.
  69246. */
  69247. ol.renderer.webgl.Layer.prototype.composeFrame =
  69248. function(frameState, layerState, context) {
  69249. this.dispatchComposeEvent_(
  69250. ol.render.EventType.PRECOMPOSE, context, frameState);
  69251. context.bindBuffer(goog.webgl.ARRAY_BUFFER, this.arrayBuffer_);
  69252. var gl = context.getGL();
  69253. var fragmentShader =
  69254. ol.renderer.webgl.map.shader.DefaultFragment.getInstance();
  69255. var vertexShader = ol.renderer.webgl.map.shader.DefaultVertex.getInstance();
  69256. var program = context.getProgram(fragmentShader, vertexShader);
  69257. var locations;
  69258. if (!this.defaultLocations_) {
  69259. locations =
  69260. new ol.renderer.webgl.map.shader.Default.Locations(gl, program);
  69261. this.defaultLocations_ = locations;
  69262. } else {
  69263. locations = this.defaultLocations_;
  69264. }
  69265. if (context.useProgram(program)) {
  69266. gl.enableVertexAttribArray(locations.a_position);
  69267. gl.vertexAttribPointer(
  69268. locations.a_position, 2, goog.webgl.FLOAT, false, 16, 0);
  69269. gl.enableVertexAttribArray(locations.a_texCoord);
  69270. gl.vertexAttribPointer(
  69271. locations.a_texCoord, 2, goog.webgl.FLOAT, false, 16, 8);
  69272. gl.uniform1i(locations.u_texture, 0);
  69273. }
  69274. gl.uniformMatrix4fv(
  69275. locations.u_texCoordMatrix, false, this.getTexCoordMatrix());
  69276. gl.uniformMatrix4fv(locations.u_projectionMatrix, false,
  69277. this.getProjectionMatrix());
  69278. gl.uniform1f(locations.u_opacity, layerState.opacity);
  69279. gl.bindTexture(goog.webgl.TEXTURE_2D, this.getTexture());
  69280. gl.drawArrays(goog.webgl.TRIANGLE_STRIP, 0, 4);
  69281. this.dispatchComposeEvent_(
  69282. ol.render.EventType.POSTCOMPOSE, context, frameState);
  69283. };
  69284. /**
  69285. * @param {ol.render.EventType} type Event type.
  69286. * @param {ol.webgl.Context} context WebGL context.
  69287. * @param {olx.FrameState} frameState Frame state.
  69288. * @private
  69289. */
  69290. ol.renderer.webgl.Layer.prototype.dispatchComposeEvent_ =
  69291. function(type, context, frameState) {
  69292. var layer = this.getLayer();
  69293. if (layer.hasListener(type)) {
  69294. var viewState = frameState.viewState;
  69295. var resolution = viewState.resolution;
  69296. var pixelRatio = frameState.pixelRatio;
  69297. var extent = frameState.extent;
  69298. var center = viewState.center;
  69299. var rotation = viewState.rotation;
  69300. var size = frameState.size;
  69301. var render = new ol.render.webgl.Immediate(
  69302. context, center, resolution, rotation, size, extent, pixelRatio);
  69303. var composeEvent = new ol.render.Event(
  69304. type, layer, render, frameState, null, context);
  69305. layer.dispatchEvent(composeEvent);
  69306. }
  69307. };
  69308. /**
  69309. * @return {!goog.vec.Mat4.Number} Matrix.
  69310. */
  69311. ol.renderer.webgl.Layer.prototype.getTexCoordMatrix = function() {
  69312. return this.texCoordMatrix;
  69313. };
  69314. /**
  69315. * @return {WebGLTexture} Texture.
  69316. */
  69317. ol.renderer.webgl.Layer.prototype.getTexture = function() {
  69318. return this.texture;
  69319. };
  69320. /**
  69321. * @return {!goog.vec.Mat4.Number} Matrix.
  69322. */
  69323. ol.renderer.webgl.Layer.prototype.getProjectionMatrix = function() {
  69324. return this.projectionMatrix;
  69325. };
  69326. /**
  69327. * Handle webglcontextlost.
  69328. */
  69329. ol.renderer.webgl.Layer.prototype.handleWebGLContextLost = function() {
  69330. this.texture = null;
  69331. this.framebuffer = null;
  69332. this.framebufferDimension = undefined;
  69333. };
  69334. /**
  69335. * @param {olx.FrameState} frameState Frame state.
  69336. * @param {ol.layer.LayerState} layerState Layer state.
  69337. * @param {ol.webgl.Context} context Context.
  69338. * @return {boolean} whether composeFrame should be called.
  69339. */
  69340. ol.renderer.webgl.Layer.prototype.prepareFrame = goog.abstractMethod;
  69341. goog.provide('ol.renderer.webgl.ImageLayer');
  69342. goog.require('goog.asserts');
  69343. goog.require('goog.functions');
  69344. goog.require('goog.vec.Mat4');
  69345. goog.require('goog.webgl');
  69346. goog.require('ol.Coordinate');
  69347. goog.require('ol.Extent');
  69348. goog.require('ol.ImageBase');
  69349. goog.require('ol.ViewHint');
  69350. goog.require('ol.dom');
  69351. goog.require('ol.extent');
  69352. goog.require('ol.layer.Image');
  69353. goog.require('ol.proj');
  69354. goog.require('ol.renderer.webgl.Layer');
  69355. goog.require('ol.source.ImageVector');
  69356. goog.require('ol.vec.Mat4');
  69357. goog.require('ol.webgl.Context');
  69358. /**
  69359. * @constructor
  69360. * @extends {ol.renderer.webgl.Layer}
  69361. * @param {ol.renderer.webgl.Map} mapRenderer Map renderer.
  69362. * @param {ol.layer.Image} imageLayer Tile layer.
  69363. */
  69364. ol.renderer.webgl.ImageLayer = function(mapRenderer, imageLayer) {
  69365. goog.base(this, mapRenderer, imageLayer);
  69366. /**
  69367. * The last rendered image.
  69368. * @private
  69369. * @type {?ol.ImageBase}
  69370. */
  69371. this.image_ = null;
  69372. /**
  69373. * @private
  69374. * @type {CanvasRenderingContext2D}
  69375. */
  69376. this.hitCanvasContext_ = null;
  69377. /**
  69378. * @private
  69379. * @type {?goog.vec.Mat4.Number}
  69380. */
  69381. this.hitTransformationMatrix_ = null;
  69382. };
  69383. goog.inherits(ol.renderer.webgl.ImageLayer, ol.renderer.webgl.Layer);
  69384. /**
  69385. * @param {ol.ImageBase} image Image.
  69386. * @private
  69387. * @return {WebGLTexture} Texture.
  69388. */
  69389. ol.renderer.webgl.ImageLayer.prototype.createTexture_ = function(image) {
  69390. // We meet the conditions to work with non-power of two textures.
  69391. // http://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences#Non-Power_of_Two_Texture_Support
  69392. // http://learningwebgl.com/blog/?p=2101
  69393. var imageElement = image.getImage();
  69394. var gl = this.mapRenderer.getGL();
  69395. return ol.webgl.Context.createTexture(
  69396. gl, imageElement, goog.webgl.CLAMP_TO_EDGE, goog.webgl.CLAMP_TO_EDGE);
  69397. };
  69398. /**
  69399. * @inheritDoc
  69400. */
  69401. ol.renderer.webgl.ImageLayer.prototype.forEachFeatureAtCoordinate =
  69402. function(coordinate, frameState, callback, thisArg) {
  69403. var layer = this.getLayer();
  69404. var source = layer.getSource();
  69405. var resolution = frameState.viewState.resolution;
  69406. var rotation = frameState.viewState.rotation;
  69407. var skippedFeatureUids = frameState.skippedFeatureUids;
  69408. return source.forEachFeatureAtCoordinate(
  69409. coordinate, resolution, rotation, skippedFeatureUids,
  69410. /**
  69411. * @param {ol.Feature} feature Feature.
  69412. * @return {?} Callback result.
  69413. */
  69414. function(feature) {
  69415. return callback.call(thisArg, feature, layer);
  69416. });
  69417. };
  69418. /**
  69419. * @inheritDoc
  69420. */
  69421. ol.renderer.webgl.ImageLayer.prototype.prepareFrame =
  69422. function(frameState, layerState, context) {
  69423. var gl = this.mapRenderer.getGL();
  69424. var pixelRatio = frameState.pixelRatio;
  69425. var viewState = frameState.viewState;
  69426. var viewCenter = viewState.center;
  69427. var viewResolution = viewState.resolution;
  69428. var viewRotation = viewState.rotation;
  69429. var image = this.image_;
  69430. var texture = this.texture;
  69431. var imageLayer = this.getLayer();
  69432. goog.asserts.assertInstanceof(imageLayer, ol.layer.Image,
  69433. 'layer is an instance of ol.layer.Image');
  69434. var imageSource = imageLayer.getSource();
  69435. var hints = frameState.viewHints;
  69436. var renderedExtent = frameState.extent;
  69437. if (layerState.extent !== undefined) {
  69438. renderedExtent = ol.extent.getIntersection(
  69439. renderedExtent, layerState.extent);
  69440. }
  69441. if (!hints[ol.ViewHint.ANIMATING] && !hints[ol.ViewHint.INTERACTING] &&
  69442. !ol.extent.isEmpty(renderedExtent)) {
  69443. var projection = viewState.projection;
  69444. var sourceProjection = imageSource.getProjection();
  69445. if (sourceProjection) {
  69446. goog.asserts.assert(ol.proj.equivalent(projection, sourceProjection),
  69447. 'projection and sourceProjection are equivalent');
  69448. projection = sourceProjection;
  69449. }
  69450. var image_ = imageSource.getImage(renderedExtent, viewResolution,
  69451. pixelRatio, projection);
  69452. if (image_) {
  69453. var loaded = this.loadImage(image_);
  69454. if (loaded) {
  69455. image = image_;
  69456. texture = this.createTexture_(image_);
  69457. if (this.texture) {
  69458. frameState.postRenderFunctions.push(
  69459. goog.partial(
  69460. /**
  69461. * @param {WebGLRenderingContext} gl GL.
  69462. * @param {WebGLTexture} texture Texture.
  69463. */
  69464. function(gl, texture) {
  69465. if (!gl.isContextLost()) {
  69466. gl.deleteTexture(texture);
  69467. }
  69468. }, gl, this.texture));
  69469. }
  69470. }
  69471. }
  69472. }
  69473. if (image) {
  69474. goog.asserts.assert(texture, 'texture is truthy');
  69475. var canvas = this.mapRenderer.getContext().getCanvas();
  69476. this.updateProjectionMatrix_(canvas.width, canvas.height,
  69477. pixelRatio, viewCenter, viewResolution, viewRotation,
  69478. image.getExtent());
  69479. this.hitTransformationMatrix_ = null;
  69480. // Translate and scale to flip the Y coord.
  69481. var texCoordMatrix = this.texCoordMatrix;
  69482. goog.vec.Mat4.makeIdentity(texCoordMatrix);
  69483. goog.vec.Mat4.scale(texCoordMatrix, 1, -1, 1);
  69484. goog.vec.Mat4.translate(texCoordMatrix, 0, -1, 0);
  69485. this.image_ = image;
  69486. this.texture = texture;
  69487. this.updateAttributions(frameState.attributions, image.getAttributions());
  69488. this.updateLogos(frameState, imageSource);
  69489. }
  69490. return true;
  69491. };
  69492. /**
  69493. * @param {number} canvasWidth Canvas width.
  69494. * @param {number} canvasHeight Canvas height.
  69495. * @param {number} pixelRatio Pixel ratio.
  69496. * @param {ol.Coordinate} viewCenter View center.
  69497. * @param {number} viewResolution View resolution.
  69498. * @param {number} viewRotation View rotation.
  69499. * @param {ol.Extent} imageExtent Image extent.
  69500. * @private
  69501. */
  69502. ol.renderer.webgl.ImageLayer.prototype.updateProjectionMatrix_ =
  69503. function(canvasWidth, canvasHeight, pixelRatio,
  69504. viewCenter, viewResolution, viewRotation, imageExtent) {
  69505. var canvasExtentWidth = canvasWidth * viewResolution;
  69506. var canvasExtentHeight = canvasHeight * viewResolution;
  69507. var projectionMatrix = this.projectionMatrix;
  69508. goog.vec.Mat4.makeIdentity(projectionMatrix);
  69509. goog.vec.Mat4.scale(projectionMatrix,
  69510. pixelRatio * 2 / canvasExtentWidth,
  69511. pixelRatio * 2 / canvasExtentHeight, 1);
  69512. goog.vec.Mat4.rotateZ(projectionMatrix, -viewRotation);
  69513. goog.vec.Mat4.translate(projectionMatrix,
  69514. imageExtent[0] - viewCenter[0],
  69515. imageExtent[1] - viewCenter[1],
  69516. 0);
  69517. goog.vec.Mat4.scale(projectionMatrix,
  69518. (imageExtent[2] - imageExtent[0]) / 2,
  69519. (imageExtent[3] - imageExtent[1]) / 2,
  69520. 1);
  69521. goog.vec.Mat4.translate(projectionMatrix, 1, 1, 0);
  69522. };
  69523. /**
  69524. * @inheritDoc
  69525. */
  69526. ol.renderer.webgl.ImageLayer.prototype.hasFeatureAtCoordinate =
  69527. function(coordinate, frameState) {
  69528. var hasFeature = this.forEachFeatureAtCoordinate(
  69529. coordinate, frameState, goog.functions.TRUE, this);
  69530. return hasFeature !== undefined;
  69531. };
  69532. /**
  69533. * @inheritDoc
  69534. */
  69535. ol.renderer.webgl.ImageLayer.prototype.forEachLayerAtPixel =
  69536. function(pixel, frameState, callback, thisArg) {
  69537. if (!this.image_ || !this.image_.getImage()) {
  69538. return undefined;
  69539. }
  69540. if (this.getLayer().getSource() instanceof ol.source.ImageVector) {
  69541. // for ImageVector sources use the original hit-detection logic,
  69542. // so that for example also transparent polygons are detected
  69543. var coordinate = pixel.slice();
  69544. ol.vec.Mat4.multVec2(
  69545. frameState.pixelToCoordinateMatrix, coordinate, coordinate);
  69546. var hasFeature = this.forEachFeatureAtCoordinate(
  69547. coordinate, frameState, goog.functions.TRUE, this);
  69548. if (hasFeature) {
  69549. return callback.call(thisArg, this.getLayer());
  69550. } else {
  69551. return undefined;
  69552. }
  69553. } else {
  69554. var imageSize =
  69555. [this.image_.getImage().width, this.image_.getImage().height];
  69556. if (!this.hitTransformationMatrix_) {
  69557. this.hitTransformationMatrix_ = this.getHitTransformationMatrix_(
  69558. frameState.size, imageSize);
  69559. }
  69560. var pixelOnFrameBuffer = [0, 0];
  69561. ol.vec.Mat4.multVec2(
  69562. this.hitTransformationMatrix_, pixel, pixelOnFrameBuffer);
  69563. if (pixelOnFrameBuffer[0] < 0 || pixelOnFrameBuffer[0] > imageSize[0] ||
  69564. pixelOnFrameBuffer[1] < 0 || pixelOnFrameBuffer[1] > imageSize[1]) {
  69565. // outside the image, no need to check
  69566. return undefined;
  69567. }
  69568. if (!this.hitCanvasContext_) {
  69569. this.hitCanvasContext_ = ol.dom.createCanvasContext2D(1, 1);
  69570. }
  69571. this.hitCanvasContext_.clearRect(0, 0, 1, 1);
  69572. this.hitCanvasContext_.drawImage(this.image_.getImage(),
  69573. pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1, 0, 0, 1, 1);
  69574. var imageData = this.hitCanvasContext_.getImageData(0, 0, 1, 1).data;
  69575. if (imageData[3] > 0) {
  69576. return callback.call(thisArg, this.getLayer());
  69577. } else {
  69578. return undefined;
  69579. }
  69580. }
  69581. };
  69582. /**
  69583. * The transformation matrix to get the pixel on the image for a
  69584. * pixel on the map.
  69585. * @param {ol.Size} mapSize
  69586. * @param {ol.Size} imageSize
  69587. * @return {goog.vec.Mat4.Number}
  69588. * @private
  69589. */
  69590. ol.renderer.webgl.ImageLayer.prototype.getHitTransformationMatrix_ =
  69591. function(mapSize, imageSize) {
  69592. // the first matrix takes a map pixel, flips the y-axis and scales to
  69593. // a range between -1 ... 1
  69594. var mapCoordMatrix = goog.vec.Mat4.createNumber();
  69595. goog.vec.Mat4.makeIdentity(mapCoordMatrix);
  69596. goog.vec.Mat4.translate(mapCoordMatrix, -1, -1, 0);
  69597. goog.vec.Mat4.scale(mapCoordMatrix, 2 / mapSize[0], 2 / mapSize[1], 1);
  69598. goog.vec.Mat4.translate(mapCoordMatrix, 0, mapSize[1], 0);
  69599. goog.vec.Mat4.scale(mapCoordMatrix, 1, -1, 1);
  69600. // the second matrix is the inverse of the projection matrix used in the
  69601. // shader for drawing
  69602. var projectionMatrixInv = goog.vec.Mat4.createNumber();
  69603. goog.vec.Mat4.invert(this.projectionMatrix, projectionMatrixInv);
  69604. // the third matrix scales to the image dimensions and flips the y-axis again
  69605. var imageCoordMatrix = goog.vec.Mat4.createNumber();
  69606. goog.vec.Mat4.makeIdentity(imageCoordMatrix);
  69607. goog.vec.Mat4.translate(imageCoordMatrix, 0, imageSize[1], 0);
  69608. goog.vec.Mat4.scale(imageCoordMatrix, 1, -1, 1);
  69609. goog.vec.Mat4.scale(imageCoordMatrix, imageSize[0] / 2, imageSize[1] / 2, 1);
  69610. goog.vec.Mat4.translate(imageCoordMatrix, 1, 1, 0);
  69611. var transformMatrix = goog.vec.Mat4.createNumber();
  69612. goog.vec.Mat4.multMat(
  69613. imageCoordMatrix, projectionMatrixInv, transformMatrix);
  69614. goog.vec.Mat4.multMat(
  69615. transformMatrix, mapCoordMatrix, transformMatrix);
  69616. return transformMatrix;
  69617. };
  69618. // This file is automatically generated, do not edit
  69619. goog.provide('ol.renderer.webgl.tilelayer.shader');
  69620. goog.provide('ol.renderer.webgl.tilelayer.shader.Locations');
  69621. goog.provide('ol.renderer.webgl.tilelayer.shader.Fragment');
  69622. goog.provide('ol.renderer.webgl.tilelayer.shader.Vertex');
  69623. goog.require('ol.webgl.shader');
  69624. /**
  69625. * @constructor
  69626. * @extends {ol.webgl.shader.Fragment}
  69627. * @struct
  69628. */
  69629. ol.renderer.webgl.tilelayer.shader.Fragment = function() {
  69630. goog.base(this, ol.renderer.webgl.tilelayer.shader.Fragment.SOURCE);
  69631. };
  69632. goog.inherits(ol.renderer.webgl.tilelayer.shader.Fragment, ol.webgl.shader.Fragment);
  69633. goog.addSingletonGetter(ol.renderer.webgl.tilelayer.shader.Fragment);
  69634. /**
  69635. * @const
  69636. * @type {string}
  69637. */
  69638. ol.renderer.webgl.tilelayer.shader.Fragment.DEBUG_SOURCE = 'precision mediump float;\nvarying vec2 v_texCoord;\n\n\nuniform sampler2D u_texture;\n\nvoid main(void) {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n}\n';
  69639. /**
  69640. * @const
  69641. * @type {string}
  69642. */
  69643. ol.renderer.webgl.tilelayer.shader.Fragment.OPTIMIZED_SOURCE = 'precision mediump float;varying vec2 a;uniform sampler2D e;void main(void){gl_FragColor=texture2D(e,a);}';
  69644. /**
  69645. * @const
  69646. * @type {string}
  69647. */
  69648. ol.renderer.webgl.tilelayer.shader.Fragment.SOURCE = goog.DEBUG ?
  69649. ol.renderer.webgl.tilelayer.shader.Fragment.DEBUG_SOURCE :
  69650. ol.renderer.webgl.tilelayer.shader.Fragment.OPTIMIZED_SOURCE;
  69651. /**
  69652. * @constructor
  69653. * @extends {ol.webgl.shader.Vertex}
  69654. * @struct
  69655. */
  69656. ol.renderer.webgl.tilelayer.shader.Vertex = function() {
  69657. goog.base(this, ol.renderer.webgl.tilelayer.shader.Vertex.SOURCE);
  69658. };
  69659. goog.inherits(ol.renderer.webgl.tilelayer.shader.Vertex, ol.webgl.shader.Vertex);
  69660. goog.addSingletonGetter(ol.renderer.webgl.tilelayer.shader.Vertex);
  69661. /**
  69662. * @const
  69663. * @type {string}
  69664. */
  69665. ol.renderer.webgl.tilelayer.shader.Vertex.DEBUG_SOURCE = 'varying vec2 v_texCoord;\n\n\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nuniform vec4 u_tileOffset;\n\nvoid main(void) {\n gl_Position = vec4(a_position * u_tileOffset.xy + u_tileOffset.zw, 0., 1.);\n v_texCoord = a_texCoord;\n}\n\n\n';
  69666. /**
  69667. * @const
  69668. * @type {string}
  69669. */
  69670. ol.renderer.webgl.tilelayer.shader.Vertex.OPTIMIZED_SOURCE = 'varying vec2 a;attribute vec2 b;attribute vec2 c;uniform vec4 d;void main(void){gl_Position=vec4(b*d.xy+d.zw,0.,1.);a=c;}';
  69671. /**
  69672. * @const
  69673. * @type {string}
  69674. */
  69675. ol.renderer.webgl.tilelayer.shader.Vertex.SOURCE = goog.DEBUG ?
  69676. ol.renderer.webgl.tilelayer.shader.Vertex.DEBUG_SOURCE :
  69677. ol.renderer.webgl.tilelayer.shader.Vertex.OPTIMIZED_SOURCE;
  69678. /**
  69679. * @constructor
  69680. * @param {WebGLRenderingContext} gl GL.
  69681. * @param {WebGLProgram} program Program.
  69682. * @struct
  69683. */
  69684. ol.renderer.webgl.tilelayer.shader.Locations = function(gl, program) {
  69685. /**
  69686. * @type {WebGLUniformLocation}
  69687. */
  69688. this.u_texture = gl.getUniformLocation(
  69689. program, goog.DEBUG ? 'u_texture' : 'e');
  69690. /**
  69691. * @type {WebGLUniformLocation}
  69692. */
  69693. this.u_tileOffset = gl.getUniformLocation(
  69694. program, goog.DEBUG ? 'u_tileOffset' : 'd');
  69695. /**
  69696. * @type {number}
  69697. */
  69698. this.a_position = gl.getAttribLocation(
  69699. program, goog.DEBUG ? 'a_position' : 'b');
  69700. /**
  69701. * @type {number}
  69702. */
  69703. this.a_texCoord = gl.getAttribLocation(
  69704. program, goog.DEBUG ? 'a_texCoord' : 'c');
  69705. };
  69706. // FIXME large resolutions lead to too large framebuffers :-(
  69707. // FIXME animated shaders! check in redraw
  69708. goog.provide('ol.renderer.webgl.TileLayer');
  69709. goog.require('goog.array');
  69710. goog.require('goog.asserts');
  69711. goog.require('goog.vec.Mat4');
  69712. goog.require('goog.vec.Vec4');
  69713. goog.require('goog.webgl');
  69714. goog.require('ol.TileRange');
  69715. goog.require('ol.TileState');
  69716. goog.require('ol.extent');
  69717. goog.require('ol.layer.Tile');
  69718. goog.require('ol.math');
  69719. goog.require('ol.renderer.webgl.Layer');
  69720. goog.require('ol.renderer.webgl.tilelayer.shader.Fragment');
  69721. goog.require('ol.renderer.webgl.tilelayer.shader.Locations');
  69722. goog.require('ol.renderer.webgl.tilelayer.shader.Vertex');
  69723. goog.require('ol.size');
  69724. goog.require('ol.tilecoord');
  69725. goog.require('ol.vec.Mat4');
  69726. goog.require('ol.webgl.Buffer');
  69727. /**
  69728. * @constructor
  69729. * @extends {ol.renderer.webgl.Layer}
  69730. * @param {ol.renderer.webgl.Map} mapRenderer Map renderer.
  69731. * @param {ol.layer.Tile} tileLayer Tile layer.
  69732. */
  69733. ol.renderer.webgl.TileLayer = function(mapRenderer, tileLayer) {
  69734. goog.base(this, mapRenderer, tileLayer);
  69735. /**
  69736. * @private
  69737. * @type {ol.webgl.shader.Fragment}
  69738. */
  69739. this.fragmentShader_ =
  69740. ol.renderer.webgl.tilelayer.shader.Fragment.getInstance();
  69741. /**
  69742. * @private
  69743. * @type {ol.webgl.shader.Vertex}
  69744. */
  69745. this.vertexShader_ = ol.renderer.webgl.tilelayer.shader.Vertex.getInstance();
  69746. /**
  69747. * @private
  69748. * @type {ol.renderer.webgl.tilelayer.shader.Locations}
  69749. */
  69750. this.locations_ = null;
  69751. /**
  69752. * @private
  69753. * @type {ol.webgl.Buffer}
  69754. */
  69755. this.renderArrayBuffer_ = new ol.webgl.Buffer([
  69756. 0, 0, 0, 1,
  69757. 1, 0, 1, 1,
  69758. 0, 1, 0, 0,
  69759. 1, 1, 1, 0
  69760. ]);
  69761. /**
  69762. * @private
  69763. * @type {ol.TileRange}
  69764. */
  69765. this.renderedTileRange_ = null;
  69766. /**
  69767. * @private
  69768. * @type {ol.Extent}
  69769. */
  69770. this.renderedFramebufferExtent_ = null;
  69771. /**
  69772. * @private
  69773. * @type {number}
  69774. */
  69775. this.renderedRevision_ = -1;
  69776. /**
  69777. * @private
  69778. * @type {ol.Size}
  69779. */
  69780. this.tmpSize_ = [0, 0];
  69781. };
  69782. goog.inherits(ol.renderer.webgl.TileLayer, ol.renderer.webgl.Layer);
  69783. /**
  69784. * @inheritDoc
  69785. */
  69786. ol.renderer.webgl.TileLayer.prototype.disposeInternal = function() {
  69787. var context = this.mapRenderer.getContext();
  69788. context.deleteBuffer(this.renderArrayBuffer_);
  69789. goog.base(this, 'disposeInternal');
  69790. };
  69791. /**
  69792. * Create a function that adds loaded tiles to the tile lookup.
  69793. * @param {ol.source.Tile} source Tile source.
  69794. * @param {Object.<number, Object.<string, ol.Tile>>} tiles Lookup of loaded
  69795. * tiles by zoom level.
  69796. * @return {function(number, ol.TileRange):boolean} A function that can be
  69797. * called with a zoom level and a tile range to add loaded tiles to the
  69798. * lookup.
  69799. * @protected
  69800. */
  69801. ol.renderer.webgl.TileLayer.prototype.createLoadedTileFinder =
  69802. function(source, tiles) {
  69803. var mapRenderer = this.mapRenderer;
  69804. return (
  69805. /**
  69806. * @param {number} zoom Zoom level.
  69807. * @param {ol.TileRange} tileRange Tile range.
  69808. * @return {boolean} The tile range is fully loaded.
  69809. */
  69810. function(zoom, tileRange) {
  69811. return source.forEachLoadedTile(zoom, tileRange, function(tile) {
  69812. var loaded = mapRenderer.isTileTextureLoaded(tile);
  69813. if (loaded) {
  69814. if (!tiles[zoom]) {
  69815. tiles[zoom] = {};
  69816. }
  69817. tiles[zoom][tile.tileCoord.toString()] = tile;
  69818. }
  69819. return loaded;
  69820. });
  69821. });
  69822. };
  69823. /**
  69824. * @inheritDoc
  69825. */
  69826. ol.renderer.webgl.TileLayer.prototype.handleWebGLContextLost = function() {
  69827. goog.base(this, 'handleWebGLContextLost');
  69828. this.locations_ = null;
  69829. };
  69830. /**
  69831. * @inheritDoc
  69832. */
  69833. ol.renderer.webgl.TileLayer.prototype.prepareFrame =
  69834. function(frameState, layerState, context) {
  69835. var mapRenderer = this.mapRenderer;
  69836. var gl = context.getGL();
  69837. var viewState = frameState.viewState;
  69838. var projection = viewState.projection;
  69839. var tileLayer = this.getLayer();
  69840. goog.asserts.assertInstanceof(tileLayer, ol.layer.Tile,
  69841. 'layer is an instance of ol.layer.Tile');
  69842. var tileSource = tileLayer.getSource();
  69843. var tileGrid = tileSource.getTileGridForProjection(projection);
  69844. var z = tileGrid.getZForResolution(viewState.resolution);
  69845. var tileResolution = tileGrid.getResolution(z);
  69846. var tilePixelSize =
  69847. tileSource.getTilePixelSize(z, frameState.pixelRatio, projection);
  69848. var pixelRatio = tilePixelSize[0] /
  69849. ol.size.toSize(tileGrid.getTileSize(z), this.tmpSize_)[0];
  69850. var tilePixelResolution = tileResolution / pixelRatio;
  69851. var tileGutter = tileSource.getGutter();
  69852. var center = viewState.center;
  69853. var extent;
  69854. if (tileResolution == viewState.resolution) {
  69855. center = this.snapCenterToPixel(center, tileResolution, frameState.size);
  69856. extent = ol.extent.getForViewAndSize(
  69857. center, tileResolution, viewState.rotation, frameState.size);
  69858. } else {
  69859. extent = frameState.extent;
  69860. }
  69861. var tileRange = tileGrid.getTileRangeForExtentAndResolution(
  69862. extent, tileResolution);
  69863. var framebufferExtent;
  69864. if (this.renderedTileRange_ &&
  69865. this.renderedTileRange_.equals(tileRange) &&
  69866. this.renderedRevision_ == tileSource.getRevision()) {
  69867. framebufferExtent = this.renderedFramebufferExtent_;
  69868. } else {
  69869. var tileRangeSize = tileRange.getSize();
  69870. var maxDimension = Math.max(
  69871. tileRangeSize[0] * tilePixelSize[0],
  69872. tileRangeSize[1] * tilePixelSize[1]);
  69873. var framebufferDimension = ol.math.roundUpToPowerOfTwo(maxDimension);
  69874. var framebufferExtentDimension = tilePixelResolution * framebufferDimension;
  69875. var origin = tileGrid.getOrigin(z);
  69876. var minX = origin[0] +
  69877. tileRange.minX * tilePixelSize[0] * tilePixelResolution;
  69878. var minY = origin[1] +
  69879. tileRange.minY * tilePixelSize[1] * tilePixelResolution;
  69880. framebufferExtent = [
  69881. minX, minY,
  69882. minX + framebufferExtentDimension, minY + framebufferExtentDimension
  69883. ];
  69884. this.bindFramebuffer(frameState, framebufferDimension);
  69885. gl.viewport(0, 0, framebufferDimension, framebufferDimension);
  69886. gl.clearColor(0, 0, 0, 0);
  69887. gl.clear(goog.webgl.COLOR_BUFFER_BIT);
  69888. gl.disable(goog.webgl.BLEND);
  69889. var program = context.getProgram(this.fragmentShader_, this.vertexShader_);
  69890. context.useProgram(program);
  69891. if (!this.locations_) {
  69892. this.locations_ =
  69893. new ol.renderer.webgl.tilelayer.shader.Locations(gl, program);
  69894. }
  69895. context.bindBuffer(goog.webgl.ARRAY_BUFFER, this.renderArrayBuffer_);
  69896. gl.enableVertexAttribArray(this.locations_.a_position);
  69897. gl.vertexAttribPointer(
  69898. this.locations_.a_position, 2, goog.webgl.FLOAT, false, 16, 0);
  69899. gl.enableVertexAttribArray(this.locations_.a_texCoord);
  69900. gl.vertexAttribPointer(
  69901. this.locations_.a_texCoord, 2, goog.webgl.FLOAT, false, 16, 8);
  69902. gl.uniform1i(this.locations_.u_texture, 0);
  69903. /**
  69904. * @type {Object.<number, Object.<string, ol.Tile>>}
  69905. */
  69906. var tilesToDrawByZ = {};
  69907. tilesToDrawByZ[z] = {};
  69908. var findLoadedTiles = this.createLoadedTileFinder(
  69909. tileSource, tilesToDrawByZ);
  69910. var useInterimTilesOnError = tileLayer.getUseInterimTilesOnError();
  69911. var allTilesLoaded = true;
  69912. var tmpExtent = ol.extent.createEmpty();
  69913. var tmpTileRange = new ol.TileRange(0, 0, 0, 0);
  69914. var childTileRange, fullyLoaded, tile, tileState, x, y, tileExtent;
  69915. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  69916. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  69917. tile = tileSource.getTile(z, x, y, pixelRatio, projection);
  69918. if (layerState.extent !== undefined) {
  69919. // ignore tiles outside layer extent
  69920. tileExtent = tileGrid.getTileCoordExtent(tile.tileCoord, tmpExtent);
  69921. if (!ol.extent.intersects(tileExtent, layerState.extent)) {
  69922. continue;
  69923. }
  69924. }
  69925. tileState = tile.getState();
  69926. if (tileState == ol.TileState.LOADED) {
  69927. if (mapRenderer.isTileTextureLoaded(tile)) {
  69928. tilesToDrawByZ[z][ol.tilecoord.toString(tile.tileCoord)] = tile;
  69929. continue;
  69930. }
  69931. } else if (tileState == ol.TileState.EMPTY ||
  69932. (tileState == ol.TileState.ERROR &&
  69933. !useInterimTilesOnError)) {
  69934. continue;
  69935. }
  69936. allTilesLoaded = false;
  69937. fullyLoaded = tileGrid.forEachTileCoordParentTileRange(
  69938. tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent);
  69939. if (!fullyLoaded) {
  69940. childTileRange = tileGrid.getTileCoordChildTileRange(
  69941. tile.tileCoord, tmpTileRange, tmpExtent);
  69942. if (childTileRange) {
  69943. findLoadedTiles(z + 1, childTileRange);
  69944. }
  69945. }
  69946. }
  69947. }
  69948. /** @type {Array.<number>} */
  69949. var zs = Object.keys(tilesToDrawByZ).map(Number);
  69950. goog.array.sort(zs);
  69951. var u_tileOffset = goog.vec.Vec4.createFloat32();
  69952. var i, ii, sx, sy, tileKey, tilesToDraw, tx, ty;
  69953. for (i = 0, ii = zs.length; i < ii; ++i) {
  69954. tilesToDraw = tilesToDrawByZ[zs[i]];
  69955. for (tileKey in tilesToDraw) {
  69956. tile = tilesToDraw[tileKey];
  69957. tileExtent = tileGrid.getTileCoordExtent(tile.tileCoord, tmpExtent);
  69958. sx = 2 * (tileExtent[2] - tileExtent[0]) /
  69959. framebufferExtentDimension;
  69960. sy = 2 * (tileExtent[3] - tileExtent[1]) /
  69961. framebufferExtentDimension;
  69962. tx = 2 * (tileExtent[0] - framebufferExtent[0]) /
  69963. framebufferExtentDimension - 1;
  69964. ty = 2 * (tileExtent[1] - framebufferExtent[1]) /
  69965. framebufferExtentDimension - 1;
  69966. goog.vec.Vec4.setFromValues(u_tileOffset, sx, sy, tx, ty);
  69967. gl.uniform4fv(this.locations_.u_tileOffset, u_tileOffset);
  69968. mapRenderer.bindTileTexture(tile, tilePixelSize,
  69969. tileGutter * pixelRatio, goog.webgl.LINEAR, goog.webgl.LINEAR);
  69970. gl.drawArrays(goog.webgl.TRIANGLE_STRIP, 0, 4);
  69971. }
  69972. }
  69973. if (allTilesLoaded) {
  69974. this.renderedTileRange_ = tileRange;
  69975. this.renderedFramebufferExtent_ = framebufferExtent;
  69976. this.renderedRevision_ = tileSource.getRevision();
  69977. } else {
  69978. this.renderedTileRange_ = null;
  69979. this.renderedFramebufferExtent_ = null;
  69980. this.renderedRevision_ = -1;
  69981. frameState.animate = true;
  69982. }
  69983. }
  69984. this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange);
  69985. var tileTextureQueue = mapRenderer.getTileTextureQueue();
  69986. this.manageTilePyramid(
  69987. frameState, tileSource, tileGrid, pixelRatio, projection, extent, z,
  69988. tileLayer.getPreload(),
  69989. /**
  69990. * @param {ol.Tile} tile Tile.
  69991. */
  69992. function(tile) {
  69993. if (tile.getState() == ol.TileState.LOADED &&
  69994. !mapRenderer.isTileTextureLoaded(tile) &&
  69995. !tileTextureQueue.isKeyQueued(tile.getKey())) {
  69996. tileTextureQueue.enqueue([
  69997. tile,
  69998. tileGrid.getTileCoordCenter(tile.tileCoord),
  69999. tileGrid.getResolution(tile.tileCoord[0]),
  70000. tilePixelSize, tileGutter * pixelRatio
  70001. ]);
  70002. }
  70003. }, this);
  70004. this.scheduleExpireCache(frameState, tileSource);
  70005. this.updateLogos(frameState, tileSource);
  70006. var texCoordMatrix = this.texCoordMatrix;
  70007. goog.vec.Mat4.makeIdentity(texCoordMatrix);
  70008. goog.vec.Mat4.translate(texCoordMatrix,
  70009. (center[0] - framebufferExtent[0]) /
  70010. (framebufferExtent[2] - framebufferExtent[0]),
  70011. (center[1] - framebufferExtent[1]) /
  70012. (framebufferExtent[3] - framebufferExtent[1]),
  70013. 0);
  70014. if (viewState.rotation !== 0) {
  70015. goog.vec.Mat4.rotateZ(texCoordMatrix, viewState.rotation);
  70016. }
  70017. goog.vec.Mat4.scale(texCoordMatrix,
  70018. frameState.size[0] * viewState.resolution /
  70019. (framebufferExtent[2] - framebufferExtent[0]),
  70020. frameState.size[1] * viewState.resolution /
  70021. (framebufferExtent[3] - framebufferExtent[1]),
  70022. 1);
  70023. goog.vec.Mat4.translate(texCoordMatrix,
  70024. -0.5,
  70025. -0.5,
  70026. 0);
  70027. return true;
  70028. };
  70029. /**
  70030. * @inheritDoc
  70031. */
  70032. ol.renderer.webgl.TileLayer.prototype.forEachLayerAtPixel =
  70033. function(pixel, frameState, callback, thisArg) {
  70034. if (!this.framebuffer) {
  70035. return undefined;
  70036. }
  70037. var pixelOnMapScaled = [
  70038. pixel[0] / frameState.size[0],
  70039. (frameState.size[1] - pixel[1]) / frameState.size[1]];
  70040. var pixelOnFrameBufferScaled = [0, 0];
  70041. ol.vec.Mat4.multVec2(
  70042. this.texCoordMatrix, pixelOnMapScaled, pixelOnFrameBufferScaled);
  70043. var pixelOnFrameBuffer = [
  70044. pixelOnFrameBufferScaled[0] * this.framebufferDimension,
  70045. pixelOnFrameBufferScaled[1] * this.framebufferDimension];
  70046. var gl = this.mapRenderer.getContext().getGL();
  70047. gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  70048. var imageData = new Uint8Array(4);
  70049. gl.readPixels(pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1,
  70050. gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70051. if (imageData[3] > 0) {
  70052. return callback.call(thisArg, this.getLayer());
  70053. } else {
  70054. return undefined;
  70055. }
  70056. };
  70057. goog.provide('ol.renderer.webgl.VectorLayer');
  70058. goog.require('goog.array');
  70059. goog.require('goog.asserts');
  70060. goog.require('goog.events');
  70061. goog.require('ol.ViewHint');
  70062. goog.require('ol.extent');
  70063. goog.require('ol.layer.Vector');
  70064. goog.require('ol.render.webgl.ReplayGroup');
  70065. goog.require('ol.renderer.vector');
  70066. goog.require('ol.renderer.webgl.Layer');
  70067. goog.require('ol.vec.Mat4');
  70068. /**
  70069. * @constructor
  70070. * @extends {ol.renderer.webgl.Layer}
  70071. * @param {ol.renderer.webgl.Map} mapRenderer Map renderer.
  70072. * @param {ol.layer.Vector} vectorLayer Vector layer.
  70073. */
  70074. ol.renderer.webgl.VectorLayer = function(mapRenderer, vectorLayer) {
  70075. goog.base(this, mapRenderer, vectorLayer);
  70076. /**
  70077. * @private
  70078. * @type {boolean}
  70079. */
  70080. this.dirty_ = false;
  70081. /**
  70082. * @private
  70083. * @type {number}
  70084. */
  70085. this.renderedRevision_ = -1;
  70086. /**
  70087. * @private
  70088. * @type {number}
  70089. */
  70090. this.renderedResolution_ = NaN;
  70091. /**
  70092. * @private
  70093. * @type {ol.Extent}
  70094. */
  70095. this.renderedExtent_ = ol.extent.createEmpty();
  70096. /**
  70097. * @private
  70098. * @type {function(ol.Feature, ol.Feature): number|null}
  70099. */
  70100. this.renderedRenderOrder_ = null;
  70101. /**
  70102. * @private
  70103. * @type {ol.render.webgl.ReplayGroup}
  70104. */
  70105. this.replayGroup_ = null;
  70106. /**
  70107. * The last layer state.
  70108. * @private
  70109. * @type {?ol.layer.LayerState}
  70110. */
  70111. this.layerState_ = null;
  70112. };
  70113. goog.inherits(ol.renderer.webgl.VectorLayer, ol.renderer.webgl.Layer);
  70114. /**
  70115. * @inheritDoc
  70116. */
  70117. ol.renderer.webgl.VectorLayer.prototype.composeFrame =
  70118. function(frameState, layerState, context) {
  70119. this.layerState_ = layerState;
  70120. var viewState = frameState.viewState;
  70121. var replayGroup = this.replayGroup_;
  70122. if (replayGroup && !replayGroup.isEmpty()) {
  70123. replayGroup.replay(context,
  70124. viewState.center, viewState.resolution, viewState.rotation,
  70125. frameState.size, frameState.pixelRatio, layerState.opacity,
  70126. layerState.managed ? frameState.skippedFeatureUids : {});
  70127. }
  70128. };
  70129. /**
  70130. * @inheritDoc
  70131. */
  70132. ol.renderer.webgl.VectorLayer.prototype.disposeInternal = function() {
  70133. var replayGroup = this.replayGroup_;
  70134. if (replayGroup) {
  70135. var context = this.mapRenderer.getContext();
  70136. replayGroup.getDeleteResourcesFunction(context)();
  70137. this.replayGroup_ = null;
  70138. }
  70139. goog.base(this, 'disposeInternal');
  70140. };
  70141. /**
  70142. * @inheritDoc
  70143. */
  70144. ol.renderer.webgl.VectorLayer.prototype.forEachFeatureAtCoordinate =
  70145. function(coordinate, frameState, callback, thisArg) {
  70146. if (!this.replayGroup_ || !this.layerState_) {
  70147. return undefined;
  70148. } else {
  70149. var context = this.mapRenderer.getContext();
  70150. var viewState = frameState.viewState;
  70151. var layer = this.getLayer();
  70152. var layerState = this.layerState_;
  70153. /** @type {Object.<string, boolean>} */
  70154. var features = {};
  70155. return this.replayGroup_.forEachFeatureAtCoordinate(coordinate,
  70156. context, viewState.center, viewState.resolution, viewState.rotation,
  70157. frameState.size, frameState.pixelRatio, layerState.opacity,
  70158. layerState.managed ? frameState.skippedFeatureUids : {},
  70159. /**
  70160. * @param {ol.Feature} feature Feature.
  70161. * @return {?} Callback result.
  70162. */
  70163. function(feature) {
  70164. goog.asserts.assert(feature !== undefined, 'received a feature');
  70165. var key = goog.getUid(feature).toString();
  70166. if (!(key in features)) {
  70167. features[key] = true;
  70168. return callback.call(thisArg, feature, layer);
  70169. }
  70170. });
  70171. }
  70172. };
  70173. /**
  70174. * @inheritDoc
  70175. */
  70176. ol.renderer.webgl.VectorLayer.prototype.hasFeatureAtCoordinate =
  70177. function(coordinate, frameState) {
  70178. if (!this.replayGroup_ || !this.layerState_) {
  70179. return false;
  70180. } else {
  70181. var context = this.mapRenderer.getContext();
  70182. var viewState = frameState.viewState;
  70183. var layerState = this.layerState_;
  70184. return this.replayGroup_.hasFeatureAtCoordinate(coordinate,
  70185. context, viewState.center, viewState.resolution, viewState.rotation,
  70186. frameState.size, frameState.pixelRatio, layerState.opacity,
  70187. frameState.skippedFeatureUids);
  70188. }
  70189. };
  70190. /**
  70191. * @inheritDoc
  70192. */
  70193. ol.renderer.webgl.VectorLayer.prototype.forEachLayerAtPixel =
  70194. function(pixel, frameState, callback, thisArg) {
  70195. var coordinate = pixel.slice();
  70196. ol.vec.Mat4.multVec2(
  70197. frameState.pixelToCoordinateMatrix, coordinate, coordinate);
  70198. var hasFeature = this.hasFeatureAtCoordinate(coordinate, frameState);
  70199. if (hasFeature) {
  70200. return callback.call(thisArg, this.getLayer());
  70201. } else {
  70202. return undefined;
  70203. }
  70204. };
  70205. /**
  70206. * Handle changes in image style state.
  70207. * @param {goog.events.Event} event Image style change event.
  70208. * @private
  70209. */
  70210. ol.renderer.webgl.VectorLayer.prototype.handleStyleImageChange_ =
  70211. function(event) {
  70212. this.renderIfReadyAndVisible();
  70213. };
  70214. /**
  70215. * @inheritDoc
  70216. */
  70217. ol.renderer.webgl.VectorLayer.prototype.prepareFrame =
  70218. function(frameState, layerState, context) {
  70219. var vectorLayer = /** @type {ol.layer.Vector} */ (this.getLayer());
  70220. goog.asserts.assertInstanceof(vectorLayer, ol.layer.Vector,
  70221. 'layer is an instance of ol.layer.Vector');
  70222. var vectorSource = vectorLayer.getSource();
  70223. this.updateAttributions(
  70224. frameState.attributions, vectorSource.getAttributions());
  70225. this.updateLogos(frameState, vectorSource);
  70226. var animating = frameState.viewHints[ol.ViewHint.ANIMATING];
  70227. var interacting = frameState.viewHints[ol.ViewHint.INTERACTING];
  70228. var updateWhileAnimating = vectorLayer.getUpdateWhileAnimating();
  70229. var updateWhileInteracting = vectorLayer.getUpdateWhileInteracting();
  70230. if (!this.dirty_ && (!updateWhileAnimating && animating) ||
  70231. (!updateWhileInteracting && interacting)) {
  70232. return true;
  70233. }
  70234. var frameStateExtent = frameState.extent;
  70235. var viewState = frameState.viewState;
  70236. var projection = viewState.projection;
  70237. var resolution = viewState.resolution;
  70238. var pixelRatio = frameState.pixelRatio;
  70239. var vectorLayerRevision = vectorLayer.getRevision();
  70240. var vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();
  70241. var vectorLayerRenderOrder = vectorLayer.getRenderOrder();
  70242. if (vectorLayerRenderOrder === undefined) {
  70243. vectorLayerRenderOrder = ol.renderer.vector.defaultOrder;
  70244. }
  70245. var extent = ol.extent.buffer(frameStateExtent,
  70246. vectorLayerRenderBuffer * resolution);
  70247. if (!this.dirty_ &&
  70248. this.renderedResolution_ == resolution &&
  70249. this.renderedRevision_ == vectorLayerRevision &&
  70250. this.renderedRenderOrder_ == vectorLayerRenderOrder &&
  70251. ol.extent.containsExtent(this.renderedExtent_, extent)) {
  70252. return true;
  70253. }
  70254. if (this.replayGroup_) {
  70255. frameState.postRenderFunctions.push(
  70256. this.replayGroup_.getDeleteResourcesFunction(context));
  70257. }
  70258. this.dirty_ = false;
  70259. var replayGroup = new ol.render.webgl.ReplayGroup(
  70260. ol.renderer.vector.getTolerance(resolution, pixelRatio),
  70261. extent, vectorLayer.getRenderBuffer());
  70262. vectorSource.loadFeatures(extent, resolution, projection);
  70263. var renderFeature =
  70264. /**
  70265. * @param {ol.Feature} feature Feature.
  70266. * @this {ol.renderer.webgl.VectorLayer}
  70267. */
  70268. function(feature) {
  70269. var styles;
  70270. var styleFunction = feature.getStyleFunction();
  70271. if (styleFunction) {
  70272. styles = styleFunction.call(feature, resolution);
  70273. } else {
  70274. styleFunction = vectorLayer.getStyleFunction();
  70275. if (styleFunction) {
  70276. styles = styleFunction(feature, resolution);
  70277. }
  70278. }
  70279. if (styles) {
  70280. var dirty = this.renderFeature(
  70281. feature, resolution, pixelRatio, styles, replayGroup);
  70282. this.dirty_ = this.dirty_ || dirty;
  70283. }
  70284. };
  70285. if (vectorLayerRenderOrder) {
  70286. /** @type {Array.<ol.Feature>} */
  70287. var features = [];
  70288. vectorSource.forEachFeatureInExtentAtResolution(extent, resolution,
  70289. /**
  70290. * @param {ol.Feature} feature Feature.
  70291. */
  70292. function(feature) {
  70293. features.push(feature);
  70294. }, this);
  70295. goog.array.sort(features, vectorLayerRenderOrder);
  70296. features.forEach(renderFeature, this);
  70297. } else {
  70298. vectorSource.forEachFeatureInExtentAtResolution(
  70299. extent, resolution, renderFeature, this);
  70300. }
  70301. replayGroup.finish(context);
  70302. this.renderedResolution_ = resolution;
  70303. this.renderedRevision_ = vectorLayerRevision;
  70304. this.renderedRenderOrder_ = vectorLayerRenderOrder;
  70305. this.renderedExtent_ = extent;
  70306. this.replayGroup_ = replayGroup;
  70307. return true;
  70308. };
  70309. /**
  70310. * @param {ol.Feature} feature Feature.
  70311. * @param {number} resolution Resolution.
  70312. * @param {number} pixelRatio Pixel ratio.
  70313. * @param {Array.<ol.style.Style>} styles Array of styles
  70314. * @param {ol.render.webgl.ReplayGroup} replayGroup Replay group.
  70315. * @return {boolean} `true` if an image is loading.
  70316. */
  70317. ol.renderer.webgl.VectorLayer.prototype.renderFeature =
  70318. function(feature, resolution, pixelRatio, styles, replayGroup) {
  70319. if (!styles) {
  70320. return false;
  70321. }
  70322. var i, ii, loading = false;
  70323. for (i = 0, ii = styles.length; i < ii; ++i) {
  70324. loading = ol.renderer.vector.renderFeature(
  70325. replayGroup, feature, styles[i],
  70326. ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
  70327. this.handleStyleImageChange_, this) || loading;
  70328. }
  70329. return loading;
  70330. };
  70331. // FIXME check against gl.getParameter(webgl.MAX_TEXTURE_SIZE)
  70332. goog.provide('ol.renderer.webgl.Map');
  70333. goog.require('goog.array');
  70334. goog.require('goog.asserts');
  70335. goog.require('goog.dom');
  70336. goog.require('goog.dom.TagName');
  70337. goog.require('goog.events');
  70338. goog.require('goog.events.Event');
  70339. goog.require('goog.log');
  70340. goog.require('goog.log.Logger');
  70341. goog.require('goog.object');
  70342. goog.require('goog.style');
  70343. goog.require('goog.webgl');
  70344. goog.require('ol');
  70345. goog.require('ol.RendererType');
  70346. goog.require('ol.css');
  70347. goog.require('ol.dom');
  70348. goog.require('ol.layer.Image');
  70349. goog.require('ol.layer.Layer');
  70350. goog.require('ol.layer.Tile');
  70351. goog.require('ol.layer.Vector');
  70352. goog.require('ol.render.Event');
  70353. goog.require('ol.render.EventType');
  70354. goog.require('ol.render.webgl.Immediate');
  70355. goog.require('ol.renderer.Map');
  70356. goog.require('ol.renderer.webgl.ImageLayer');
  70357. goog.require('ol.renderer.webgl.Layer');
  70358. goog.require('ol.renderer.webgl.TileLayer');
  70359. goog.require('ol.renderer.webgl.VectorLayer');
  70360. goog.require('ol.source.State');
  70361. goog.require('ol.structs.LRUCache');
  70362. goog.require('ol.structs.PriorityQueue');
  70363. goog.require('ol.webgl');
  70364. goog.require('ol.webgl.Context');
  70365. goog.require('ol.webgl.WebGLContextEventType');
  70366. /**
  70367. * @typedef {{magFilter: number, minFilter: number, texture: WebGLTexture}}
  70368. */
  70369. ol.renderer.webgl.TextureCacheEntry;
  70370. /**
  70371. * @constructor
  70372. * @extends {ol.renderer.Map}
  70373. * @param {Element} container Container.
  70374. * @param {ol.Map} map Map.
  70375. */
  70376. ol.renderer.webgl.Map = function(container, map) {
  70377. goog.base(this, container, map);
  70378. /**
  70379. * @private
  70380. * @type {HTMLCanvasElement}
  70381. */
  70382. this.canvas_ = /** @type {HTMLCanvasElement} */
  70383. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  70384. this.canvas_.style.width = '100%';
  70385. this.canvas_.style.height = '100%';
  70386. this.canvas_.className = ol.css.CLASS_UNSELECTABLE;
  70387. goog.dom.insertChildAt(container, this.canvas_, 0);
  70388. /**
  70389. * @private
  70390. * @type {number}
  70391. */
  70392. this.clipTileCanvasWidth_ = 0;
  70393. /**
  70394. * @private
  70395. * @type {number}
  70396. */
  70397. this.clipTileCanvasHeight_ = 0;
  70398. /**
  70399. * @private
  70400. * @type {CanvasRenderingContext2D}
  70401. */
  70402. this.clipTileContext_ = ol.dom.createCanvasContext2D();
  70403. /**
  70404. * @private
  70405. * @type {boolean}
  70406. */
  70407. this.renderedVisible_ = true;
  70408. /**
  70409. * @private
  70410. * @type {WebGLRenderingContext}
  70411. */
  70412. this.gl_ = ol.webgl.getContext(this.canvas_, {
  70413. antialias: true,
  70414. depth: false,
  70415. failIfMajorPerformanceCaveat: true,
  70416. preserveDrawingBuffer: false,
  70417. stencil: true
  70418. });
  70419. goog.asserts.assert(this.gl_, 'got a WebGLRenderingContext');
  70420. /**
  70421. * @private
  70422. * @type {ol.webgl.Context}
  70423. */
  70424. this.context_ = new ol.webgl.Context(this.canvas_, this.gl_);
  70425. goog.events.listen(this.canvas_, ol.webgl.WebGLContextEventType.LOST,
  70426. this.handleWebGLContextLost, false, this);
  70427. goog.events.listen(this.canvas_, ol.webgl.WebGLContextEventType.RESTORED,
  70428. this.handleWebGLContextRestored, false, this);
  70429. /**
  70430. * @private
  70431. * @type {ol.structs.LRUCache.<ol.renderer.webgl.TextureCacheEntry|null>}
  70432. */
  70433. this.textureCache_ = new ol.structs.LRUCache();
  70434. /**
  70435. * @private
  70436. * @type {ol.Coordinate}
  70437. */
  70438. this.focus_ = null;
  70439. /**
  70440. * @private
  70441. * @type {ol.structs.PriorityQueue.<Array>}
  70442. */
  70443. this.tileTextureQueue_ = new ol.structs.PriorityQueue(
  70444. goog.bind(
  70445. /**
  70446. * @param {Array.<*>} element Element.
  70447. * @return {number} Priority.
  70448. * @this {ol.renderer.webgl.Map}
  70449. */
  70450. function(element) {
  70451. var tileCenter = /** @type {ol.Coordinate} */ (element[1]);
  70452. var tileResolution = /** @type {number} */ (element[2]);
  70453. var deltaX = tileCenter[0] - this.focus_[0];
  70454. var deltaY = tileCenter[1] - this.focus_[1];
  70455. return 65536 * Math.log(tileResolution) +
  70456. Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution;
  70457. }, this),
  70458. /**
  70459. * @param {Array.<*>} element Element.
  70460. * @return {string} Key.
  70461. */
  70462. function(element) {
  70463. return /** @type {ol.Tile} */ (element[0]).getKey();
  70464. });
  70465. /**
  70466. * @private
  70467. * @type {ol.PostRenderFunction}
  70468. */
  70469. this.loadNextTileTexture_ = goog.bind(
  70470. function(map, frameState) {
  70471. if (!this.tileTextureQueue_.isEmpty()) {
  70472. this.tileTextureQueue_.reprioritize();
  70473. var element = this.tileTextureQueue_.dequeue();
  70474. var tile = /** @type {ol.Tile} */ (element[0]);
  70475. var tileSize = /** @type {ol.Size} */ (element[3]);
  70476. var tileGutter = /** @type {number} */ (element[4]);
  70477. this.bindTileTexture(
  70478. tile, tileSize, tileGutter, goog.webgl.LINEAR, goog.webgl.LINEAR);
  70479. }
  70480. }, this);
  70481. /**
  70482. * @private
  70483. * @type {number}
  70484. */
  70485. this.textureCacheFrameMarkerCount_ = 0;
  70486. this.initializeGL_();
  70487. };
  70488. goog.inherits(ol.renderer.webgl.Map, ol.renderer.Map);
  70489. /**
  70490. * @param {ol.Tile} tile Tile.
  70491. * @param {ol.Size} tileSize Tile size.
  70492. * @param {number} tileGutter Tile gutter.
  70493. * @param {number} magFilter Mag filter.
  70494. * @param {number} minFilter Min filter.
  70495. */
  70496. ol.renderer.webgl.Map.prototype.bindTileTexture =
  70497. function(tile, tileSize, tileGutter, magFilter, minFilter) {
  70498. var gl = this.getGL();
  70499. var tileKey = tile.getKey();
  70500. if (this.textureCache_.containsKey(tileKey)) {
  70501. var textureCacheEntry = this.textureCache_.get(tileKey);
  70502. goog.asserts.assert(textureCacheEntry,
  70503. 'a texture cache entry exists for key %s', tileKey);
  70504. gl.bindTexture(goog.webgl.TEXTURE_2D, textureCacheEntry.texture);
  70505. if (textureCacheEntry.magFilter != magFilter) {
  70506. gl.texParameteri(
  70507. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_MAG_FILTER, magFilter);
  70508. textureCacheEntry.magFilter = magFilter;
  70509. }
  70510. if (textureCacheEntry.minFilter != minFilter) {
  70511. gl.texParameteri(
  70512. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_MAG_FILTER, minFilter);
  70513. textureCacheEntry.minFilter = minFilter;
  70514. }
  70515. } else {
  70516. var texture = gl.createTexture();
  70517. gl.bindTexture(goog.webgl.TEXTURE_2D, texture);
  70518. if (tileGutter > 0) {
  70519. var clipTileCanvas = this.clipTileContext_.canvas;
  70520. var clipTileContext = this.clipTileContext_;
  70521. if (this.clipTileCanvasWidth_ !== tileSize[0] ||
  70522. this.clipTileCanvasHeight_ !== tileSize[1]) {
  70523. clipTileCanvas.width = tileSize[0];
  70524. clipTileCanvas.height = tileSize[1];
  70525. this.clipTileCanvasWidth_ = tileSize[0];
  70526. this.clipTileCanvasHeight_ = tileSize[1];
  70527. } else {
  70528. clipTileContext.clearRect(0, 0, tileSize[0], tileSize[1]);
  70529. }
  70530. clipTileContext.drawImage(tile.getImage(), tileGutter, tileGutter,
  70531. tileSize[0], tileSize[1], 0, 0, tileSize[0], tileSize[1]);
  70532. gl.texImage2D(goog.webgl.TEXTURE_2D, 0,
  70533. goog.webgl.RGBA, goog.webgl.RGBA,
  70534. goog.webgl.UNSIGNED_BYTE, clipTileCanvas);
  70535. } else {
  70536. gl.texImage2D(goog.webgl.TEXTURE_2D, 0,
  70537. goog.webgl.RGBA, goog.webgl.RGBA,
  70538. goog.webgl.UNSIGNED_BYTE, tile.getImage());
  70539. }
  70540. gl.texParameteri(
  70541. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_MAG_FILTER, magFilter);
  70542. gl.texParameteri(
  70543. goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_MIN_FILTER, minFilter);
  70544. gl.texParameteri(goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_WRAP_S,
  70545. goog.webgl.CLAMP_TO_EDGE);
  70546. gl.texParameteri(goog.webgl.TEXTURE_2D, goog.webgl.TEXTURE_WRAP_T,
  70547. goog.webgl.CLAMP_TO_EDGE);
  70548. this.textureCache_.set(tileKey, {
  70549. texture: texture,
  70550. magFilter: magFilter,
  70551. minFilter: minFilter
  70552. });
  70553. }
  70554. };
  70555. /**
  70556. * @inheritDoc
  70557. */
  70558. ol.renderer.webgl.Map.prototype.createLayerRenderer = function(layer) {
  70559. if (ol.ENABLE_IMAGE && layer instanceof ol.layer.Image) {
  70560. return new ol.renderer.webgl.ImageLayer(this, layer);
  70561. } else if (ol.ENABLE_TILE && layer instanceof ol.layer.Tile) {
  70562. return new ol.renderer.webgl.TileLayer(this, layer);
  70563. } else if (ol.ENABLE_VECTOR && layer instanceof ol.layer.Vector) {
  70564. return new ol.renderer.webgl.VectorLayer(this, layer);
  70565. } else {
  70566. goog.asserts.fail('unexpected layer configuration');
  70567. return null;
  70568. }
  70569. };
  70570. /**
  70571. * @param {ol.render.EventType} type Event type.
  70572. * @param {olx.FrameState} frameState Frame state.
  70573. * @private
  70574. */
  70575. ol.renderer.webgl.Map.prototype.dispatchComposeEvent_ =
  70576. function(type, frameState) {
  70577. var map = this.getMap();
  70578. if (map.hasListener(type)) {
  70579. var context = this.context_;
  70580. var extent = frameState.extent;
  70581. var size = frameState.size;
  70582. var viewState = frameState.viewState;
  70583. var pixelRatio = frameState.pixelRatio;
  70584. var resolution = viewState.resolution;
  70585. var center = viewState.center;
  70586. var rotation = viewState.rotation;
  70587. var vectorContext = new ol.render.webgl.Immediate(context,
  70588. center, resolution, rotation, size, extent, pixelRatio);
  70589. var composeEvent = new ol.render.Event(type, map, vectorContext,
  70590. frameState, null, context);
  70591. map.dispatchEvent(composeEvent);
  70592. vectorContext.flush();
  70593. }
  70594. };
  70595. /**
  70596. * @inheritDoc
  70597. */
  70598. ol.renderer.webgl.Map.prototype.disposeInternal = function() {
  70599. var gl = this.getGL();
  70600. if (!gl.isContextLost()) {
  70601. this.textureCache_.forEach(
  70602. /**
  70603. * @param {?ol.renderer.webgl.TextureCacheEntry} textureCacheEntry
  70604. * Texture cache entry.
  70605. */
  70606. function(textureCacheEntry) {
  70607. if (textureCacheEntry) {
  70608. gl.deleteTexture(textureCacheEntry.texture);
  70609. }
  70610. });
  70611. }
  70612. goog.dispose(this.context_);
  70613. goog.base(this, 'disposeInternal');
  70614. };
  70615. /**
  70616. * @param {ol.Map} map Map.
  70617. * @param {olx.FrameState} frameState Frame state.
  70618. * @private
  70619. */
  70620. ol.renderer.webgl.Map.prototype.expireCache_ = function(map, frameState) {
  70621. var gl = this.getGL();
  70622. var textureCacheEntry;
  70623. while (this.textureCache_.getCount() - this.textureCacheFrameMarkerCount_ >
  70624. ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK) {
  70625. textureCacheEntry = this.textureCache_.peekLast();
  70626. if (!textureCacheEntry) {
  70627. if (+this.textureCache_.peekLastKey() == frameState.index) {
  70628. break;
  70629. } else {
  70630. --this.textureCacheFrameMarkerCount_;
  70631. }
  70632. } else {
  70633. gl.deleteTexture(textureCacheEntry.texture);
  70634. }
  70635. this.textureCache_.pop();
  70636. }
  70637. };
  70638. /**
  70639. * @return {ol.webgl.Context}
  70640. */
  70641. ol.renderer.webgl.Map.prototype.getContext = function() {
  70642. return this.context_;
  70643. };
  70644. /**
  70645. * @return {WebGLRenderingContext} GL.
  70646. */
  70647. ol.renderer.webgl.Map.prototype.getGL = function() {
  70648. return this.gl_;
  70649. };
  70650. /**
  70651. * @return {ol.structs.PriorityQueue.<Array>} Tile texture queue.
  70652. */
  70653. ol.renderer.webgl.Map.prototype.getTileTextureQueue = function() {
  70654. return this.tileTextureQueue_;
  70655. };
  70656. /**
  70657. * @inheritDoc
  70658. */
  70659. ol.renderer.webgl.Map.prototype.getType = function() {
  70660. return ol.RendererType.WEBGL;
  70661. };
  70662. /**
  70663. * @param {goog.events.Event} event Event.
  70664. * @protected
  70665. */
  70666. ol.renderer.webgl.Map.prototype.handleWebGLContextLost = function(event) {
  70667. event.preventDefault();
  70668. this.textureCache_.clear();
  70669. this.textureCacheFrameMarkerCount_ = 0;
  70670. goog.object.forEach(this.getLayerRenderers(),
  70671. /**
  70672. * @param {ol.renderer.Layer} layerRenderer Layer renderer.
  70673. * @param {string} key Key.
  70674. * @param {Object.<string, ol.renderer.Layer>} object Object.
  70675. */
  70676. function(layerRenderer, key, object) {
  70677. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.webgl.Layer,
  70678. 'renderer is an instance of ol.renderer.webgl.Layer');
  70679. layerRenderer.handleWebGLContextLost();
  70680. });
  70681. };
  70682. /**
  70683. * @protected
  70684. */
  70685. ol.renderer.webgl.Map.prototype.handleWebGLContextRestored = function() {
  70686. this.initializeGL_();
  70687. this.getMap().render();
  70688. };
  70689. /**
  70690. * @private
  70691. */
  70692. ol.renderer.webgl.Map.prototype.initializeGL_ = function() {
  70693. var gl = this.gl_;
  70694. gl.activeTexture(goog.webgl.TEXTURE0);
  70695. gl.blendFuncSeparate(
  70696. goog.webgl.SRC_ALPHA, goog.webgl.ONE_MINUS_SRC_ALPHA,
  70697. goog.webgl.ONE, goog.webgl.ONE_MINUS_SRC_ALPHA);
  70698. gl.disable(goog.webgl.CULL_FACE);
  70699. gl.disable(goog.webgl.DEPTH_TEST);
  70700. gl.disable(goog.webgl.SCISSOR_TEST);
  70701. gl.disable(goog.webgl.STENCIL_TEST);
  70702. };
  70703. /**
  70704. * @param {ol.Tile} tile Tile.
  70705. * @return {boolean} Is tile texture loaded.
  70706. */
  70707. ol.renderer.webgl.Map.prototype.isTileTextureLoaded = function(tile) {
  70708. return this.textureCache_.containsKey(tile.getKey());
  70709. };
  70710. /**
  70711. * @private
  70712. * @type {goog.log.Logger}
  70713. */
  70714. ol.renderer.webgl.Map.prototype.logger_ =
  70715. goog.log.getLogger('ol.renderer.webgl.Map');
  70716. /**
  70717. * @inheritDoc
  70718. */
  70719. ol.renderer.webgl.Map.prototype.renderFrame = function(frameState) {
  70720. var context = this.getContext();
  70721. var gl = this.getGL();
  70722. if (gl.isContextLost()) {
  70723. return false;
  70724. }
  70725. if (!frameState) {
  70726. if (this.renderedVisible_) {
  70727. goog.style.setElementShown(this.canvas_, false);
  70728. this.renderedVisible_ = false;
  70729. }
  70730. return false;
  70731. }
  70732. this.focus_ = frameState.focus;
  70733. this.textureCache_.set((-frameState.index).toString(), null);
  70734. ++this.textureCacheFrameMarkerCount_;
  70735. this.dispatchComposeEvent_(ol.render.EventType.PRECOMPOSE, frameState);
  70736. /** @type {Array.<ol.layer.LayerState>} */
  70737. var layerStatesToDraw = [];
  70738. var layerStatesArray = frameState.layerStatesArray;
  70739. goog.array.stableSort(layerStatesArray, ol.renderer.Map.sortByZIndex);
  70740. var viewResolution = frameState.viewState.resolution;
  70741. var i, ii, layerRenderer, layerState;
  70742. for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
  70743. layerState = layerStatesArray[i];
  70744. if (ol.layer.Layer.visibleAtResolution(layerState, viewResolution) &&
  70745. layerState.sourceState == ol.source.State.READY) {
  70746. layerRenderer = this.getLayerRenderer(layerState.layer);
  70747. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.webgl.Layer,
  70748. 'renderer is an instance of ol.renderer.webgl.Layer');
  70749. if (layerRenderer.prepareFrame(frameState, layerState, context)) {
  70750. layerStatesToDraw.push(layerState);
  70751. }
  70752. }
  70753. }
  70754. var width = frameState.size[0] * frameState.pixelRatio;
  70755. var height = frameState.size[1] * frameState.pixelRatio;
  70756. if (this.canvas_.width != width || this.canvas_.height != height) {
  70757. this.canvas_.width = width;
  70758. this.canvas_.height = height;
  70759. }
  70760. gl.bindFramebuffer(goog.webgl.FRAMEBUFFER, null);
  70761. gl.clearColor(0, 0, 0, 0);
  70762. gl.clear(goog.webgl.COLOR_BUFFER_BIT);
  70763. gl.enable(goog.webgl.BLEND);
  70764. gl.viewport(0, 0, this.canvas_.width, this.canvas_.height);
  70765. for (i = 0, ii = layerStatesToDraw.length; i < ii; ++i) {
  70766. layerState = layerStatesToDraw[i];
  70767. layerRenderer = this.getLayerRenderer(layerState.layer);
  70768. goog.asserts.assertInstanceof(layerRenderer, ol.renderer.webgl.Layer,
  70769. 'renderer is an instance of ol.renderer.webgl.Layer');
  70770. layerRenderer.composeFrame(frameState, layerState, context);
  70771. }
  70772. if (!this.renderedVisible_) {
  70773. goog.style.setElementShown(this.canvas_, true);
  70774. this.renderedVisible_ = true;
  70775. }
  70776. this.calculateMatrices2D(frameState);
  70777. if (this.textureCache_.getCount() - this.textureCacheFrameMarkerCount_ >
  70778. ol.WEBGL_TEXTURE_CACHE_HIGH_WATER_MARK) {
  70779. frameState.postRenderFunctions.push(goog.bind(this.expireCache_, this));
  70780. }
  70781. if (!this.tileTextureQueue_.isEmpty()) {
  70782. frameState.postRenderFunctions.push(this.loadNextTileTexture_);
  70783. frameState.animate = true;
  70784. }
  70785. this.dispatchComposeEvent_(ol.render.EventType.POSTCOMPOSE, frameState);
  70786. this.scheduleRemoveUnusedLayerRenderers(frameState);
  70787. this.scheduleExpireIconCache(frameState);
  70788. };
  70789. /**
  70790. * @inheritDoc
  70791. */
  70792. ol.renderer.webgl.Map.prototype.forEachFeatureAtCoordinate =
  70793. function(coordinate, frameState, callback, thisArg,
  70794. layerFilter, thisArg2) {
  70795. var result;
  70796. if (this.getGL().isContextLost()) {
  70797. return false;
  70798. }
  70799. var viewState = frameState.viewState;
  70800. var layerStates = frameState.layerStatesArray;
  70801. var numLayers = layerStates.length;
  70802. var i;
  70803. for (i = numLayers - 1; i >= 0; --i) {
  70804. var layerState = layerStates[i];
  70805. var layer = layerState.layer;
  70806. if (ol.layer.Layer.visibleAtResolution(layerState, viewState.resolution) &&
  70807. layerFilter.call(thisArg2, layer)) {
  70808. var layerRenderer = this.getLayerRenderer(layer);
  70809. result = layerRenderer.forEachFeatureAtCoordinate(
  70810. coordinate, frameState, callback, thisArg);
  70811. if (result) {
  70812. return result;
  70813. }
  70814. }
  70815. }
  70816. return undefined;
  70817. };
  70818. /**
  70819. * @inheritDoc
  70820. */
  70821. ol.renderer.webgl.Map.prototype.hasFeatureAtCoordinate =
  70822. function(coordinate, frameState, layerFilter, thisArg) {
  70823. var hasFeature = false;
  70824. if (this.getGL().isContextLost()) {
  70825. return false;
  70826. }
  70827. var viewState = frameState.viewState;
  70828. var layerStates = frameState.layerStatesArray;
  70829. var numLayers = layerStates.length;
  70830. var i;
  70831. for (i = numLayers - 1; i >= 0; --i) {
  70832. var layerState = layerStates[i];
  70833. var layer = layerState.layer;
  70834. if (ol.layer.Layer.visibleAtResolution(layerState, viewState.resolution) &&
  70835. layerFilter.call(thisArg, layer)) {
  70836. var layerRenderer = this.getLayerRenderer(layer);
  70837. hasFeature =
  70838. layerRenderer.hasFeatureAtCoordinate(coordinate, frameState);
  70839. if (hasFeature) {
  70840. return true;
  70841. }
  70842. }
  70843. }
  70844. return hasFeature;
  70845. };
  70846. /**
  70847. * @inheritDoc
  70848. */
  70849. ol.renderer.webgl.Map.prototype.forEachLayerAtPixel =
  70850. function(pixel, frameState, callback, thisArg,
  70851. layerFilter, thisArg2) {
  70852. if (this.getGL().isContextLost()) {
  70853. return false;
  70854. }
  70855. var viewState = frameState.viewState;
  70856. var result;
  70857. var layerStates = frameState.layerStatesArray;
  70858. var numLayers = layerStates.length;
  70859. var i;
  70860. for (i = numLayers - 1; i >= 0; --i) {
  70861. var layerState = layerStates[i];
  70862. var layer = layerState.layer;
  70863. if (ol.layer.Layer.visibleAtResolution(layerState, viewState.resolution) &&
  70864. layerFilter.call(thisArg, layer)) {
  70865. var layerRenderer = this.getLayerRenderer(layer);
  70866. result = layerRenderer.forEachLayerAtPixel(
  70867. pixel, frameState, callback, thisArg);
  70868. if (result) {
  70869. return result;
  70870. }
  70871. }
  70872. }
  70873. return undefined;
  70874. };
  70875. // FIXME recheck layer/map projection compatibility when projection changes
  70876. // FIXME layer renderers should skip when they can't reproject
  70877. // FIXME add tilt and height?
  70878. goog.provide('ol.Map');
  70879. goog.provide('ol.MapProperty');
  70880. goog.require('goog.array');
  70881. goog.require('goog.asserts');
  70882. goog.require('goog.async.AnimationDelay');
  70883. goog.require('goog.async.nextTick');
  70884. goog.require('goog.debug.Console');
  70885. goog.require('goog.dom');
  70886. goog.require('goog.dom.TagName');
  70887. goog.require('goog.dom.ViewportSizeMonitor');
  70888. goog.require('goog.dom.classlist');
  70889. goog.require('goog.events');
  70890. goog.require('goog.events.BrowserEvent');
  70891. goog.require('goog.events.Event');
  70892. goog.require('goog.events.EventType');
  70893. goog.require('goog.events.KeyHandler');
  70894. goog.require('goog.events.KeyHandler.EventType');
  70895. goog.require('goog.events.MouseWheelHandler');
  70896. goog.require('goog.events.MouseWheelHandler.EventType');
  70897. goog.require('goog.functions');
  70898. goog.require('goog.log');
  70899. goog.require('goog.log.Level');
  70900. goog.require('goog.object');
  70901. goog.require('goog.style');
  70902. goog.require('goog.vec.Mat4');
  70903. goog.require('ol.Collection');
  70904. goog.require('ol.CollectionEventType');
  70905. goog.require('ol.MapBrowserEvent');
  70906. goog.require('ol.MapBrowserEvent.EventType');
  70907. goog.require('ol.MapBrowserEventHandler');
  70908. goog.require('ol.MapEvent');
  70909. goog.require('ol.MapEventType');
  70910. goog.require('ol.Object');
  70911. goog.require('ol.ObjectEvent');
  70912. goog.require('ol.ObjectEventType');
  70913. goog.require('ol.Pixel');
  70914. goog.require('ol.PostRenderFunction');
  70915. goog.require('ol.PreRenderFunction');
  70916. goog.require('ol.RendererType');
  70917. goog.require('ol.Size');
  70918. goog.require('ol.TileQueue');
  70919. goog.require('ol.View');
  70920. goog.require('ol.ViewHint');
  70921. goog.require('ol.control');
  70922. goog.require('ol.extent');
  70923. goog.require('ol.has');
  70924. goog.require('ol.interaction');
  70925. goog.require('ol.layer.Base');
  70926. goog.require('ol.layer.Group');
  70927. goog.require('ol.proj');
  70928. goog.require('ol.proj.common');
  70929. goog.require('ol.renderer.Map');
  70930. goog.require('ol.renderer.canvas.Map');
  70931. goog.require('ol.renderer.dom.Map');
  70932. goog.require('ol.renderer.webgl.Map');
  70933. goog.require('ol.size');
  70934. goog.require('ol.structs.PriorityQueue');
  70935. goog.require('ol.tilecoord');
  70936. goog.require('ol.vec.Mat4');
  70937. /**
  70938. * @const
  70939. * @type {string}
  70940. */
  70941. ol.OL3_URL = 'http://openlayers.org/';
  70942. /**
  70943. * @const
  70944. * @type {string}
  70945. */
  70946. ol.OL3_LOGO_URL = 'data:image/png;base64,' +
  70947. 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAA3NCSVQICAjb4U/gAAAACXBI' +
  70948. 'WXMAAAHGAAABxgEXwfpGAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAA' +
  70949. 'AhNQTFRF////AP//AICAgP//AFVVQECA////K1VVSbbbYL/fJ05idsTYJFtbbcjbJllmZszW' +
  70950. 'WMTOIFhoHlNiZszTa9DdUcHNHlNlV8XRIVdiasrUHlZjIVZjaMnVH1RlIFRkH1RkH1ZlasvY' +
  70951. 'asvXVsPQH1VkacnVa8vWIVZjIFRjVMPQa8rXIVVkXsXRsNveIFVkIFZlIVVj3eDeh6GmbMvX' +
  70952. 'H1ZkIFRka8rWbMvXIFVkIFVjIFVkbMvWH1VjbMvWIFVlbcvWIFVla8vVIFVkbMvWbMvVH1Vk' +
  70953. 'bMvWIFVlbcvWIFVkbcvVbMvWjNPbIFVkU8LPwMzNIFVkbczWIFVkbsvWbMvXIFVkRnB8bcvW' +
  70954. '2+TkW8XRIFVkIlZlJVloJlpoKlxrLl9tMmJwOWd0Omh1RXF8TneCT3iDUHiDU8LPVMLPVcLP' +
  70955. 'VcPQVsPPVsPQV8PQWMTQWsTQW8TQXMXSXsXRX4SNX8bSYMfTYcfTYsfTY8jUZcfSZsnUaIqT' +
  70956. 'acrVasrVa8jTa8rWbI2VbMvWbcvWdJObdcvUdszUd8vVeJaee87Yfc3WgJyjhqGnitDYjaar' +
  70957. 'ldPZnrK2oNbborW5o9bbo9fbpLa6q9ndrL3ArtndscDDutzfu8fJwN7gwt7gxc/QyuHhy+Hi' +
  70958. 'zeHi0NfX0+Pj19zb1+Tj2uXk29/e3uLg3+Lh3+bl4uXj4ufl4+fl5Ofl5ufl5ujm5+jmySDn' +
  70959. 'BAAAAFp0Uk5TAAECAgMEBAYHCA0NDg4UGRogIiMmKSssLzU7PkJJT1JTVFliY2hrdHZ3foSF' +
  70960. 'hYeJjY2QkpugqbG1tre5w8zQ09XY3uXn6+zx8vT09vf4+Pj5+fr6/P39/f3+gz7SsAAAAVVJ' +
  70961. 'REFUOMtjYKA7EBDnwCPLrObS1BRiLoJLnte6CQy8FLHLCzs2QUG4FjZ5GbcmBDDjxJBXDWxC' +
  70962. 'Brb8aM4zbkIDzpLYnAcE9VXlJSWlZRU13koIeW57mGx5XjoMZEUqwxWYQaQbSzLSkYGfKFSe' +
  70963. '0QMsX5WbjgY0YS4MBplemI4BdGBW+DQ11eZiymfqQuXZIjqwyadPNoSZ4L+0FVM6e+oGI6g8' +
  70964. 'a9iKNT3o8kVzNkzRg5lgl7p4wyRUL9Yt2jAxVh6mQCogae6GmflI8p0r13VFWTHBQ0rWPW7a' +
  70965. 'hgWVcPm+9cuLoyy4kCJDzCm6d8PSFoh0zvQNC5OjDJhQopPPJqph1doJBUD5tnkbZiUEqaCn' +
  70966. 'B3bTqLTFG1bPn71kw4b+GFdpLElKIzRxxgYgWNYc5SCENVHKeUaltHdXx0dZ8uBI1hJ2UUDg' +
  70967. 'q82CM2MwKeibqAvSO7MCABq0wXEPiqWEAAAAAElFTkSuQmCC';
  70968. /**
  70969. * @type {Array.<ol.RendererType>}
  70970. * @const
  70971. */
  70972. ol.DEFAULT_RENDERER_TYPES = [
  70973. ol.RendererType.CANVAS,
  70974. ol.RendererType.WEBGL,
  70975. ol.RendererType.DOM
  70976. ];
  70977. /**
  70978. * @enum {string}
  70979. */
  70980. ol.MapProperty = {
  70981. LAYERGROUP: 'layergroup',
  70982. SIZE: 'size',
  70983. TARGET: 'target',
  70984. VIEW: 'view'
  70985. };
  70986. /**
  70987. * @classdesc
  70988. * The map is the core component of OpenLayers. For a map to render, a view,
  70989. * one or more layers, and a target container are needed:
  70990. *
  70991. * var map = new ol.Map({
  70992. * view: new ol.View({
  70993. * center: [0, 0],
  70994. * zoom: 1
  70995. * }),
  70996. * layers: [
  70997. * new ol.layer.Tile({
  70998. * source: new ol.source.MapQuest({layer: 'osm'})
  70999. * })
  71000. * ],
  71001. * target: 'map'
  71002. * });
  71003. *
  71004. * The above snippet creates a map using a {@link ol.layer.Tile} to display
  71005. * {@link ol.source.MapQuest} OSM data and render it to a DOM element with the
  71006. * id `map`.
  71007. *
  71008. * The constructor places a viewport container (with CSS class name
  71009. * `ol-viewport`) in the target element (see `getViewport()`), and then two
  71010. * further elements within the viewport: one with CSS class name
  71011. * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with
  71012. * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent`
  71013. * option of {@link ol.Overlay} for the difference). The map itself is placed in
  71014. * a further element within the viewport, either DOM or Canvas, depending on the
  71015. * renderer.
  71016. *
  71017. * Layers are stored as a `ol.Collection` in layerGroups. A top-level group is
  71018. * provided by the library. This is what is accessed by `getLayerGroup` and
  71019. * `setLayerGroup`. Layers entered in the options are added to this group, and
  71020. * `addLayer` and `removeLayer` change the layer collection in the group.
  71021. * `getLayers` is a convenience function for `getLayerGroup().getLayers()`.
  71022. * Note that `ol.layer.Group` is a subclass of `ol.layer.Base`, so layers
  71023. * entered in the options or added with `addLayer` can be groups, which can
  71024. * contain further groups, and so on.
  71025. *
  71026. * @constructor
  71027. * @extends {ol.Object}
  71028. * @param {olx.MapOptions} options Map options.
  71029. * @fires ol.MapBrowserEvent
  71030. * @fires ol.MapEvent
  71031. * @fires ol.render.Event#postcompose
  71032. * @fires ol.render.Event#precompose
  71033. * @api stable
  71034. */
  71035. ol.Map = function(options) {
  71036. goog.base(this);
  71037. var optionsInternal = ol.Map.createOptionsInternal(options);
  71038. /**
  71039. * @type {boolean}
  71040. * @private
  71041. */
  71042. this.loadTilesWhileAnimating_ =
  71043. options.loadTilesWhileAnimating !== undefined ?
  71044. options.loadTilesWhileAnimating : false;
  71045. /**
  71046. * @type {boolean}
  71047. * @private
  71048. */
  71049. this.loadTilesWhileInteracting_ =
  71050. options.loadTilesWhileInteracting !== undefined ?
  71051. options.loadTilesWhileInteracting : false;
  71052. /**
  71053. * @private
  71054. * @type {number}
  71055. */
  71056. this.pixelRatio_ = options.pixelRatio !== undefined ?
  71057. options.pixelRatio : ol.has.DEVICE_PIXEL_RATIO;
  71058. /**
  71059. * @private
  71060. * @type {Object.<string, string>}
  71061. */
  71062. this.logos_ = optionsInternal.logos;
  71063. /**
  71064. * @private
  71065. * @type {goog.async.AnimationDelay}
  71066. */
  71067. this.animationDelay_ =
  71068. new goog.async.AnimationDelay(this.renderFrame_, undefined, this);
  71069. this.registerDisposable(this.animationDelay_);
  71070. /**
  71071. * @private
  71072. * @type {goog.vec.Mat4.Number}
  71073. */
  71074. this.coordinateToPixelMatrix_ = goog.vec.Mat4.createNumber();
  71075. /**
  71076. * @private
  71077. * @type {goog.vec.Mat4.Number}
  71078. */
  71079. this.pixelToCoordinateMatrix_ = goog.vec.Mat4.createNumber();
  71080. /**
  71081. * @private
  71082. * @type {number}
  71083. */
  71084. this.frameIndex_ = 0;
  71085. /**
  71086. * @private
  71087. * @type {?olx.FrameState}
  71088. */
  71089. this.frameState_ = null;
  71090. /**
  71091. * The extent at the previous 'moveend' event.
  71092. * @private
  71093. * @type {ol.Extent}
  71094. */
  71095. this.previousExtent_ = ol.extent.createEmpty();
  71096. /**
  71097. * @private
  71098. * @type {goog.events.Key}
  71099. */
  71100. this.viewPropertyListenerKey_ = null;
  71101. /**
  71102. * @private
  71103. * @type {Array.<goog.events.Key>}
  71104. */
  71105. this.layerGroupPropertyListenerKeys_ = null;
  71106. /**
  71107. * @private
  71108. * @type {Element}
  71109. */
  71110. this.viewport_ = goog.dom.createDom(goog.dom.TagName.DIV, 'ol-viewport');
  71111. this.viewport_.style.position = 'relative';
  71112. this.viewport_.style.overflow = 'hidden';
  71113. this.viewport_.style.width = '100%';
  71114. this.viewport_.style.height = '100%';
  71115. // prevent page zoom on IE >= 10 browsers
  71116. this.viewport_.style.msTouchAction = 'none';
  71117. this.viewport_.style.touchAction = 'none';
  71118. if (ol.has.TOUCH) {
  71119. goog.dom.classlist.add(this.viewport_, 'ol-touch');
  71120. }
  71121. /**
  71122. * @private
  71123. * @type {Element}
  71124. */
  71125. this.overlayContainer_ = goog.dom.createDom(goog.dom.TagName.DIV,
  71126. 'ol-overlaycontainer');
  71127. this.viewport_.appendChild(this.overlayContainer_);
  71128. /**
  71129. * @private
  71130. * @type {Element}
  71131. */
  71132. this.overlayContainerStopEvent_ = goog.dom.createDom(goog.dom.TagName.DIV,
  71133. 'ol-overlaycontainer-stopevent');
  71134. goog.events.listen(this.overlayContainerStopEvent_, [
  71135. goog.events.EventType.CLICK,
  71136. goog.events.EventType.DBLCLICK,
  71137. goog.events.EventType.MOUSEDOWN,
  71138. goog.events.EventType.TOUCHSTART,
  71139. goog.events.EventType.MSPOINTERDOWN,
  71140. ol.MapBrowserEvent.EventType.POINTERDOWN,
  71141. goog.userAgent.GECKO ? 'DOMMouseScroll' : 'mousewheel'
  71142. ], goog.events.Event.stopPropagation);
  71143. this.viewport_.appendChild(this.overlayContainerStopEvent_);
  71144. var mapBrowserEventHandler = new ol.MapBrowserEventHandler(this);
  71145. goog.events.listen(mapBrowserEventHandler,
  71146. goog.object.getValues(ol.MapBrowserEvent.EventType),
  71147. this.handleMapBrowserEvent, false, this);
  71148. this.registerDisposable(mapBrowserEventHandler);
  71149. /**
  71150. * @private
  71151. * @type {Element|Document}
  71152. */
  71153. this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget;
  71154. /**
  71155. * @private
  71156. * @type {goog.events.KeyHandler}
  71157. */
  71158. this.keyHandler_ = new goog.events.KeyHandler();
  71159. goog.events.listen(this.keyHandler_, goog.events.KeyHandler.EventType.KEY,
  71160. this.handleBrowserEvent, false, this);
  71161. this.registerDisposable(this.keyHandler_);
  71162. var mouseWheelHandler = new goog.events.MouseWheelHandler(this.viewport_);
  71163. goog.events.listen(mouseWheelHandler,
  71164. goog.events.MouseWheelHandler.EventType.MOUSEWHEEL,
  71165. this.handleBrowserEvent, false, this);
  71166. this.registerDisposable(mouseWheelHandler);
  71167. /**
  71168. * @type {ol.Collection.<ol.control.Control>}
  71169. * @private
  71170. */
  71171. this.controls_ = optionsInternal.controls;
  71172. /**
  71173. * @type {ol.Collection.<ol.interaction.Interaction>}
  71174. * @private
  71175. */
  71176. this.interactions_ = optionsInternal.interactions;
  71177. /**
  71178. * @type {ol.Collection.<ol.Overlay>}
  71179. * @private
  71180. */
  71181. this.overlays_ = optionsInternal.overlays;
  71182. /**
  71183. * @type {ol.renderer.Map}
  71184. * @private
  71185. */
  71186. this.renderer_ =
  71187. new optionsInternal.rendererConstructor(this.viewport_, this);
  71188. this.registerDisposable(this.renderer_);
  71189. /**
  71190. * @type {goog.dom.ViewportSizeMonitor}
  71191. * @private
  71192. */
  71193. this.viewportSizeMonitor_ = new goog.dom.ViewportSizeMonitor();
  71194. this.registerDisposable(this.viewportSizeMonitor_);
  71195. /**
  71196. * @type {goog.events.Key}
  71197. * @private
  71198. */
  71199. this.viewportResizeListenerKey_ = null;
  71200. /**
  71201. * @private
  71202. * @type {ol.Coordinate}
  71203. */
  71204. this.focus_ = null;
  71205. /**
  71206. * @private
  71207. * @type {Array.<ol.PreRenderFunction>}
  71208. */
  71209. this.preRenderFunctions_ = [];
  71210. /**
  71211. * @private
  71212. * @type {Array.<ol.PostRenderFunction>}
  71213. */
  71214. this.postRenderFunctions_ = [];
  71215. /**
  71216. * @private
  71217. * @type {ol.TileQueue}
  71218. */
  71219. this.tileQueue_ = new ol.TileQueue(
  71220. goog.bind(this.getTilePriority, this),
  71221. goog.bind(this.handleTileChange_, this));
  71222. /**
  71223. * Uids of features to skip at rendering time.
  71224. * @type {Object.<string, boolean>}
  71225. * @private
  71226. */
  71227. this.skippedFeatureUids_ = {};
  71228. goog.events.listen(
  71229. this, ol.Object.getChangeEventType(ol.MapProperty.LAYERGROUP),
  71230. this.handleLayerGroupChanged_, false, this);
  71231. goog.events.listen(this, ol.Object.getChangeEventType(ol.MapProperty.VIEW),
  71232. this.handleViewChanged_, false, this);
  71233. goog.events.listen(this, ol.Object.getChangeEventType(ol.MapProperty.SIZE),
  71234. this.handleSizeChanged_, false, this);
  71235. goog.events.listen(this, ol.Object.getChangeEventType(ol.MapProperty.TARGET),
  71236. this.handleTargetChanged_, false, this);
  71237. // setProperties will trigger the rendering of the map if the map
  71238. // is "defined" already.
  71239. this.setProperties(optionsInternal.values);
  71240. this.controls_.forEach(
  71241. /**
  71242. * @param {ol.control.Control} control Control.
  71243. * @this {ol.Map}
  71244. */
  71245. function(control) {
  71246. control.setMap(this);
  71247. }, this);
  71248. goog.events.listen(this.controls_, ol.CollectionEventType.ADD,
  71249. /**
  71250. * @param {ol.CollectionEvent} event Collection event.
  71251. */
  71252. function(event) {
  71253. event.element.setMap(this);
  71254. }, false, this);
  71255. goog.events.listen(this.controls_, ol.CollectionEventType.REMOVE,
  71256. /**
  71257. * @param {ol.CollectionEvent} event Collection event.
  71258. */
  71259. function(event) {
  71260. event.element.setMap(null);
  71261. }, false, this);
  71262. this.interactions_.forEach(
  71263. /**
  71264. * @param {ol.interaction.Interaction} interaction Interaction.
  71265. * @this {ol.Map}
  71266. */
  71267. function(interaction) {
  71268. interaction.setMap(this);
  71269. }, this);
  71270. goog.events.listen(this.interactions_, ol.CollectionEventType.ADD,
  71271. /**
  71272. * @param {ol.CollectionEvent} event Collection event.
  71273. */
  71274. function(event) {
  71275. event.element.setMap(this);
  71276. }, false, this);
  71277. goog.events.listen(this.interactions_, ol.CollectionEventType.REMOVE,
  71278. /**
  71279. * @param {ol.CollectionEvent} event Collection event.
  71280. */
  71281. function(event) {
  71282. event.element.setMap(null);
  71283. }, false, this);
  71284. this.overlays_.forEach(
  71285. /**
  71286. * @param {ol.Overlay} overlay Overlay.
  71287. * @this {ol.Map}
  71288. */
  71289. function(overlay) {
  71290. overlay.setMap(this);
  71291. }, this);
  71292. goog.events.listen(this.overlays_, ol.CollectionEventType.ADD,
  71293. /**
  71294. * @param {ol.CollectionEvent} event Collection event.
  71295. */
  71296. function(event) {
  71297. event.element.setMap(this);
  71298. }, false, this);
  71299. goog.events.listen(this.overlays_, ol.CollectionEventType.REMOVE,
  71300. /**
  71301. * @param {ol.CollectionEvent} event Collection event.
  71302. */
  71303. function(event) {
  71304. event.element.setMap(null);
  71305. }, false, this);
  71306. };
  71307. goog.inherits(ol.Map, ol.Object);
  71308. /**
  71309. * Add the given control to the map.
  71310. * @param {ol.control.Control} control Control.
  71311. * @api stable
  71312. */
  71313. ol.Map.prototype.addControl = function(control) {
  71314. var controls = this.getControls();
  71315. goog.asserts.assert(controls !== undefined, 'controls should be defined');
  71316. controls.push(control);
  71317. };
  71318. /**
  71319. * Add the given interaction to the map.
  71320. * @param {ol.interaction.Interaction} interaction Interaction to add.
  71321. * @api stable
  71322. */
  71323. ol.Map.prototype.addInteraction = function(interaction) {
  71324. var interactions = this.getInteractions();
  71325. goog.asserts.assert(interactions !== undefined,
  71326. 'interactions should be defined');
  71327. interactions.push(interaction);
  71328. };
  71329. /**
  71330. * Adds the given layer to the top of this map. If you want to add a layer
  71331. * elsewhere in the stack, use `getLayers()` and the methods available on
  71332. * {@link ol.Collection}.
  71333. * @param {ol.layer.Base} layer Layer.
  71334. * @api stable
  71335. */
  71336. ol.Map.prototype.addLayer = function(layer) {
  71337. var layers = this.getLayerGroup().getLayers();
  71338. layers.push(layer);
  71339. };
  71340. /**
  71341. * Add the given overlay to the map.
  71342. * @param {ol.Overlay} overlay Overlay.
  71343. * @api stable
  71344. */
  71345. ol.Map.prototype.addOverlay = function(overlay) {
  71346. var overlays = this.getOverlays();
  71347. goog.asserts.assert(overlays !== undefined, 'overlays should be defined');
  71348. overlays.push(overlay);
  71349. };
  71350. /**
  71351. * Add functions to be called before rendering. This can be used for attaching
  71352. * animations before updating the map's view. The {@link ol.animation}
  71353. * namespace provides several static methods for creating prerender functions.
  71354. * @param {...ol.PreRenderFunction} var_args Any number of pre-render functions.
  71355. * @api
  71356. */
  71357. ol.Map.prototype.beforeRender = function(var_args) {
  71358. this.render();
  71359. Array.prototype.push.apply(this.preRenderFunctions_, arguments);
  71360. };
  71361. /**
  71362. * @param {ol.PreRenderFunction} preRenderFunction Pre-render function.
  71363. * @return {boolean} Whether the preRenderFunction has been found and removed.
  71364. */
  71365. ol.Map.prototype.removePreRenderFunction = function(preRenderFunction) {
  71366. return goog.array.remove(this.preRenderFunctions_, preRenderFunction);
  71367. };
  71368. /**
  71369. *
  71370. * @inheritDoc
  71371. */
  71372. ol.Map.prototype.disposeInternal = function() {
  71373. goog.dom.removeNode(this.viewport_);
  71374. goog.base(this, 'disposeInternal');
  71375. };
  71376. /**
  71377. * Detect features that intersect a pixel on the viewport, and execute a
  71378. * callback with each intersecting feature. Layers included in the detection can
  71379. * be configured through `opt_layerFilter`.
  71380. * @param {ol.Pixel} pixel Pixel.
  71381. * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
  71382. * callback. The callback will be called with two arguments. The first
  71383. * argument is one {@link ol.Feature feature} at the pixel, the second is
  71384. * the {@link ol.layer.Layer layer} of the feature. To stop detection,
  71385. * callback functions can return a truthy value.
  71386. * @param {S=} opt_this Value to use as `this` when executing `callback`.
  71387. * @param {(function(this: U, ol.layer.Layer): boolean)=} opt_layerFilter Layer
  71388. * filter function. The filter function will receive one argument, the
  71389. * {@link ol.layer.Layer layer-candidate} and it should return a boolean
  71390. * value. Only layers which are visible and for which this function returns
  71391. * `true` will be tested for features. By default, all visible layers will
  71392. * be tested.
  71393. * @param {U=} opt_this2 Value to use as `this` when executing `layerFilter`.
  71394. * @return {T|undefined} Callback result, i.e. the return value of last
  71395. * callback execution, or the first truthy callback return value.
  71396. * @template S,T,U
  71397. * @api stable
  71398. */
  71399. ol.Map.prototype.forEachFeatureAtPixel =
  71400. function(pixel, callback, opt_this, opt_layerFilter, opt_this2) {
  71401. if (!this.frameState_) {
  71402. return;
  71403. }
  71404. var coordinate = this.getCoordinateFromPixel(pixel);
  71405. var thisArg = opt_this !== undefined ? opt_this : null;
  71406. var layerFilter = opt_layerFilter !== undefined ?
  71407. opt_layerFilter : goog.functions.TRUE;
  71408. var thisArg2 = opt_this2 !== undefined ? opt_this2 : null;
  71409. return this.renderer_.forEachFeatureAtCoordinate(
  71410. coordinate, this.frameState_, callback, thisArg,
  71411. layerFilter, thisArg2);
  71412. };
  71413. /**
  71414. * Detect layers that have a color value at a pixel on the viewport, and
  71415. * execute a callback with each matching layer. Layers included in the
  71416. * detection can be configured through `opt_layerFilter`.
  71417. * @param {ol.Pixel} pixel Pixel.
  71418. * @param {function(this: S, ol.layer.Layer): T} callback Layer
  71419. * callback. Will receive one argument, the {@link ol.layer.Layer layer}
  71420. * that contains the color pixel. To stop detection, callback functions can
  71421. * return a truthy value.
  71422. * @param {S=} opt_this Value to use as `this` when executing `callback`.
  71423. * @param {(function(this: U, ol.layer.Layer): boolean)=} opt_layerFilter Layer
  71424. * filter function. The filter function will receive one argument, the
  71425. * {@link ol.layer.Layer layer-candidate} and it should return a boolean
  71426. * value. Only layers which are visible and for which this function returns
  71427. * `true` will be tested for features. By default, all visible layers will
  71428. * be tested.
  71429. * @param {U=} opt_this2 Value to use as `this` when executing `layerFilter`.
  71430. * @return {T|undefined} Callback result, i.e. the return value of last
  71431. * callback execution, or the first truthy callback return value.
  71432. * @template S,T,U
  71433. * @api stable
  71434. */
  71435. ol.Map.prototype.forEachLayerAtPixel =
  71436. function(pixel, callback, opt_this, opt_layerFilter, opt_this2) {
  71437. if (!this.frameState_) {
  71438. return;
  71439. }
  71440. var thisArg = opt_this !== undefined ? opt_this : null;
  71441. var layerFilter = opt_layerFilter !== undefined ?
  71442. opt_layerFilter : goog.functions.TRUE;
  71443. var thisArg2 = opt_this2 !== undefined ? opt_this2 : null;
  71444. return this.renderer_.forEachLayerAtPixel(
  71445. pixel, this.frameState_, callback, thisArg,
  71446. layerFilter, thisArg2);
  71447. };
  71448. /**
  71449. * Detect if features intersect a pixel on the viewport. Layers included in the
  71450. * detection can be configured through `opt_layerFilter`.
  71451. * @param {ol.Pixel} pixel Pixel.
  71452. * @param {(function(this: U, ol.layer.Layer): boolean)=} opt_layerFilter Layer
  71453. * filter function. The filter function will receive one argument, the
  71454. * {@link ol.layer.Layer layer-candidate} and it should return a boolean
  71455. * value. Only layers which are visible and for which this function returns
  71456. * `true` will be tested for features. By default, all visible layers will
  71457. * be tested.
  71458. * @param {U=} opt_this Value to use as `this` when executing `layerFilter`.
  71459. * @return {boolean} Is there a feature at the given pixel?
  71460. * @template U
  71461. * @api
  71462. */
  71463. ol.Map.prototype.hasFeatureAtPixel =
  71464. function(pixel, opt_layerFilter, opt_this) {
  71465. if (!this.frameState_) {
  71466. return false;
  71467. }
  71468. var coordinate = this.getCoordinateFromPixel(pixel);
  71469. var layerFilter = opt_layerFilter !== undefined ?
  71470. opt_layerFilter : goog.functions.TRUE;
  71471. var thisArg = opt_this !== undefined ? opt_this : null;
  71472. return this.renderer_.hasFeatureAtCoordinate(
  71473. coordinate, this.frameState_, layerFilter, thisArg);
  71474. };
  71475. /**
  71476. * Returns the geographical coordinate for a browser event.
  71477. * @param {Event} event Event.
  71478. * @return {ol.Coordinate} Coordinate.
  71479. * @api stable
  71480. */
  71481. ol.Map.prototype.getEventCoordinate = function(event) {
  71482. return this.getCoordinateFromPixel(this.getEventPixel(event));
  71483. };
  71484. /**
  71485. * Returns the map pixel position for a browser event relative to the viewport.
  71486. * @param {Event} event Event.
  71487. * @return {ol.Pixel} Pixel.
  71488. * @api stable
  71489. */
  71490. ol.Map.prototype.getEventPixel = function(event) {
  71491. var eventPosition = goog.style.getRelativePosition(event, this.viewport_);
  71492. return [eventPosition.x, eventPosition.y];
  71493. };
  71494. /**
  71495. * Get the target in which this map is rendered.
  71496. * Note that this returns what is entered as an option or in setTarget:
  71497. * if that was an element, it returns an element; if a string, it returns that.
  71498. * @return {Element|string|undefined} The Element or id of the Element that the
  71499. * map is rendered in.
  71500. * @observable
  71501. * @api stable
  71502. */
  71503. ol.Map.prototype.getTarget = function() {
  71504. return /** @type {Element|string|undefined} */ (
  71505. this.get(ol.MapProperty.TARGET));
  71506. };
  71507. /**
  71508. * Get the DOM element into which this map is rendered. In contrast to
  71509. * `getTarget` this method always return an `Element`, or `null` if the
  71510. * map has no target.
  71511. * @return {Element} The element that the map is rendered in.
  71512. * @api
  71513. */
  71514. ol.Map.prototype.getTargetElement = function() {
  71515. var target = this.getTarget();
  71516. return target !== undefined ? goog.dom.getElement(target) : null;
  71517. };
  71518. /**
  71519. * Get the coordinate for a given pixel. This returns a coordinate in the
  71520. * map view projection.
  71521. * @param {ol.Pixel} pixel Pixel position in the map viewport.
  71522. * @return {ol.Coordinate} The coordinate for the pixel position.
  71523. * @api stable
  71524. */
  71525. ol.Map.prototype.getCoordinateFromPixel = function(pixel) {
  71526. var frameState = this.frameState_;
  71527. if (!frameState) {
  71528. return null;
  71529. } else {
  71530. var vec2 = pixel.slice();
  71531. return ol.vec.Mat4.multVec2(frameState.pixelToCoordinateMatrix, vec2, vec2);
  71532. }
  71533. };
  71534. /**
  71535. * Get the map controls. Modifying this collection changes the controls
  71536. * associated with the map.
  71537. * @return {ol.Collection.<ol.control.Control>} Controls.
  71538. * @api stable
  71539. */
  71540. ol.Map.prototype.getControls = function() {
  71541. return this.controls_;
  71542. };
  71543. /**
  71544. * Get the map overlays. Modifying this collection changes the overlays
  71545. * associated with the map.
  71546. * @return {ol.Collection.<ol.Overlay>} Overlays.
  71547. * @api stable
  71548. */
  71549. ol.Map.prototype.getOverlays = function() {
  71550. return this.overlays_;
  71551. };
  71552. /**
  71553. * Get the map interactions. Modifying this collection changes the interactions
  71554. * associated with the map.
  71555. *
  71556. * Interactions are used for e.g. pan, zoom and rotate.
  71557. * @return {ol.Collection.<ol.interaction.Interaction>} Interactions.
  71558. * @api stable
  71559. */
  71560. ol.Map.prototype.getInteractions = function() {
  71561. return this.interactions_;
  71562. };
  71563. /**
  71564. * Get the layergroup associated with this map.
  71565. * @return {ol.layer.Group} A layer group containing the layers in this map.
  71566. * @observable
  71567. * @api stable
  71568. */
  71569. ol.Map.prototype.getLayerGroup = function() {
  71570. return /** @type {ol.layer.Group} */ (this.get(ol.MapProperty.LAYERGROUP));
  71571. };
  71572. /**
  71573. * Get the collection of layers associated with this map.
  71574. * @return {!ol.Collection.<ol.layer.Base>} Layers.
  71575. * @api stable
  71576. */
  71577. ol.Map.prototype.getLayers = function() {
  71578. var layers = this.getLayerGroup().getLayers();
  71579. return layers;
  71580. };
  71581. /**
  71582. * Get the pixel for a coordinate. This takes a coordinate in the map view
  71583. * projection and returns the corresponding pixel.
  71584. * @param {ol.Coordinate} coordinate A map coordinate.
  71585. * @return {ol.Pixel} A pixel position in the map viewport.
  71586. * @api stable
  71587. */
  71588. ol.Map.prototype.getPixelFromCoordinate = function(coordinate) {
  71589. var frameState = this.frameState_;
  71590. if (!frameState) {
  71591. return null;
  71592. } else {
  71593. var vec2 = coordinate.slice(0, 2);
  71594. return ol.vec.Mat4.multVec2(frameState.coordinateToPixelMatrix, vec2, vec2);
  71595. }
  71596. };
  71597. /**
  71598. * Get the map renderer.
  71599. * @return {ol.renderer.Map} Renderer
  71600. */
  71601. ol.Map.prototype.getRenderer = function() {
  71602. return this.renderer_;
  71603. };
  71604. /**
  71605. * Get the size of this map.
  71606. * @return {ol.Size|undefined} The size in pixels of the map in the DOM.
  71607. * @observable
  71608. * @api stable
  71609. */
  71610. ol.Map.prototype.getSize = function() {
  71611. return /** @type {ol.Size|undefined} */ (this.get(ol.MapProperty.SIZE));
  71612. };
  71613. /**
  71614. * Get the view associated with this map. A view manages properties such as
  71615. * center and resolution.
  71616. * @return {ol.View} The view that controls this map.
  71617. * @observable
  71618. * @api stable
  71619. */
  71620. ol.Map.prototype.getView = function() {
  71621. return /** @type {ol.View} */ (this.get(ol.MapProperty.VIEW));
  71622. };
  71623. /**
  71624. * Get the element that serves as the map viewport.
  71625. * @return {Element} Viewport.
  71626. * @api stable
  71627. */
  71628. ol.Map.prototype.getViewport = function() {
  71629. return this.viewport_;
  71630. };
  71631. /**
  71632. * Get the element that serves as the container for overlays. Elements added to
  71633. * this container will let mousedown and touchstart events through to the map,
  71634. * so clicks and gestures on an overlay will trigger {@link ol.MapBrowserEvent}
  71635. * events.
  71636. * @return {Element} The map's overlay container.
  71637. */
  71638. ol.Map.prototype.getOverlayContainer = function() {
  71639. return this.overlayContainer_;
  71640. };
  71641. /**
  71642. * Get the element that serves as a container for overlays that don't allow
  71643. * event propagation. Elements added to this container won't let mousedown and
  71644. * touchstart events through to the map, so clicks and gestures on an overlay
  71645. * don't trigger any {@link ol.MapBrowserEvent}.
  71646. * @return {Element} The map's overlay container that stops events.
  71647. */
  71648. ol.Map.prototype.getOverlayContainerStopEvent = function() {
  71649. return this.overlayContainerStopEvent_;
  71650. };
  71651. /**
  71652. * @param {ol.Tile} tile Tile.
  71653. * @param {string} tileSourceKey Tile source key.
  71654. * @param {ol.Coordinate} tileCenter Tile center.
  71655. * @param {number} tileResolution Tile resolution.
  71656. * @return {number} Tile priority.
  71657. */
  71658. ol.Map.prototype.getTilePriority =
  71659. function(tile, tileSourceKey, tileCenter, tileResolution) {
  71660. // Filter out tiles at higher zoom levels than the current zoom level, or that
  71661. // are outside the visible extent.
  71662. var frameState = this.frameState_;
  71663. if (!frameState || !(tileSourceKey in frameState.wantedTiles)) {
  71664. return ol.structs.PriorityQueue.DROP;
  71665. }
  71666. var coordKey = ol.tilecoord.toString(tile.tileCoord);
  71667. if (!frameState.wantedTiles[tileSourceKey][coordKey]) {
  71668. return ol.structs.PriorityQueue.DROP;
  71669. }
  71670. // Prioritize the highest zoom level tiles closest to the focus.
  71671. // Tiles at higher zoom levels are prioritized using Math.log(tileResolution).
  71672. // Within a zoom level, tiles are prioritized by the distance in pixels
  71673. // between the center of the tile and the focus. The factor of 65536 means
  71674. // that the prioritization should behave as desired for tiles up to
  71675. // 65536 * Math.log(2) = 45426 pixels from the focus.
  71676. var deltaX = tileCenter[0] - frameState.focus[0];
  71677. var deltaY = tileCenter[1] - frameState.focus[1];
  71678. return 65536 * Math.log(tileResolution) +
  71679. Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution;
  71680. };
  71681. /**
  71682. * @param {goog.events.BrowserEvent} browserEvent Browser event.
  71683. * @param {string=} opt_type Type.
  71684. */
  71685. ol.Map.prototype.handleBrowserEvent = function(browserEvent, opt_type) {
  71686. var type = opt_type || browserEvent.type;
  71687. var mapBrowserEvent = new ol.MapBrowserEvent(type, this, browserEvent);
  71688. this.handleMapBrowserEvent(mapBrowserEvent);
  71689. };
  71690. /**
  71691. * @param {ol.MapBrowserEvent} mapBrowserEvent The event to handle.
  71692. */
  71693. ol.Map.prototype.handleMapBrowserEvent = function(mapBrowserEvent) {
  71694. if (!this.frameState_) {
  71695. // With no view defined, we cannot translate pixels into geographical
  71696. // coordinates so interactions cannot be used.
  71697. return;
  71698. }
  71699. this.focus_ = mapBrowserEvent.coordinate;
  71700. mapBrowserEvent.frameState = this.frameState_;
  71701. var interactions = this.getInteractions();
  71702. goog.asserts.assert(interactions !== undefined,
  71703. 'interactions should be defined');
  71704. var interactionsArray = interactions.getArray();
  71705. var i;
  71706. if (this.dispatchEvent(mapBrowserEvent) !== false) {
  71707. for (i = interactionsArray.length - 1; i >= 0; i--) {
  71708. var interaction = interactionsArray[i];
  71709. if (!interaction.getActive()) {
  71710. continue;
  71711. }
  71712. var cont = interaction.handleEvent(mapBrowserEvent);
  71713. if (!cont) {
  71714. break;
  71715. }
  71716. }
  71717. }
  71718. };
  71719. /**
  71720. * @protected
  71721. */
  71722. ol.Map.prototype.handlePostRender = function() {
  71723. var frameState = this.frameState_;
  71724. // Manage the tile queue
  71725. // Image loads are expensive and a limited resource, so try to use them
  71726. // efficiently:
  71727. // * When the view is static we allow a large number of parallel tile loads
  71728. // to complete the frame as quickly as possible.
  71729. // * When animating or interacting, image loads can cause janks, so we reduce
  71730. // the maximum number of loads per frame and limit the number of parallel
  71731. // tile loads to remain reactive to view changes and to reduce the chance of
  71732. // loading tiles that will quickly disappear from view.
  71733. var tileQueue = this.tileQueue_;
  71734. if (!tileQueue.isEmpty()) {
  71735. var maxTotalLoading = 16;
  71736. var maxNewLoads = maxTotalLoading;
  71737. var tileSourceCount = 0;
  71738. if (frameState) {
  71739. var hints = frameState.viewHints;
  71740. if (hints[ol.ViewHint.ANIMATING]) {
  71741. maxTotalLoading = this.loadTilesWhileAnimating_ ? 8 : 0;
  71742. maxNewLoads = 2;
  71743. }
  71744. if (hints[ol.ViewHint.INTERACTING]) {
  71745. maxTotalLoading = this.loadTilesWhileInteracting_ ? 8 : 0;
  71746. maxNewLoads = 2;
  71747. }
  71748. tileSourceCount = goog.object.getCount(frameState.wantedTiles);
  71749. }
  71750. maxTotalLoading *= tileSourceCount;
  71751. maxNewLoads *= tileSourceCount;
  71752. if (tileQueue.getTilesLoading() < maxTotalLoading) {
  71753. tileQueue.reprioritize(); // FIXME only call if view has changed
  71754. tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads);
  71755. }
  71756. }
  71757. var postRenderFunctions = this.postRenderFunctions_;
  71758. var i, ii;
  71759. for (i = 0, ii = postRenderFunctions.length; i < ii; ++i) {
  71760. postRenderFunctions[i](this, frameState);
  71761. }
  71762. postRenderFunctions.length = 0;
  71763. };
  71764. /**
  71765. * @private
  71766. */
  71767. ol.Map.prototype.handleSizeChanged_ = function() {
  71768. this.render();
  71769. };
  71770. /**
  71771. * @private
  71772. */
  71773. ol.Map.prototype.handleTargetChanged_ = function() {
  71774. // target may be undefined, null, a string or an Element.
  71775. // If it's a string we convert it to an Element before proceeding.
  71776. // If it's not now an Element we remove the viewport from the DOM.
  71777. // If it's an Element we append the viewport element to it.
  71778. var targetElement = this.getTargetElement();
  71779. this.keyHandler_.detach();
  71780. if (!targetElement) {
  71781. goog.dom.removeNode(this.viewport_);
  71782. if (this.viewportResizeListenerKey_) {
  71783. goog.events.unlistenByKey(this.viewportResizeListenerKey_);
  71784. this.viewportResizeListenerKey_ = null;
  71785. }
  71786. } else {
  71787. targetElement.appendChild(this.viewport_);
  71788. var keyboardEventTarget = !this.keyboardEventTarget_ ?
  71789. targetElement : this.keyboardEventTarget_;
  71790. this.keyHandler_.attach(keyboardEventTarget);
  71791. if (!this.viewportResizeListenerKey_) {
  71792. this.viewportResizeListenerKey_ = goog.events.listen(
  71793. this.viewportSizeMonitor_, goog.events.EventType.RESIZE,
  71794. this.updateSize, false, this);
  71795. }
  71796. }
  71797. this.updateSize();
  71798. // updateSize calls setSize, so no need to call this.render
  71799. // ourselves here.
  71800. };
  71801. /**
  71802. * @private
  71803. */
  71804. ol.Map.prototype.handleTileChange_ = function() {
  71805. this.render();
  71806. };
  71807. /**
  71808. * @private
  71809. */
  71810. ol.Map.prototype.handleViewPropertyChanged_ = function() {
  71811. this.render();
  71812. };
  71813. /**
  71814. * @private
  71815. */
  71816. ol.Map.prototype.handleViewChanged_ = function() {
  71817. if (this.viewPropertyListenerKey_) {
  71818. goog.events.unlistenByKey(this.viewPropertyListenerKey_);
  71819. this.viewPropertyListenerKey_ = null;
  71820. }
  71821. var view = this.getView();
  71822. if (view) {
  71823. this.viewPropertyListenerKey_ = goog.events.listen(
  71824. view, ol.ObjectEventType.PROPERTYCHANGE,
  71825. this.handleViewPropertyChanged_, false, this);
  71826. }
  71827. this.render();
  71828. };
  71829. /**
  71830. * @param {goog.events.Event} event Event.
  71831. * @private
  71832. */
  71833. ol.Map.prototype.handleLayerGroupMemberChanged_ = function(event) {
  71834. goog.asserts.assertInstanceof(event, goog.events.Event,
  71835. 'event should be an Event');
  71836. this.render();
  71837. };
  71838. /**
  71839. * @param {ol.ObjectEvent} event Event.
  71840. * @private
  71841. */
  71842. ol.Map.prototype.handleLayerGroupPropertyChanged_ = function(event) {
  71843. goog.asserts.assertInstanceof(event, ol.ObjectEvent,
  71844. 'event should be an ol.ObjectEvent');
  71845. this.render();
  71846. };
  71847. /**
  71848. * @private
  71849. */
  71850. ol.Map.prototype.handleLayerGroupChanged_ = function() {
  71851. if (this.layerGroupPropertyListenerKeys_) {
  71852. this.layerGroupPropertyListenerKeys_.forEach(goog.events.unlistenByKey);
  71853. this.layerGroupPropertyListenerKeys_ = null;
  71854. }
  71855. var layerGroup = this.getLayerGroup();
  71856. if (layerGroup) {
  71857. this.layerGroupPropertyListenerKeys_ = [
  71858. goog.events.listen(
  71859. layerGroup, ol.ObjectEventType.PROPERTYCHANGE,
  71860. this.handleLayerGroupPropertyChanged_, false, this),
  71861. goog.events.listen(
  71862. layerGroup, goog.events.EventType.CHANGE,
  71863. this.handleLayerGroupMemberChanged_, false, this)
  71864. ];
  71865. }
  71866. this.render();
  71867. };
  71868. /**
  71869. * Returns `true` if the map is defined, `false` otherwise. The map is defined
  71870. * if it is contained in `document`, visible, has non-zero height and width, and
  71871. * has a defined view.
  71872. * @return {boolean} Is defined.
  71873. */
  71874. ol.Map.prototype.isDef = function() {
  71875. if (!goog.dom.contains(document, this.viewport_)) {
  71876. return false;
  71877. }
  71878. if (!goog.style.isElementShown(this.viewport_)) {
  71879. return false;
  71880. }
  71881. var size = this.getSize();
  71882. if (!size || size[0] <= 0 || size[1] <= 0) {
  71883. return false;
  71884. }
  71885. var view = this.getView();
  71886. if (!view || !view.isDef()) {
  71887. return false;
  71888. }
  71889. return true;
  71890. };
  71891. /**
  71892. * @return {boolean} Is rendered.
  71893. */
  71894. ol.Map.prototype.isRendered = function() {
  71895. return !!this.frameState_;
  71896. };
  71897. /**
  71898. * Requests an immediate render in a synchronous manner.
  71899. * @api stable
  71900. */
  71901. ol.Map.prototype.renderSync = function() {
  71902. this.animationDelay_.fire();
  71903. };
  71904. /**
  71905. * Request a map rendering (at the next animation frame).
  71906. * @api stable
  71907. */
  71908. ol.Map.prototype.render = function() {
  71909. if (!this.animationDelay_.isActive()) {
  71910. this.animationDelay_.start();
  71911. }
  71912. };
  71913. /**
  71914. * Remove the given control from the map.
  71915. * @param {ol.control.Control} control Control.
  71916. * @return {ol.control.Control|undefined} The removed control (or undefined
  71917. * if the control was not found).
  71918. * @api stable
  71919. */
  71920. ol.Map.prototype.removeControl = function(control) {
  71921. var controls = this.getControls();
  71922. goog.asserts.assert(controls !== undefined, 'controls should be defined');
  71923. return controls.remove(control);
  71924. };
  71925. /**
  71926. * Remove the given interaction from the map.
  71927. * @param {ol.interaction.Interaction} interaction Interaction to remove.
  71928. * @return {ol.interaction.Interaction|undefined} The removed interaction (or
  71929. * undefined if the interaction was not found).
  71930. * @api stable
  71931. */
  71932. ol.Map.prototype.removeInteraction = function(interaction) {
  71933. var interactions = this.getInteractions();
  71934. goog.asserts.assert(interactions !== undefined,
  71935. 'interactions should be defined');
  71936. return interactions.remove(interaction);
  71937. };
  71938. /**
  71939. * Removes the given layer from the map.
  71940. * @param {ol.layer.Base} layer Layer.
  71941. * @return {ol.layer.Base|undefined} The removed layer (or undefined if the
  71942. * layer was not found).
  71943. * @api stable
  71944. */
  71945. ol.Map.prototype.removeLayer = function(layer) {
  71946. var layers = this.getLayerGroup().getLayers();
  71947. return layers.remove(layer);
  71948. };
  71949. /**
  71950. * Remove the given overlay from the map.
  71951. * @param {ol.Overlay} overlay Overlay.
  71952. * @return {ol.Overlay|undefined} The removed overlay (or undefined
  71953. * if the overlay was not found).
  71954. * @api stable
  71955. */
  71956. ol.Map.prototype.removeOverlay = function(overlay) {
  71957. var overlays = this.getOverlays();
  71958. goog.asserts.assert(overlays !== undefined, 'overlays should be defined');
  71959. return overlays.remove(overlay);
  71960. };
  71961. /**
  71962. * @param {number} time Time.
  71963. * @private
  71964. */
  71965. ol.Map.prototype.renderFrame_ = function(time) {
  71966. var i, ii, viewState;
  71967. var size = this.getSize();
  71968. var view = this.getView();
  71969. /** @type {?olx.FrameState} */
  71970. var frameState = null;
  71971. if (size !== undefined && ol.size.hasArea(size) &&
  71972. view && view.isDef()) {
  71973. var viewHints = view.getHints();
  71974. var layerStatesArray = this.getLayerGroup().getLayerStatesArray();
  71975. var layerStates = {};
  71976. for (i = 0, ii = layerStatesArray.length; i < ii; ++i) {
  71977. layerStates[goog.getUid(layerStatesArray[i].layer)] = layerStatesArray[i];
  71978. }
  71979. viewState = view.getState();
  71980. frameState = /** @type {olx.FrameState} */ ({
  71981. animate: false,
  71982. attributions: {},
  71983. coordinateToPixelMatrix: this.coordinateToPixelMatrix_,
  71984. extent: null,
  71985. focus: !this.focus_ ? viewState.center : this.focus_,
  71986. index: this.frameIndex_++,
  71987. layerStates: layerStates,
  71988. layerStatesArray: layerStatesArray,
  71989. logos: goog.object.clone(this.logos_),
  71990. pixelRatio: this.pixelRatio_,
  71991. pixelToCoordinateMatrix: this.pixelToCoordinateMatrix_,
  71992. postRenderFunctions: [],
  71993. size: size,
  71994. skippedFeatureUids: this.skippedFeatureUids_,
  71995. tileQueue: this.tileQueue_,
  71996. time: time,
  71997. usedTiles: {},
  71998. viewState: viewState,
  71999. viewHints: viewHints,
  72000. wantedTiles: {}
  72001. });
  72002. }
  72003. if (frameState) {
  72004. var preRenderFunctions = this.preRenderFunctions_;
  72005. var n = 0, preRenderFunction;
  72006. for (i = 0, ii = preRenderFunctions.length; i < ii; ++i) {
  72007. preRenderFunction = preRenderFunctions[i];
  72008. if (preRenderFunction(this, frameState)) {
  72009. preRenderFunctions[n++] = preRenderFunction;
  72010. }
  72011. }
  72012. preRenderFunctions.length = n;
  72013. frameState.extent = ol.extent.getForViewAndSize(viewState.center,
  72014. viewState.resolution, viewState.rotation, frameState.size);
  72015. }
  72016. this.frameState_ = frameState;
  72017. this.renderer_.renderFrame(frameState);
  72018. if (frameState) {
  72019. if (frameState.animate) {
  72020. this.render();
  72021. }
  72022. Array.prototype.push.apply(
  72023. this.postRenderFunctions_, frameState.postRenderFunctions);
  72024. var idle = this.preRenderFunctions_.length === 0 &&
  72025. !frameState.viewHints[ol.ViewHint.ANIMATING] &&
  72026. !frameState.viewHints[ol.ViewHint.INTERACTING] &&
  72027. !ol.extent.equals(frameState.extent, this.previousExtent_);
  72028. if (idle) {
  72029. this.dispatchEvent(
  72030. new ol.MapEvent(ol.MapEventType.MOVEEND, this, frameState));
  72031. ol.extent.clone(frameState.extent, this.previousExtent_);
  72032. }
  72033. }
  72034. this.dispatchEvent(
  72035. new ol.MapEvent(ol.MapEventType.POSTRENDER, this, frameState));
  72036. goog.async.nextTick(this.handlePostRender, this);
  72037. };
  72038. /**
  72039. * Sets the layergroup of this map.
  72040. * @param {ol.layer.Group} layerGroup A layer group containing the layers in
  72041. * this map.
  72042. * @observable
  72043. * @api stable
  72044. */
  72045. ol.Map.prototype.setLayerGroup = function(layerGroup) {
  72046. this.set(ol.MapProperty.LAYERGROUP, layerGroup);
  72047. };
  72048. /**
  72049. * Set the size of this map.
  72050. * @param {ol.Size|undefined} size The size in pixels of the map in the DOM.
  72051. * @observable
  72052. * @api
  72053. */
  72054. ol.Map.prototype.setSize = function(size) {
  72055. this.set(ol.MapProperty.SIZE, size);
  72056. };
  72057. /**
  72058. * Set the target element to render this map into.
  72059. * @param {Element|string|undefined} target The Element or id of the Element
  72060. * that the map is rendered in.
  72061. * @observable
  72062. * @api stable
  72063. */
  72064. ol.Map.prototype.setTarget = function(target) {
  72065. this.set(ol.MapProperty.TARGET, target);
  72066. };
  72067. /**
  72068. * Set the view for this map.
  72069. * @param {ol.View} view The view that controls this map.
  72070. * @observable
  72071. * @api stable
  72072. */
  72073. ol.Map.prototype.setView = function(view) {
  72074. this.set(ol.MapProperty.VIEW, view);
  72075. };
  72076. /**
  72077. * @param {ol.Feature} feature Feature.
  72078. */
  72079. ol.Map.prototype.skipFeature = function(feature) {
  72080. var featureUid = goog.getUid(feature).toString();
  72081. this.skippedFeatureUids_[featureUid] = true;
  72082. this.render();
  72083. };
  72084. /**
  72085. * Force a recalculation of the map viewport size. This should be called when
  72086. * third-party code changes the size of the map viewport.
  72087. * @api stable
  72088. */
  72089. ol.Map.prototype.updateSize = function() {
  72090. var targetElement = this.getTargetElement();
  72091. if (!targetElement) {
  72092. this.setSize(undefined);
  72093. } else {
  72094. var size = goog.style.getContentBoxSize(targetElement);
  72095. this.setSize([size.width, size.height]);
  72096. }
  72097. };
  72098. /**
  72099. * @param {ol.Feature} feature Feature.
  72100. */
  72101. ol.Map.prototype.unskipFeature = function(feature) {
  72102. var featureUid = goog.getUid(feature).toString();
  72103. delete this.skippedFeatureUids_[featureUid];
  72104. this.render();
  72105. };
  72106. /**
  72107. * @typedef {{controls: ol.Collection.<ol.control.Control>,
  72108. * interactions: ol.Collection.<ol.interaction.Interaction>,
  72109. * keyboardEventTarget: (Element|Document),
  72110. * logos: Object.<string, string>,
  72111. * overlays: ol.Collection.<ol.Overlay>,
  72112. * rendererConstructor:
  72113. * function(new: ol.renderer.Map, Element, ol.Map),
  72114. * values: Object.<string, *>}}
  72115. */
  72116. ol.MapOptionsInternal;
  72117. /**
  72118. * @param {olx.MapOptions} options Map options.
  72119. * @return {ol.MapOptionsInternal} Internal map options.
  72120. */
  72121. ol.Map.createOptionsInternal = function(options) {
  72122. /**
  72123. * @type {Element|Document}
  72124. */
  72125. var keyboardEventTarget = null;
  72126. if (options.keyboardEventTarget !== undefined) {
  72127. // cannot use goog.dom.getElement because its argument cannot be
  72128. // of type Document
  72129. keyboardEventTarget = goog.isString(options.keyboardEventTarget) ?
  72130. document.getElementById(options.keyboardEventTarget) :
  72131. options.keyboardEventTarget;
  72132. }
  72133. /**
  72134. * @type {Object.<string, *>}
  72135. */
  72136. var values = {};
  72137. var logos = {};
  72138. if (options.logo === undefined ||
  72139. (goog.isBoolean(options.logo) && options.logo)) {
  72140. logos[ol.OL3_LOGO_URL] = ol.OL3_URL;
  72141. } else {
  72142. var logo = options.logo;
  72143. if (goog.isString(logo)) {
  72144. logos[logo] = '';
  72145. } else if (goog.isObject(logo)) {
  72146. goog.asserts.assertString(logo.href, 'logo.href should be a string');
  72147. goog.asserts.assertString(logo.src, 'logo.src should be a string');
  72148. logos[logo.src] = logo.href;
  72149. }
  72150. }
  72151. var layerGroup = (options.layers instanceof ol.layer.Group) ?
  72152. options.layers : new ol.layer.Group({layers: options.layers});
  72153. values[ol.MapProperty.LAYERGROUP] = layerGroup;
  72154. values[ol.MapProperty.TARGET] = options.target;
  72155. values[ol.MapProperty.VIEW] = options.view !== undefined ?
  72156. options.view : new ol.View();
  72157. /**
  72158. * @type {function(new: ol.renderer.Map, Element, ol.Map)}
  72159. */
  72160. var rendererConstructor = ol.renderer.Map;
  72161. /**
  72162. * @type {Array.<ol.RendererType>}
  72163. */
  72164. var rendererTypes;
  72165. if (options.renderer !== undefined) {
  72166. if (goog.isArray(options.renderer)) {
  72167. rendererTypes = options.renderer;
  72168. } else if (goog.isString(options.renderer)) {
  72169. rendererTypes = [options.renderer];
  72170. } else {
  72171. goog.asserts.fail('Incorrect format for renderer option');
  72172. }
  72173. } else {
  72174. rendererTypes = ol.DEFAULT_RENDERER_TYPES;
  72175. }
  72176. var i, ii;
  72177. for (i = 0, ii = rendererTypes.length; i < ii; ++i) {
  72178. /** @type {ol.RendererType} */
  72179. var rendererType = rendererTypes[i];
  72180. if (ol.ENABLE_CANVAS && rendererType == ol.RendererType.CANVAS) {
  72181. if (ol.has.CANVAS) {
  72182. rendererConstructor = ol.renderer.canvas.Map;
  72183. break;
  72184. }
  72185. } else if (ol.ENABLE_DOM && rendererType == ol.RendererType.DOM) {
  72186. if (ol.has.DOM) {
  72187. rendererConstructor = ol.renderer.dom.Map;
  72188. break;
  72189. }
  72190. } else if (ol.ENABLE_WEBGL && rendererType == ol.RendererType.WEBGL) {
  72191. if (ol.has.WEBGL) {
  72192. rendererConstructor = ol.renderer.webgl.Map;
  72193. break;
  72194. }
  72195. }
  72196. }
  72197. var controls;
  72198. if (options.controls !== undefined) {
  72199. if (goog.isArray(options.controls)) {
  72200. controls = new ol.Collection(options.controls.slice());
  72201. } else {
  72202. goog.asserts.assertInstanceof(options.controls, ol.Collection,
  72203. 'options.controls should be an ol.Collection');
  72204. controls = options.controls;
  72205. }
  72206. } else {
  72207. controls = ol.control.defaults();
  72208. }
  72209. var interactions;
  72210. if (options.interactions !== undefined) {
  72211. if (goog.isArray(options.interactions)) {
  72212. interactions = new ol.Collection(options.interactions.slice());
  72213. } else {
  72214. goog.asserts.assertInstanceof(options.interactions, ol.Collection,
  72215. 'options.interactions should be an ol.Collection');
  72216. interactions = options.interactions;
  72217. }
  72218. } else {
  72219. interactions = ol.interaction.defaults();
  72220. }
  72221. var overlays;
  72222. if (options.overlays !== undefined) {
  72223. if (goog.isArray(options.overlays)) {
  72224. overlays = new ol.Collection(options.overlays.slice());
  72225. } else {
  72226. goog.asserts.assertInstanceof(options.overlays, ol.Collection,
  72227. 'options.overlays should be an ol.Collection');
  72228. overlays = options.overlays;
  72229. }
  72230. } else {
  72231. overlays = new ol.Collection();
  72232. }
  72233. return {
  72234. controls: controls,
  72235. interactions: interactions,
  72236. keyboardEventTarget: keyboardEventTarget,
  72237. logos: logos,
  72238. overlays: overlays,
  72239. rendererConstructor: rendererConstructor,
  72240. values: values
  72241. };
  72242. };
  72243. ol.proj.common.add();
  72244. if (goog.DEBUG) {
  72245. (function() {
  72246. goog.debug.Console.autoInstall();
  72247. var logger = goog.log.getLogger('ol');
  72248. logger.setLevel(goog.log.Level.FINEST);
  72249. })();
  72250. }
  72251. goog.provide('ol.Overlay');
  72252. goog.provide('ol.OverlayPositioning');
  72253. goog.provide('ol.OverlayProperty');
  72254. goog.require('goog.asserts');
  72255. goog.require('goog.dom');
  72256. goog.require('goog.dom.TagName');
  72257. goog.require('goog.events');
  72258. goog.require('goog.style');
  72259. goog.require('ol.Coordinate');
  72260. goog.require('ol.Map');
  72261. goog.require('ol.MapEventType');
  72262. goog.require('ol.Object');
  72263. goog.require('ol.animation');
  72264. goog.require('ol.dom');
  72265. goog.require('ol.extent');
  72266. /**
  72267. * @enum {string}
  72268. */
  72269. ol.OverlayProperty = {
  72270. ELEMENT: 'element',
  72271. MAP: 'map',
  72272. OFFSET: 'offset',
  72273. POSITION: 'position',
  72274. POSITIONING: 'positioning'
  72275. };
  72276. /**
  72277. * Overlay position: `'bottom-left'`, `'bottom-center'`, `'bottom-right'`,
  72278. * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,
  72279. * `'top-center'`, `'top-right'`
  72280. * @enum {string}
  72281. * @api stable
  72282. */
  72283. ol.OverlayPositioning = {
  72284. BOTTOM_LEFT: 'bottom-left',
  72285. BOTTOM_CENTER: 'bottom-center',
  72286. BOTTOM_RIGHT: 'bottom-right',
  72287. CENTER_LEFT: 'center-left',
  72288. CENTER_CENTER: 'center-center',
  72289. CENTER_RIGHT: 'center-right',
  72290. TOP_LEFT: 'top-left',
  72291. TOP_CENTER: 'top-center',
  72292. TOP_RIGHT: 'top-right'
  72293. };
  72294. /**
  72295. * @classdesc
  72296. * An element to be displayed over the map and attached to a single map
  72297. * location. Like {@link ol.control.Control}, Overlays are visible widgets.
  72298. * Unlike Controls, they are not in a fixed position on the screen, but are tied
  72299. * to a geographical coordinate, so panning the map will move an Overlay but not
  72300. * a Control.
  72301. *
  72302. * Example:
  72303. *
  72304. * var popup = new ol.Overlay({
  72305. * element: document.getElementById('popup')
  72306. * });
  72307. * popup.setPosition(coordinate);
  72308. * map.addOverlay(popup);
  72309. *
  72310. * @constructor
  72311. * @extends {ol.Object}
  72312. * @param {olx.OverlayOptions} options Overlay options.
  72313. * @api stable
  72314. */
  72315. ol.Overlay = function(options) {
  72316. goog.base(this);
  72317. /**
  72318. * @private
  72319. * @type {boolean}
  72320. */
  72321. this.insertFirst_ = options.insertFirst !== undefined ?
  72322. options.insertFirst : true;
  72323. /**
  72324. * @private
  72325. * @type {boolean}
  72326. */
  72327. this.stopEvent_ = options.stopEvent !== undefined ? options.stopEvent : true;
  72328. /**
  72329. * @private
  72330. * @type {Element}
  72331. */
  72332. this.element_ = goog.dom.createDom(goog.dom.TagName.DIV, {
  72333. 'class': 'ol-overlay-container'
  72334. });
  72335. this.element_.style.position = 'absolute';
  72336. /**
  72337. * @protected
  72338. * @type {boolean}
  72339. */
  72340. this.autoPan = options.autoPan !== undefined ? options.autoPan : false;
  72341. /**
  72342. * @private
  72343. * @type {olx.animation.PanOptions}
  72344. */
  72345. this.autoPanAnimation_ = options.autoPanAnimation !== undefined ?
  72346. options.autoPanAnimation : /** @type {olx.animation.PanOptions} */ ({});
  72347. /**
  72348. * @private
  72349. * @type {number}
  72350. */
  72351. this.autoPanMargin_ = options.autoPanMargin !== undefined ?
  72352. options.autoPanMargin : 20;
  72353. /**
  72354. * @private
  72355. * @type {{bottom_: string,
  72356. * left_: string,
  72357. * right_: string,
  72358. * top_: string,
  72359. * visible: boolean}}
  72360. */
  72361. this.rendered_ = {
  72362. bottom_: '',
  72363. left_: '',
  72364. right_: '',
  72365. top_: '',
  72366. visible: true
  72367. };
  72368. /**
  72369. * @private
  72370. * @type {goog.events.Key}
  72371. */
  72372. this.mapPostrenderListenerKey_ = null;
  72373. goog.events.listen(
  72374. this, ol.Object.getChangeEventType(ol.OverlayProperty.ELEMENT),
  72375. this.handleElementChanged, false, this);
  72376. goog.events.listen(
  72377. this, ol.Object.getChangeEventType(ol.OverlayProperty.MAP),
  72378. this.handleMapChanged, false, this);
  72379. goog.events.listen(
  72380. this, ol.Object.getChangeEventType(ol.OverlayProperty.OFFSET),
  72381. this.handleOffsetChanged, false, this);
  72382. goog.events.listen(
  72383. this, ol.Object.getChangeEventType(ol.OverlayProperty.POSITION),
  72384. this.handlePositionChanged, false, this);
  72385. goog.events.listen(
  72386. this, ol.Object.getChangeEventType(ol.OverlayProperty.POSITIONING),
  72387. this.handlePositioningChanged, false, this);
  72388. if (options.element !== undefined) {
  72389. this.setElement(options.element);
  72390. }
  72391. this.setOffset(options.offset !== undefined ? options.offset : [0, 0]);
  72392. this.setPositioning(options.positioning !== undefined ?
  72393. /** @type {ol.OverlayPositioning} */ (options.positioning) :
  72394. ol.OverlayPositioning.TOP_LEFT);
  72395. if (options.position !== undefined) {
  72396. this.setPosition(options.position);
  72397. }
  72398. };
  72399. goog.inherits(ol.Overlay, ol.Object);
  72400. /**
  72401. * Get the DOM element of this overlay.
  72402. * @return {Element|undefined} The Element containing the overlay.
  72403. * @observable
  72404. * @api stable
  72405. */
  72406. ol.Overlay.prototype.getElement = function() {
  72407. return /** @type {Element|undefined} */ (
  72408. this.get(ol.OverlayProperty.ELEMENT));
  72409. };
  72410. /**
  72411. * Get the map associated with this overlay.
  72412. * @return {ol.Map|undefined} The map that the overlay is part of.
  72413. * @observable
  72414. * @api stable
  72415. */
  72416. ol.Overlay.prototype.getMap = function() {
  72417. return /** @type {ol.Map|undefined} */ (
  72418. this.get(ol.OverlayProperty.MAP));
  72419. };
  72420. /**
  72421. * Get the offset of this overlay.
  72422. * @return {Array.<number>} The offset.
  72423. * @observable
  72424. * @api stable
  72425. */
  72426. ol.Overlay.prototype.getOffset = function() {
  72427. return /** @type {Array.<number>} */ (
  72428. this.get(ol.OverlayProperty.OFFSET));
  72429. };
  72430. /**
  72431. * Get the current position of this overlay.
  72432. * @return {ol.Coordinate|undefined} The spatial point that the overlay is
  72433. * anchored at.
  72434. * @observable
  72435. * @api stable
  72436. */
  72437. ol.Overlay.prototype.getPosition = function() {
  72438. return /** @type {ol.Coordinate|undefined} */ (
  72439. this.get(ol.OverlayProperty.POSITION));
  72440. };
  72441. /**
  72442. * Get the current positioning of this overlay.
  72443. * @return {ol.OverlayPositioning} How the overlay is positioned
  72444. * relative to its point on the map.
  72445. * @observable
  72446. * @api stable
  72447. */
  72448. ol.Overlay.prototype.getPositioning = function() {
  72449. return /** @type {ol.OverlayPositioning} */ (
  72450. this.get(ol.OverlayProperty.POSITIONING));
  72451. };
  72452. /**
  72453. * @protected
  72454. */
  72455. ol.Overlay.prototype.handleElementChanged = function() {
  72456. goog.dom.removeChildren(this.element_);
  72457. var element = this.getElement();
  72458. if (element) {
  72459. goog.dom.append(/** @type {!Node} */ (this.element_), element);
  72460. }
  72461. };
  72462. /**
  72463. * @protected
  72464. */
  72465. ol.Overlay.prototype.handleMapChanged = function() {
  72466. if (this.mapPostrenderListenerKey_) {
  72467. goog.dom.removeNode(this.element_);
  72468. goog.events.unlistenByKey(this.mapPostrenderListenerKey_);
  72469. this.mapPostrenderListenerKey_ = null;
  72470. }
  72471. var map = this.getMap();
  72472. if (map) {
  72473. this.mapPostrenderListenerKey_ = goog.events.listen(map,
  72474. ol.MapEventType.POSTRENDER, this.render, false, this);
  72475. this.updatePixelPosition();
  72476. var container = this.stopEvent_ ?
  72477. map.getOverlayContainerStopEvent() : map.getOverlayContainer();
  72478. if (this.insertFirst_) {
  72479. goog.dom.insertChildAt(/** @type {!Element} */ (
  72480. container), this.element_, 0);
  72481. } else {
  72482. goog.dom.append(/** @type {!Node} */ (container), this.element_);
  72483. }
  72484. }
  72485. };
  72486. /**
  72487. * @protected
  72488. */
  72489. ol.Overlay.prototype.render = function() {
  72490. this.updatePixelPosition();
  72491. };
  72492. /**
  72493. * @protected
  72494. */
  72495. ol.Overlay.prototype.handleOffsetChanged = function() {
  72496. this.updatePixelPosition();
  72497. };
  72498. /**
  72499. * @protected
  72500. */
  72501. ol.Overlay.prototype.handlePositionChanged = function() {
  72502. this.updatePixelPosition();
  72503. if (this.get(ol.OverlayProperty.POSITION) !== undefined && this.autoPan) {
  72504. this.panIntoView_();
  72505. }
  72506. };
  72507. /**
  72508. * @protected
  72509. */
  72510. ol.Overlay.prototype.handlePositioningChanged = function() {
  72511. this.updatePixelPosition();
  72512. };
  72513. /**
  72514. * Set the DOM element to be associated with this overlay.
  72515. * @param {Element|undefined} element The Element containing the overlay.
  72516. * @observable
  72517. * @api stable
  72518. */
  72519. ol.Overlay.prototype.setElement = function(element) {
  72520. this.set(ol.OverlayProperty.ELEMENT, element);
  72521. };
  72522. /**
  72523. * Set the map to be associated with this overlay.
  72524. * @param {ol.Map|undefined} map The map that the overlay is part of.
  72525. * @observable
  72526. * @api stable
  72527. */
  72528. ol.Overlay.prototype.setMap = function(map) {
  72529. this.set(ol.OverlayProperty.MAP, map);
  72530. };
  72531. /**
  72532. * Set the offset for this overlay.
  72533. * @param {Array.<number>} offset Offset.
  72534. * @observable
  72535. * @api stable
  72536. */
  72537. ol.Overlay.prototype.setOffset = function(offset) {
  72538. this.set(ol.OverlayProperty.OFFSET, offset);
  72539. };
  72540. /**
  72541. * Set the position for this overlay. If the position is `undefined` the
  72542. * overlay is hidden.
  72543. * @param {ol.Coordinate|undefined} position The spatial point that the overlay
  72544. * is anchored at.
  72545. * @observable
  72546. * @api stable
  72547. */
  72548. ol.Overlay.prototype.setPosition = function(position) {
  72549. this.set(ol.OverlayProperty.POSITION, position);
  72550. };
  72551. /**
  72552. * Pan the map so that the overlay is entirely visible in the current viewport
  72553. * (if necessary).
  72554. * @private
  72555. */
  72556. ol.Overlay.prototype.panIntoView_ = function() {
  72557. goog.asserts.assert(this.autoPan, 'this.autoPan should be true');
  72558. var map = this.getMap();
  72559. if (map === undefined || !map.getTargetElement()) {
  72560. return;
  72561. }
  72562. var mapRect = this.getRect_(map.getTargetElement(), map.getSize());
  72563. var element = this.getElement();
  72564. goog.asserts.assert(element, 'element should be defined');
  72565. var overlayRect = this.getRect_(element,
  72566. [ol.dom.outerWidth(element), ol.dom.outerHeight(element)]);
  72567. var margin = this.autoPanMargin_;
  72568. if (!ol.extent.containsExtent(mapRect, overlayRect)) {
  72569. // the overlay is not completely inside the viewport, so pan the map
  72570. var offsetLeft = overlayRect[0] - mapRect[0];
  72571. var offsetRight = mapRect[2] - overlayRect[2];
  72572. var offsetTop = overlayRect[1] - mapRect[1];
  72573. var offsetBottom = mapRect[3] - overlayRect[3];
  72574. var delta = [0, 0];
  72575. if (offsetLeft < 0) {
  72576. // move map to the left
  72577. delta[0] = offsetLeft - margin;
  72578. } else if (offsetRight < 0) {
  72579. // move map to the right
  72580. delta[0] = Math.abs(offsetRight) + margin;
  72581. }
  72582. if (offsetTop < 0) {
  72583. // move map up
  72584. delta[1] = offsetTop - margin;
  72585. } else if (offsetBottom < 0) {
  72586. // move map down
  72587. delta[1] = Math.abs(offsetBottom) + margin;
  72588. }
  72589. if (delta[0] !== 0 || delta[1] !== 0) {
  72590. var center = map.getView().getCenter();
  72591. goog.asserts.assert(center !== undefined, 'center should be defined');
  72592. var centerPx = map.getPixelFromCoordinate(center);
  72593. var newCenterPx = [
  72594. centerPx[0] + delta[0],
  72595. centerPx[1] + delta[1]
  72596. ];
  72597. if (this.autoPanAnimation_) {
  72598. this.autoPanAnimation_.source = center;
  72599. map.beforeRender(ol.animation.pan(this.autoPanAnimation_));
  72600. }
  72601. map.getView().setCenter(map.getCoordinateFromPixel(newCenterPx));
  72602. }
  72603. }
  72604. };
  72605. /**
  72606. * Get the extent of an element relative to the document
  72607. * @param {Element|undefined} element The element.
  72608. * @param {ol.Size|undefined} size The size of the element.
  72609. * @return {ol.Extent}
  72610. * @private
  72611. */
  72612. ol.Overlay.prototype.getRect_ = function(element, size) {
  72613. goog.asserts.assert(element, 'element should be defined');
  72614. goog.asserts.assert(size !== undefined, 'size should be defined');
  72615. var offset = goog.style.getPageOffset(element);
  72616. return [
  72617. offset.x,
  72618. offset.y,
  72619. offset.x + size[0],
  72620. offset.y + size[1]
  72621. ];
  72622. };
  72623. /**
  72624. * Set the positioning for this overlay.
  72625. * @param {ol.OverlayPositioning} positioning how the overlay is
  72626. * positioned relative to its point on the map.
  72627. * @observable
  72628. * @api stable
  72629. */
  72630. ol.Overlay.prototype.setPositioning = function(positioning) {
  72631. this.set(ol.OverlayProperty.POSITIONING, positioning);
  72632. };
  72633. /**
  72634. * Modify the visibility of the element.
  72635. * @param {boolean} visible
  72636. * @protected
  72637. */
  72638. ol.Overlay.prototype.setVisible = function(visible) {
  72639. if (this.rendered_.visible !== visible) {
  72640. goog.style.setElementShown(this.element_, visible);
  72641. this.rendered_.visible = visible;
  72642. }
  72643. };
  72644. /**
  72645. * Update pixel position.
  72646. * @protected
  72647. */
  72648. ol.Overlay.prototype.updatePixelPosition = function() {
  72649. var map = this.getMap();
  72650. var position = this.getPosition();
  72651. if (map === undefined || !map.isRendered() || position === undefined) {
  72652. this.setVisible(false);
  72653. return;
  72654. }
  72655. var pixel = map.getPixelFromCoordinate(position);
  72656. var mapSize = map.getSize();
  72657. this.updateRenderedPosition(pixel, mapSize);
  72658. };
  72659. /**
  72660. * @param {ol.Pixel} pixel
  72661. * @param {ol.Size|undefined} mapSize
  72662. * @protected
  72663. */
  72664. ol.Overlay.prototype.updateRenderedPosition = function(pixel, mapSize) {
  72665. goog.asserts.assert(pixel, 'pixel should not be null');
  72666. goog.asserts.assert(mapSize !== undefined, 'mapSize should be defined');
  72667. var style = this.element_.style;
  72668. var offset = this.getOffset();
  72669. goog.asserts.assert(goog.isArray(offset), 'offset should be an array');
  72670. var positioning = this.getPositioning();
  72671. goog.asserts.assert(positioning !== undefined,
  72672. 'positioning should be defined');
  72673. var offsetX = offset[0];
  72674. var offsetY = offset[1];
  72675. if (positioning == ol.OverlayPositioning.BOTTOM_RIGHT ||
  72676. positioning == ol.OverlayPositioning.CENTER_RIGHT ||
  72677. positioning == ol.OverlayPositioning.TOP_RIGHT) {
  72678. if (this.rendered_.left_ !== '') {
  72679. this.rendered_.left_ = style.left = '';
  72680. }
  72681. var right = Math.round(mapSize[0] - pixel[0] - offsetX) + 'px';
  72682. if (this.rendered_.right_ != right) {
  72683. this.rendered_.right_ = style.right = right;
  72684. }
  72685. } else {
  72686. if (this.rendered_.right_ !== '') {
  72687. this.rendered_.right_ = style.right = '';
  72688. }
  72689. if (positioning == ol.OverlayPositioning.BOTTOM_CENTER ||
  72690. positioning == ol.OverlayPositioning.CENTER_CENTER ||
  72691. positioning == ol.OverlayPositioning.TOP_CENTER) {
  72692. offsetX -= goog.style.getSize(this.element_).width / 2;
  72693. }
  72694. var left = Math.round(pixel[0] + offsetX) + 'px';
  72695. if (this.rendered_.left_ != left) {
  72696. this.rendered_.left_ = style.left = left;
  72697. }
  72698. }
  72699. if (positioning == ol.OverlayPositioning.BOTTOM_LEFT ||
  72700. positioning == ol.OverlayPositioning.BOTTOM_CENTER ||
  72701. positioning == ol.OverlayPositioning.BOTTOM_RIGHT) {
  72702. if (this.rendered_.top_ !== '') {
  72703. this.rendered_.top_ = style.top = '';
  72704. }
  72705. var bottom = Math.round(mapSize[1] - pixel[1] - offsetY) + 'px';
  72706. if (this.rendered_.bottom_ != bottom) {
  72707. this.rendered_.bottom_ = style.bottom = bottom;
  72708. }
  72709. } else {
  72710. if (this.rendered_.bottom_ !== '') {
  72711. this.rendered_.bottom_ = style.bottom = '';
  72712. }
  72713. if (positioning == ol.OverlayPositioning.CENTER_LEFT ||
  72714. positioning == ol.OverlayPositioning.CENTER_CENTER ||
  72715. positioning == ol.OverlayPositioning.CENTER_RIGHT) {
  72716. offsetY -= goog.style.getSize(this.element_).height / 2;
  72717. }
  72718. var top = Math.round(pixel[1] + offsetY) + 'px';
  72719. if (this.rendered_.top_ != top) {
  72720. this.rendered_.top_ = style.top = top;
  72721. }
  72722. }
  72723. this.setVisible(true);
  72724. };
  72725. goog.provide('ol.control.OverviewMap');
  72726. goog.require('goog.asserts');
  72727. goog.require('goog.dom');
  72728. goog.require('goog.dom.TagName');
  72729. goog.require('goog.dom.classlist');
  72730. goog.require('goog.events');
  72731. goog.require('goog.events.EventType');
  72732. goog.require('goog.math.Size');
  72733. goog.require('goog.style');
  72734. goog.require('ol');
  72735. goog.require('ol.Collection');
  72736. goog.require('ol.Map');
  72737. goog.require('ol.MapEventType');
  72738. goog.require('ol.Object');
  72739. goog.require('ol.ObjectEventType');
  72740. goog.require('ol.Overlay');
  72741. goog.require('ol.OverlayPositioning');
  72742. goog.require('ol.View');
  72743. goog.require('ol.ViewProperty');
  72744. goog.require('ol.control.Control');
  72745. goog.require('ol.coordinate');
  72746. goog.require('ol.css');
  72747. goog.require('ol.extent');
  72748. /**
  72749. * Create a new control with a map acting as an overview map for an other
  72750. * defined map.
  72751. * @constructor
  72752. * @extends {ol.control.Control}
  72753. * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options.
  72754. * @api
  72755. */
  72756. ol.control.OverviewMap = function(opt_options) {
  72757. var options = opt_options ? opt_options : {};
  72758. /**
  72759. * @type {boolean}
  72760. * @private
  72761. */
  72762. this.collapsed_ = options.collapsed !== undefined ? options.collapsed : true;
  72763. /**
  72764. * @private
  72765. * @type {boolean}
  72766. */
  72767. this.collapsible_ = options.collapsible !== undefined ?
  72768. options.collapsible : true;
  72769. if (!this.collapsible_) {
  72770. this.collapsed_ = false;
  72771. }
  72772. var className = options.className ? options.className : 'ol-overviewmap';
  72773. var tipLabel = options.tipLabel ? options.tipLabel : 'Overview map';
  72774. var collapseLabel = options.collapseLabel ? options.collapseLabel : '\u00AB';
  72775. /**
  72776. * @private
  72777. * @type {Node}
  72778. */
  72779. this.collapseLabel_ = goog.isString(collapseLabel) ?
  72780. goog.dom.createDom(goog.dom.TagName.SPAN, {}, collapseLabel) :
  72781. collapseLabel;
  72782. var label = options.label ? options.label : '\u00BB';
  72783. /**
  72784. * @private
  72785. * @type {Node}
  72786. */
  72787. this.label_ = goog.isString(label) ?
  72788. goog.dom.createDom(goog.dom.TagName.SPAN, {}, label) :
  72789. label;
  72790. var activeLabel = (this.collapsible_ && !this.collapsed_) ?
  72791. this.collapseLabel_ : this.label_;
  72792. var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  72793. 'type': 'button',
  72794. 'title': tipLabel
  72795. }, activeLabel);
  72796. goog.events.listen(button, goog.events.EventType.CLICK,
  72797. this.handleClick_, false, this);
  72798. var ovmapDiv = goog.dom.createDom(goog.dom.TagName.DIV, 'ol-overviewmap-map');
  72799. /**
  72800. * @type {ol.Map}
  72801. * @private
  72802. */
  72803. this.ovmap_ = new ol.Map({
  72804. controls: new ol.Collection(),
  72805. interactions: new ol.Collection(),
  72806. target: ovmapDiv,
  72807. view: options.view
  72808. });
  72809. var ovmap = this.ovmap_;
  72810. if (options.layers) {
  72811. options.layers.forEach(
  72812. /**
  72813. * @param {ol.layer.Layer} layer Layer.
  72814. */
  72815. function(layer) {
  72816. ovmap.addLayer(layer);
  72817. }, this);
  72818. }
  72819. var box = goog.dom.createDom(goog.dom.TagName.DIV, 'ol-overviewmap-box');
  72820. /**
  72821. * @type {ol.Overlay}
  72822. * @private
  72823. */
  72824. this.boxOverlay_ = new ol.Overlay({
  72825. position: [0, 0],
  72826. positioning: ol.OverlayPositioning.BOTTOM_LEFT,
  72827. element: box
  72828. });
  72829. this.ovmap_.addOverlay(this.boxOverlay_);
  72830. var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
  72831. ol.css.CLASS_CONTROL +
  72832. (this.collapsed_ && this.collapsible_ ? ' ol-collapsed' : '') +
  72833. (this.collapsible_ ? '' : ' ol-uncollapsible');
  72834. var element = goog.dom.createDom(goog.dom.TagName.DIV,
  72835. cssClasses, ovmapDiv, button);
  72836. var render = options.render ? options.render : ol.control.OverviewMap.render;
  72837. goog.base(this, {
  72838. element: element,
  72839. render: render,
  72840. target: options.target
  72841. });
  72842. };
  72843. goog.inherits(ol.control.OverviewMap, ol.control.Control);
  72844. /**
  72845. * @inheritDoc
  72846. * @api
  72847. */
  72848. ol.control.OverviewMap.prototype.setMap = function(map) {
  72849. var oldMap = this.getMap();
  72850. if (map === oldMap) {
  72851. return;
  72852. }
  72853. if (oldMap) {
  72854. var oldView = oldMap.getView();
  72855. if (oldView) {
  72856. this.unbindView_(oldView);
  72857. }
  72858. }
  72859. goog.base(this, 'setMap', map);
  72860. if (map) {
  72861. this.listenerKeys.push(goog.events.listen(
  72862. map, ol.ObjectEventType.PROPERTYCHANGE,
  72863. this.handleMapPropertyChange_, false, this));
  72864. // TODO: to really support map switching, this would need to be reworked
  72865. if (this.ovmap_.getLayers().getLength() === 0) {
  72866. this.ovmap_.setLayerGroup(map.getLayerGroup());
  72867. }
  72868. var view = map.getView();
  72869. if (view) {
  72870. this.bindView_(view);
  72871. if (view.isDef()) {
  72872. this.ovmap_.updateSize();
  72873. this.resetExtent_();
  72874. }
  72875. }
  72876. }
  72877. };
  72878. /**
  72879. * Handle map property changes. This only deals with changes to the map's view.
  72880. * @param {ol.ObjectEvent} event The propertychange event.
  72881. * @private
  72882. */
  72883. ol.control.OverviewMap.prototype.handleMapPropertyChange_ = function(event) {
  72884. if (event.key === ol.MapProperty.VIEW) {
  72885. var oldView = /** @type {ol.View} */ (event.oldValue);
  72886. if (oldView) {
  72887. this.unbindView_(oldView);
  72888. }
  72889. var newView = this.getMap().getView();
  72890. this.bindView_(newView);
  72891. }
  72892. };
  72893. /**
  72894. * Register listeners for view property changes.
  72895. * @param {ol.View} view The view.
  72896. * @private
  72897. */
  72898. ol.control.OverviewMap.prototype.bindView_ = function(view) {
  72899. goog.events.listen(view,
  72900. ol.Object.getChangeEventType(ol.ViewProperty.ROTATION),
  72901. this.handleRotationChanged_, false, this);
  72902. };
  72903. /**
  72904. * Unregister listeners for view property changes.
  72905. * @param {ol.View} view The view.
  72906. * @private
  72907. */
  72908. ol.control.OverviewMap.prototype.unbindView_ = function(view) {
  72909. goog.events.unlisten(view,
  72910. ol.Object.getChangeEventType(ol.ViewProperty.ROTATION),
  72911. this.handleRotationChanged_, false, this);
  72912. };
  72913. /**
  72914. * Handle rotation changes to the main map.
  72915. * TODO: This should rotate the extent rectrangle instead of the
  72916. * overview map's view.
  72917. * @private
  72918. */
  72919. ol.control.OverviewMap.prototype.handleRotationChanged_ = function() {
  72920. this.ovmap_.getView().setRotation(this.getMap().getView().getRotation());
  72921. };
  72922. /**
  72923. * Update the overview map element.
  72924. * @param {ol.MapEvent} mapEvent Map event.
  72925. * @this {ol.control.OverviewMap}
  72926. * @api
  72927. */
  72928. ol.control.OverviewMap.render = function(mapEvent) {
  72929. this.validateExtent_();
  72930. this.updateBox_();
  72931. };
  72932. /**
  72933. * Reset the overview map extent if the box size (width or
  72934. * height) is less than the size of the overview map size times minRatio
  72935. * or is greater than the size of the overview size times maxRatio.
  72936. *
  72937. * If the map extent was not reset, the box size can fits in the defined
  72938. * ratio sizes. This method then checks if is contained inside the overview
  72939. * map current extent. If not, recenter the overview map to the current
  72940. * main map center location.
  72941. * @private
  72942. */
  72943. ol.control.OverviewMap.prototype.validateExtent_ = function() {
  72944. var map = this.getMap();
  72945. var ovmap = this.ovmap_;
  72946. if (!map.isRendered() || !ovmap.isRendered()) {
  72947. return;
  72948. }
  72949. var mapSize = map.getSize();
  72950. goog.asserts.assertArray(mapSize, 'mapSize should be an array');
  72951. var view = map.getView();
  72952. goog.asserts.assert(view, 'view should be defined');
  72953. var extent = view.calculateExtent(mapSize);
  72954. var ovmapSize = ovmap.getSize();
  72955. goog.asserts.assertArray(ovmapSize, 'ovmapSize should be an array');
  72956. var ovview = ovmap.getView();
  72957. goog.asserts.assert(ovview, 'ovview should be defined');
  72958. var ovextent = ovview.calculateExtent(ovmapSize);
  72959. var topLeftPixel =
  72960. ovmap.getPixelFromCoordinate(ol.extent.getTopLeft(extent));
  72961. var bottomRightPixel =
  72962. ovmap.getPixelFromCoordinate(ol.extent.getBottomRight(extent));
  72963. var boxSize = new goog.math.Size(
  72964. Math.abs(topLeftPixel[0] - bottomRightPixel[0]),
  72965. Math.abs(topLeftPixel[1] - bottomRightPixel[1]));
  72966. var ovmapWidth = ovmapSize[0];
  72967. var ovmapHeight = ovmapSize[1];
  72968. if (boxSize.width < ovmapWidth * ol.OVERVIEWMAP_MIN_RATIO ||
  72969. boxSize.height < ovmapHeight * ol.OVERVIEWMAP_MIN_RATIO ||
  72970. boxSize.width > ovmapWidth * ol.OVERVIEWMAP_MAX_RATIO ||
  72971. boxSize.height > ovmapHeight * ol.OVERVIEWMAP_MAX_RATIO) {
  72972. this.resetExtent_();
  72973. } else if (!ol.extent.containsExtent(ovextent, extent)) {
  72974. this.recenter_();
  72975. }
  72976. };
  72977. /**
  72978. * Reset the overview map extent to half calculated min and max ratio times
  72979. * the extent of the main map.
  72980. * @private
  72981. */
  72982. ol.control.OverviewMap.prototype.resetExtent_ = function() {
  72983. if (ol.OVERVIEWMAP_MAX_RATIO === 0 || ol.OVERVIEWMAP_MIN_RATIO === 0) {
  72984. return;
  72985. }
  72986. var map = this.getMap();
  72987. var ovmap = this.ovmap_;
  72988. var mapSize = map.getSize();
  72989. goog.asserts.assertArray(mapSize, 'mapSize should be an array');
  72990. var view = map.getView();
  72991. goog.asserts.assert(view, 'view should be defined');
  72992. var extent = view.calculateExtent(mapSize);
  72993. var ovmapSize = ovmap.getSize();
  72994. goog.asserts.assertArray(ovmapSize, 'ovmapSize should be an array');
  72995. var ovview = ovmap.getView();
  72996. goog.asserts.assert(ovview, 'ovview should be defined');
  72997. // get how many times the current map overview could hold different
  72998. // box sizes using the min and max ratio, pick the step in the middle used
  72999. // to calculate the extent from the main map to set it to the overview map,
  73000. var steps = Math.log(
  73001. ol.OVERVIEWMAP_MAX_RATIO / ol.OVERVIEWMAP_MIN_RATIO) / Math.LN2;
  73002. var ratio = 1 / (Math.pow(2, steps / 2) * ol.OVERVIEWMAP_MIN_RATIO);
  73003. ol.extent.scaleFromCenter(extent, ratio);
  73004. ovview.fit(extent, ovmapSize);
  73005. };
  73006. /**
  73007. * Set the center of the overview map to the map center without changing its
  73008. * resolution.
  73009. * @private
  73010. */
  73011. ol.control.OverviewMap.prototype.recenter_ = function() {
  73012. var map = this.getMap();
  73013. var ovmap = this.ovmap_;
  73014. var view = map.getView();
  73015. goog.asserts.assert(view, 'view should be defined');
  73016. var ovview = ovmap.getView();
  73017. goog.asserts.assert(ovview, 'ovview should be defined');
  73018. ovview.setCenter(view.getCenter());
  73019. };
  73020. /**
  73021. * Update the box using the main map extent
  73022. * @private
  73023. */
  73024. ol.control.OverviewMap.prototype.updateBox_ = function() {
  73025. var map = this.getMap();
  73026. var ovmap = this.ovmap_;
  73027. if (!map.isRendered() || !ovmap.isRendered()) {
  73028. return;
  73029. }
  73030. var mapSize = map.getSize();
  73031. goog.asserts.assertArray(mapSize, 'mapSize should be an array');
  73032. var view = map.getView();
  73033. goog.asserts.assert(view, 'view should be defined');
  73034. var ovview = ovmap.getView();
  73035. goog.asserts.assert(ovview, 'ovview should be defined');
  73036. var ovmapSize = ovmap.getSize();
  73037. goog.asserts.assertArray(ovmapSize, 'ovmapSize should be an array');
  73038. var rotation = view.getRotation();
  73039. goog.asserts.assert(rotation !== undefined, 'rotation should be defined');
  73040. var overlay = this.boxOverlay_;
  73041. var box = this.boxOverlay_.getElement();
  73042. var extent = view.calculateExtent(mapSize);
  73043. var ovresolution = ovview.getResolution();
  73044. var bottomLeft = ol.extent.getBottomLeft(extent);
  73045. var topRight = ol.extent.getTopRight(extent);
  73046. // set position using bottom left coordinates
  73047. var rotateBottomLeft = this.calculateCoordinateRotate_(rotation, bottomLeft);
  73048. overlay.setPosition(rotateBottomLeft);
  73049. // set box size calculated from map extent size and overview map resolution
  73050. if (box) {
  73051. var boxWidth = Math.abs((bottomLeft[0] - topRight[0]) / ovresolution);
  73052. var boxHeight = Math.abs((topRight[1] - bottomLeft[1]) / ovresolution);
  73053. goog.style.setBorderBoxSize(box, new goog.math.Size(
  73054. boxWidth, boxHeight));
  73055. }
  73056. };
  73057. /**
  73058. * @param {number} rotation Target rotation.
  73059. * @param {ol.Coordinate} coordinate Coordinate.
  73060. * @return {ol.Coordinate|undefined} Coordinate for rotation and center anchor.
  73061. * @private
  73062. */
  73063. ol.control.OverviewMap.prototype.calculateCoordinateRotate_ = function(
  73064. rotation, coordinate) {
  73065. var coordinateRotate;
  73066. var map = this.getMap();
  73067. var view = map.getView();
  73068. goog.asserts.assert(view, 'view should be defined');
  73069. var currentCenter = view.getCenter();
  73070. if (currentCenter) {
  73071. coordinateRotate = [
  73072. coordinate[0] - currentCenter[0],
  73073. coordinate[1] - currentCenter[1]
  73074. ];
  73075. ol.coordinate.rotate(coordinateRotate, rotation);
  73076. ol.coordinate.add(coordinateRotate, currentCenter);
  73077. }
  73078. return coordinateRotate;
  73079. };
  73080. /**
  73081. * @param {goog.events.BrowserEvent} event The event to handle
  73082. * @private
  73083. */
  73084. ol.control.OverviewMap.prototype.handleClick_ = function(event) {
  73085. event.preventDefault();
  73086. this.handleToggle_();
  73087. };
  73088. /**
  73089. * @private
  73090. */
  73091. ol.control.OverviewMap.prototype.handleToggle_ = function() {
  73092. goog.dom.classlist.toggle(this.element, 'ol-collapsed');
  73093. if (this.collapsed_) {
  73094. goog.dom.replaceNode(this.collapseLabel_, this.label_);
  73095. } else {
  73096. goog.dom.replaceNode(this.label_, this.collapseLabel_);
  73097. }
  73098. this.collapsed_ = !this.collapsed_;
  73099. // manage overview map if it had not been rendered before and control
  73100. // is expanded
  73101. var ovmap = this.ovmap_;
  73102. if (!this.collapsed_ && !ovmap.isRendered()) {
  73103. ovmap.updateSize();
  73104. this.resetExtent_();
  73105. goog.events.listenOnce(ovmap, ol.MapEventType.POSTRENDER,
  73106. function(event) {
  73107. this.updateBox_();
  73108. },
  73109. false, this);
  73110. }
  73111. };
  73112. /**
  73113. * Return `true` if the overview map is collapsible, `false` otherwise.
  73114. * @return {boolean} True if the widget is collapsible.
  73115. * @api stable
  73116. */
  73117. ol.control.OverviewMap.prototype.getCollapsible = function() {
  73118. return this.collapsible_;
  73119. };
  73120. /**
  73121. * Set whether the overview map should be collapsible.
  73122. * @param {boolean} collapsible True if the widget is collapsible.
  73123. * @api stable
  73124. */
  73125. ol.control.OverviewMap.prototype.setCollapsible = function(collapsible) {
  73126. if (this.collapsible_ === collapsible) {
  73127. return;
  73128. }
  73129. this.collapsible_ = collapsible;
  73130. goog.dom.classlist.toggle(this.element, 'ol-uncollapsible');
  73131. if (!collapsible && this.collapsed_) {
  73132. this.handleToggle_();
  73133. }
  73134. };
  73135. /**
  73136. * Collapse or expand the overview map according to the passed parameter. Will
  73137. * not do anything if the overview map isn't collapsible or if the current
  73138. * collapsed state is already the one requested.
  73139. * @param {boolean} collapsed True if the widget is collapsed.
  73140. * @api stable
  73141. */
  73142. ol.control.OverviewMap.prototype.setCollapsed = function(collapsed) {
  73143. if (!this.collapsible_ || this.collapsed_ === collapsed) {
  73144. return;
  73145. }
  73146. this.handleToggle_();
  73147. };
  73148. /**
  73149. * Determine if the overview map is collapsed.
  73150. * @return {boolean} The overview map is collapsed.
  73151. * @api stable
  73152. */
  73153. ol.control.OverviewMap.prototype.getCollapsed = function() {
  73154. return this.collapsed_;
  73155. };
  73156. goog.provide('ol.control.ScaleLine');
  73157. goog.provide('ol.control.ScaleLineProperty');
  73158. goog.provide('ol.control.ScaleLineUnits');
  73159. goog.require('goog.asserts');
  73160. goog.require('goog.dom');
  73161. goog.require('goog.dom.TagName');
  73162. goog.require('goog.events');
  73163. goog.require('goog.math');
  73164. goog.require('goog.style');
  73165. goog.require('ol');
  73166. goog.require('ol.Object');
  73167. goog.require('ol.TransformFunction');
  73168. goog.require('ol.control.Control');
  73169. goog.require('ol.css');
  73170. goog.require('ol.proj');
  73171. goog.require('ol.proj.METERS_PER_UNIT');
  73172. goog.require('ol.proj.Units');
  73173. goog.require('ol.sphere.NORMAL');
  73174. /**
  73175. * @enum {string}
  73176. */
  73177. ol.control.ScaleLineProperty = {
  73178. UNITS: 'units'
  73179. };
  73180. /**
  73181. * Units for the scale line. Supported values are `'degrees'`, `'imperial'`,
  73182. * `'nautical'`, `'metric'`, `'us'`.
  73183. * @enum {string}
  73184. * @api stable
  73185. */
  73186. ol.control.ScaleLineUnits = {
  73187. DEGREES: 'degrees',
  73188. IMPERIAL: 'imperial',
  73189. NAUTICAL: 'nautical',
  73190. METRIC: 'metric',
  73191. US: 'us'
  73192. };
  73193. /**
  73194. * @classdesc
  73195. * A control displaying rough x-axis distances, calculated for the center of the
  73196. * viewport.
  73197. * No scale line will be shown when the x-axis distance cannot be calculated in
  73198. * the view projection (e.g. at or beyond the poles in EPSG:4326).
  73199. * By default the scale line will show in the bottom left portion of the map,
  73200. * but this can be changed by using the css selector `.ol-scale-line`.
  73201. *
  73202. * @constructor
  73203. * @extends {ol.control.Control}
  73204. * @param {olx.control.ScaleLineOptions=} opt_options Scale line options.
  73205. * @api stable
  73206. */
  73207. ol.control.ScaleLine = function(opt_options) {
  73208. var options = opt_options ? opt_options : {};
  73209. var className = options.className ? options.className : 'ol-scale-line';
  73210. /**
  73211. * @private
  73212. * @type {Element}
  73213. */
  73214. this.innerElement_ = goog.dom.createDom(goog.dom.TagName.DIV,
  73215. className + '-inner');
  73216. /**
  73217. * @private
  73218. * @type {Element}
  73219. */
  73220. this.element_ = goog.dom.createDom(goog.dom.TagName.DIV,
  73221. className + ' ' + ol.css.CLASS_UNSELECTABLE, this.innerElement_);
  73222. /**
  73223. * @private
  73224. * @type {?olx.ViewState}
  73225. */
  73226. this.viewState_ = null;
  73227. /**
  73228. * @private
  73229. * @type {number}
  73230. */
  73231. this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64;
  73232. /**
  73233. * @private
  73234. * @type {boolean}
  73235. */
  73236. this.renderedVisible_ = false;
  73237. /**
  73238. * @private
  73239. * @type {number|undefined}
  73240. */
  73241. this.renderedWidth_ = undefined;
  73242. /**
  73243. * @private
  73244. * @type {string}
  73245. */
  73246. this.renderedHTML_ = '';
  73247. /**
  73248. * @private
  73249. * @type {?ol.TransformFunction}
  73250. */
  73251. this.toEPSG4326_ = null;
  73252. var render = options.render ? options.render : ol.control.ScaleLine.render;
  73253. goog.base(this, {
  73254. element: this.element_,
  73255. render: render,
  73256. target: options.target
  73257. });
  73258. goog.events.listen(
  73259. this, ol.Object.getChangeEventType(ol.control.ScaleLineProperty.UNITS),
  73260. this.handleUnitsChanged_, false, this);
  73261. this.setUnits(/** @type {ol.control.ScaleLineUnits} */ (options.units) ||
  73262. ol.control.ScaleLineUnits.METRIC);
  73263. };
  73264. goog.inherits(ol.control.ScaleLine, ol.control.Control);
  73265. /**
  73266. * @const
  73267. * @type {Array.<number>}
  73268. */
  73269. ol.control.ScaleLine.LEADING_DIGITS = [1, 2, 5];
  73270. /**
  73271. * Return the units to use in the scale line.
  73272. * @return {ol.control.ScaleLineUnits|undefined} The units to use in the scale
  73273. * line.
  73274. * @observable
  73275. * @api stable
  73276. */
  73277. ol.control.ScaleLine.prototype.getUnits = function() {
  73278. return /** @type {ol.control.ScaleLineUnits|undefined} */ (
  73279. this.get(ol.control.ScaleLineProperty.UNITS));
  73280. };
  73281. /**
  73282. * Update the scale line element.
  73283. * @param {ol.MapEvent} mapEvent Map event.
  73284. * @this {ol.control.ScaleLine}
  73285. * @api
  73286. */
  73287. ol.control.ScaleLine.render = function(mapEvent) {
  73288. var frameState = mapEvent.frameState;
  73289. if (!frameState) {
  73290. this.viewState_ = null;
  73291. } else {
  73292. this.viewState_ = frameState.viewState;
  73293. }
  73294. this.updateElement_();
  73295. };
  73296. /**
  73297. * @private
  73298. */
  73299. ol.control.ScaleLine.prototype.handleUnitsChanged_ = function() {
  73300. this.updateElement_();
  73301. };
  73302. /**
  73303. * Set the units to use in the scale line.
  73304. * @param {ol.control.ScaleLineUnits} units The units to use in the scale line.
  73305. * @observable
  73306. * @api stable
  73307. */
  73308. ol.control.ScaleLine.prototype.setUnits = function(units) {
  73309. this.set(ol.control.ScaleLineProperty.UNITS, units);
  73310. };
  73311. /**
  73312. * @private
  73313. */
  73314. ol.control.ScaleLine.prototype.updateElement_ = function() {
  73315. var viewState = this.viewState_;
  73316. if (!viewState) {
  73317. if (this.renderedVisible_) {
  73318. goog.style.setElementShown(this.element_, false);
  73319. this.renderedVisible_ = false;
  73320. }
  73321. return;
  73322. }
  73323. var center = viewState.center;
  73324. var projection = viewState.projection;
  73325. var pointResolution =
  73326. projection.getPointResolution(viewState.resolution, center);
  73327. var projectionUnits = projection.getUnits();
  73328. var cosLatitude;
  73329. var units = this.getUnits();
  73330. if (projectionUnits == ol.proj.Units.DEGREES &&
  73331. (units == ol.control.ScaleLineUnits.METRIC ||
  73332. units == ol.control.ScaleLineUnits.IMPERIAL ||
  73333. units == ol.control.ScaleLineUnits.US ||
  73334. units == ol.control.ScaleLineUnits.NAUTICAL)) {
  73335. // Convert pointResolution from degrees to meters
  73336. this.toEPSG4326_ = null;
  73337. cosLatitude = Math.cos(goog.math.toRadians(center[1]));
  73338. pointResolution *= Math.PI * cosLatitude * ol.sphere.NORMAL.radius / 180;
  73339. projectionUnits = ol.proj.Units.METERS;
  73340. } else if (projectionUnits != ol.proj.Units.DEGREES &&
  73341. units == ol.control.ScaleLineUnits.DEGREES) {
  73342. // Convert pointResolution from other units to degrees
  73343. if (!this.toEPSG4326_) {
  73344. this.toEPSG4326_ = ol.proj.getTransformFromProjections(
  73345. projection, ol.proj.get('EPSG:4326'));
  73346. }
  73347. cosLatitude = Math.cos(goog.math.toRadians(this.toEPSG4326_(center)[1]));
  73348. var radius = ol.sphere.NORMAL.radius;
  73349. goog.asserts.assert(ol.proj.METERS_PER_UNIT[projectionUnits],
  73350. 'Meters per unit should be defined for the projection unit');
  73351. radius /= ol.proj.METERS_PER_UNIT[projectionUnits];
  73352. pointResolution *= 180 / (Math.PI * cosLatitude * radius);
  73353. projectionUnits = ol.proj.Units.DEGREES;
  73354. } else {
  73355. this.toEPSG4326_ = null;
  73356. }
  73357. goog.asserts.assert(
  73358. ((units == ol.control.ScaleLineUnits.METRIC ||
  73359. units == ol.control.ScaleLineUnits.IMPERIAL ||
  73360. units == ol.control.ScaleLineUnits.US ||
  73361. units == ol.control.ScaleLineUnits.NAUTICAL) &&
  73362. projectionUnits == ol.proj.Units.METERS) ||
  73363. (units == ol.control.ScaleLineUnits.DEGREES &&
  73364. projectionUnits == ol.proj.Units.DEGREES),
  73365. 'Scale line units and projection units should match');
  73366. var nominalCount = this.minWidth_ * pointResolution;
  73367. var suffix = '';
  73368. if (units == ol.control.ScaleLineUnits.DEGREES) {
  73369. if (nominalCount < 1 / 60) {
  73370. suffix = '\u2033'; // seconds
  73371. pointResolution *= 3600;
  73372. } else if (nominalCount < 1) {
  73373. suffix = '\u2032'; // minutes
  73374. pointResolution *= 60;
  73375. } else {
  73376. suffix = '\u00b0'; // degrees
  73377. }
  73378. } else if (units == ol.control.ScaleLineUnits.IMPERIAL) {
  73379. if (nominalCount < 0.9144) {
  73380. suffix = 'in';
  73381. pointResolution /= 0.0254;
  73382. } else if (nominalCount < 1609.344) {
  73383. suffix = 'ft';
  73384. pointResolution /= 0.3048;
  73385. } else {
  73386. suffix = 'mi';
  73387. pointResolution /= 1609.344;
  73388. }
  73389. } else if (units == ol.control.ScaleLineUnits.NAUTICAL) {
  73390. pointResolution /= 1852;
  73391. suffix = 'nm';
  73392. } else if (units == ol.control.ScaleLineUnits.METRIC) {
  73393. if (nominalCount < 1) {
  73394. suffix = 'mm';
  73395. pointResolution *= 1000;
  73396. } else if (nominalCount < 1000) {
  73397. suffix = 'm';
  73398. } else {
  73399. suffix = 'km';
  73400. pointResolution /= 1000;
  73401. }
  73402. } else if (units == ol.control.ScaleLineUnits.US) {
  73403. if (nominalCount < 0.9144) {
  73404. suffix = 'in';
  73405. pointResolution *= 39.37;
  73406. } else if (nominalCount < 1609.344) {
  73407. suffix = 'ft';
  73408. pointResolution /= 0.30480061;
  73409. } else {
  73410. suffix = 'mi';
  73411. pointResolution /= 1609.3472;
  73412. }
  73413. } else {
  73414. goog.asserts.fail('Scale line element cannot be updated');
  73415. }
  73416. var i = 3 * Math.floor(
  73417. Math.log(this.minWidth_ * pointResolution) / Math.log(10));
  73418. var count, width;
  73419. while (true) {
  73420. count = ol.control.ScaleLine.LEADING_DIGITS[i % 3] *
  73421. Math.pow(10, Math.floor(i / 3));
  73422. width = Math.round(count / pointResolution);
  73423. if (isNaN(width)) {
  73424. goog.style.setElementShown(this.element_, false);
  73425. this.renderedVisible_ = false;
  73426. return;
  73427. } else if (width >= this.minWidth_) {
  73428. break;
  73429. }
  73430. ++i;
  73431. }
  73432. var html = count + ' ' + suffix;
  73433. if (this.renderedHTML_ != html) {
  73434. this.innerElement_.innerHTML = html;
  73435. this.renderedHTML_ = html;
  73436. }
  73437. if (this.renderedWidth_ != width) {
  73438. this.innerElement_.style.width = width + 'px';
  73439. this.renderedWidth_ = width;
  73440. }
  73441. if (!this.renderedVisible_) {
  73442. goog.style.setElementShown(this.element_, true);
  73443. this.renderedVisible_ = true;
  73444. }
  73445. };
  73446. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  73447. //
  73448. // Licensed under the Apache License, Version 2.0 (the "License");
  73449. // you may not use this file except in compliance with the License.
  73450. // You may obtain a copy of the License at
  73451. //
  73452. // http://www.apache.org/licenses/LICENSE-2.0
  73453. //
  73454. // Unless required by applicable law or agreed to in writing, software
  73455. // distributed under the License is distributed on an "AS-IS" BASIS,
  73456. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  73457. // See the License for the specific language governing permissions and
  73458. // limitations under the License.
  73459. /**
  73460. * @fileoverview Class to create objects which want to handle multiple events
  73461. * and have their listeners easily cleaned up via a dispose method.
  73462. *
  73463. * Example:
  73464. * <pre>
  73465. * function Something() {
  73466. * Something.base(this);
  73467. *
  73468. * ... set up object ...
  73469. *
  73470. * // Add event listeners
  73471. * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);
  73472. * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);
  73473. * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);
  73474. * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);
  73475. * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);
  73476. * }
  73477. * goog.inherits(Something, goog.events.EventHandler);
  73478. *
  73479. * Something.prototype.disposeInternal = function() {
  73480. * Something.base(this, 'disposeInternal');
  73481. * goog.dom.removeNode(this.container);
  73482. * };
  73483. *
  73484. *
  73485. * // Then elsewhere:
  73486. *
  73487. * var activeSomething = null;
  73488. * function openSomething() {
  73489. * activeSomething = new Something();
  73490. * }
  73491. *
  73492. * function closeSomething() {
  73493. * if (activeSomething) {
  73494. * activeSomething.dispose(); // Remove event listeners
  73495. * activeSomething = null;
  73496. * }
  73497. * }
  73498. * </pre>
  73499. *
  73500. */
  73501. goog.provide('goog.events.EventHandler');
  73502. goog.require('goog.Disposable');
  73503. goog.require('goog.events');
  73504. goog.require('goog.object');
  73505. goog.forwardDeclare('goog.events.EventWrapper');
  73506. /**
  73507. * Super class for objects that want to easily manage a number of event
  73508. * listeners. It allows a short cut to listen and also provides a quick way
  73509. * to remove all events listeners belonging to this object.
  73510. * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.
  73511. * @constructor
  73512. * @extends {goog.Disposable}
  73513. * @template SCOPE
  73514. */
  73515. goog.events.EventHandler = function(opt_scope) {
  73516. goog.Disposable.call(this);
  73517. // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3
  73518. // that access this private variable. :(
  73519. this.handler_ = opt_scope;
  73520. /**
  73521. * Keys for events that are being listened to.
  73522. * @type {!Object<!goog.events.Key>}
  73523. * @private
  73524. */
  73525. this.keys_ = {};
  73526. };
  73527. goog.inherits(goog.events.EventHandler, goog.Disposable);
  73528. /**
  73529. * Utility array used to unify the cases of listening for an array of types
  73530. * and listening for a single event, without using recursion or allocating
  73531. * an array each time.
  73532. * @type {!Array<string>}
  73533. * @const
  73534. * @private
  73535. */
  73536. goog.events.EventHandler.typeArray_ = [];
  73537. /**
  73538. * Listen to an event on a Listenable. If the function is omitted then the
  73539. * EventHandler's handleEvent method will be used.
  73540. * @param {goog.events.ListenableType} src Event source.
  73541. * @param {string|Array<string>|
  73542. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73543. * type Event type to listen for or array of event types.
  73544. * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}
  73545. * opt_fn Optional callback function to be used as the listener or an object
  73546. * with handleEvent function.
  73547. * @param {boolean=} opt_capture Optional whether to use capture phase.
  73548. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73549. * chaining of calls.
  73550. * @template EVENTOBJ
  73551. */
  73552. goog.events.EventHandler.prototype.listen = function(
  73553. src, type, opt_fn, opt_capture) {
  73554. return this.listen_(src, type, opt_fn, opt_capture);
  73555. };
  73556. /**
  73557. * Listen to an event on a Listenable. If the function is omitted then the
  73558. * EventHandler's handleEvent method will be used.
  73559. * @param {goog.events.ListenableType} src Event source.
  73560. * @param {string|Array<string>|
  73561. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73562. * type Event type to listen for or array of event types.
  73563. * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|
  73564. * null|undefined} fn Optional callback function to be used as the
  73565. * listener or an object with handleEvent function.
  73566. * @param {boolean|undefined} capture Optional whether to use capture phase.
  73567. * @param {T} scope Object in whose scope to call the listener.
  73568. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73569. * chaining of calls.
  73570. * @template T,EVENTOBJ
  73571. */
  73572. goog.events.EventHandler.prototype.listenWithScope = function(
  73573. src, type, fn, capture, scope) {
  73574. // TODO(mknichel): Deprecate this function.
  73575. return this.listen_(src, type, fn, capture, scope);
  73576. };
  73577. /**
  73578. * Listen to an event on a Listenable. If the function is omitted then the
  73579. * EventHandler's handleEvent method will be used.
  73580. * @param {goog.events.ListenableType} src Event source.
  73581. * @param {string|Array<string>|
  73582. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73583. * type Event type to listen for or array of event types.
  73584. * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn
  73585. * Optional callback function to be used as the listener or an object with
  73586. * handleEvent function.
  73587. * @param {boolean=} opt_capture Optional whether to use capture phase.
  73588. * @param {Object=} opt_scope Object in whose scope to call the listener.
  73589. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73590. * chaining of calls.
  73591. * @template EVENTOBJ
  73592. * @private
  73593. */
  73594. goog.events.EventHandler.prototype.listen_ = function(src, type, opt_fn,
  73595. opt_capture,
  73596. opt_scope) {
  73597. if (!goog.isArray(type)) {
  73598. if (type) {
  73599. goog.events.EventHandler.typeArray_[0] = type.toString();
  73600. }
  73601. type = goog.events.EventHandler.typeArray_;
  73602. }
  73603. for (var i = 0; i < type.length; i++) {
  73604. var listenerObj = goog.events.listen(
  73605. src, type[i], opt_fn || this.handleEvent,
  73606. opt_capture || false,
  73607. opt_scope || this.handler_ || this);
  73608. if (!listenerObj) {
  73609. // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT
  73610. // (goog.events.CaptureSimulationMode) in IE8-, it will return null
  73611. // value.
  73612. return this;
  73613. }
  73614. var key = listenerObj.key;
  73615. this.keys_[key] = listenerObj;
  73616. }
  73617. return this;
  73618. };
  73619. /**
  73620. * Listen to an event on a Listenable. If the function is omitted, then the
  73621. * EventHandler's handleEvent method will be used. After the event has fired the
  73622. * event listener is removed from the target. If an array of event types is
  73623. * provided, each event type will be listened to once.
  73624. * @param {goog.events.ListenableType} src Event source.
  73625. * @param {string|Array<string>|
  73626. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73627. * type Event type to listen for or array of event types.
  73628. * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn
  73629. * Optional callback function to be used as the listener or an object with
  73630. * handleEvent function.
  73631. * @param {boolean=} opt_capture Optional whether to use capture phase.
  73632. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73633. * chaining of calls.
  73634. * @template EVENTOBJ
  73635. */
  73636. goog.events.EventHandler.prototype.listenOnce = function(
  73637. src, type, opt_fn, opt_capture) {
  73638. return this.listenOnce_(src, type, opt_fn, opt_capture);
  73639. };
  73640. /**
  73641. * Listen to an event on a Listenable. If the function is omitted, then the
  73642. * EventHandler's handleEvent method will be used. After the event has fired the
  73643. * event listener is removed from the target. If an array of event types is
  73644. * provided, each event type will be listened to once.
  73645. * @param {goog.events.ListenableType} src Event source.
  73646. * @param {string|Array<string>|
  73647. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73648. * type Event type to listen for or array of event types.
  73649. * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|
  73650. * null|undefined} fn Optional callback function to be used as the
  73651. * listener or an object with handleEvent function.
  73652. * @param {boolean|undefined} capture Optional whether to use capture phase.
  73653. * @param {T} scope Object in whose scope to call the listener.
  73654. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73655. * chaining of calls.
  73656. * @template T,EVENTOBJ
  73657. */
  73658. goog.events.EventHandler.prototype.listenOnceWithScope = function(
  73659. src, type, fn, capture, scope) {
  73660. // TODO(mknichel): Deprecate this function.
  73661. return this.listenOnce_(src, type, fn, capture, scope);
  73662. };
  73663. /**
  73664. * Listen to an event on a Listenable. If the function is omitted, then the
  73665. * EventHandler's handleEvent method will be used. After the event has fired
  73666. * the event listener is removed from the target. If an array of event types is
  73667. * provided, each event type will be listened to once.
  73668. * @param {goog.events.ListenableType} src Event source.
  73669. * @param {string|Array<string>|
  73670. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73671. * type Event type to listen for or array of event types.
  73672. * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn
  73673. * Optional callback function to be used as the listener or an object with
  73674. * handleEvent function.
  73675. * @param {boolean=} opt_capture Optional whether to use capture phase.
  73676. * @param {Object=} opt_scope Object in whose scope to call the listener.
  73677. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73678. * chaining of calls.
  73679. * @template EVENTOBJ
  73680. * @private
  73681. */
  73682. goog.events.EventHandler.prototype.listenOnce_ = function(
  73683. src, type, opt_fn, opt_capture, opt_scope) {
  73684. if (goog.isArray(type)) {
  73685. for (var i = 0; i < type.length; i++) {
  73686. this.listenOnce_(src, type[i], opt_fn, opt_capture, opt_scope);
  73687. }
  73688. } else {
  73689. var listenerObj = goog.events.listenOnce(
  73690. src, type, opt_fn || this.handleEvent, opt_capture,
  73691. opt_scope || this.handler_ || this);
  73692. if (!listenerObj) {
  73693. // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT
  73694. // (goog.events.CaptureSimulationMode) in IE8-, it will return null
  73695. // value.
  73696. return this;
  73697. }
  73698. var key = listenerObj.key;
  73699. this.keys_[key] = listenerObj;
  73700. }
  73701. return this;
  73702. };
  73703. /**
  73704. * Adds an event listener with a specific event wrapper on a DOM Node or an
  73705. * object that has implemented {@link goog.events.EventTarget}. A listener can
  73706. * only be added once to an object.
  73707. *
  73708. * @param {EventTarget|goog.events.EventTarget} src The node to listen to
  73709. * events on.
  73710. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  73711. * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener
  73712. * Callback method, or an object with a handleEvent function.
  73713. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
  73714. * false).
  73715. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73716. * chaining of calls.
  73717. */
  73718. goog.events.EventHandler.prototype.listenWithWrapper = function(
  73719. src, wrapper, listener, opt_capt) {
  73720. // TODO(mknichel): Remove the opt_scope from this function and then
  73721. // templatize it.
  73722. return this.listenWithWrapper_(src, wrapper, listener, opt_capt);
  73723. };
  73724. /**
  73725. * Adds an event listener with a specific event wrapper on a DOM Node or an
  73726. * object that has implemented {@link goog.events.EventTarget}. A listener can
  73727. * only be added once to an object.
  73728. *
  73729. * @param {EventTarget|goog.events.EventTarget} src The node to listen to
  73730. * events on.
  73731. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  73732. * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}
  73733. * listener Optional callback function to be used as the
  73734. * listener or an object with handleEvent function.
  73735. * @param {boolean|undefined} capture Optional whether to use capture phase.
  73736. * @param {T} scope Object in whose scope to call the listener.
  73737. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73738. * chaining of calls.
  73739. * @template T
  73740. */
  73741. goog.events.EventHandler.prototype.listenWithWrapperAndScope = function(
  73742. src, wrapper, listener, capture, scope) {
  73743. // TODO(mknichel): Deprecate this function.
  73744. return this.listenWithWrapper_(src, wrapper, listener, capture, scope);
  73745. };
  73746. /**
  73747. * Adds an event listener with a specific event wrapper on a DOM Node or an
  73748. * object that has implemented {@link goog.events.EventTarget}. A listener can
  73749. * only be added once to an object.
  73750. *
  73751. * @param {EventTarget|goog.events.EventTarget} src The node to listen to
  73752. * events on.
  73753. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  73754. * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback
  73755. * method, or an object with a handleEvent function.
  73756. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to
  73757. * false).
  73758. * @param {Object=} opt_scope Element in whose scope to call the listener.
  73759. * @return {!goog.events.EventHandler<SCOPE>} This object, allowing for
  73760. * chaining of calls.
  73761. * @private
  73762. */
  73763. goog.events.EventHandler.prototype.listenWithWrapper_ = function(
  73764. src, wrapper, listener, opt_capt, opt_scope) {
  73765. wrapper.listen(src, listener, opt_capt, opt_scope || this.handler_ || this,
  73766. this);
  73767. return this;
  73768. };
  73769. /**
  73770. * @return {number} Number of listeners registered by this handler.
  73771. */
  73772. goog.events.EventHandler.prototype.getListenerCount = function() {
  73773. var count = 0;
  73774. for (var key in this.keys_) {
  73775. if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {
  73776. count++;
  73777. }
  73778. }
  73779. return count;
  73780. };
  73781. /**
  73782. * Unlistens on an event.
  73783. * @param {goog.events.ListenableType} src Event source.
  73784. * @param {string|Array<string>|
  73785. * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}
  73786. * type Event type or array of event types to unlisten to.
  73787. * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn
  73788. * Optional callback function to be used as the listener or an object with
  73789. * handleEvent function.
  73790. * @param {boolean=} opt_capture Optional whether to use capture phase.
  73791. * @param {Object=} opt_scope Object in whose scope to call the listener.
  73792. * @return {!goog.events.EventHandler} This object, allowing for chaining of
  73793. * calls.
  73794. * @template EVENTOBJ
  73795. */
  73796. goog.events.EventHandler.prototype.unlisten = function(src, type, opt_fn,
  73797. opt_capture,
  73798. opt_scope) {
  73799. if (goog.isArray(type)) {
  73800. for (var i = 0; i < type.length; i++) {
  73801. this.unlisten(src, type[i], opt_fn, opt_capture, opt_scope);
  73802. }
  73803. } else {
  73804. var listener = goog.events.getListener(src, type,
  73805. opt_fn || this.handleEvent,
  73806. opt_capture, opt_scope || this.handler_ || this);
  73807. if (listener) {
  73808. goog.events.unlistenByKey(listener);
  73809. delete this.keys_[listener.key];
  73810. }
  73811. }
  73812. return this;
  73813. };
  73814. /**
  73815. * Removes an event listener which was added with listenWithWrapper().
  73816. *
  73817. * @param {EventTarget|goog.events.EventTarget} src The target to stop
  73818. * listening to events on.
  73819. * @param {goog.events.EventWrapper} wrapper Event wrapper to use.
  73820. * @param {function(?):?|{handleEvent:function(?):?}|null} listener The
  73821. * listener function to remove.
  73822. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines
  73823. * whether the listener is fired during the capture or bubble phase of the
  73824. * event.
  73825. * @param {Object=} opt_scope Element in whose scope to call the listener.
  73826. * @return {!goog.events.EventHandler} This object, allowing for chaining of
  73827. * calls.
  73828. */
  73829. goog.events.EventHandler.prototype.unlistenWithWrapper = function(src, wrapper,
  73830. listener, opt_capt, opt_scope) {
  73831. wrapper.unlisten(src, listener, opt_capt,
  73832. opt_scope || this.handler_ || this, this);
  73833. return this;
  73834. };
  73835. /**
  73836. * Unlistens to all events.
  73837. */
  73838. goog.events.EventHandler.prototype.removeAll = function() {
  73839. goog.object.forEach(this.keys_, function(listenerObj, key) {
  73840. if (this.keys_.hasOwnProperty(key)) {
  73841. goog.events.unlistenByKey(listenerObj);
  73842. }
  73843. }, this);
  73844. this.keys_ = {};
  73845. };
  73846. /**
  73847. * Disposes of this EventHandler and removes all listeners that it registered.
  73848. * @override
  73849. * @protected
  73850. */
  73851. goog.events.EventHandler.prototype.disposeInternal = function() {
  73852. goog.events.EventHandler.superClass_.disposeInternal.call(this);
  73853. this.removeAll();
  73854. };
  73855. /**
  73856. * Default event handler
  73857. * @param {goog.events.Event} e Event object.
  73858. */
  73859. goog.events.EventHandler.prototype.handleEvent = function(e) {
  73860. throw Error('EventHandler.handleEvent not implemented');
  73861. };
  73862. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  73863. //
  73864. // Licensed under the Apache License, Version 2.0 (the "License");
  73865. // you may not use this file except in compliance with the License.
  73866. // You may obtain a copy of the License at
  73867. //
  73868. // http://www.apache.org/licenses/LICENSE-2.0
  73869. //
  73870. // Unless required by applicable law or agreed to in writing, software
  73871. // distributed under the License is distributed on an "AS-IS" BASIS,
  73872. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  73873. // See the License for the specific language governing permissions and
  73874. // limitations under the License.
  73875. /**
  73876. * @fileoverview Bidi utility functions.
  73877. *
  73878. */
  73879. goog.provide('goog.style.bidi');
  73880. goog.require('goog.dom');
  73881. goog.require('goog.style');
  73882. goog.require('goog.userAgent');
  73883. /**
  73884. * Returns the normalized scrollLeft position for a scrolled element.
  73885. * @param {Element} element The scrolled element.
  73886. * @return {number} The number of pixels the element is scrolled. 0 indicates
  73887. * that the element is not scrolled at all (which, in general, is the
  73888. * left-most position in ltr and the right-most position in rtl).
  73889. */
  73890. goog.style.bidi.getScrollLeft = function(element) {
  73891. var isRtl = goog.style.isRightToLeft(element);
  73892. if (isRtl && goog.userAgent.GECKO) {
  73893. // ScrollLeft starts at 0 and then goes negative as the element is scrolled
  73894. // towards the left.
  73895. return -element.scrollLeft;
  73896. } else if (isRtl &&
  73897. !(goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8'))) {
  73898. // ScrollLeft starts at the maximum positive value and decreases towards
  73899. // 0 as the element is scrolled towards the left. However, for overflow
  73900. // visible, there is no scrollLeft and the value always stays correctly at 0
  73901. var overflowX = goog.style.getComputedOverflowX(element);
  73902. if (overflowX == 'visible') {
  73903. return element.scrollLeft;
  73904. } else {
  73905. return element.scrollWidth - element.clientWidth - element.scrollLeft;
  73906. }
  73907. }
  73908. // ScrollLeft behavior is identical in rtl and ltr, it starts at 0 and
  73909. // increases as the element is scrolled away from the start.
  73910. return element.scrollLeft;
  73911. };
  73912. /**
  73913. * Returns the "offsetStart" of an element, analagous to offsetLeft but
  73914. * normalized for right-to-left environments and various browser
  73915. * inconsistencies. This value returned can always be passed to setScrollOffset
  73916. * to scroll to an element's left edge in a left-to-right offsetParent or
  73917. * right edge in a right-to-left offsetParent.
  73918. *
  73919. * For example, here offsetStart is 10px in an LTR environment and 5px in RTL:
  73920. *
  73921. * <pre>
  73922. * | xxxxxxxxxx |
  73923. * ^^^^^^^^^^ ^^^^ ^^^^^
  73924. * 10px elem 5px
  73925. * </pre>
  73926. *
  73927. * If an element is positioned before the start of its offsetParent, the
  73928. * startOffset may be negative. This can be used with setScrollOffset to
  73929. * reliably scroll to an element:
  73930. *
  73931. * <pre>
  73932. * var scrollOffset = goog.style.bidi.getOffsetStart(element);
  73933. * goog.style.bidi.setScrollOffset(element.offsetParent, scrollOffset);
  73934. * </pre>
  73935. *
  73936. * @see setScrollOffset
  73937. *
  73938. * @param {Element} element The element for which we need to determine the
  73939. * offsetStart position.
  73940. * @return {number} The offsetStart for that element.
  73941. */
  73942. goog.style.bidi.getOffsetStart = function(element) {
  73943. element = /** @type {!HTMLElement} */ (element);
  73944. var offsetLeftForReal = element.offsetLeft;
  73945. // The element might not have an offsetParent.
  73946. // For example, the node might not be attached to the DOM tree,
  73947. // and position:fixed children do not have an offset parent.
  73948. // Just try to do the best we can with what we have.
  73949. var bestParent = element.offsetParent;
  73950. if (!bestParent && goog.style.getComputedPosition(element) == 'fixed') {
  73951. bestParent = goog.dom.getOwnerDocument(element).documentElement;
  73952. }
  73953. // Just give up in this case.
  73954. if (!bestParent) {
  73955. return offsetLeftForReal;
  73956. }
  73957. if (goog.userAgent.GECKO) {
  73958. // When calculating an element's offsetLeft, Firefox erroneously subtracts
  73959. // the border width from the actual distance. So we need to add it back.
  73960. var borderWidths = goog.style.getBorderBox(bestParent);
  73961. offsetLeftForReal += borderWidths.left;
  73962. } else if (goog.userAgent.isDocumentModeOrHigher(8) &&
  73963. !goog.userAgent.isDocumentModeOrHigher(9)) {
  73964. // When calculating an element's offsetLeft, IE8/9-Standards Mode
  73965. // erroneously adds the border width to the actual distance. So we need to
  73966. // subtract it.
  73967. var borderWidths = goog.style.getBorderBox(bestParent);
  73968. offsetLeftForReal -= borderWidths.left;
  73969. }
  73970. if (goog.style.isRightToLeft(bestParent)) {
  73971. // Right edge of the element relative to the left edge of its parent.
  73972. var elementRightOffset = offsetLeftForReal + element.offsetWidth;
  73973. // Distance from the parent's right edge to the element's right edge.
  73974. return bestParent.clientWidth - elementRightOffset;
  73975. }
  73976. return offsetLeftForReal;
  73977. };
  73978. /**
  73979. * Sets the element's scrollLeft attribute so it is correctly scrolled by
  73980. * offsetStart pixels. This takes into account whether the element is RTL and
  73981. * the nuances of different browsers. To scroll to the "beginning" of an
  73982. * element use getOffsetStart to obtain the element's offsetStart value and then
  73983. * pass the value to setScrollOffset.
  73984. * @see getOffsetStart
  73985. * @param {Element} element The element to set scrollLeft on.
  73986. * @param {number} offsetStart The number of pixels to scroll the element.
  73987. * If this value is < 0, 0 is used.
  73988. */
  73989. goog.style.bidi.setScrollOffset = function(element, offsetStart) {
  73990. offsetStart = Math.max(offsetStart, 0);
  73991. // In LTR and in "mirrored" browser RTL (such as IE), we set scrollLeft to
  73992. // the number of pixels to scroll.
  73993. // Otherwise, in RTL, we need to account for different browser behavior.
  73994. if (!goog.style.isRightToLeft(element)) {
  73995. element.scrollLeft = offsetStart;
  73996. } else if (goog.userAgent.GECKO) {
  73997. // Negative scroll-left positions in RTL.
  73998. element.scrollLeft = -offsetStart;
  73999. } else if (!(goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8'))) {
  74000. // Take the current scrollLeft value and move to the right by the
  74001. // offsetStart to get to the left edge of the element, and then by
  74002. // the clientWidth of the element to get to the right edge.
  74003. element.scrollLeft =
  74004. element.scrollWidth - offsetStart - element.clientWidth;
  74005. } else {
  74006. element.scrollLeft = offsetStart;
  74007. }
  74008. };
  74009. /**
  74010. * Sets the element's left style attribute in LTR or right style attribute in
  74011. * RTL. Also clears the left attribute in RTL and the right attribute in LTR.
  74012. * @param {Element} elem The element to position.
  74013. * @param {number} left The left position in LTR; will be set as right in RTL.
  74014. * @param {?number} top The top position. If null only the left/right is set.
  74015. * @param {boolean} isRtl Whether we are in RTL mode.
  74016. */
  74017. goog.style.bidi.setPosition = function(elem, left, top, isRtl) {
  74018. if (!goog.isNull(top)) {
  74019. elem.style.top = top + 'px';
  74020. }
  74021. if (isRtl) {
  74022. elem.style.right = left + 'px';
  74023. elem.style.left = '';
  74024. } else {
  74025. elem.style.left = left + 'px';
  74026. elem.style.right = '';
  74027. }
  74028. };
  74029. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  74030. //
  74031. // Licensed under the Apache License, Version 2.0 (the "License");
  74032. // you may not use this file except in compliance with the License.
  74033. // You may obtain a copy of the License at
  74034. //
  74035. // http://www.apache.org/licenses/LICENSE-2.0
  74036. //
  74037. // Unless required by applicable law or agreed to in writing, software
  74038. // distributed under the License is distributed on an "AS-IS" BASIS,
  74039. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  74040. // See the License for the specific language governing permissions and
  74041. // limitations under the License.
  74042. /**
  74043. * @fileoverview Drag Utilities.
  74044. *
  74045. * Provides extensible functionality for drag & drop behaviour.
  74046. *
  74047. * @see ../demos/drag.html
  74048. * @see ../demos/dragger.html
  74049. */
  74050. goog.provide('goog.fx.DragEvent');
  74051. goog.provide('goog.fx.Dragger');
  74052. goog.provide('goog.fx.Dragger.EventType');
  74053. goog.require('goog.dom');
  74054. goog.require('goog.dom.TagName');
  74055. goog.require('goog.events');
  74056. goog.require('goog.events.Event');
  74057. goog.require('goog.events.EventHandler');
  74058. goog.require('goog.events.EventTarget');
  74059. goog.require('goog.events.EventType');
  74060. goog.require('goog.math.Coordinate');
  74061. goog.require('goog.math.Rect');
  74062. goog.require('goog.style');
  74063. goog.require('goog.style.bidi');
  74064. goog.require('goog.userAgent');
  74065. /**
  74066. * A class that allows mouse or touch-based dragging (moving) of an element
  74067. *
  74068. * @param {Element} target The element that will be dragged.
  74069. * @param {Element=} opt_handle An optional handle to control the drag, if null
  74070. * the target is used.
  74071. * @param {goog.math.Rect=} opt_limits Object containing left, top, width,
  74072. * and height.
  74073. *
  74074. * @extends {goog.events.EventTarget}
  74075. * @constructor
  74076. * @struct
  74077. */
  74078. goog.fx.Dragger = function(target, opt_handle, opt_limits) {
  74079. goog.fx.Dragger.base(this, 'constructor');
  74080. /**
  74081. * Reference to drag target element.
  74082. * @type {?Element}
  74083. */
  74084. this.target = target;
  74085. /**
  74086. * Reference to the handler that initiates the drag.
  74087. * @type {?Element}
  74088. */
  74089. this.handle = opt_handle || target;
  74090. /**
  74091. * Object representing the limits of the drag region.
  74092. * @type {goog.math.Rect}
  74093. */
  74094. this.limits = opt_limits || new goog.math.Rect(NaN, NaN, NaN, NaN);
  74095. /**
  74096. * Reference to a document object to use for the events.
  74097. * @private {Document}
  74098. */
  74099. this.document_ = goog.dom.getOwnerDocument(target);
  74100. /** @private {!goog.events.EventHandler} */
  74101. this.eventHandler_ = new goog.events.EventHandler(this);
  74102. this.registerDisposable(this.eventHandler_);
  74103. /**
  74104. * Whether the element is rendered right-to-left. We initialize this lazily.
  74105. * @private {boolean|undefined}}
  74106. */
  74107. this.rightToLeft_;
  74108. /**
  74109. * Current x position of mouse or touch relative to viewport.
  74110. * @type {number}
  74111. */
  74112. this.clientX = 0;
  74113. /**
  74114. * Current y position of mouse or touch relative to viewport.
  74115. * @type {number}
  74116. */
  74117. this.clientY = 0;
  74118. /**
  74119. * Current x position of mouse or touch relative to screen. Deprecated because
  74120. * it doesn't take into affect zoom level or pixel density.
  74121. * @type {number}
  74122. * @deprecated Consider switching to clientX instead.
  74123. */
  74124. this.screenX = 0;
  74125. /**
  74126. * Current y position of mouse or touch relative to screen. Deprecated because
  74127. * it doesn't take into affect zoom level or pixel density.
  74128. * @type {number}
  74129. * @deprecated Consider switching to clientY instead.
  74130. */
  74131. this.screenY = 0;
  74132. /**
  74133. * The x position where the first mousedown or touchstart occurred.
  74134. * @type {number}
  74135. */
  74136. this.startX = 0;
  74137. /**
  74138. * The y position where the first mousedown or touchstart occurred.
  74139. * @type {number}
  74140. */
  74141. this.startY = 0;
  74142. /**
  74143. * Current x position of drag relative to target's parent.
  74144. * @type {number}
  74145. */
  74146. this.deltaX = 0;
  74147. /**
  74148. * Current y position of drag relative to target's parent.
  74149. * @type {number}
  74150. */
  74151. this.deltaY = 0;
  74152. /**
  74153. * The current page scroll value.
  74154. * @type {?goog.math.Coordinate}
  74155. */
  74156. this.pageScroll;
  74157. /**
  74158. * Whether dragging is currently enabled.
  74159. * @private {boolean}
  74160. */
  74161. this.enabled_ = true;
  74162. /**
  74163. * Whether object is currently being dragged.
  74164. * @private {boolean}
  74165. */
  74166. this.dragging_ = false;
  74167. /**
  74168. * Whether mousedown should be default prevented.
  74169. * @private {boolean}
  74170. **/
  74171. this.preventMouseDown_ = true;
  74172. /**
  74173. * The amount of distance, in pixels, after which a mousedown or touchstart is
  74174. * considered a drag.
  74175. * @private {number}
  74176. */
  74177. this.hysteresisDistanceSquared_ = 0;
  74178. /**
  74179. * The SCROLL event target used to make drag element follow scrolling.
  74180. * @private {?EventTarget}
  74181. */
  74182. this.scrollTarget_;
  74183. /**
  74184. * Whether IE drag events cancelling is on.
  74185. * @private {boolean}
  74186. */
  74187. this.ieDragStartCancellingOn_ = false;
  74188. /**
  74189. * Whether the dragger implements the changes described in http://b/6324964,
  74190. * making it truly RTL. This is a temporary flag to allow clients to
  74191. * transition to the new behavior at their convenience. At some point it will
  74192. * be the default.
  74193. * @private {boolean}
  74194. */
  74195. this.useRightPositioningForRtl_ = false;
  74196. // Add listener. Do not use the event handler here since the event handler is
  74197. // used for listeners added and removed during the drag operation.
  74198. goog.events.listen(this.handle,
  74199. [goog.events.EventType.TOUCHSTART, goog.events.EventType.MOUSEDOWN],
  74200. this.startDrag, false, this);
  74201. };
  74202. goog.inherits(goog.fx.Dragger, goog.events.EventTarget);
  74203. // Dragger is meant to be extended, but defines most properties on its
  74204. // prototype, thus making it unsuitable for sealing.
  74205. goog.tagUnsealableClass(goog.fx.Dragger);
  74206. /**
  74207. * Whether setCapture is supported by the browser.
  74208. * @type {boolean}
  74209. * @private
  74210. */
  74211. goog.fx.Dragger.HAS_SET_CAPTURE_ =
  74212. // IE and Gecko after 1.9.3 has setCapture
  74213. // WebKit does not yet: https://bugs.webkit.org/show_bug.cgi?id=27330
  74214. goog.userAgent.IE ||
  74215. goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9.3');
  74216. /**
  74217. * Creates copy of node being dragged. This is a utility function to be used
  74218. * wherever it is inappropriate for the original source to follow the mouse
  74219. * cursor itself.
  74220. *
  74221. * @param {Element} sourceEl Element to copy.
  74222. * @return {!Element} The clone of {@code sourceEl}.
  74223. */
  74224. goog.fx.Dragger.cloneNode = function(sourceEl) {
  74225. var clonedEl = /** @type {Element} */ (sourceEl.cloneNode(true)),
  74226. origTexts = sourceEl.getElementsByTagName(goog.dom.TagName.TEXTAREA),
  74227. dragTexts = clonedEl.getElementsByTagName(goog.dom.TagName.TEXTAREA);
  74228. // Cloning does not copy the current value of textarea elements, so correct
  74229. // this manually.
  74230. for (var i = 0; i < origTexts.length; i++) {
  74231. dragTexts[i].value = origTexts[i].value;
  74232. }
  74233. switch (sourceEl.tagName) {
  74234. case goog.dom.TagName.TR:
  74235. return goog.dom.createDom(goog.dom.TagName.TABLE, null,
  74236. goog.dom.createDom(goog.dom.TagName.TBODY,
  74237. null, clonedEl));
  74238. case goog.dom.TagName.TD:
  74239. case goog.dom.TagName.TH:
  74240. return goog.dom.createDom(
  74241. goog.dom.TagName.TABLE, null, goog.dom.createDom(
  74242. goog.dom.TagName.TBODY, null, goog.dom.createDom(
  74243. goog.dom.TagName.TR, null, clonedEl)));
  74244. case goog.dom.TagName.TEXTAREA:
  74245. clonedEl.value = sourceEl.value;
  74246. default:
  74247. return clonedEl;
  74248. }
  74249. };
  74250. /**
  74251. * Constants for event names.
  74252. * @enum {string}
  74253. */
  74254. goog.fx.Dragger.EventType = {
  74255. // The drag action was canceled before the START event. Possible reasons:
  74256. // disabled dragger, dragging with the right mouse button or releasing the
  74257. // button before reaching the hysteresis distance.
  74258. EARLY_CANCEL: 'earlycancel',
  74259. START: 'start',
  74260. BEFOREDRAG: 'beforedrag',
  74261. DRAG: 'drag',
  74262. END: 'end'
  74263. };
  74264. /**
  74265. * Turns on/off true RTL behavior. This should be called immediately after
  74266. * construction. This is a temporary flag to allow clients to transition
  74267. * to the new component at their convenience. At some point true will be the
  74268. * default.
  74269. * @param {boolean} useRightPositioningForRtl True if "right" should be used for
  74270. * positioning, false if "left" should be used for positioning.
  74271. */
  74272. goog.fx.Dragger.prototype.enableRightPositioningForRtl =
  74273. function(useRightPositioningForRtl) {
  74274. this.useRightPositioningForRtl_ = useRightPositioningForRtl;
  74275. };
  74276. /**
  74277. * Returns the event handler, intended for subclass use.
  74278. * @return {!goog.events.EventHandler<T>} The event handler.
  74279. * @this {T}
  74280. * @template T
  74281. */
  74282. goog.fx.Dragger.prototype.getHandler = function() {
  74283. // TODO(user): templated "this" values currently result in "this" being
  74284. // "unknown" in the body of the function.
  74285. var self = /** @type {goog.fx.Dragger} */ (this);
  74286. return self.eventHandler_;
  74287. };
  74288. /**
  74289. * Sets (or reset) the Drag limits after a Dragger is created.
  74290. * @param {goog.math.Rect?} limits Object containing left, top, width,
  74291. * height for new Dragger limits. If target is right-to-left and
  74292. * enableRightPositioningForRtl(true) is called, then rect is interpreted as
  74293. * right, top, width, and height.
  74294. */
  74295. goog.fx.Dragger.prototype.setLimits = function(limits) {
  74296. this.limits = limits || new goog.math.Rect(NaN, NaN, NaN, NaN);
  74297. };
  74298. /**
  74299. * Sets the distance the user has to drag the element before a drag operation is
  74300. * started.
  74301. * @param {number} distance The number of pixels after which a mousedown and
  74302. * move is considered a drag.
  74303. */
  74304. goog.fx.Dragger.prototype.setHysteresis = function(distance) {
  74305. this.hysteresisDistanceSquared_ = Math.pow(distance, 2);
  74306. };
  74307. /**
  74308. * Gets the distance the user has to drag the element before a drag operation is
  74309. * started.
  74310. * @return {number} distance The number of pixels after which a mousedown and
  74311. * move is considered a drag.
  74312. */
  74313. goog.fx.Dragger.prototype.getHysteresis = function() {
  74314. return Math.sqrt(this.hysteresisDistanceSquared_);
  74315. };
  74316. /**
  74317. * Sets the SCROLL event target to make drag element follow scrolling.
  74318. *
  74319. * @param {EventTarget} scrollTarget The event target that dispatches SCROLL
  74320. * events.
  74321. */
  74322. goog.fx.Dragger.prototype.setScrollTarget = function(scrollTarget) {
  74323. this.scrollTarget_ = scrollTarget;
  74324. };
  74325. /**
  74326. * Enables cancelling of built-in IE drag events.
  74327. * @param {boolean} cancelIeDragStart Whether to enable cancelling of IE
  74328. * dragstart event.
  74329. */
  74330. goog.fx.Dragger.prototype.setCancelIeDragStart = function(cancelIeDragStart) {
  74331. this.ieDragStartCancellingOn_ = cancelIeDragStart;
  74332. };
  74333. /**
  74334. * @return {boolean} Whether the dragger is enabled.
  74335. */
  74336. goog.fx.Dragger.prototype.getEnabled = function() {
  74337. return this.enabled_;
  74338. };
  74339. /**
  74340. * Set whether dragger is enabled
  74341. * @param {boolean} enabled Whether dragger is enabled.
  74342. */
  74343. goog.fx.Dragger.prototype.setEnabled = function(enabled) {
  74344. this.enabled_ = enabled;
  74345. };
  74346. /**
  74347. * Set whether mousedown should be default prevented.
  74348. * @param {boolean} preventMouseDown Whether mousedown should be default
  74349. * prevented.
  74350. */
  74351. goog.fx.Dragger.prototype.setPreventMouseDown = function(preventMouseDown) {
  74352. this.preventMouseDown_ = preventMouseDown;
  74353. };
  74354. /** @override */
  74355. goog.fx.Dragger.prototype.disposeInternal = function() {
  74356. goog.fx.Dragger.superClass_.disposeInternal.call(this);
  74357. goog.events.unlisten(this.handle,
  74358. [goog.events.EventType.TOUCHSTART, goog.events.EventType.MOUSEDOWN],
  74359. this.startDrag, false, this);
  74360. this.cleanUpAfterDragging_();
  74361. this.target = null;
  74362. this.handle = null;
  74363. };
  74364. /**
  74365. * Whether the DOM element being manipulated is rendered right-to-left.
  74366. * @return {boolean} True if the DOM element is rendered right-to-left, false
  74367. * otherwise.
  74368. * @private
  74369. */
  74370. goog.fx.Dragger.prototype.isRightToLeft_ = function() {
  74371. if (!goog.isDef(this.rightToLeft_)) {
  74372. this.rightToLeft_ = goog.style.isRightToLeft(this.target);
  74373. }
  74374. return this.rightToLeft_;
  74375. };
  74376. /**
  74377. * Event handler that is used to start the drag
  74378. * @param {goog.events.BrowserEvent} e Event object.
  74379. */
  74380. goog.fx.Dragger.prototype.startDrag = function(e) {
  74381. var isMouseDown = e.type == goog.events.EventType.MOUSEDOWN;
  74382. // Dragger.startDrag() can be called by AbstractDragDrop with a mousemove
  74383. // event and IE does not report pressed mouse buttons on mousemove. Also,
  74384. // it does not make sense to check for the button if the user is already
  74385. // dragging.
  74386. if (this.enabled_ && !this.dragging_ &&
  74387. (!isMouseDown || e.isMouseActionButton())) {
  74388. if (this.hysteresisDistanceSquared_ == 0) {
  74389. if (this.fireDragStart_(e)) {
  74390. this.dragging_ = true;
  74391. if (this.preventMouseDown_) {
  74392. e.preventDefault();
  74393. }
  74394. } else {
  74395. // If the start drag is cancelled, don't setup for a drag.
  74396. return;
  74397. }
  74398. } else if (this.preventMouseDown_) {
  74399. // Need to preventDefault for hysteresis to prevent page getting selected.
  74400. e.preventDefault();
  74401. }
  74402. this.setupDragHandlers();
  74403. this.clientX = this.startX = e.clientX;
  74404. this.clientY = this.startY = e.clientY;
  74405. this.screenX = e.screenX;
  74406. this.screenY = e.screenY;
  74407. this.computeInitialPosition();
  74408. this.pageScroll = goog.dom.getDomHelper(this.document_).getDocumentScroll();
  74409. } else {
  74410. this.dispatchEvent(goog.fx.Dragger.EventType.EARLY_CANCEL);
  74411. }
  74412. };
  74413. /**
  74414. * Sets up event handlers when dragging starts.
  74415. * @protected
  74416. */
  74417. goog.fx.Dragger.prototype.setupDragHandlers = function() {
  74418. var doc = this.document_;
  74419. var docEl = doc.documentElement;
  74420. // Use bubbling when we have setCapture since we got reports that IE has
  74421. // problems with the capturing events in combination with setCapture.
  74422. var useCapture = !goog.fx.Dragger.HAS_SET_CAPTURE_;
  74423. this.eventHandler_.listen(doc,
  74424. [goog.events.EventType.TOUCHMOVE, goog.events.EventType.MOUSEMOVE],
  74425. this.handleMove_, useCapture);
  74426. this.eventHandler_.listen(doc,
  74427. [goog.events.EventType.TOUCHEND, goog.events.EventType.MOUSEUP],
  74428. this.endDrag, useCapture);
  74429. if (goog.fx.Dragger.HAS_SET_CAPTURE_) {
  74430. docEl.setCapture(false);
  74431. this.eventHandler_.listen(docEl,
  74432. goog.events.EventType.LOSECAPTURE,
  74433. this.endDrag);
  74434. } else {
  74435. // Make sure we stop the dragging if the window loses focus.
  74436. // Don't use capture in this listener because we only want to end the drag
  74437. // if the actual window loses focus. Since blur events do not bubble we use
  74438. // a bubbling listener on the window.
  74439. this.eventHandler_.listen(goog.dom.getWindow(doc),
  74440. goog.events.EventType.BLUR,
  74441. this.endDrag);
  74442. }
  74443. if (goog.userAgent.IE && this.ieDragStartCancellingOn_) {
  74444. // Cancel IE's 'ondragstart' event.
  74445. this.eventHandler_.listen(doc, goog.events.EventType.DRAGSTART,
  74446. goog.events.Event.preventDefault);
  74447. }
  74448. if (this.scrollTarget_) {
  74449. this.eventHandler_.listen(this.scrollTarget_, goog.events.EventType.SCROLL,
  74450. this.onScroll_, useCapture);
  74451. }
  74452. };
  74453. /**
  74454. * Fires a goog.fx.Dragger.EventType.START event.
  74455. * @param {goog.events.BrowserEvent} e Browser event that triggered the drag.
  74456. * @return {boolean} False iff preventDefault was called on the DragEvent.
  74457. * @private
  74458. */
  74459. goog.fx.Dragger.prototype.fireDragStart_ = function(e) {
  74460. return this.dispatchEvent(new goog.fx.DragEvent(
  74461. goog.fx.Dragger.EventType.START, this, e.clientX, e.clientY, e));
  74462. };
  74463. /**
  74464. * Unregisters the event handlers that are only active during dragging, and
  74465. * releases mouse capture.
  74466. * @private
  74467. */
  74468. goog.fx.Dragger.prototype.cleanUpAfterDragging_ = function() {
  74469. this.eventHandler_.removeAll();
  74470. if (goog.fx.Dragger.HAS_SET_CAPTURE_) {
  74471. this.document_.releaseCapture();
  74472. }
  74473. };
  74474. /**
  74475. * Event handler that is used to end the drag.
  74476. * @param {goog.events.BrowserEvent} e Event object.
  74477. * @param {boolean=} opt_dragCanceled Whether the drag has been canceled.
  74478. */
  74479. goog.fx.Dragger.prototype.endDrag = function(e, opt_dragCanceled) {
  74480. this.cleanUpAfterDragging_();
  74481. if (this.dragging_) {
  74482. this.dragging_ = false;
  74483. var x = this.limitX(this.deltaX);
  74484. var y = this.limitY(this.deltaY);
  74485. var dragCanceled = opt_dragCanceled ||
  74486. e.type == goog.events.EventType.TOUCHCANCEL;
  74487. this.dispatchEvent(new goog.fx.DragEvent(
  74488. goog.fx.Dragger.EventType.END, this, e.clientX, e.clientY, e, x, y,
  74489. dragCanceled));
  74490. } else {
  74491. this.dispatchEvent(goog.fx.Dragger.EventType.EARLY_CANCEL);
  74492. }
  74493. };
  74494. /**
  74495. * Event handler that is used to end the drag by cancelling it.
  74496. * @param {goog.events.BrowserEvent} e Event object.
  74497. */
  74498. goog.fx.Dragger.prototype.endDragCancel = function(e) {
  74499. this.endDrag(e, true);
  74500. };
  74501. /**
  74502. * Event handler that is used on mouse / touch move to update the drag
  74503. * @param {goog.events.BrowserEvent} e Event object.
  74504. * @private
  74505. */
  74506. goog.fx.Dragger.prototype.handleMove_ = function(e) {
  74507. if (this.enabled_) {
  74508. // dx in right-to-left cases is relative to the right.
  74509. var sign = this.useRightPositioningForRtl_ &&
  74510. this.isRightToLeft_() ? -1 : 1;
  74511. var dx = sign * (e.clientX - this.clientX);
  74512. var dy = e.clientY - this.clientY;
  74513. this.clientX = e.clientX;
  74514. this.clientY = e.clientY;
  74515. this.screenX = e.screenX;
  74516. this.screenY = e.screenY;
  74517. if (!this.dragging_) {
  74518. var diffX = this.startX - this.clientX;
  74519. var diffY = this.startY - this.clientY;
  74520. var distance = diffX * diffX + diffY * diffY;
  74521. if (distance > this.hysteresisDistanceSquared_) {
  74522. if (this.fireDragStart_(e)) {
  74523. this.dragging_ = true;
  74524. } else {
  74525. // DragListGroup disposes of the dragger if BEFOREDRAGSTART is
  74526. // canceled.
  74527. if (!this.isDisposed()) {
  74528. this.endDrag(e);
  74529. }
  74530. return;
  74531. }
  74532. }
  74533. }
  74534. var pos = this.calculatePosition_(dx, dy);
  74535. var x = pos.x;
  74536. var y = pos.y;
  74537. if (this.dragging_) {
  74538. var rv = this.dispatchEvent(new goog.fx.DragEvent(
  74539. goog.fx.Dragger.EventType.BEFOREDRAG, this, e.clientX, e.clientY,
  74540. e, x, y));
  74541. // Only do the defaultAction and dispatch drag event if predrag didn't
  74542. // prevent default
  74543. if (rv) {
  74544. this.doDrag(e, x, y, false);
  74545. e.preventDefault();
  74546. }
  74547. }
  74548. }
  74549. };
  74550. /**
  74551. * Calculates the drag position.
  74552. *
  74553. * @param {number} dx The horizontal movement delta.
  74554. * @param {number} dy The vertical movement delta.
  74555. * @return {!goog.math.Coordinate} The newly calculated drag element position.
  74556. * @private
  74557. */
  74558. goog.fx.Dragger.prototype.calculatePosition_ = function(dx, dy) {
  74559. // Update the position for any change in body scrolling
  74560. var pageScroll = goog.dom.getDomHelper(this.document_).getDocumentScroll();
  74561. dx += pageScroll.x - this.pageScroll.x;
  74562. dy += pageScroll.y - this.pageScroll.y;
  74563. this.pageScroll = pageScroll;
  74564. this.deltaX += dx;
  74565. this.deltaY += dy;
  74566. var x = this.limitX(this.deltaX);
  74567. var y = this.limitY(this.deltaY);
  74568. return new goog.math.Coordinate(x, y);
  74569. };
  74570. /**
  74571. * Event handler for scroll target scrolling.
  74572. * @param {goog.events.BrowserEvent} e The event.
  74573. * @private
  74574. */
  74575. goog.fx.Dragger.prototype.onScroll_ = function(e) {
  74576. var pos = this.calculatePosition_(0, 0);
  74577. e.clientX = this.clientX;
  74578. e.clientY = this.clientY;
  74579. this.doDrag(e, pos.x, pos.y, true);
  74580. };
  74581. /**
  74582. * @param {goog.events.BrowserEvent} e The closure object
  74583. * representing the browser event that caused a drag event.
  74584. * @param {number} x The new horizontal position for the drag element.
  74585. * @param {number} y The new vertical position for the drag element.
  74586. * @param {boolean} dragFromScroll Whether dragging was caused by scrolling
  74587. * the associated scroll target.
  74588. * @protected
  74589. */
  74590. goog.fx.Dragger.prototype.doDrag = function(e, x, y, dragFromScroll) {
  74591. this.defaultAction(x, y);
  74592. this.dispatchEvent(new goog.fx.DragEvent(
  74593. goog.fx.Dragger.EventType.DRAG, this, e.clientX, e.clientY, e, x, y));
  74594. };
  74595. /**
  74596. * Returns the 'real' x after limits are applied (allows for some
  74597. * limits to be undefined).
  74598. * @param {number} x X-coordinate to limit.
  74599. * @return {number} The 'real' X-coordinate after limits are applied.
  74600. */
  74601. goog.fx.Dragger.prototype.limitX = function(x) {
  74602. var rect = this.limits;
  74603. var left = !isNaN(rect.left) ? rect.left : null;
  74604. var width = !isNaN(rect.width) ? rect.width : 0;
  74605. var maxX = left != null ? left + width : Infinity;
  74606. var minX = left != null ? left : -Infinity;
  74607. return Math.min(maxX, Math.max(minX, x));
  74608. };
  74609. /**
  74610. * Returns the 'real' y after limits are applied (allows for some
  74611. * limits to be undefined).
  74612. * @param {number} y Y-coordinate to limit.
  74613. * @return {number} The 'real' Y-coordinate after limits are applied.
  74614. */
  74615. goog.fx.Dragger.prototype.limitY = function(y) {
  74616. var rect = this.limits;
  74617. var top = !isNaN(rect.top) ? rect.top : null;
  74618. var height = !isNaN(rect.height) ? rect.height : 0;
  74619. var maxY = top != null ? top + height : Infinity;
  74620. var minY = top != null ? top : -Infinity;
  74621. return Math.min(maxY, Math.max(minY, y));
  74622. };
  74623. /**
  74624. * Overridable function for computing the initial position of the target
  74625. * before dragging begins.
  74626. * @protected
  74627. */
  74628. goog.fx.Dragger.prototype.computeInitialPosition = function() {
  74629. this.deltaX = this.useRightPositioningForRtl_ ?
  74630. goog.style.bidi.getOffsetStart(this.target) :
  74631. /** @type {!HTMLElement} */ (this.target).offsetLeft;
  74632. this.deltaY = /** @type {!HTMLElement} */ (this.target).offsetTop;
  74633. };
  74634. /**
  74635. * Overridable function for handling the default action of the drag behaviour.
  74636. * Normally this is simply moving the element to x,y though in some cases it
  74637. * might be used to resize the layer. This is basically a shortcut to
  74638. * implementing a default ondrag event handler.
  74639. * @param {number} x X-coordinate for target element. In right-to-left, x this
  74640. * is the number of pixels the target should be moved to from the right.
  74641. * @param {number} y Y-coordinate for target element.
  74642. */
  74643. goog.fx.Dragger.prototype.defaultAction = function(x, y) {
  74644. if (this.useRightPositioningForRtl_ && this.isRightToLeft_()) {
  74645. this.target.style.right = x + 'px';
  74646. } else {
  74647. this.target.style.left = x + 'px';
  74648. }
  74649. this.target.style.top = y + 'px';
  74650. };
  74651. /**
  74652. * @return {boolean} Whether the dragger is currently in the midst of a drag.
  74653. */
  74654. goog.fx.Dragger.prototype.isDragging = function() {
  74655. return this.dragging_;
  74656. };
  74657. /**
  74658. * Object representing a drag event
  74659. * @param {string} type Event type.
  74660. * @param {goog.fx.Dragger} dragobj Drag object initiating event.
  74661. * @param {number} clientX X-coordinate relative to the viewport.
  74662. * @param {number} clientY Y-coordinate relative to the viewport.
  74663. * @param {goog.events.BrowserEvent} browserEvent The closure object
  74664. * representing the browser event that caused this drag event.
  74665. * @param {number=} opt_actX Optional actual x for drag if it has been limited.
  74666. * @param {number=} opt_actY Optional actual y for drag if it has been limited.
  74667. * @param {boolean=} opt_dragCanceled Whether the drag has been canceled.
  74668. * @constructor
  74669. * @struct
  74670. * @extends {goog.events.Event}
  74671. */
  74672. goog.fx.DragEvent = function(type, dragobj, clientX, clientY, browserEvent,
  74673. opt_actX, opt_actY, opt_dragCanceled) {
  74674. goog.events.Event.call(this, type);
  74675. /**
  74676. * X-coordinate relative to the viewport
  74677. * @type {number}
  74678. */
  74679. this.clientX = clientX;
  74680. /**
  74681. * Y-coordinate relative to the viewport
  74682. * @type {number}
  74683. */
  74684. this.clientY = clientY;
  74685. /**
  74686. * The closure object representing the browser event that caused this drag
  74687. * event.
  74688. * @type {goog.events.BrowserEvent}
  74689. */
  74690. this.browserEvent = browserEvent;
  74691. /**
  74692. * The real x-position of the drag if it has been limited
  74693. * @type {number}
  74694. */
  74695. this.left = goog.isDef(opt_actX) ? opt_actX : dragobj.deltaX;
  74696. /**
  74697. * The real y-position of the drag if it has been limited
  74698. * @type {number}
  74699. */
  74700. this.top = goog.isDef(opt_actY) ? opt_actY : dragobj.deltaY;
  74701. /**
  74702. * Reference to the drag object for this event
  74703. * @type {goog.fx.Dragger}
  74704. */
  74705. this.dragger = dragobj;
  74706. /**
  74707. * Whether drag was canceled with this event. Used to differentiate between
  74708. * a legitimate drag END that can result in an action and a drag END which is
  74709. * a result of a drag cancelation. For now it can happen 1) with drag END
  74710. * event on FireFox when user drags the mouse out of the window, 2) with
  74711. * drag END event on IE7 which is generated on MOUSEMOVE event when user
  74712. * moves the mouse into the document after the mouse button has been
  74713. * released, 3) when TOUCHCANCEL is raised instead of TOUCHEND (on touch
  74714. * events).
  74715. * @type {boolean}
  74716. */
  74717. this.dragCanceled = !!opt_dragCanceled;
  74718. };
  74719. goog.inherits(goog.fx.DragEvent, goog.events.Event);
  74720. // FIXME should possibly show tooltip when dragging?
  74721. goog.provide('ol.control.ZoomSlider');
  74722. goog.require('goog.asserts');
  74723. goog.require('goog.dom');
  74724. goog.require('goog.dom.TagName');
  74725. goog.require('goog.events');
  74726. goog.require('goog.events.Event');
  74727. goog.require('goog.events.EventType');
  74728. goog.require('goog.fx.DragEvent');
  74729. goog.require('goog.fx.Dragger');
  74730. goog.require('goog.fx.Dragger.EventType');
  74731. goog.require('goog.math.Rect');
  74732. goog.require('goog.style');
  74733. goog.require('ol.Size');
  74734. goog.require('ol.ViewHint');
  74735. goog.require('ol.animation');
  74736. goog.require('ol.control.Control');
  74737. goog.require('ol.css');
  74738. goog.require('ol.easing');
  74739. goog.require('ol.math');
  74740. /**
  74741. * @classdesc
  74742. * A slider type of control for zooming.
  74743. *
  74744. * Example:
  74745. *
  74746. * map.addControl(new ol.control.ZoomSlider());
  74747. *
  74748. * @constructor
  74749. * @extends {ol.control.Control}
  74750. * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options.
  74751. * @api stable
  74752. */
  74753. ol.control.ZoomSlider = function(opt_options) {
  74754. var options = opt_options ? opt_options : {};
  74755. /**
  74756. * Will hold the current resolution of the view.
  74757. *
  74758. * @type {number|undefined}
  74759. * @private
  74760. */
  74761. this.currentResolution_ = undefined;
  74762. /**
  74763. * The direction of the slider. Will be determined from actual display of the
  74764. * container and defaults to ol.control.ZoomSlider.direction.VERTICAL.
  74765. *
  74766. * @type {ol.control.ZoomSlider.direction}
  74767. * @private
  74768. */
  74769. this.direction_ = ol.control.ZoomSlider.direction.VERTICAL;
  74770. /**
  74771. * The calculated thumb size (border box plus margins). Set when initSlider_
  74772. * is called.
  74773. * @type {ol.Size}
  74774. * @private
  74775. */
  74776. this.thumbSize_ = null;
  74777. /**
  74778. * Whether the slider is initialized.
  74779. * @type {boolean}
  74780. * @private
  74781. */
  74782. this.sliderInitialized_ = false;
  74783. /**
  74784. * @private
  74785. * @type {number}
  74786. */
  74787. this.duration_ = options.duration ? options.duration : 200;
  74788. var className = options.className ? options.className : 'ol-zoomslider';
  74789. var thumbElement = goog.dom.createDom(goog.dom.TagName.DIV,
  74790. [className + '-thumb', ol.css.CLASS_UNSELECTABLE]);
  74791. var containerElement = goog.dom.createDom(goog.dom.TagName.DIV,
  74792. [className, ol.css.CLASS_UNSELECTABLE, ol.css.CLASS_CONTROL],
  74793. thumbElement);
  74794. /**
  74795. * @type {goog.fx.Dragger}
  74796. * @private
  74797. */
  74798. this.dragger_ = new goog.fx.Dragger(thumbElement);
  74799. this.registerDisposable(this.dragger_);
  74800. goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.START,
  74801. this.handleDraggerStart_, false, this);
  74802. goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.DRAG,
  74803. this.handleDraggerDrag_, false, this);
  74804. goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.END,
  74805. this.handleDraggerEnd_, false, this);
  74806. goog.events.listen(containerElement, goog.events.EventType.CLICK,
  74807. this.handleContainerClick_, false, this);
  74808. goog.events.listen(thumbElement, goog.events.EventType.CLICK,
  74809. goog.events.Event.stopPropagation);
  74810. var render = options.render ? options.render : ol.control.ZoomSlider.render;
  74811. goog.base(this, {
  74812. element: containerElement,
  74813. render: render
  74814. });
  74815. };
  74816. goog.inherits(ol.control.ZoomSlider, ol.control.Control);
  74817. /**
  74818. * The enum for available directions.
  74819. *
  74820. * @enum {number}
  74821. */
  74822. ol.control.ZoomSlider.direction = {
  74823. VERTICAL: 0,
  74824. HORIZONTAL: 1
  74825. };
  74826. /**
  74827. * @inheritDoc
  74828. */
  74829. ol.control.ZoomSlider.prototype.setMap = function(map) {
  74830. goog.base(this, 'setMap', map);
  74831. if (map) {
  74832. map.render();
  74833. }
  74834. };
  74835. /**
  74836. * Initializes the slider element. This will determine and set this controls
  74837. * direction_ and also constrain the dragging of the thumb to always be within
  74838. * the bounds of the container.
  74839. *
  74840. * @private
  74841. */
  74842. ol.control.ZoomSlider.prototype.initSlider_ = function() {
  74843. var container = this.element;
  74844. var containerSize = goog.style.getSize(container);
  74845. var thumb = goog.dom.getFirstElementChild(container);
  74846. var thumbMargins = goog.style.getMarginBox(thumb);
  74847. var thumbBorderBoxSize = goog.style.getBorderBoxSize(thumb);
  74848. var thumbWidth = thumbBorderBoxSize.width +
  74849. thumbMargins.right + thumbMargins.left;
  74850. var thumbHeight = thumbBorderBoxSize.height +
  74851. thumbMargins.top + thumbMargins.bottom;
  74852. this.thumbSize_ = [thumbWidth, thumbHeight];
  74853. var width = containerSize.width - thumbWidth;
  74854. var height = containerSize.height - thumbHeight;
  74855. var limits;
  74856. if (containerSize.width > containerSize.height) {
  74857. this.direction_ = ol.control.ZoomSlider.direction.HORIZONTAL;
  74858. limits = new goog.math.Rect(0, 0, width, 0);
  74859. } else {
  74860. this.direction_ = ol.control.ZoomSlider.direction.VERTICAL;
  74861. limits = new goog.math.Rect(0, 0, 0, height);
  74862. }
  74863. this.dragger_.setLimits(limits);
  74864. this.sliderInitialized_ = true;
  74865. };
  74866. /**
  74867. * Update the zoomslider element.
  74868. * @param {ol.MapEvent} mapEvent Map event.
  74869. * @this {ol.control.ZoomSlider}
  74870. * @api
  74871. */
  74872. ol.control.ZoomSlider.render = function(mapEvent) {
  74873. if (!mapEvent.frameState) {
  74874. return;
  74875. }
  74876. goog.asserts.assert(mapEvent.frameState.viewState,
  74877. 'viewState should be defined');
  74878. if (!this.sliderInitialized_) {
  74879. this.initSlider_();
  74880. }
  74881. var res = mapEvent.frameState.viewState.resolution;
  74882. if (res !== this.currentResolution_) {
  74883. this.currentResolution_ = res;
  74884. this.setThumbPosition_(res);
  74885. }
  74886. };
  74887. /**
  74888. * @param {goog.events.BrowserEvent} browserEvent The browser event to handle.
  74889. * @private
  74890. */
  74891. ol.control.ZoomSlider.prototype.handleContainerClick_ = function(browserEvent) {
  74892. var map = this.getMap();
  74893. var view = map.getView();
  74894. var currentResolution = view.getResolution();
  74895. goog.asserts.assert(currentResolution,
  74896. 'currentResolution should be defined');
  74897. map.beforeRender(ol.animation.zoom({
  74898. resolution: currentResolution,
  74899. duration: this.duration_,
  74900. easing: ol.easing.easeOut
  74901. }));
  74902. var relativePosition = this.getRelativePosition_(
  74903. browserEvent.offsetX - this.thumbSize_[0] / 2,
  74904. browserEvent.offsetY - this.thumbSize_[1] / 2);
  74905. var resolution = this.getResolutionForPosition_(relativePosition);
  74906. view.setResolution(view.constrainResolution(resolution));
  74907. };
  74908. /**
  74909. * Handle dragger start events.
  74910. * @param {goog.fx.DragEvent} event The drag event.
  74911. * @private
  74912. */
  74913. ol.control.ZoomSlider.prototype.handleDraggerStart_ = function(event) {
  74914. this.getMap().getView().setHint(ol.ViewHint.INTERACTING, 1);
  74915. };
  74916. /**
  74917. * Handle dragger drag events.
  74918. *
  74919. * @param {goog.fx.DragEvent} event The drag event.
  74920. * @private
  74921. */
  74922. ol.control.ZoomSlider.prototype.handleDraggerDrag_ = function(event) {
  74923. var relativePosition = this.getRelativePosition_(event.left, event.top);
  74924. this.currentResolution_ = this.getResolutionForPosition_(relativePosition);
  74925. this.getMap().getView().setResolution(this.currentResolution_);
  74926. };
  74927. /**
  74928. * Handle dragger end events.
  74929. * @param {goog.fx.DragEvent} event The drag event.
  74930. * @private
  74931. */
  74932. ol.control.ZoomSlider.prototype.handleDraggerEnd_ = function(event) {
  74933. var map = this.getMap();
  74934. var view = map.getView();
  74935. view.setHint(ol.ViewHint.INTERACTING, -1);
  74936. goog.asserts.assert(this.currentResolution_,
  74937. 'this.currentResolution_ should be defined');
  74938. map.beforeRender(ol.animation.zoom({
  74939. resolution: this.currentResolution_,
  74940. duration: this.duration_,
  74941. easing: ol.easing.easeOut
  74942. }));
  74943. var resolution = view.constrainResolution(this.currentResolution_);
  74944. view.setResolution(resolution);
  74945. };
  74946. /**
  74947. * Positions the thumb inside its container according to the given resolution.
  74948. *
  74949. * @param {number} res The res.
  74950. * @private
  74951. */
  74952. ol.control.ZoomSlider.prototype.setThumbPosition_ = function(res) {
  74953. var position = this.getPositionForResolution_(res);
  74954. var dragger = this.dragger_;
  74955. var thumb = goog.dom.getFirstElementChild(this.element);
  74956. if (this.direction_ == ol.control.ZoomSlider.direction.HORIZONTAL) {
  74957. var left = dragger.limits.left + dragger.limits.width * position;
  74958. goog.style.setPosition(thumb, left);
  74959. } else {
  74960. var top = dragger.limits.top + dragger.limits.height * position;
  74961. goog.style.setPosition(thumb, dragger.limits.left, top);
  74962. }
  74963. };
  74964. /**
  74965. * Calculates the relative position of the thumb given x and y offsets. The
  74966. * relative position scales from 0 to 1. The x and y offsets are assumed to be
  74967. * in pixel units within the dragger limits.
  74968. *
  74969. * @param {number} x Pixel position relative to the left of the slider.
  74970. * @param {number} y Pixel position relative to the top of the slider.
  74971. * @return {number} The relative position of the thumb.
  74972. * @private
  74973. */
  74974. ol.control.ZoomSlider.prototype.getRelativePosition_ = function(x, y) {
  74975. var draggerLimits = this.dragger_.limits;
  74976. var amount;
  74977. if (this.direction_ === ol.control.ZoomSlider.direction.HORIZONTAL) {
  74978. amount = (x - draggerLimits.left) / draggerLimits.width;
  74979. } else {
  74980. amount = (y - draggerLimits.top) / draggerLimits.height;
  74981. }
  74982. return ol.math.clamp(amount, 0, 1);
  74983. };
  74984. /**
  74985. * Calculates the corresponding resolution of the thumb given its relative
  74986. * position (where 0 is the minimum and 1 is the maximum).
  74987. *
  74988. * @param {number} position The relative position of the thumb.
  74989. * @return {number} The corresponding resolution.
  74990. * @private
  74991. */
  74992. ol.control.ZoomSlider.prototype.getResolutionForPosition_ = function(position) {
  74993. var fn = this.getMap().getView().getResolutionForValueFunction();
  74994. return fn(1 - position);
  74995. };
  74996. /**
  74997. * Determines the relative position of the slider for the given resolution. A
  74998. * relative position of 0 corresponds to the minimum view resolution. A
  74999. * relative position of 1 corresponds to the maximum view resolution.
  75000. *
  75001. * @param {number} res The resolution.
  75002. * @return {number} The relative position value (between 0 and 1).
  75003. * @private
  75004. */
  75005. ol.control.ZoomSlider.prototype.getPositionForResolution_ = function(res) {
  75006. var fn = this.getMap().getView().getValueForResolutionFunction();
  75007. return 1 - fn(res);
  75008. };
  75009. goog.provide('ol.control.ZoomToExtent');
  75010. goog.require('goog.asserts');
  75011. goog.require('goog.dom');
  75012. goog.require('goog.dom.TagName');
  75013. goog.require('goog.events');
  75014. goog.require('goog.events.EventType');
  75015. goog.require('ol.control.Control');
  75016. goog.require('ol.css');
  75017. /**
  75018. * @classdesc
  75019. * A button control which, when pressed, changes the map view to a specific
  75020. * extent. To style this control use the css selector `.ol-zoom-extent`.
  75021. *
  75022. * @constructor
  75023. * @extends {ol.control.Control}
  75024. * @param {olx.control.ZoomToExtentOptions=} opt_options Options.
  75025. * @api stable
  75026. */
  75027. ol.control.ZoomToExtent = function(opt_options) {
  75028. var options = opt_options ? opt_options : {};
  75029. /**
  75030. * @type {ol.Extent}
  75031. * @private
  75032. */
  75033. this.extent_ = options.extent ? options.extent : null;
  75034. var className = options.className ? options.className :
  75035. 'ol-zoom-extent';
  75036. var label = options.label ? options.label : 'E';
  75037. var tipLabel = options.tipLabel ?
  75038. options.tipLabel : 'Fit to extent';
  75039. var button = goog.dom.createDom(goog.dom.TagName.BUTTON, {
  75040. 'type': 'button',
  75041. 'title': tipLabel
  75042. }, label);
  75043. goog.events.listen(button, goog.events.EventType.CLICK,
  75044. this.handleClick_, false, this);
  75045. var cssClasses = className + ' ' + ol.css.CLASS_UNSELECTABLE + ' ' +
  75046. ol.css.CLASS_CONTROL;
  75047. var element = goog.dom.createDom(goog.dom.TagName.DIV, cssClasses, button);
  75048. goog.base(this, {
  75049. element: element,
  75050. target: options.target
  75051. });
  75052. };
  75053. goog.inherits(ol.control.ZoomToExtent, ol.control.Control);
  75054. /**
  75055. * @param {goog.events.BrowserEvent} event The event to handle
  75056. * @private
  75057. */
  75058. ol.control.ZoomToExtent.prototype.handleClick_ = function(event) {
  75059. event.preventDefault();
  75060. this.handleZoomToExtent_();
  75061. };
  75062. /**
  75063. * @private
  75064. */
  75065. ol.control.ZoomToExtent.prototype.handleZoomToExtent_ = function() {
  75066. var map = this.getMap();
  75067. var view = map.getView();
  75068. var extent = !this.extent_ ?
  75069. view.getProjection().getExtent() : this.extent_;
  75070. var size = map.getSize();
  75071. goog.asserts.assert(size, 'size should be defined');
  75072. view.fit(extent, size);
  75073. };
  75074. goog.provide('ol.DeviceOrientation');
  75075. goog.provide('ol.DeviceOrientationProperty');
  75076. goog.require('goog.events');
  75077. goog.require('goog.math');
  75078. goog.require('ol');
  75079. goog.require('ol.Object');
  75080. goog.require('ol.has');
  75081. /**
  75082. * @enum {string}
  75083. */
  75084. ol.DeviceOrientationProperty = {
  75085. ALPHA: 'alpha',
  75086. BETA: 'beta',
  75087. GAMMA: 'gamma',
  75088. HEADING: 'heading',
  75089. TRACKING: 'tracking'
  75090. };
  75091. /**
  75092. * @classdesc
  75093. * The ol.DeviceOrientation class provides access to information from
  75094. * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification](
  75095. * http://www.w3.org/TR/orientation-event/) for more details.
  75096. *
  75097. * Many new computers, and especially mobile phones
  75098. * and tablets, provide hardware support for device orientation. Web
  75099. * developers targeting mobile devices will be especially interested in this
  75100. * class.
  75101. *
  75102. * Device orientation data are relative to a common starting point. For mobile
  75103. * devices, the starting point is to lay your phone face up on a table with the
  75104. * top of the phone pointing north. This represents the zero state. All
  75105. * angles are then relative to this state. For computers, it is the same except
  75106. * the screen is open at 90 degrees.
  75107. *
  75108. * Device orientation is reported as three angles - `alpha`, `beta`, and
  75109. * `gamma` - relative to the starting position along the three planar axes X, Y
  75110. * and Z. The X axis runs from the left edge to the right edge through the
  75111. * middle of the device. Similarly, the Y axis runs from the bottom to the top
  75112. * of the device through the middle. The Z axis runs from the back to the front
  75113. * through the middle. In the starting position, the X axis points to the
  75114. * right, the Y axis points away from you and the Z axis points straight up
  75115. * from the device lying flat.
  75116. *
  75117. * The three angles representing the device orientation are relative to the
  75118. * three axes. `alpha` indicates how much the device has been rotated around the
  75119. * Z axis, which is commonly interpreted as the compass heading (see note
  75120. * below). `beta` indicates how much the device has been rotated around the X
  75121. * axis, or how much it is tilted from front to back. `gamma` indicates how
  75122. * much the device has been rotated around the Y axis, or how much it is tilted
  75123. * from left to right.
  75124. *
  75125. * For most browsers, the `alpha` value returns the compass heading so if the
  75126. * device points north, it will be 0. With Safari on iOS, the 0 value of
  75127. * `alpha` is calculated from when device orientation was first requested.
  75128. * ol.DeviceOrientation provides the `heading` property which normalizes this
  75129. * behavior across all browsers for you.
  75130. *
  75131. * It is important to note that the HTML 5 DeviceOrientation specification
  75132. * indicates that `alpha`, `beta` and `gamma` are in degrees while the
  75133. * equivalent properties in ol.DeviceOrientation are in radians for consistency
  75134. * with all other uses of angles throughout OpenLayers.
  75135. *
  75136. * @see http://www.w3.org/TR/orientation-event/
  75137. *
  75138. * To get notified of device orientation changes, register a listener for the
  75139. * generic `change` event on your `ol.DeviceOrientation` instance.
  75140. *
  75141. * @constructor
  75142. * @extends {ol.Object}
  75143. * @param {olx.DeviceOrientationOptions=} opt_options Options.
  75144. * @api
  75145. */
  75146. ol.DeviceOrientation = function(opt_options) {
  75147. goog.base(this);
  75148. var options = opt_options ? opt_options : {};
  75149. /**
  75150. * @private
  75151. * @type {goog.events.Key}
  75152. */
  75153. this.listenerKey_ = null;
  75154. goog.events.listen(this,
  75155. ol.Object.getChangeEventType(ol.DeviceOrientationProperty.TRACKING),
  75156. this.handleTrackingChanged_, false, this);
  75157. this.setTracking(options.tracking !== undefined ? options.tracking : false);
  75158. };
  75159. goog.inherits(ol.DeviceOrientation, ol.Object);
  75160. /**
  75161. * @inheritDoc
  75162. */
  75163. ol.DeviceOrientation.prototype.disposeInternal = function() {
  75164. this.setTracking(false);
  75165. goog.base(this, 'disposeInternal');
  75166. };
  75167. /**
  75168. * @private
  75169. * @param {goog.events.BrowserEvent} browserEvent Event.
  75170. */
  75171. ol.DeviceOrientation.prototype.orientationChange_ = function(browserEvent) {
  75172. var event = /** @type {DeviceOrientationEvent} */
  75173. (browserEvent.getBrowserEvent());
  75174. if (event.alpha !== null) {
  75175. var alpha = goog.math.toRadians(event.alpha);
  75176. this.set(ol.DeviceOrientationProperty.ALPHA, alpha);
  75177. // event.absolute is undefined in iOS.
  75178. if (goog.isBoolean(event.absolute) && event.absolute) {
  75179. this.set(ol.DeviceOrientationProperty.HEADING, alpha);
  75180. } else if (goog.isNumber(event.webkitCompassHeading) &&
  75181. event.webkitCompassAccuracy != -1) {
  75182. var heading = goog.math.toRadians(event.webkitCompassHeading);
  75183. this.set(ol.DeviceOrientationProperty.HEADING, heading);
  75184. }
  75185. }
  75186. if (event.beta !== null) {
  75187. this.set(ol.DeviceOrientationProperty.BETA,
  75188. goog.math.toRadians(event.beta));
  75189. }
  75190. if (event.gamma !== null) {
  75191. this.set(ol.DeviceOrientationProperty.GAMMA,
  75192. goog.math.toRadians(event.gamma));
  75193. }
  75194. this.changed();
  75195. };
  75196. /**
  75197. * Rotation around the device z-axis (in radians).
  75198. * @return {number|undefined} The euler angle in radians of the device from the
  75199. * standard Z axis.
  75200. * @observable
  75201. * @api
  75202. */
  75203. ol.DeviceOrientation.prototype.getAlpha = function() {
  75204. return /** @type {number|undefined} */ (
  75205. this.get(ol.DeviceOrientationProperty.ALPHA));
  75206. };
  75207. /**
  75208. * Rotation around the device x-axis (in radians).
  75209. * @return {number|undefined} The euler angle in radians of the device from the
  75210. * planar X axis.
  75211. * @observable
  75212. * @api
  75213. */
  75214. ol.DeviceOrientation.prototype.getBeta = function() {
  75215. return /** @type {number|undefined} */ (
  75216. this.get(ol.DeviceOrientationProperty.BETA));
  75217. };
  75218. /**
  75219. * Rotation around the device y-axis (in radians).
  75220. * @return {number|undefined} The euler angle in radians of the device from the
  75221. * planar Y axis.
  75222. * @observable
  75223. * @api
  75224. */
  75225. ol.DeviceOrientation.prototype.getGamma = function() {
  75226. return /** @type {number|undefined} */ (
  75227. this.get(ol.DeviceOrientationProperty.GAMMA));
  75228. };
  75229. /**
  75230. * The heading of the device relative to north (in radians).
  75231. * @return {number|undefined} The heading of the device relative to north, in
  75232. * radians, normalizing for different browser behavior.
  75233. * @observable
  75234. * @api
  75235. */
  75236. ol.DeviceOrientation.prototype.getHeading = function() {
  75237. return /** @type {number|undefined} */ (
  75238. this.get(ol.DeviceOrientationProperty.HEADING));
  75239. };
  75240. /**
  75241. * Determine if orientation is being tracked.
  75242. * @return {boolean} Changes in device orientation are being tracked.
  75243. * @observable
  75244. * @api
  75245. */
  75246. ol.DeviceOrientation.prototype.getTracking = function() {
  75247. return /** @type {boolean} */ (
  75248. this.get(ol.DeviceOrientationProperty.TRACKING));
  75249. };
  75250. /**
  75251. * @private
  75252. */
  75253. ol.DeviceOrientation.prototype.handleTrackingChanged_ = function() {
  75254. if (ol.has.DEVICE_ORIENTATION) {
  75255. var tracking = this.getTracking();
  75256. if (tracking && !this.listenerKey_) {
  75257. this.listenerKey_ = goog.events.listen(goog.global, 'deviceorientation',
  75258. this.orientationChange_, false, this);
  75259. } else if (!tracking && this.listenerKey_) {
  75260. goog.events.unlistenByKey(this.listenerKey_);
  75261. this.listenerKey_ = null;
  75262. }
  75263. }
  75264. };
  75265. /**
  75266. * Enable or disable tracking of device orientation events.
  75267. * @param {boolean} tracking The status of tracking changes to alpha, beta and
  75268. * gamma. If true, changes are tracked and reported immediately.
  75269. * @observable
  75270. * @api
  75271. */
  75272. ol.DeviceOrientation.prototype.setTracking = function(tracking) {
  75273. this.set(ol.DeviceOrientationProperty.TRACKING, tracking);
  75274. };
  75275. goog.provide('ol.format.Feature');
  75276. goog.require('ol.geom.Geometry');
  75277. goog.require('ol.proj');
  75278. /**
  75279. * @classdesc
  75280. * Abstract base class; normally only used for creating subclasses and not
  75281. * instantiated in apps.
  75282. * Base class for feature formats.
  75283. * {ol.format.Feature} subclasses provide the ability to decode and encode
  75284. * {@link ol.Feature} objects from a variety of commonly used geospatial
  75285. * file formats. See the documentation for each format for more details.
  75286. *
  75287. * @constructor
  75288. * @api stable
  75289. */
  75290. ol.format.Feature = function() {
  75291. /**
  75292. * @protected
  75293. * @type {ol.proj.Projection}
  75294. */
  75295. this.defaultDataProjection = null;
  75296. };
  75297. /**
  75298. * @return {Array.<string>} Extensions.
  75299. */
  75300. ol.format.Feature.prototype.getExtensions = goog.abstractMethod;
  75301. /**
  75302. * Adds the data projection to the read options.
  75303. * @param {Document|Node|Object|string} source Source.
  75304. * @param {olx.format.ReadOptions=} opt_options Options.
  75305. * @return {olx.format.ReadOptions|undefined} Options.
  75306. * @protected
  75307. */
  75308. ol.format.Feature.prototype.getReadOptions = function(source, opt_options) {
  75309. var options;
  75310. if (opt_options) {
  75311. options = {
  75312. dataProjection: opt_options.dataProjection ?
  75313. opt_options.dataProjection : this.readProjection(source),
  75314. featureProjection: opt_options.featureProjection
  75315. };
  75316. }
  75317. return this.adaptOptions(options);
  75318. };
  75319. /**
  75320. * Sets the `defaultDataProjection` on the options, if no `dataProjection`
  75321. * is set.
  75322. * @param {olx.format.WriteOptions|olx.format.ReadOptions|undefined} options
  75323. * Options.
  75324. * @protected
  75325. * @return {olx.format.WriteOptions|olx.format.ReadOptions|undefined}
  75326. * Updated options.
  75327. */
  75328. ol.format.Feature.prototype.adaptOptions = function(options) {
  75329. var updatedOptions;
  75330. if (options) {
  75331. updatedOptions = {
  75332. featureProjection: options.featureProjection,
  75333. dataProjection: options.dataProjection ?
  75334. options.dataProjection : this.defaultDataProjection,
  75335. rightHanded: options.rightHanded
  75336. };
  75337. }
  75338. return updatedOptions;
  75339. };
  75340. /**
  75341. * @return {ol.format.FormatType} Format.
  75342. */
  75343. ol.format.Feature.prototype.getType = goog.abstractMethod;
  75344. /**
  75345. * Read a single feature from a source.
  75346. *
  75347. * @param {Document|Node|Object|string} source Source.
  75348. * @param {olx.format.ReadOptions=} opt_options Read options.
  75349. * @return {ol.Feature} Feature.
  75350. */
  75351. ol.format.Feature.prototype.readFeature = goog.abstractMethod;
  75352. /**
  75353. * Read all features from a source.
  75354. *
  75355. * @param {Document|Node|Object|string} source Source.
  75356. * @param {olx.format.ReadOptions=} opt_options Read options.
  75357. * @return {Array.<ol.Feature>} Features.
  75358. */
  75359. ol.format.Feature.prototype.readFeatures = goog.abstractMethod;
  75360. /**
  75361. * Read a single geometry from a source.
  75362. *
  75363. * @param {Document|Node|Object|string} source Source.
  75364. * @param {olx.format.ReadOptions=} opt_options Read options.
  75365. * @return {ol.geom.Geometry} Geometry.
  75366. */
  75367. ol.format.Feature.prototype.readGeometry = goog.abstractMethod;
  75368. /**
  75369. * Read the projection from a source.
  75370. *
  75371. * @param {Document|Node|Object|string} source Source.
  75372. * @return {ol.proj.Projection} Projection.
  75373. */
  75374. ol.format.Feature.prototype.readProjection = goog.abstractMethod;
  75375. /**
  75376. * Encode a feature in this format.
  75377. *
  75378. * @param {ol.Feature} feature Feature.
  75379. * @param {olx.format.WriteOptions=} opt_options Write options.
  75380. * @return {string} Result.
  75381. */
  75382. ol.format.Feature.prototype.writeFeature = goog.abstractMethod;
  75383. /**
  75384. * Encode an array of features in this format.
  75385. *
  75386. * @param {Array.<ol.Feature>} features Features.
  75387. * @param {olx.format.WriteOptions=} opt_options Write options.
  75388. * @return {string} Result.
  75389. */
  75390. ol.format.Feature.prototype.writeFeatures = goog.abstractMethod;
  75391. /**
  75392. * Write a single geometry in this format.
  75393. *
  75394. * @param {ol.geom.Geometry} geometry Geometry.
  75395. * @param {olx.format.WriteOptions=} opt_options Write options.
  75396. * @return {string} Result.
  75397. */
  75398. ol.format.Feature.prototype.writeGeometry = goog.abstractMethod;
  75399. /**
  75400. * @param {ol.geom.Geometry|ol.Extent} geometry Geometry.
  75401. * @param {boolean} write Set to true for writing, false for reading.
  75402. * @param {(olx.format.WriteOptions|olx.format.ReadOptions)=} opt_options
  75403. * Options.
  75404. * @return {ol.geom.Geometry|ol.Extent} Transformed geometry.
  75405. * @protected
  75406. */
  75407. ol.format.Feature.transformWithOptions = function(
  75408. geometry, write, opt_options) {
  75409. var featureProjection = opt_options ?
  75410. ol.proj.get(opt_options.featureProjection) : null;
  75411. var dataProjection = opt_options ?
  75412. ol.proj.get(opt_options.dataProjection) : null;
  75413. if (featureProjection && dataProjection &&
  75414. !ol.proj.equivalent(featureProjection, dataProjection)) {
  75415. if (geometry instanceof ol.geom.Geometry) {
  75416. return (write ? geometry.clone() : geometry).transform(
  75417. write ? featureProjection : dataProjection,
  75418. write ? dataProjection : featureProjection);
  75419. } else {
  75420. // FIXME this is necessary because ol.format.GML treats extents
  75421. // as geometries
  75422. return ol.proj.transformExtent(
  75423. write ? geometry.slice() : geometry,
  75424. write ? featureProjection : dataProjection,
  75425. write ? dataProjection : featureProjection);
  75426. }
  75427. } else {
  75428. return geometry;
  75429. }
  75430. };
  75431. goog.provide('ol.format.JSONFeature');
  75432. goog.require('goog.asserts');
  75433. goog.require('goog.json');
  75434. goog.require('ol.format.Feature');
  75435. goog.require('ol.format.FormatType');
  75436. /**
  75437. * @classdesc
  75438. * Abstract base class; normally only used for creating subclasses and not
  75439. * instantiated in apps.
  75440. * Base class for JSON feature formats.
  75441. *
  75442. * @constructor
  75443. * @extends {ol.format.Feature}
  75444. */
  75445. ol.format.JSONFeature = function() {
  75446. goog.base(this);
  75447. };
  75448. goog.inherits(ol.format.JSONFeature, ol.format.Feature);
  75449. /**
  75450. * @param {Document|Node|Object|string} source Source.
  75451. * @private
  75452. * @return {Object} Object.
  75453. */
  75454. ol.format.JSONFeature.prototype.getObject_ = function(source) {
  75455. if (goog.isObject(source)) {
  75456. return source;
  75457. } else if (goog.isString(source)) {
  75458. var object = goog.json.parse(source);
  75459. return object ? object : null;
  75460. } else {
  75461. goog.asserts.fail();
  75462. return null;
  75463. }
  75464. };
  75465. /**
  75466. * @inheritDoc
  75467. */
  75468. ol.format.JSONFeature.prototype.getType = function() {
  75469. return ol.format.FormatType.JSON;
  75470. };
  75471. /**
  75472. * @inheritDoc
  75473. */
  75474. ol.format.JSONFeature.prototype.readFeature = function(source, opt_options) {
  75475. return this.readFeatureFromObject(
  75476. this.getObject_(source), this.getReadOptions(source, opt_options));
  75477. };
  75478. /**
  75479. * @inheritDoc
  75480. */
  75481. ol.format.JSONFeature.prototype.readFeatures = function(source, opt_options) {
  75482. return this.readFeaturesFromObject(
  75483. this.getObject_(source), this.getReadOptions(source, opt_options));
  75484. };
  75485. /**
  75486. * @param {Object} object Object.
  75487. * @param {olx.format.ReadOptions=} opt_options Read options.
  75488. * @protected
  75489. * @return {ol.Feature} Feature.
  75490. */
  75491. ol.format.JSONFeature.prototype.readFeatureFromObject = goog.abstractMethod;
  75492. /**
  75493. * @param {Object} object Object.
  75494. * @param {olx.format.ReadOptions=} opt_options Read options.
  75495. * @protected
  75496. * @return {Array.<ol.Feature>} Features.
  75497. */
  75498. ol.format.JSONFeature.prototype.readFeaturesFromObject = goog.abstractMethod;
  75499. /**
  75500. * @inheritDoc
  75501. */
  75502. ol.format.JSONFeature.prototype.readGeometry = function(source, opt_options) {
  75503. return this.readGeometryFromObject(
  75504. this.getObject_(source), this.getReadOptions(source, opt_options));
  75505. };
  75506. /**
  75507. * @param {Object} object Object.
  75508. * @param {olx.format.ReadOptions=} opt_options Read options.
  75509. * @protected
  75510. * @return {ol.geom.Geometry} Geometry.
  75511. */
  75512. ol.format.JSONFeature.prototype.readGeometryFromObject = goog.abstractMethod;
  75513. /**
  75514. * @inheritDoc
  75515. */
  75516. ol.format.JSONFeature.prototype.readProjection = function(source) {
  75517. return this.readProjectionFromObject(this.getObject_(source));
  75518. };
  75519. /**
  75520. * @param {Object} object Object.
  75521. * @protected
  75522. * @return {ol.proj.Projection} Projection.
  75523. */
  75524. ol.format.JSONFeature.prototype.readProjectionFromObject = goog.abstractMethod;
  75525. /**
  75526. * @inheritDoc
  75527. */
  75528. ol.format.JSONFeature.prototype.writeFeature = function(feature, opt_options) {
  75529. return goog.json.serialize(this.writeFeatureObject(feature, opt_options));
  75530. };
  75531. /**
  75532. * @param {ol.Feature} feature Feature.
  75533. * @param {olx.format.WriteOptions=} opt_options Write options.
  75534. * @return {Object} Object.
  75535. */
  75536. ol.format.JSONFeature.prototype.writeFeatureObject = goog.abstractMethod;
  75537. /**
  75538. * @inheritDoc
  75539. */
  75540. ol.format.JSONFeature.prototype.writeFeatures = function(
  75541. features, opt_options) {
  75542. return goog.json.serialize(this.writeFeaturesObject(features, opt_options));
  75543. };
  75544. /**
  75545. * @param {Array.<ol.Feature>} features Features.
  75546. * @param {olx.format.WriteOptions=} opt_options Write options.
  75547. * @return {Object} Object.
  75548. */
  75549. ol.format.JSONFeature.prototype.writeFeaturesObject = goog.abstractMethod;
  75550. /**
  75551. * @inheritDoc
  75552. */
  75553. ol.format.JSONFeature.prototype.writeGeometry = function(
  75554. geometry, opt_options) {
  75555. return goog.json.serialize(this.writeGeometryObject(geometry, opt_options));
  75556. };
  75557. /**
  75558. * @param {ol.geom.Geometry} geometry Geometry.
  75559. * @param {olx.format.WriteOptions=} opt_options Write options.
  75560. * @return {Object} Object.
  75561. */
  75562. ol.format.JSONFeature.prototype.writeGeometryObject = goog.abstractMethod;
  75563. goog.provide('ol.format.EsriJSON');
  75564. goog.require('goog.array');
  75565. goog.require('goog.asserts');
  75566. goog.require('goog.object');
  75567. goog.require('ol.Feature');
  75568. goog.require('ol.extent');
  75569. goog.require('ol.format.Feature');
  75570. goog.require('ol.format.JSONFeature');
  75571. goog.require('ol.geom.GeometryLayout');
  75572. goog.require('ol.geom.GeometryType');
  75573. goog.require('ol.geom.LineString');
  75574. goog.require('ol.geom.LinearRing');
  75575. goog.require('ol.geom.MultiLineString');
  75576. goog.require('ol.geom.MultiPoint');
  75577. goog.require('ol.geom.MultiPolygon');
  75578. goog.require('ol.geom.Point');
  75579. goog.require('ol.geom.Polygon');
  75580. goog.require('ol.geom.flat.orient');
  75581. goog.require('ol.proj');
  75582. /**
  75583. * @classdesc
  75584. * Feature format for reading and writing data in the EsriJSON format.
  75585. *
  75586. * @constructor
  75587. * @extends {ol.format.JSONFeature}
  75588. * @param {olx.format.EsriJSONOptions=} opt_options Options.
  75589. * @api
  75590. */
  75591. ol.format.EsriJSON = function(opt_options) {
  75592. var options = opt_options ? opt_options : {};
  75593. goog.base(this);
  75594. /**
  75595. * Name of the geometry attribute for features.
  75596. * @type {string|undefined}
  75597. * @private
  75598. */
  75599. this.geometryName_ = options.geometryName;
  75600. };
  75601. goog.inherits(ol.format.EsriJSON, ol.format.JSONFeature);
  75602. /**
  75603. * @param {EsriJSONGeometry} object Object.
  75604. * @param {olx.format.ReadOptions=} opt_options Read options.
  75605. * @private
  75606. * @return {ol.geom.Geometry} Geometry.
  75607. */
  75608. ol.format.EsriJSON.readGeometry_ = function(object, opt_options) {
  75609. if (!object) {
  75610. return null;
  75611. }
  75612. var type;
  75613. if (goog.isNumber(object.x) && goog.isNumber(object.y)) {
  75614. type = ol.geom.GeometryType.POINT;
  75615. } else if (object.points) {
  75616. type = ol.geom.GeometryType.MULTI_POINT;
  75617. } else if (object.paths) {
  75618. if (object.paths.length === 1) {
  75619. type = ol.geom.GeometryType.LINE_STRING;
  75620. } else {
  75621. type = ol.geom.GeometryType.MULTI_LINE_STRING;
  75622. }
  75623. } else if (object.rings) {
  75624. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75625. var rings = ol.format.EsriJSON.convertRings_(object.rings, layout);
  75626. object = /** @type {EsriJSONGeometry} */(goog.object.clone(object));
  75627. if (rings.length === 1) {
  75628. type = ol.geom.GeometryType.POLYGON;
  75629. object.rings = rings[0];
  75630. } else {
  75631. type = ol.geom.GeometryType.MULTI_POLYGON;
  75632. object.rings = rings;
  75633. }
  75634. }
  75635. goog.asserts.assert(type, 'geometry type should be defined');
  75636. var geometryReader = ol.format.EsriJSON.GEOMETRY_READERS_[type];
  75637. goog.asserts.assert(geometryReader,
  75638. 'geometryReader should be defined');
  75639. return /** @type {ol.geom.Geometry} */ (
  75640. ol.format.Feature.transformWithOptions(
  75641. geometryReader(object), false, opt_options));
  75642. };
  75643. /**
  75644. * Determines inner and outer rings.
  75645. * Checks if any polygons in this array contain any other polygons in this
  75646. * array. It is used for checking for holes.
  75647. * Logic inspired by: https://github.com/Esri/terraformer-arcgis-parser
  75648. * @param {Array.<!Array.<!Array.<number>>>} rings Rings.
  75649. * @param {ol.geom.GeometryLayout} layout Geometry layout.
  75650. * @private
  75651. * @return {Array.<!Array.<!Array.<number>>>} Transoformed rings.
  75652. */
  75653. ol.format.EsriJSON.convertRings_ = function(rings, layout) {
  75654. var outerRings = [];
  75655. var holes = [];
  75656. var i, ii;
  75657. for (i = 0, ii = rings.length; i < ii; ++i) {
  75658. var flatRing = goog.array.flatten(rings[i]);
  75659. // is this ring an outer ring? is it clockwise?
  75660. var clockwise = ol.geom.flat.orient.linearRingIsClockwise(flatRing, 0,
  75661. flatRing.length, layout.length);
  75662. if (clockwise) {
  75663. outerRings.push([rings[i]]);
  75664. } else {
  75665. holes.push(rings[i]);
  75666. }
  75667. }
  75668. while (holes.length) {
  75669. var hole = holes.shift();
  75670. var matched = false;
  75671. // loop over all outer rings and see if they contain our hole.
  75672. for (i = outerRings.length - 1; i >= 0; i--) {
  75673. var outerRing = outerRings[i][0];
  75674. if (ol.extent.containsExtent(new ol.geom.LinearRing(
  75675. outerRing).getExtent(),
  75676. new ol.geom.LinearRing(hole).getExtent())) {
  75677. // the hole is contained push it into our polygon
  75678. outerRings[i].push(hole);
  75679. matched = true;
  75680. break;
  75681. }
  75682. }
  75683. if (!matched) {
  75684. // no outer rings contain this hole turn it into and outer
  75685. // ring (reverse it)
  75686. outerRings.push([hole.reverse()]);
  75687. }
  75688. }
  75689. return outerRings;
  75690. };
  75691. /**
  75692. * @param {EsriJSONGeometry} object Object.
  75693. * @private
  75694. * @return {ol.geom.Geometry} Point.
  75695. */
  75696. ol.format.EsriJSON.readPointGeometry_ = function(object) {
  75697. goog.asserts.assert(goog.isNumber(object.x), 'object.x should be number');
  75698. goog.asserts.assert(goog.isNumber(object.y), 'object.y should be number');
  75699. var point;
  75700. if (object.m !== undefined && object.z !== undefined) {
  75701. point = new ol.geom.Point([object.x, object.y, object.z, object.m],
  75702. ol.geom.GeometryLayout.XYZM);
  75703. } else if (object.z !== undefined) {
  75704. point = new ol.geom.Point([object.x, object.y, object.z],
  75705. ol.geom.GeometryLayout.XYZ);
  75706. } else if (object.m !== undefined) {
  75707. point = new ol.geom.Point([object.x, object.y, object.m],
  75708. ol.geom.GeometryLayout.XYM);
  75709. } else {
  75710. point = new ol.geom.Point([object.x, object.y]);
  75711. }
  75712. return point;
  75713. };
  75714. /**
  75715. * @param {EsriJSONGeometry} object Object.
  75716. * @private
  75717. * @return {ol.geom.Geometry} LineString.
  75718. */
  75719. ol.format.EsriJSON.readLineStringGeometry_ = function(object) {
  75720. goog.asserts.assert(goog.isArray(object.paths),
  75721. 'object.paths should be an array');
  75722. goog.asserts.assert(object.paths.length === 1,
  75723. 'object.paths array length should be 1');
  75724. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75725. return new ol.geom.LineString(object.paths[0], layout);
  75726. };
  75727. /**
  75728. * @param {EsriJSONGeometry} object Object.
  75729. * @private
  75730. * @return {ol.geom.Geometry} MultiLineString.
  75731. */
  75732. ol.format.EsriJSON.readMultiLineStringGeometry_ = function(object) {
  75733. goog.asserts.assert(goog.isArray(object.paths),
  75734. 'object.paths should be an array');
  75735. goog.asserts.assert(object.paths.length > 1,
  75736. 'object.paths array length should be more than 1');
  75737. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75738. return new ol.geom.MultiLineString(object.paths, layout);
  75739. };
  75740. /**
  75741. * @param {EsriJSONGeometry} object Object.
  75742. * @private
  75743. * @return {ol.geom.GeometryLayout} The geometry layout to use.
  75744. */
  75745. ol.format.EsriJSON.getGeometryLayout_ = function(object) {
  75746. var layout = ol.geom.GeometryLayout.XY;
  75747. if (object.hasZ === true && object.hasM === true) {
  75748. layout = ol.geom.GeometryLayout.XYZM;
  75749. } else if (object.hasZ === true) {
  75750. layout = ol.geom.GeometryLayout.XYZ;
  75751. } else if (object.hasM === true) {
  75752. layout = ol.geom.GeometryLayout.XYM;
  75753. }
  75754. return layout;
  75755. };
  75756. /**
  75757. * @param {EsriJSONGeometry} object Object.
  75758. * @private
  75759. * @return {ol.geom.Geometry} MultiPoint.
  75760. */
  75761. ol.format.EsriJSON.readMultiPointGeometry_ = function(object) {
  75762. goog.asserts.assert(object.points, 'object.points should be defined');
  75763. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75764. return new ol.geom.MultiPoint(object.points, layout);
  75765. };
  75766. /**
  75767. * @param {EsriJSONGeometry} object Object.
  75768. * @private
  75769. * @return {ol.geom.Geometry} MultiPolygon.
  75770. */
  75771. ol.format.EsriJSON.readMultiPolygonGeometry_ = function(object) {
  75772. goog.asserts.assert(object.rings);
  75773. goog.asserts.assert(object.rings.length > 1,
  75774. 'object.rings should have length larger than 1');
  75775. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75776. return new ol.geom.MultiPolygon(
  75777. /** @type {Array.<Array.<Array.<Array.<number>>>>} */(object.rings),
  75778. layout);
  75779. };
  75780. /**
  75781. * @param {EsriJSONGeometry} object Object.
  75782. * @private
  75783. * @return {ol.geom.Geometry} Polygon.
  75784. */
  75785. ol.format.EsriJSON.readPolygonGeometry_ = function(object) {
  75786. goog.asserts.assert(object.rings);
  75787. var layout = ol.format.EsriJSON.getGeometryLayout_(object);
  75788. return new ol.geom.Polygon(object.rings, layout);
  75789. };
  75790. /**
  75791. * @param {ol.geom.Geometry} geometry Geometry.
  75792. * @param {olx.format.WriteOptions=} opt_options Write options.
  75793. * @private
  75794. * @return {EsriJSONGeometry} EsriJSON geometry.
  75795. */
  75796. ol.format.EsriJSON.writePointGeometry_ = function(geometry, opt_options) {
  75797. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  75798. 'geometry should be an ol.geom.Point');
  75799. var coordinates = geometry.getCoordinates();
  75800. var layout = geometry.getLayout();
  75801. if (layout === ol.geom.GeometryLayout.XYZ) {
  75802. return /** @type {EsriJSONPoint} */ ({
  75803. x: coordinates[0],
  75804. y: coordinates[1],
  75805. z: coordinates[2]
  75806. });
  75807. } else if (layout === ol.geom.GeometryLayout.XYM) {
  75808. return /** @type {EsriJSONPoint} */ ({
  75809. x: coordinates[0],
  75810. y: coordinates[1],
  75811. m: coordinates[2]
  75812. });
  75813. } else if (layout === ol.geom.GeometryLayout.XYZM) {
  75814. return /** @type {EsriJSONPoint} */ ({
  75815. x: coordinates[0],
  75816. y: coordinates[1],
  75817. z: coordinates[2],
  75818. m: coordinates[3]
  75819. });
  75820. } else if (layout === ol.geom.GeometryLayout.XY) {
  75821. return /** @type {EsriJSONPoint} */ ({
  75822. x: coordinates[0],
  75823. y: coordinates[1]
  75824. });
  75825. } else {
  75826. goog.asserts.fail('Unknown geometry layout');
  75827. }
  75828. };
  75829. /**
  75830. * @param {ol.geom.SimpleGeometry} geometry Geometry.
  75831. * @private
  75832. * @return {Object} Object with boolean hasZ and hasM keys.
  75833. */
  75834. ol.format.EsriJSON.getHasZM_ = function(geometry) {
  75835. var layout = geometry.getLayout();
  75836. return {
  75837. hasZ: (layout === ol.geom.GeometryLayout.XYZ ||
  75838. layout === ol.geom.GeometryLayout.XYZM),
  75839. hasM: (layout === ol.geom.GeometryLayout.XYM ||
  75840. layout === ol.geom.GeometryLayout.XYZM)
  75841. };
  75842. };
  75843. /**
  75844. * @param {ol.geom.Geometry} geometry Geometry.
  75845. * @param {olx.format.WriteOptions=} opt_options Write options.
  75846. * @private
  75847. * @return {EsriJSONPolyline} EsriJSON geometry.
  75848. */
  75849. ol.format.EsriJSON.writeLineStringGeometry_ = function(geometry, opt_options) {
  75850. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  75851. 'geometry should be an ol.geom.LineString');
  75852. var hasZM = ol.format.EsriJSON.getHasZM_(geometry);
  75853. return /** @type {EsriJSONPolyline} */ ({
  75854. hasZ: hasZM.hasZ,
  75855. hasM: hasZM.hasM,
  75856. paths: [geometry.getCoordinates()]
  75857. });
  75858. };
  75859. /**
  75860. * @param {ol.geom.Geometry} geometry Geometry.
  75861. * @param {olx.format.WriteOptions=} opt_options Write options.
  75862. * @private
  75863. * @return {EsriJSONPolygon} EsriJSON geometry.
  75864. */
  75865. ol.format.EsriJSON.writePolygonGeometry_ = function(geometry, opt_options) {
  75866. goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
  75867. 'geometry should be an ol.geom.Polygon');
  75868. // Esri geometries use the left-hand rule
  75869. var hasZM = ol.format.EsriJSON.getHasZM_(geometry);
  75870. return /** @type {EsriJSONPolygon} */ ({
  75871. hasZ: hasZM.hasZ,
  75872. hasM: hasZM.hasM,
  75873. rings: geometry.getCoordinates(false)
  75874. });
  75875. };
  75876. /**
  75877. * @param {ol.geom.Geometry} geometry Geometry.
  75878. * @param {olx.format.WriteOptions=} opt_options Write options.
  75879. * @private
  75880. * @return {EsriJSONPolyline} EsriJSON geometry.
  75881. */
  75882. ol.format.EsriJSON.writeMultiLineStringGeometry_ =
  75883. function(geometry, opt_options) {
  75884. goog.asserts.assertInstanceof(geometry, ol.geom.MultiLineString,
  75885. 'geometry should be an ol.geom.MultiLineString');
  75886. var hasZM = ol.format.EsriJSON.getHasZM_(geometry);
  75887. return /** @type {EsriJSONPolyline} */ ({
  75888. hasZ: hasZM.hasZ,
  75889. hasM: hasZM.hasM,
  75890. paths: geometry.getCoordinates()
  75891. });
  75892. };
  75893. /**
  75894. * @param {ol.geom.Geometry} geometry Geometry.
  75895. * @param {olx.format.WriteOptions=} opt_options Write options.
  75896. * @private
  75897. * @return {EsriJSONMultipoint} EsriJSON geometry.
  75898. */
  75899. ol.format.EsriJSON.writeMultiPointGeometry_ = function(geometry, opt_options) {
  75900. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPoint,
  75901. 'geometry should be an ol.geom.MultiPoint');
  75902. var hasZM = ol.format.EsriJSON.getHasZM_(geometry);
  75903. return /** @type {EsriJSONMultipoint} */ ({
  75904. hasZ: hasZM.hasZ,
  75905. hasM: hasZM.hasM,
  75906. points: geometry.getCoordinates()
  75907. });
  75908. };
  75909. /**
  75910. * @param {ol.geom.Geometry} geometry Geometry.
  75911. * @param {olx.format.WriteOptions=} opt_options Write options.
  75912. * @private
  75913. * @return {EsriJSONPolygon} EsriJSON geometry.
  75914. */
  75915. ol.format.EsriJSON.writeMultiPolygonGeometry_ = function(geometry,
  75916. opt_options) {
  75917. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPolygon,
  75918. 'geometry should be an ol.geom.MultiPolygon');
  75919. var hasZM = ol.format.EsriJSON.getHasZM_(geometry);
  75920. var coordinates = geometry.getCoordinates(false);
  75921. var output = [];
  75922. for (var i = 0; i < coordinates.length; i++) {
  75923. for (var x = coordinates[i].length - 1; x >= 0; x--) {
  75924. output.push(coordinates[i][x]);
  75925. }
  75926. }
  75927. return /** @type {EsriJSONPolygon} */ ({
  75928. hasZ: hasZM.hasZ,
  75929. hasM: hasZM.hasM,
  75930. rings: output
  75931. });
  75932. };
  75933. /**
  75934. * @const
  75935. * @private
  75936. * @type {Object.<ol.geom.GeometryType, function(EsriJSONGeometry): ol.geom.Geometry>}
  75937. */
  75938. ol.format.EsriJSON.GEOMETRY_READERS_ = {};
  75939. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POINT] =
  75940. ol.format.EsriJSON.readPointGeometry_;
  75941. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.LINE_STRING] =
  75942. ol.format.EsriJSON.readLineStringGeometry_;
  75943. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.POLYGON] =
  75944. ol.format.EsriJSON.readPolygonGeometry_;
  75945. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POINT] =
  75946. ol.format.EsriJSON.readMultiPointGeometry_;
  75947. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_LINE_STRING] =
  75948. ol.format.EsriJSON.readMultiLineStringGeometry_;
  75949. ol.format.EsriJSON.GEOMETRY_READERS_[ol.geom.GeometryType.MULTI_POLYGON] =
  75950. ol.format.EsriJSON.readMultiPolygonGeometry_;
  75951. /**
  75952. * @const
  75953. * @private
  75954. * @type {Object.<string, function(ol.geom.Geometry, olx.format.WriteOptions=): (EsriJSONGeometry)>}
  75955. */
  75956. ol.format.EsriJSON.GEOMETRY_WRITERS_ = {};
  75957. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POINT] =
  75958. ol.format.EsriJSON.writePointGeometry_;
  75959. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.LINE_STRING] =
  75960. ol.format.EsriJSON.writeLineStringGeometry_;
  75961. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.POLYGON] =
  75962. ol.format.EsriJSON.writePolygonGeometry_;
  75963. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POINT] =
  75964. ol.format.EsriJSON.writeMultiPointGeometry_;
  75965. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_LINE_STRING] =
  75966. ol.format.EsriJSON.writeMultiLineStringGeometry_;
  75967. ol.format.EsriJSON.GEOMETRY_WRITERS_[ol.geom.GeometryType.MULTI_POLYGON] =
  75968. ol.format.EsriJSON.writeMultiPolygonGeometry_;
  75969. /**
  75970. * Read a feature from a EsriJSON Feature source. Only works for Feature,
  75971. * use `readFeatures` to read FeatureCollection source.
  75972. *
  75973. * @function
  75974. * @param {ArrayBuffer|Document|Node|Object|string} source Source.
  75975. * @param {olx.format.ReadOptions=} opt_options Read options.
  75976. * @return {ol.Feature} Feature.
  75977. * @api
  75978. */
  75979. ol.format.EsriJSON.prototype.readFeature;
  75980. /**
  75981. * Read all features from a EsriJSON source. Works with both Feature and
  75982. * FeatureCollection sources.
  75983. *
  75984. * @function
  75985. * @param {ArrayBuffer|Document|Node|Object|string} source Source.
  75986. * @param {olx.format.ReadOptions=} opt_options Read options.
  75987. * @return {Array.<ol.Feature>} Features.
  75988. * @api
  75989. */
  75990. ol.format.EsriJSON.prototype.readFeatures;
  75991. /**
  75992. * @inheritDoc
  75993. */
  75994. ol.format.EsriJSON.prototype.readFeatureFromObject = function(
  75995. object, opt_options) {
  75996. var esriJSONFeature = /** @type {EsriJSONFeature} */ (object);
  75997. goog.asserts.assert(esriJSONFeature.geometry ||
  75998. esriJSONFeature.attributes,
  75999. 'geometry or attributes should be defined');
  76000. var geometry = ol.format.EsriJSON.readGeometry_(esriJSONFeature.geometry,
  76001. opt_options);
  76002. var feature = new ol.Feature();
  76003. if (this.geometryName_) {
  76004. feature.setGeometryName(this.geometryName_);
  76005. }
  76006. feature.setGeometry(geometry);
  76007. if (opt_options && opt_options.idField &&
  76008. esriJSONFeature.attributes[opt_options.idField]) {
  76009. goog.asserts.assert(
  76010. goog.isNumber(esriJSONFeature.attributes[opt_options.idField]),
  76011. 'objectIdFieldName value should be a number');
  76012. feature.setId(/** @type {number} */(
  76013. esriJSONFeature.attributes[opt_options.idField]));
  76014. }
  76015. if (esriJSONFeature.attributes) {
  76016. feature.setProperties(esriJSONFeature.attributes);
  76017. }
  76018. return feature;
  76019. };
  76020. /**
  76021. * @inheritDoc
  76022. */
  76023. ol.format.EsriJSON.prototype.readFeaturesFromObject = function(
  76024. object, opt_options) {
  76025. var esriJSONObject = /** @type {EsriJSONObject} */ (object);
  76026. var options = opt_options ? opt_options : {};
  76027. if (esriJSONObject.features) {
  76028. var esriJSONFeatureCollection = /** @type {EsriJSONFeatureCollection} */
  76029. (object);
  76030. /** @type {Array.<ol.Feature>} */
  76031. var features = [];
  76032. var esriJSONFeatures = esriJSONFeatureCollection.features;
  76033. var i, ii;
  76034. options.idField = object.objectIdFieldName;
  76035. for (i = 0, ii = esriJSONFeatures.length; i < ii; ++i) {
  76036. features.push(this.readFeatureFromObject(esriJSONFeatures[i],
  76037. options));
  76038. }
  76039. return features;
  76040. } else {
  76041. return [this.readFeatureFromObject(object, options)];
  76042. }
  76043. };
  76044. /**
  76045. * Read a geometry from a EsriJSON source.
  76046. *
  76047. * @function
  76048. * @param {ArrayBuffer|Document|Node|Object|string} source Source.
  76049. * @param {olx.format.ReadOptions=} opt_options Read options.
  76050. * @return {ol.geom.Geometry} Geometry.
  76051. * @api
  76052. */
  76053. ol.format.EsriJSON.prototype.readGeometry;
  76054. /**
  76055. * @inheritDoc
  76056. */
  76057. ol.format.EsriJSON.prototype.readGeometryFromObject = function(
  76058. object, opt_options) {
  76059. return ol.format.EsriJSON.readGeometry_(
  76060. /** @type {EsriJSONGeometry} */ (object), opt_options);
  76061. };
  76062. /**
  76063. * Read the projection from a EsriJSON source.
  76064. *
  76065. * @function
  76066. * @param {ArrayBuffer|Document|Node|Object|string} source Source.
  76067. * @return {ol.proj.Projection} Projection.
  76068. * @api
  76069. */
  76070. ol.format.EsriJSON.prototype.readProjection;
  76071. /**
  76072. * @inheritDoc
  76073. */
  76074. ol.format.EsriJSON.prototype.readProjectionFromObject = function(object) {
  76075. var esriJSONObject = /** @type {EsriJSONObject} */ (object);
  76076. if (esriJSONObject.spatialReference && esriJSONObject.spatialReference.wkid) {
  76077. var crs = esriJSONObject.spatialReference.wkid;
  76078. return ol.proj.get('EPSG:' + crs);
  76079. } else {
  76080. return null;
  76081. }
  76082. };
  76083. /**
  76084. * @param {ol.geom.Geometry} geometry Geometry.
  76085. * @param {olx.format.WriteOptions=} opt_options Write options.
  76086. * @private
  76087. * @return {EsriJSONGeometry} EsriJSON geometry.
  76088. */
  76089. ol.format.EsriJSON.writeGeometry_ = function(geometry, opt_options) {
  76090. var geometryWriter = ol.format.EsriJSON.GEOMETRY_WRITERS_[geometry.getType()];
  76091. goog.asserts.assert(geometryWriter, 'geometryWriter should be defined');
  76092. return geometryWriter(/** @type {ol.geom.Geometry} */ (
  76093. ol.format.Feature.transformWithOptions(geometry, true, opt_options)),
  76094. opt_options);
  76095. };
  76096. /**
  76097. * Encode a geometry as a EsriJSON string.
  76098. *
  76099. * @function
  76100. * @param {ol.geom.Geometry} geometry Geometry.
  76101. * @param {olx.format.WriteOptions=} opt_options Write options.
  76102. * @return {string} EsriJSON.
  76103. * @api
  76104. */
  76105. ol.format.EsriJSON.prototype.writeGeometry;
  76106. /**
  76107. * Encode a geometry as a EsriJSON object.
  76108. *
  76109. * @param {ol.geom.Geometry} geometry Geometry.
  76110. * @param {olx.format.WriteOptions=} opt_options Write options.
  76111. * @return {EsriJSONGeometry} Object.
  76112. * @api
  76113. */
  76114. ol.format.EsriJSON.prototype.writeGeometryObject = function(geometry,
  76115. opt_options) {
  76116. return ol.format.EsriJSON.writeGeometry_(geometry,
  76117. this.adaptOptions(opt_options));
  76118. };
  76119. /**
  76120. * Encode a feature as a EsriJSON Feature string.
  76121. *
  76122. * @function
  76123. * @param {ol.Feature} feature Feature.
  76124. * @param {olx.format.WriteOptions=} opt_options Write options.
  76125. * @return {string} EsriJSON.
  76126. * @api
  76127. */
  76128. ol.format.EsriJSON.prototype.writeFeature;
  76129. /**
  76130. * Encode a feature as a esriJSON Feature object.
  76131. *
  76132. * @param {ol.Feature} feature Feature.
  76133. * @param {olx.format.WriteOptions=} opt_options Write options.
  76134. * @return {Object} Object.
  76135. * @api
  76136. */
  76137. ol.format.EsriJSON.prototype.writeFeatureObject = function(
  76138. feature, opt_options) {
  76139. opt_options = this.adaptOptions(opt_options);
  76140. var object = {};
  76141. var geometry = feature.getGeometry();
  76142. if (geometry) {
  76143. object['geometry'] =
  76144. ol.format.EsriJSON.writeGeometry_(geometry, opt_options);
  76145. }
  76146. var properties = feature.getProperties();
  76147. delete properties[feature.getGeometryName()];
  76148. if (!goog.object.isEmpty(properties)) {
  76149. object['attributes'] = properties;
  76150. } else {
  76151. object['attributes'] = {};
  76152. }
  76153. if (opt_options && opt_options.featureProjection) {
  76154. object['spatialReference'] = /** @type {EsriJSONCRS} */({
  76155. wkid: ol.proj.get(
  76156. opt_options.featureProjection).getCode().split(':').pop()
  76157. });
  76158. }
  76159. return object;
  76160. };
  76161. /**
  76162. * Encode an array of features as EsriJSON.
  76163. *
  76164. * @function
  76165. * @param {Array.<ol.Feature>} features Features.
  76166. * @param {olx.format.WriteOptions=} opt_options Write options.
  76167. * @return {string} EsriJSON.
  76168. * @api
  76169. */
  76170. ol.format.EsriJSON.prototype.writeFeatures;
  76171. /**
  76172. * Encode an array of features as a EsriJSON object.
  76173. *
  76174. * @param {Array.<ol.Feature>} features Features.
  76175. * @param {olx.format.WriteOptions=} opt_options Write options.
  76176. * @return {Object} EsriJSON Object.
  76177. * @api
  76178. */
  76179. ol.format.EsriJSON.prototype.writeFeaturesObject =
  76180. function(features, opt_options) {
  76181. opt_options = this.adaptOptions(opt_options);
  76182. var objects = [];
  76183. var i, ii;
  76184. for (i = 0, ii = features.length; i < ii; ++i) {
  76185. objects.push(this.writeFeatureObject(features[i], opt_options));
  76186. }
  76187. return /** @type {EsriJSONFeatureCollection} */ ({
  76188. 'features': objects
  76189. });
  76190. };
  76191. // TODO: serialize dataProjection as crs member when writing
  76192. // see https://github.com/openlayers/ol3/issues/2078
  76193. goog.provide('ol.format.GeoJSON');
  76194. goog.require('goog.asserts');
  76195. goog.require('goog.object');
  76196. goog.require('ol.Feature');
  76197. goog.require('ol.format.Feature');
  76198. goog.require('ol.format.JSONFeature');
  76199. goog.require('ol.geom.GeometryCollection');
  76200. goog.require('ol.geom.LineString');
  76201. goog.require('ol.geom.MultiLineString');
  76202. goog.require('ol.geom.MultiPoint');
  76203. goog.require('ol.geom.MultiPolygon');
  76204. goog.require('ol.geom.Point');
  76205. goog.require('ol.geom.Polygon');
  76206. goog.require('ol.proj');
  76207. /**
  76208. * @classdesc
  76209. * Feature format for reading and writing data in the GeoJSON format.
  76210. *
  76211. * @constructor
  76212. * @extends {ol.format.JSONFeature}
  76213. * @param {olx.format.GeoJSONOptions=} opt_options Options.
  76214. * @api stable
  76215. */
  76216. ol.format.GeoJSON = function(opt_options) {
  76217. var options = opt_options ? opt_options : {};
  76218. goog.base(this);
  76219. /**
  76220. * @inheritDoc
  76221. */
  76222. this.defaultDataProjection = ol.proj.get(
  76223. options.defaultDataProjection ?
  76224. options.defaultDataProjection : 'EPSG:4326');
  76225. /**
  76226. * Name of the geometry attribute for features.
  76227. * @type {string|undefined}
  76228. * @private
  76229. */
  76230. this.geometryName_ = options.geometryName;
  76231. };
  76232. goog.inherits(ol.format.GeoJSON, ol.format.JSONFeature);
  76233. /**
  76234. * @const
  76235. * @type {Array.<string>}
  76236. * @private
  76237. */
  76238. ol.format.GeoJSON.EXTENSIONS_ = ['.geojson'];
  76239. /**
  76240. * @param {GeoJSONGeometry|GeoJSONGeometryCollection} object Object.
  76241. * @param {olx.format.ReadOptions=} opt_options Read options.
  76242. * @private
  76243. * @return {ol.geom.Geometry} Geometry.
  76244. */
  76245. ol.format.GeoJSON.readGeometry_ = function(object, opt_options) {
  76246. if (!object) {
  76247. return null;
  76248. }
  76249. var geometryReader = ol.format.GeoJSON.GEOMETRY_READERS_[object.type];
  76250. goog.asserts.assert(geometryReader, 'geometryReader should be defined');
  76251. return /** @type {ol.geom.Geometry} */ (
  76252. ol.format.Feature.transformWithOptions(
  76253. geometryReader(object), false, opt_options));
  76254. };
  76255. /**
  76256. * @param {GeoJSONGeometryCollection} object Object.
  76257. * @param {olx.format.ReadOptions=} opt_options Read options.
  76258. * @private
  76259. * @return {ol.geom.GeometryCollection} Geometry collection.
  76260. */
  76261. ol.format.GeoJSON.readGeometryCollectionGeometry_ = function(
  76262. object, opt_options) {
  76263. goog.asserts.assert(object.type == 'GeometryCollection',
  76264. 'object.type should be GeometryCollection');
  76265. var geometries = object.geometries.map(
  76266. /**
  76267. * @param {GeoJSONGeometry} geometry Geometry.
  76268. * @return {ol.geom.Geometry} geometry Geometry.
  76269. */
  76270. function(geometry) {
  76271. return ol.format.GeoJSON.readGeometry_(geometry, opt_options);
  76272. });
  76273. return new ol.geom.GeometryCollection(geometries);
  76274. };
  76275. /**
  76276. * @param {GeoJSONGeometry} object Object.
  76277. * @private
  76278. * @return {ol.geom.Point} Point.
  76279. */
  76280. ol.format.GeoJSON.readPointGeometry_ = function(object) {
  76281. goog.asserts.assert(object.type == 'Point',
  76282. 'object.type should be Point');
  76283. return new ol.geom.Point(object.coordinates);
  76284. };
  76285. /**
  76286. * @param {GeoJSONGeometry} object Object.
  76287. * @private
  76288. * @return {ol.geom.LineString} LineString.
  76289. */
  76290. ol.format.GeoJSON.readLineStringGeometry_ = function(object) {
  76291. goog.asserts.assert(object.type == 'LineString',
  76292. 'object.type should be LineString');
  76293. return new ol.geom.LineString(object.coordinates);
  76294. };
  76295. /**
  76296. * @param {GeoJSONGeometry} object Object.
  76297. * @private
  76298. * @return {ol.geom.MultiLineString} MultiLineString.
  76299. */
  76300. ol.format.GeoJSON.readMultiLineStringGeometry_ = function(object) {
  76301. goog.asserts.assert(object.type == 'MultiLineString',
  76302. 'object.type should be MultiLineString');
  76303. return new ol.geom.MultiLineString(object.coordinates);
  76304. };
  76305. /**
  76306. * @param {GeoJSONGeometry} object Object.
  76307. * @private
  76308. * @return {ol.geom.MultiPoint} MultiPoint.
  76309. */
  76310. ol.format.GeoJSON.readMultiPointGeometry_ = function(object) {
  76311. goog.asserts.assert(object.type == 'MultiPoint',
  76312. 'object.type should be MultiPoint');
  76313. return new ol.geom.MultiPoint(object.coordinates);
  76314. };
  76315. /**
  76316. * @param {GeoJSONGeometry} object Object.
  76317. * @private
  76318. * @return {ol.geom.MultiPolygon} MultiPolygon.
  76319. */
  76320. ol.format.GeoJSON.readMultiPolygonGeometry_ = function(object) {
  76321. goog.asserts.assert(object.type == 'MultiPolygon',
  76322. 'object.type should be MultiPolygon');
  76323. return new ol.geom.MultiPolygon(object.coordinates);
  76324. };
  76325. /**
  76326. * @param {GeoJSONGeometry} object Object.
  76327. * @private
  76328. * @return {ol.geom.Polygon} Polygon.
  76329. */
  76330. ol.format.GeoJSON.readPolygonGeometry_ = function(object) {
  76331. goog.asserts.assert(object.type == 'Polygon',
  76332. 'object.type should be Polygon');
  76333. return new ol.geom.Polygon(object.coordinates);
  76334. };
  76335. /**
  76336. * @param {ol.geom.Geometry} geometry Geometry.
  76337. * @param {olx.format.WriteOptions=} opt_options Write options.
  76338. * @private
  76339. * @return {GeoJSONGeometry|GeoJSONGeometryCollection} GeoJSON geometry.
  76340. */
  76341. ol.format.GeoJSON.writeGeometry_ = function(geometry, opt_options) {
  76342. var geometryWriter = ol.format.GeoJSON.GEOMETRY_WRITERS_[geometry.getType()];
  76343. goog.asserts.assert(geometryWriter, 'geometryWriter should be defined');
  76344. return geometryWriter(/** @type {ol.geom.Geometry} */ (
  76345. ol.format.Feature.transformWithOptions(geometry, true, opt_options)),
  76346. opt_options);
  76347. };
  76348. /**
  76349. * @param {ol.geom.Geometry} geometry Geometry.
  76350. * @private
  76351. * @return {GeoJSONGeometryCollection} Empty GeoJSON geometry collection.
  76352. */
  76353. ol.format.GeoJSON.writeEmptyGeometryCollectionGeometry_ = function(geometry) {
  76354. return /** @type {GeoJSONGeometryCollection} */ ({
  76355. type: 'GeometryCollection',
  76356. geometries: []
  76357. });
  76358. };
  76359. /**
  76360. * @param {ol.geom.Geometry} geometry Geometry.
  76361. * @param {olx.format.WriteOptions=} opt_options Write options.
  76362. * @private
  76363. * @return {GeoJSONGeometryCollection} GeoJSON geometry collection.
  76364. */
  76365. ol.format.GeoJSON.writeGeometryCollectionGeometry_ = function(
  76366. geometry, opt_options) {
  76367. goog.asserts.assertInstanceof(geometry, ol.geom.GeometryCollection,
  76368. 'geometry should be an ol.geom.GeometryCollection');
  76369. var geometries = geometry.getGeometriesArray().map(function(geometry) {
  76370. return ol.format.GeoJSON.writeGeometry_(geometry, opt_options);
  76371. });
  76372. return /** @type {GeoJSONGeometryCollection} */ ({
  76373. type: 'GeometryCollection',
  76374. geometries: geometries
  76375. });
  76376. };
  76377. /**
  76378. * @param {ol.geom.Geometry} geometry Geometry.
  76379. * @param {olx.format.WriteOptions=} opt_options Write options.
  76380. * @private
  76381. * @return {GeoJSONGeometry} GeoJSON geometry.
  76382. */
  76383. ol.format.GeoJSON.writeLineStringGeometry_ = function(geometry, opt_options) {
  76384. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  76385. 'geometry should be an ol.geom.LineString');
  76386. return /** @type {GeoJSONGeometry} */ ({
  76387. type: 'LineString',
  76388. coordinates: geometry.getCoordinates()
  76389. });
  76390. };
  76391. /**
  76392. * @param {ol.geom.Geometry} geometry Geometry.
  76393. * @param {olx.format.WriteOptions=} opt_options Write options.
  76394. * @private
  76395. * @return {GeoJSONGeometry} GeoJSON geometry.
  76396. */
  76397. ol.format.GeoJSON.writeMultiLineStringGeometry_ =
  76398. function(geometry, opt_options) {
  76399. goog.asserts.assertInstanceof(geometry, ol.geom.MultiLineString,
  76400. 'geometry should be an ol.geom.MultiLineString');
  76401. return /** @type {GeoJSONGeometry} */ ({
  76402. type: 'MultiLineString',
  76403. coordinates: geometry.getCoordinates()
  76404. });
  76405. };
  76406. /**
  76407. * @param {ol.geom.Geometry} geometry Geometry.
  76408. * @param {olx.format.WriteOptions=} opt_options Write options.
  76409. * @private
  76410. * @return {GeoJSONGeometry} GeoJSON geometry.
  76411. */
  76412. ol.format.GeoJSON.writeMultiPointGeometry_ = function(geometry, opt_options) {
  76413. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPoint,
  76414. 'geometry should be an ol.geom.MultiPoint');
  76415. return /** @type {GeoJSONGeometry} */ ({
  76416. type: 'MultiPoint',
  76417. coordinates: geometry.getCoordinates()
  76418. });
  76419. };
  76420. /**
  76421. * @param {ol.geom.Geometry} geometry Geometry.
  76422. * @param {olx.format.WriteOptions=} opt_options Write options.
  76423. * @private
  76424. * @return {GeoJSONGeometry} GeoJSON geometry.
  76425. */
  76426. ol.format.GeoJSON.writeMultiPolygonGeometry_ = function(geometry, opt_options) {
  76427. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPolygon,
  76428. 'geometry should be an ol.geom.MultiPolygon');
  76429. var right;
  76430. if (opt_options) {
  76431. right = opt_options.rightHanded;
  76432. }
  76433. return /** @type {GeoJSONGeometry} */ ({
  76434. type: 'MultiPolygon',
  76435. coordinates: geometry.getCoordinates(right)
  76436. });
  76437. };
  76438. /**
  76439. * @param {ol.geom.Geometry} geometry Geometry.
  76440. * @param {olx.format.WriteOptions=} opt_options Write options.
  76441. * @private
  76442. * @return {GeoJSONGeometry} GeoJSON geometry.
  76443. */
  76444. ol.format.GeoJSON.writePointGeometry_ = function(geometry, opt_options) {
  76445. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  76446. 'geometry should be an ol.geom.Point');
  76447. return /** @type {GeoJSONGeometry} */ ({
  76448. type: 'Point',
  76449. coordinates: geometry.getCoordinates()
  76450. });
  76451. };
  76452. /**
  76453. * @param {ol.geom.Geometry} geometry Geometry.
  76454. * @param {olx.format.WriteOptions=} opt_options Write options.
  76455. * @private
  76456. * @return {GeoJSONGeometry} GeoJSON geometry.
  76457. */
  76458. ol.format.GeoJSON.writePolygonGeometry_ = function(geometry, opt_options) {
  76459. goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
  76460. 'geometry should be an ol.geom.Polygon');
  76461. var right;
  76462. if (opt_options) {
  76463. right = opt_options.rightHanded;
  76464. }
  76465. return /** @type {GeoJSONGeometry} */ ({
  76466. type: 'Polygon',
  76467. coordinates: geometry.getCoordinates(right)
  76468. });
  76469. };
  76470. /**
  76471. * @const
  76472. * @private
  76473. * @type {Object.<string, function(GeoJSONObject): ol.geom.Geometry>}
  76474. */
  76475. ol.format.GeoJSON.GEOMETRY_READERS_ = {
  76476. 'Point': ol.format.GeoJSON.readPointGeometry_,
  76477. 'LineString': ol.format.GeoJSON.readLineStringGeometry_,
  76478. 'Polygon': ol.format.GeoJSON.readPolygonGeometry_,
  76479. 'MultiPoint': ol.format.GeoJSON.readMultiPointGeometry_,
  76480. 'MultiLineString': ol.format.GeoJSON.readMultiLineStringGeometry_,
  76481. 'MultiPolygon': ol.format.GeoJSON.readMultiPolygonGeometry_,
  76482. 'GeometryCollection': ol.format.GeoJSON.readGeometryCollectionGeometry_
  76483. };
  76484. /**
  76485. * @const
  76486. * @private
  76487. * @type {Object.<string, function(ol.geom.Geometry, olx.format.WriteOptions=): (GeoJSONGeometry|GeoJSONGeometryCollection)>}
  76488. */
  76489. ol.format.GeoJSON.GEOMETRY_WRITERS_ = {
  76490. 'Point': ol.format.GeoJSON.writePointGeometry_,
  76491. 'LineString': ol.format.GeoJSON.writeLineStringGeometry_,
  76492. 'Polygon': ol.format.GeoJSON.writePolygonGeometry_,
  76493. 'MultiPoint': ol.format.GeoJSON.writeMultiPointGeometry_,
  76494. 'MultiLineString': ol.format.GeoJSON.writeMultiLineStringGeometry_,
  76495. 'MultiPolygon': ol.format.GeoJSON.writeMultiPolygonGeometry_,
  76496. 'GeometryCollection': ol.format.GeoJSON.writeGeometryCollectionGeometry_,
  76497. 'Circle': ol.format.GeoJSON.writeEmptyGeometryCollectionGeometry_
  76498. };
  76499. /**
  76500. * @inheritDoc
  76501. */
  76502. ol.format.GeoJSON.prototype.getExtensions = function() {
  76503. return ol.format.GeoJSON.EXTENSIONS_;
  76504. };
  76505. /**
  76506. * Read a feature from a GeoJSON Feature source. Only works for Feature,
  76507. * use `readFeatures` to read FeatureCollection source.
  76508. *
  76509. * @function
  76510. * @param {Document|Node|Object|string} source Source.
  76511. * @param {olx.format.ReadOptions=} opt_options Read options.
  76512. * @return {ol.Feature} Feature.
  76513. * @api stable
  76514. */
  76515. ol.format.GeoJSON.prototype.readFeature;
  76516. /**
  76517. * Read all features from a GeoJSON source. Works with both Feature and
  76518. * FeatureCollection sources.
  76519. *
  76520. * @function
  76521. * @param {Document|Node|Object|string} source Source.
  76522. * @param {olx.format.ReadOptions=} opt_options Read options.
  76523. * @return {Array.<ol.Feature>} Features.
  76524. * @api stable
  76525. */
  76526. ol.format.GeoJSON.prototype.readFeatures;
  76527. /**
  76528. * @inheritDoc
  76529. */
  76530. ol.format.GeoJSON.prototype.readFeatureFromObject = function(
  76531. object, opt_options) {
  76532. var geoJSONFeature = /** @type {GeoJSONFeature} */ (object);
  76533. goog.asserts.assert(geoJSONFeature.type == 'Feature',
  76534. 'geoJSONFeature.type should be Feature');
  76535. var geometry = ol.format.GeoJSON.readGeometry_(geoJSONFeature.geometry,
  76536. opt_options);
  76537. var feature = new ol.Feature();
  76538. if (this.geometryName_) {
  76539. feature.setGeometryName(this.geometryName_);
  76540. }
  76541. feature.setGeometry(geometry);
  76542. if (geoJSONFeature.id) {
  76543. feature.setId(geoJSONFeature.id);
  76544. }
  76545. if (geoJSONFeature.properties) {
  76546. feature.setProperties(geoJSONFeature.properties);
  76547. }
  76548. return feature;
  76549. };
  76550. /**
  76551. * @inheritDoc
  76552. */
  76553. ol.format.GeoJSON.prototype.readFeaturesFromObject = function(
  76554. object, opt_options) {
  76555. var geoJSONObject = /** @type {GeoJSONObject} */ (object);
  76556. if (geoJSONObject.type == 'Feature') {
  76557. return [this.readFeatureFromObject(object, opt_options)];
  76558. } else if (geoJSONObject.type == 'FeatureCollection') {
  76559. var geoJSONFeatureCollection = /** @type {GeoJSONFeatureCollection} */
  76560. (object);
  76561. /** @type {Array.<ol.Feature>} */
  76562. var features = [];
  76563. var geoJSONFeatures = geoJSONFeatureCollection.features;
  76564. var i, ii;
  76565. for (i = 0, ii = geoJSONFeatures.length; i < ii; ++i) {
  76566. features.push(this.readFeatureFromObject(geoJSONFeatures[i],
  76567. opt_options));
  76568. }
  76569. return features;
  76570. } else {
  76571. goog.asserts.fail('Unknown geoJSONObject.type: ' + geoJSONObject.type);
  76572. return [];
  76573. }
  76574. };
  76575. /**
  76576. * Read a geometry from a GeoJSON source.
  76577. *
  76578. * @function
  76579. * @param {Document|Node|Object|string} source Source.
  76580. * @param {olx.format.ReadOptions=} opt_options Read options.
  76581. * @return {ol.geom.Geometry} Geometry.
  76582. * @api stable
  76583. */
  76584. ol.format.GeoJSON.prototype.readGeometry;
  76585. /**
  76586. * @inheritDoc
  76587. */
  76588. ol.format.GeoJSON.prototype.readGeometryFromObject = function(
  76589. object, opt_options) {
  76590. return ol.format.GeoJSON.readGeometry_(
  76591. /** @type {GeoJSONGeometry} */ (object), opt_options);
  76592. };
  76593. /**
  76594. * Read the projection from a GeoJSON source.
  76595. *
  76596. * @function
  76597. * @param {Document|Node|Object|string} source Source.
  76598. * @return {ol.proj.Projection} Projection.
  76599. * @api stable
  76600. */
  76601. ol.format.GeoJSON.prototype.readProjection;
  76602. /**
  76603. * @inheritDoc
  76604. */
  76605. ol.format.GeoJSON.prototype.readProjectionFromObject = function(object) {
  76606. var geoJSONObject = /** @type {GeoJSONObject} */ (object);
  76607. var crs = geoJSONObject.crs;
  76608. if (crs) {
  76609. if (crs.type == 'name') {
  76610. return ol.proj.get(crs.properties.name);
  76611. } else if (crs.type == 'EPSG') {
  76612. // 'EPSG' is not part of the GeoJSON specification, but is generated by
  76613. // GeoServer.
  76614. // TODO: remove this when http://jira.codehaus.org/browse/GEOS-5996
  76615. // is fixed and widely deployed.
  76616. return ol.proj.get('EPSG:' + crs.properties.code);
  76617. } else {
  76618. goog.asserts.fail('Unknown crs.type: ' + crs.type);
  76619. return null;
  76620. }
  76621. } else {
  76622. return this.defaultDataProjection;
  76623. }
  76624. };
  76625. /**
  76626. * Encode a feature as a GeoJSON Feature string.
  76627. *
  76628. * @function
  76629. * @param {ol.Feature} feature Feature.
  76630. * @param {olx.format.WriteOptions=} opt_options Write options.
  76631. * @return {string} GeoJSON.
  76632. * @api stable
  76633. */
  76634. ol.format.GeoJSON.prototype.writeFeature;
  76635. /**
  76636. * Encode a feature as a GeoJSON Feature object.
  76637. *
  76638. * @param {ol.Feature} feature Feature.
  76639. * @param {olx.format.WriteOptions=} opt_options Write options.
  76640. * @return {Object} Object.
  76641. * @api stable
  76642. */
  76643. ol.format.GeoJSON.prototype.writeFeatureObject = function(
  76644. feature, opt_options) {
  76645. opt_options = this.adaptOptions(opt_options);
  76646. var object = {
  76647. 'type': 'Feature'
  76648. };
  76649. var id = feature.getId();
  76650. if (id) {
  76651. object['id'] = id;
  76652. }
  76653. var geometry = feature.getGeometry();
  76654. if (geometry) {
  76655. object['geometry'] =
  76656. ol.format.GeoJSON.writeGeometry_(geometry, opt_options);
  76657. } else {
  76658. object['geometry'] = null;
  76659. }
  76660. var properties = feature.getProperties();
  76661. delete properties[feature.getGeometryName()];
  76662. if (!goog.object.isEmpty(properties)) {
  76663. object['properties'] = properties;
  76664. } else {
  76665. object['properties'] = null;
  76666. }
  76667. return object;
  76668. };
  76669. /**
  76670. * Encode an array of features as GeoJSON.
  76671. *
  76672. * @function
  76673. * @param {Array.<ol.Feature>} features Features.
  76674. * @param {olx.format.WriteOptions=} opt_options Write options.
  76675. * @return {string} GeoJSON.
  76676. * @api stable
  76677. */
  76678. ol.format.GeoJSON.prototype.writeFeatures;
  76679. /**
  76680. * Encode an array of features as a GeoJSON object.
  76681. *
  76682. * @param {Array.<ol.Feature>} features Features.
  76683. * @param {olx.format.WriteOptions=} opt_options Write options.
  76684. * @return {Object} GeoJSON Object.
  76685. * @api stable
  76686. */
  76687. ol.format.GeoJSON.prototype.writeFeaturesObject =
  76688. function(features, opt_options) {
  76689. opt_options = this.adaptOptions(opt_options);
  76690. var objects = [];
  76691. var i, ii;
  76692. for (i = 0, ii = features.length; i < ii; ++i) {
  76693. objects.push(this.writeFeatureObject(features[i], opt_options));
  76694. }
  76695. return /** @type {GeoJSONFeatureCollection} */ ({
  76696. type: 'FeatureCollection',
  76697. features: objects
  76698. });
  76699. };
  76700. /**
  76701. * Encode a geometry as a GeoJSON string.
  76702. *
  76703. * @function
  76704. * @param {ol.geom.Geometry} geometry Geometry.
  76705. * @param {olx.format.WriteOptions=} opt_options Write options.
  76706. * @return {string} GeoJSON.
  76707. * @api stable
  76708. */
  76709. ol.format.GeoJSON.prototype.writeGeometry;
  76710. /**
  76711. * Encode a geometry as a GeoJSON object.
  76712. *
  76713. * @param {ol.geom.Geometry} geometry Geometry.
  76714. * @param {olx.format.WriteOptions=} opt_options Write options.
  76715. * @return {GeoJSONGeometry|GeoJSONGeometryCollection} Object.
  76716. * @api stable
  76717. */
  76718. ol.format.GeoJSON.prototype.writeGeometryObject = function(geometry,
  76719. opt_options) {
  76720. return ol.format.GeoJSON.writeGeometry_(geometry,
  76721. this.adaptOptions(opt_options));
  76722. };
  76723. goog.provide('ol.format.XMLFeature');
  76724. goog.require('goog.array');
  76725. goog.require('goog.asserts');
  76726. goog.require('goog.dom.NodeType');
  76727. goog.require('goog.dom.xml');
  76728. goog.require('ol.format.Feature');
  76729. goog.require('ol.format.FormatType');
  76730. goog.require('ol.proj');
  76731. goog.require('ol.xml');
  76732. /**
  76733. * @classdesc
  76734. * Abstract base class; normally only used for creating subclasses and not
  76735. * instantiated in apps.
  76736. * Base class for XML feature formats.
  76737. *
  76738. * @constructor
  76739. * @extends {ol.format.Feature}
  76740. */
  76741. ol.format.XMLFeature = function() {
  76742. goog.base(this);
  76743. };
  76744. goog.inherits(ol.format.XMLFeature, ol.format.Feature);
  76745. /**
  76746. * @inheritDoc
  76747. */
  76748. ol.format.XMLFeature.prototype.getType = function() {
  76749. return ol.format.FormatType.XML;
  76750. };
  76751. /**
  76752. * @inheritDoc
  76753. */
  76754. ol.format.XMLFeature.prototype.readFeature = function(source, opt_options) {
  76755. if (ol.xml.isDocument(source)) {
  76756. return this.readFeatureFromDocument(
  76757. /** @type {Document} */ (source), opt_options);
  76758. } else if (ol.xml.isNode(source)) {
  76759. return this.readFeatureFromNode(/** @type {Node} */ (source), opt_options);
  76760. } else if (goog.isString(source)) {
  76761. var doc = ol.xml.parse(source);
  76762. return this.readFeatureFromDocument(doc, opt_options);
  76763. } else {
  76764. goog.asserts.fail('Unknown source type');
  76765. return null;
  76766. }
  76767. };
  76768. /**
  76769. * @param {Document} doc Document.
  76770. * @param {olx.format.ReadOptions=} opt_options Options.
  76771. * @return {ol.Feature} Feature.
  76772. */
  76773. ol.format.XMLFeature.prototype.readFeatureFromDocument = function(
  76774. doc, opt_options) {
  76775. var features = this.readFeaturesFromDocument(doc, opt_options);
  76776. if (features.length > 0) {
  76777. return features[0];
  76778. } else {
  76779. return null;
  76780. }
  76781. };
  76782. /**
  76783. * @param {Node} node Node.
  76784. * @param {olx.format.ReadOptions=} opt_options Options.
  76785. * @return {ol.Feature} Feature.
  76786. */
  76787. ol.format.XMLFeature.prototype.readFeatureFromNode = goog.abstractMethod;
  76788. /**
  76789. * @inheritDoc
  76790. */
  76791. ol.format.XMLFeature.prototype.readFeatures = function(source, opt_options) {
  76792. if (ol.xml.isDocument(source)) {
  76793. return this.readFeaturesFromDocument(
  76794. /** @type {Document} */ (source), opt_options);
  76795. } else if (ol.xml.isNode(source)) {
  76796. return this.readFeaturesFromNode(/** @type {Node} */ (source), opt_options);
  76797. } else if (goog.isString(source)) {
  76798. var doc = ol.xml.parse(source);
  76799. return this.readFeaturesFromDocument(doc, opt_options);
  76800. } else {
  76801. goog.asserts.fail('Unknown source type');
  76802. return [];
  76803. }
  76804. };
  76805. /**
  76806. * @param {Document} doc Document.
  76807. * @param {olx.format.ReadOptions=} opt_options Options.
  76808. * @protected
  76809. * @return {Array.<ol.Feature>} Features.
  76810. */
  76811. ol.format.XMLFeature.prototype.readFeaturesFromDocument = function(
  76812. doc, opt_options) {
  76813. /** @type {Array.<ol.Feature>} */
  76814. var features = [];
  76815. var n;
  76816. for (n = doc.firstChild; n; n = n.nextSibling) {
  76817. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  76818. goog.array.extend(features, this.readFeaturesFromNode(n, opt_options));
  76819. }
  76820. }
  76821. return features;
  76822. };
  76823. /**
  76824. * @param {Node} node Node.
  76825. * @param {olx.format.ReadOptions=} opt_options Options.
  76826. * @protected
  76827. * @return {Array.<ol.Feature>} Features.
  76828. */
  76829. ol.format.XMLFeature.prototype.readFeaturesFromNode = goog.abstractMethod;
  76830. /**
  76831. * @inheritDoc
  76832. */
  76833. ol.format.XMLFeature.prototype.readGeometry = function(source, opt_options) {
  76834. if (ol.xml.isDocument(source)) {
  76835. return this.readGeometryFromDocument(
  76836. /** @type {Document} */ (source), opt_options);
  76837. } else if (ol.xml.isNode(source)) {
  76838. return this.readGeometryFromNode(/** @type {Node} */ (source), opt_options);
  76839. } else if (goog.isString(source)) {
  76840. var doc = ol.xml.parse(source);
  76841. return this.readGeometryFromDocument(doc, opt_options);
  76842. } else {
  76843. goog.asserts.fail('Unknown source type');
  76844. return null;
  76845. }
  76846. };
  76847. /**
  76848. * @param {Document} doc Document.
  76849. * @param {olx.format.ReadOptions=} opt_options Options.
  76850. * @protected
  76851. * @return {ol.geom.Geometry} Geometry.
  76852. */
  76853. ol.format.XMLFeature.prototype.readGeometryFromDocument = goog.abstractMethod;
  76854. /**
  76855. * @param {Node} node Node.
  76856. * @param {olx.format.ReadOptions=} opt_options Options.
  76857. * @protected
  76858. * @return {ol.geom.Geometry} Geometry.
  76859. */
  76860. ol.format.XMLFeature.prototype.readGeometryFromNode = goog.abstractMethod;
  76861. /**
  76862. * @inheritDoc
  76863. */
  76864. ol.format.XMLFeature.prototype.readProjection = function(source) {
  76865. if (ol.xml.isDocument(source)) {
  76866. return this.readProjectionFromDocument(/** @type {Document} */ (source));
  76867. } else if (ol.xml.isNode(source)) {
  76868. return this.readProjectionFromNode(/** @type {Node} */ (source));
  76869. } else if (goog.isString(source)) {
  76870. var doc = ol.xml.parse(source);
  76871. return this.readProjectionFromDocument(doc);
  76872. } else {
  76873. goog.asserts.fail('Unknown source type');
  76874. return null;
  76875. }
  76876. };
  76877. /**
  76878. * @param {Document} doc Document.
  76879. * @protected
  76880. * @return {ol.proj.Projection} Projection.
  76881. */
  76882. ol.format.XMLFeature.prototype.readProjectionFromDocument = function(doc) {
  76883. return this.defaultDataProjection;
  76884. };
  76885. /**
  76886. * @param {Node} node Node.
  76887. * @protected
  76888. * @return {ol.proj.Projection} Projection.
  76889. */
  76890. ol.format.XMLFeature.prototype.readProjectionFromNode = function(node) {
  76891. return this.defaultDataProjection;
  76892. };
  76893. /**
  76894. * @inheritDoc
  76895. */
  76896. ol.format.XMLFeature.prototype.writeFeature = function(feature, opt_options) {
  76897. var node = this.writeFeatureNode(feature, opt_options);
  76898. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  76899. 'node.nodeType should be ELEMENT');
  76900. return goog.dom.xml.serialize(/** @type {Element} */(node));
  76901. };
  76902. /**
  76903. * @param {ol.Feature} feature Feature.
  76904. * @param {olx.format.WriteOptions=} opt_options Options.
  76905. * @protected
  76906. * @return {Node} Node.
  76907. */
  76908. ol.format.XMLFeature.prototype.writeFeatureNode = goog.abstractMethod;
  76909. /**
  76910. * @inheritDoc
  76911. */
  76912. ol.format.XMLFeature.prototype.writeFeatures = function(features, opt_options) {
  76913. var node = this.writeFeaturesNode(features, opt_options);
  76914. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  76915. 'node.nodeType should be ELEMENT');
  76916. return goog.dom.xml.serialize(/** @type {Element} */(node));
  76917. };
  76918. /**
  76919. * @param {Array.<ol.Feature>} features Features.
  76920. * @param {olx.format.WriteOptions=} opt_options Options.
  76921. * @return {Node} Node.
  76922. */
  76923. ol.format.XMLFeature.prototype.writeFeaturesNode = goog.abstractMethod;
  76924. /**
  76925. * @inheritDoc
  76926. */
  76927. ol.format.XMLFeature.prototype.writeGeometry = function(geometry, opt_options) {
  76928. var node = this.writeGeometryNode(geometry, opt_options);
  76929. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  76930. 'node.nodeType should be ELEMENT');
  76931. return goog.dom.xml.serialize(/** @type {Element} */(node));
  76932. };
  76933. /**
  76934. * @param {ol.geom.Geometry} geometry Geometry.
  76935. * @param {olx.format.WriteOptions=} opt_options Options.
  76936. * @return {Node} Node.
  76937. */
  76938. ol.format.XMLFeature.prototype.writeGeometryNode = goog.abstractMethod;
  76939. // FIXME Envelopes should not be treated as geometries! readEnvelope_ is part
  76940. // of GEOMETRY_PARSERS_ and methods using GEOMETRY_PARSERS_ do not expect
  76941. // envelopes/extents, only geometries!
  76942. goog.provide('ol.format.GMLBase');
  76943. goog.require('goog.array');
  76944. goog.require('goog.asserts');
  76945. goog.require('goog.dom.NodeType');
  76946. goog.require('goog.object');
  76947. goog.require('goog.string');
  76948. goog.require('ol.Feature');
  76949. goog.require('ol.format.Feature');
  76950. goog.require('ol.format.XMLFeature');
  76951. goog.require('ol.geom.Geometry');
  76952. goog.require('ol.geom.GeometryLayout');
  76953. goog.require('ol.geom.LineString');
  76954. goog.require('ol.geom.LinearRing');
  76955. goog.require('ol.geom.MultiLineString');
  76956. goog.require('ol.geom.MultiPoint');
  76957. goog.require('ol.geom.MultiPolygon');
  76958. goog.require('ol.geom.Point');
  76959. goog.require('ol.geom.Polygon');
  76960. goog.require('ol.proj');
  76961. goog.require('ol.xml');
  76962. /**
  76963. * @classdesc
  76964. * Abstract base class; normally only used for creating subclasses and not
  76965. * instantiated in apps.
  76966. * Feature base format for reading and writing data in the GML format.
  76967. * This class cannot be instantiated, it contains only base content that
  76968. * is shared with versioned format classes ol.format.GML2 and
  76969. * ol.format.GML3.
  76970. *
  76971. * @constructor
  76972. * @param {olx.format.GMLOptions=} opt_options
  76973. * Optional configuration object.
  76974. * @extends {ol.format.XMLFeature}
  76975. */
  76976. ol.format.GMLBase = function(opt_options) {
  76977. var options = /** @type {olx.format.GMLOptions} */
  76978. (opt_options ? opt_options : {});
  76979. /**
  76980. * @protected
  76981. * @type {Array.<string>|string|undefined}
  76982. */
  76983. this.featureType = options.featureType;
  76984. /**
  76985. * @protected
  76986. * @type {Object.<string, string>|string|undefined}
  76987. */
  76988. this.featureNS = options.featureNS;
  76989. /**
  76990. * @protected
  76991. * @type {string}
  76992. */
  76993. this.srsName = options.srsName;
  76994. /**
  76995. * @protected
  76996. * @type {string}
  76997. */
  76998. this.schemaLocation = '';
  76999. /**
  77000. * @type {Object.<string, Object.<string, Object>>}
  77001. */
  77002. this.FEATURE_COLLECTION_PARSERS = {};
  77003. this.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS] = {
  77004. 'featureMember': ol.xml.makeReplacer(
  77005. ol.format.GMLBase.prototype.readFeaturesInternal),
  77006. 'featureMembers': ol.xml.makeReplacer(
  77007. ol.format.GMLBase.prototype.readFeaturesInternal)
  77008. };
  77009. goog.base(this);
  77010. };
  77011. goog.inherits(ol.format.GMLBase, ol.format.XMLFeature);
  77012. /**
  77013. * @const
  77014. * @type {string}
  77015. */
  77016. ol.format.GMLBase.GMLNS = 'http://www.opengis.net/gml';
  77017. /**
  77018. * @param {Node} node Node.
  77019. * @param {Array.<*>} objectStack Object stack.
  77020. * @return {Array.<ol.Feature>} Features.
  77021. */
  77022. ol.format.GMLBase.prototype.readFeaturesInternal = function(node, objectStack) {
  77023. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77024. 'node.nodeType should be ELEMENT');
  77025. var localName = ol.xml.getLocalName(node);
  77026. var features;
  77027. if (localName == 'FeatureCollection') {
  77028. if (node.namespaceURI === 'http://www.opengis.net/wfs') {
  77029. features = ol.xml.pushParseAndPop([],
  77030. this.FEATURE_COLLECTION_PARSERS, node,
  77031. objectStack, this);
  77032. } else {
  77033. features = ol.xml.pushParseAndPop(null,
  77034. this.FEATURE_COLLECTION_PARSERS, node,
  77035. objectStack, this);
  77036. }
  77037. } else if (localName == 'featureMembers' || localName == 'featureMember') {
  77038. var context = objectStack[0];
  77039. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  77040. var featureType = context['featureType'];
  77041. var featureNS = context['featureNS'];
  77042. var i, ii, prefix = 'p', defaultPrefix = 'p0';
  77043. if (!featureType && node.childNodes) {
  77044. featureType = [], featureNS = {};
  77045. for (i = 0, ii = node.childNodes.length; i < ii; ++i) {
  77046. var child = node.childNodes[i];
  77047. if (child.nodeType === 1) {
  77048. var ft = child.nodeName.split(':').pop();
  77049. if (featureType.indexOf(ft) === -1) {
  77050. var key;
  77051. if (!goog.object.contains(featureNS, child.namespaceURI)) {
  77052. key = prefix + goog.object.getCount(featureNS);
  77053. featureNS[key] = child.namespaceURI;
  77054. } else {
  77055. key = goog.object.findKey(featureNS, function(value) {
  77056. return value === child.namespaceURI;
  77057. });
  77058. }
  77059. featureType.push(key + ':' + ft);
  77060. }
  77061. }
  77062. }
  77063. context['featureType'] = featureType;
  77064. context['featureNS'] = featureNS;
  77065. }
  77066. if (goog.isString(featureNS)) {
  77067. var ns = featureNS;
  77068. featureNS = {};
  77069. featureNS[defaultPrefix] = ns;
  77070. }
  77071. var parsersNS = {};
  77072. var featureTypes = goog.isArray(featureType) ? featureType : [featureType];
  77073. for (var p in featureNS) {
  77074. var parsers = {};
  77075. for (i = 0, ii = featureTypes.length; i < ii; ++i) {
  77076. var featurePrefix = featureTypes[i].indexOf(':') === -1 ?
  77077. defaultPrefix : featureTypes[i].split(':')[0];
  77078. if (featurePrefix === p) {
  77079. parsers[featureTypes[i].split(':').pop()] =
  77080. (localName == 'featureMembers') ?
  77081. ol.xml.makeArrayPusher(this.readFeatureElement, this) :
  77082. ol.xml.makeReplacer(this.readFeatureElement, this);
  77083. }
  77084. }
  77085. parsersNS[featureNS[p]] = parsers;
  77086. }
  77087. features = ol.xml.pushParseAndPop([], parsersNS, node, objectStack);
  77088. }
  77089. if (!features) {
  77090. features = [];
  77091. }
  77092. return features;
  77093. };
  77094. /**
  77095. * @param {Node} node Node.
  77096. * @param {Array.<*>} objectStack Object stack.
  77097. * @return {ol.geom.Geometry|undefined} Geometry.
  77098. */
  77099. ol.format.GMLBase.prototype.readGeometryElement = function(node, objectStack) {
  77100. var context = objectStack[0];
  77101. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  77102. context['srsName'] = node.firstElementChild.getAttribute('srsName');
  77103. var geometry = ol.xml.pushParseAndPop(/** @type {ol.geom.Geometry} */(null),
  77104. this.GEOMETRY_PARSERS_, node, objectStack, this);
  77105. if (geometry) {
  77106. return /** @type {ol.geom.Geometry} */ (
  77107. ol.format.Feature.transformWithOptions(geometry, false, context));
  77108. } else {
  77109. return undefined;
  77110. }
  77111. };
  77112. /**
  77113. * @param {Node} node Node.
  77114. * @param {Array.<*>} objectStack Object stack.
  77115. * @return {ol.Feature} Feature.
  77116. */
  77117. ol.format.GMLBase.prototype.readFeatureElement = function(node, objectStack) {
  77118. var n;
  77119. var fid = node.getAttribute('fid') ||
  77120. ol.xml.getAttributeNS(node, ol.format.GMLBase.GMLNS, 'id');
  77121. var values = {}, geometryName;
  77122. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  77123. var localName = ol.xml.getLocalName(n);
  77124. // Assume attribute elements have one child node and that the child
  77125. // is a text or CDATA node (to be treated as text).
  77126. // Otherwise assume it is a geometry node.
  77127. if (n.childNodes.length === 0 ||
  77128. (n.childNodes.length === 1 &&
  77129. (n.firstChild.nodeType === 3 || n.firstChild.nodeType === 4))) {
  77130. var value = ol.xml.getAllTextContent(n, false);
  77131. if (goog.string.isEmpty(value)) {
  77132. value = undefined;
  77133. }
  77134. values[localName] = value;
  77135. } else {
  77136. // boundedBy is an extent and must not be considered as a geometry
  77137. if (localName !== 'boundedBy') {
  77138. geometryName = localName;
  77139. }
  77140. values[localName] = this.readGeometryElement(n, objectStack);
  77141. }
  77142. }
  77143. var feature = new ol.Feature(values);
  77144. if (geometryName) {
  77145. feature.setGeometryName(geometryName);
  77146. }
  77147. if (fid) {
  77148. feature.setId(fid);
  77149. }
  77150. return feature;
  77151. };
  77152. /**
  77153. * @param {Node} node Node.
  77154. * @param {Array.<*>} objectStack Object stack.
  77155. * @return {ol.geom.Point|undefined} Point.
  77156. */
  77157. ol.format.GMLBase.prototype.readPoint = function(node, objectStack) {
  77158. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77159. 'node.nodeType should be ELEMENT');
  77160. goog.asserts.assert(node.localName == 'Point', 'localName should be Point');
  77161. var flatCoordinates =
  77162. this.readFlatCoordinatesFromNode_(node, objectStack);
  77163. if (flatCoordinates) {
  77164. var point = new ol.geom.Point(null);
  77165. goog.asserts.assert(flatCoordinates.length == 3,
  77166. 'flatCoordinates should have a length of 3');
  77167. point.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  77168. return point;
  77169. }
  77170. };
  77171. /**
  77172. * @param {Node} node Node.
  77173. * @param {Array.<*>} objectStack Object stack.
  77174. * @return {ol.geom.MultiPoint|undefined} MultiPoint.
  77175. */
  77176. ol.format.GMLBase.prototype.readMultiPoint = function(node, objectStack) {
  77177. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77178. 'node.nodeType should be ELEMENT');
  77179. goog.asserts.assert(node.localName == 'MultiPoint',
  77180. 'localName should be MultiPoint');
  77181. var coordinates = ol.xml.pushParseAndPop(
  77182. /** @type {Array.<Array.<number>>} */ ([]),
  77183. this.MULTIPOINT_PARSERS_, node, objectStack, this);
  77184. if (coordinates) {
  77185. return new ol.geom.MultiPoint(coordinates);
  77186. } else {
  77187. return undefined;
  77188. }
  77189. };
  77190. /**
  77191. * @param {Node} node Node.
  77192. * @param {Array.<*>} objectStack Object stack.
  77193. * @return {ol.geom.MultiLineString|undefined} MultiLineString.
  77194. */
  77195. ol.format.GMLBase.prototype.readMultiLineString = function(node, objectStack) {
  77196. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77197. 'node.nodeType should be ELEMENT');
  77198. goog.asserts.assert(node.localName == 'MultiLineString',
  77199. 'localName should be MultiLineString');
  77200. var lineStrings = ol.xml.pushParseAndPop(
  77201. /** @type {Array.<ol.geom.LineString>} */ ([]),
  77202. this.MULTILINESTRING_PARSERS_, node, objectStack, this);
  77203. if (lineStrings) {
  77204. var multiLineString = new ol.geom.MultiLineString(null);
  77205. multiLineString.setLineStrings(lineStrings);
  77206. return multiLineString;
  77207. } else {
  77208. return undefined;
  77209. }
  77210. };
  77211. /**
  77212. * @param {Node} node Node.
  77213. * @param {Array.<*>} objectStack Object stack.
  77214. * @return {ol.geom.MultiPolygon|undefined} MultiPolygon.
  77215. */
  77216. ol.format.GMLBase.prototype.readMultiPolygon = function(node, objectStack) {
  77217. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77218. 'node.nodeType should be ELEMENT');
  77219. goog.asserts.assert(node.localName == 'MultiPolygon',
  77220. 'localName should be MultiPolygon');
  77221. var polygons = ol.xml.pushParseAndPop(
  77222. /** @type {Array.<ol.geom.Polygon>} */ ([]),
  77223. this.MULTIPOLYGON_PARSERS_, node, objectStack, this);
  77224. if (polygons) {
  77225. var multiPolygon = new ol.geom.MultiPolygon(null);
  77226. multiPolygon.setPolygons(polygons);
  77227. return multiPolygon;
  77228. } else {
  77229. return undefined;
  77230. }
  77231. };
  77232. /**
  77233. * @param {Node} node Node.
  77234. * @param {Array.<*>} objectStack Object stack.
  77235. * @private
  77236. */
  77237. ol.format.GMLBase.prototype.pointMemberParser_ = function(node, objectStack) {
  77238. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77239. 'node.nodeType should be ELEMENT');
  77240. goog.asserts.assert(node.localName == 'pointMember' ||
  77241. node.localName == 'pointMembers',
  77242. 'localName should be pointMember or pointMembers');
  77243. ol.xml.parseNode(this.POINTMEMBER_PARSERS_,
  77244. node, objectStack, this);
  77245. };
  77246. /**
  77247. * @param {Node} node Node.
  77248. * @param {Array.<*>} objectStack Object stack.
  77249. * @private
  77250. */
  77251. ol.format.GMLBase.prototype.lineStringMemberParser_ =
  77252. function(node, objectStack) {
  77253. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77254. 'node.nodeType should be ELEMENT');
  77255. goog.asserts.assert(node.localName == 'lineStringMember' ||
  77256. node.localName == 'lineStringMembers',
  77257. 'localName should be LineStringMember or LineStringMembers');
  77258. ol.xml.parseNode(this.LINESTRINGMEMBER_PARSERS_,
  77259. node, objectStack, this);
  77260. };
  77261. /**
  77262. * @param {Node} node Node.
  77263. * @param {Array.<*>} objectStack Object stack.
  77264. * @private
  77265. */
  77266. ol.format.GMLBase.prototype.polygonMemberParser_ =
  77267. function(node, objectStack) {
  77268. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77269. 'node.nodeType should be ELEMENT');
  77270. goog.asserts.assert(node.localName == 'polygonMember' ||
  77271. node.localName == 'polygonMembers',
  77272. 'localName should be polygonMember or polygonMembers');
  77273. ol.xml.parseNode(this.POLYGONMEMBER_PARSERS_, node,
  77274. objectStack, this);
  77275. };
  77276. /**
  77277. * @param {Node} node Node.
  77278. * @param {Array.<*>} objectStack Object stack.
  77279. * @return {ol.geom.LineString|undefined} LineString.
  77280. */
  77281. ol.format.GMLBase.prototype.readLineString = function(node, objectStack) {
  77282. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77283. 'node.nodeType should be ELEMENT');
  77284. goog.asserts.assert(node.localName == 'LineString',
  77285. 'localName should be LineString');
  77286. var flatCoordinates =
  77287. this.readFlatCoordinatesFromNode_(node, objectStack);
  77288. if (flatCoordinates) {
  77289. var lineString = new ol.geom.LineString(null);
  77290. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  77291. return lineString;
  77292. } else {
  77293. return undefined;
  77294. }
  77295. };
  77296. /**
  77297. * @param {Node} node Node.
  77298. * @param {Array.<*>} objectStack Object stack.
  77299. * @private
  77300. * @return {Array.<number>|undefined} LinearRing flat coordinates.
  77301. */
  77302. ol.format.GMLBase.prototype.readFlatLinearRing_ = function(node, objectStack) {
  77303. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77304. 'node.nodeType should be ELEMENT');
  77305. goog.asserts.assert(node.localName == 'LinearRing',
  77306. 'localName should be LinearRing');
  77307. var ring = ol.xml.pushParseAndPop(/** @type {Array.<number>} */(null),
  77308. this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node,
  77309. objectStack, this);
  77310. if (ring) {
  77311. return ring;
  77312. } else {
  77313. return undefined;
  77314. }
  77315. };
  77316. /**
  77317. * @param {Node} node Node.
  77318. * @param {Array.<*>} objectStack Object stack.
  77319. * @return {ol.geom.LinearRing|undefined} LinearRing.
  77320. */
  77321. ol.format.GMLBase.prototype.readLinearRing = function(node, objectStack) {
  77322. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77323. 'node.nodeType should be ELEMENT');
  77324. goog.asserts.assert(node.localName == 'LinearRing',
  77325. 'localName should be LinearRing');
  77326. var flatCoordinates =
  77327. this.readFlatCoordinatesFromNode_(node, objectStack);
  77328. if (flatCoordinates) {
  77329. var ring = new ol.geom.LinearRing(null);
  77330. ring.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  77331. return ring;
  77332. } else {
  77333. return undefined;
  77334. }
  77335. };
  77336. /**
  77337. * @param {Node} node Node.
  77338. * @param {Array.<*>} objectStack Object stack.
  77339. * @return {ol.geom.Polygon|undefined} Polygon.
  77340. */
  77341. ol.format.GMLBase.prototype.readPolygon = function(node, objectStack) {
  77342. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77343. 'node.nodeType should be ELEMENT');
  77344. goog.asserts.assert(node.localName == 'Polygon',
  77345. 'localName should be Polygon');
  77346. var flatLinearRings = ol.xml.pushParseAndPop(
  77347. /** @type {Array.<Array.<number>>} */ ([null]),
  77348. this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this);
  77349. if (flatLinearRings && flatLinearRings[0]) {
  77350. var polygon = new ol.geom.Polygon(null);
  77351. var flatCoordinates = flatLinearRings[0];
  77352. var ends = [flatCoordinates.length];
  77353. var i, ii;
  77354. for (i = 1, ii = flatLinearRings.length; i < ii; ++i) {
  77355. goog.array.extend(flatCoordinates, flatLinearRings[i]);
  77356. ends.push(flatCoordinates.length);
  77357. }
  77358. polygon.setFlatCoordinates(
  77359. ol.geom.GeometryLayout.XYZ, flatCoordinates, ends);
  77360. return polygon;
  77361. } else {
  77362. return undefined;
  77363. }
  77364. };
  77365. /**
  77366. * @param {Node} node Node.
  77367. * @param {Array.<*>} objectStack Object stack.
  77368. * @private
  77369. * @return {Array.<number>} Flat coordinates.
  77370. */
  77371. ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_ =
  77372. function(node, objectStack) {
  77373. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77374. 'node.nodeType should be ELEMENT');
  77375. return /** @type {Array.<number>} */ (ol.xml.pushParseAndPop(
  77376. null,
  77377. this.GEOMETRY_FLAT_COORDINATES_PARSERS_, node,
  77378. objectStack, this));
  77379. };
  77380. /**
  77381. * @const
  77382. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77383. * @private
  77384. */
  77385. ol.format.GMLBase.prototype.MULTIPOINT_PARSERS_ = Object({
  77386. 'http://www.opengis.net/gml' : {
  77387. 'pointMember': ol.xml.makeArrayPusher(
  77388. ol.format.GMLBase.prototype.pointMemberParser_),
  77389. 'pointMembers': ol.xml.makeArrayPusher(
  77390. ol.format.GMLBase.prototype.pointMemberParser_)
  77391. }
  77392. });
  77393. /**
  77394. * @const
  77395. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77396. * @private
  77397. */
  77398. ol.format.GMLBase.prototype.MULTILINESTRING_PARSERS_ = Object({
  77399. 'http://www.opengis.net/gml' : {
  77400. 'lineStringMember': ol.xml.makeArrayPusher(
  77401. ol.format.GMLBase.prototype.lineStringMemberParser_),
  77402. 'lineStringMembers': ol.xml.makeArrayPusher(
  77403. ol.format.GMLBase.prototype.lineStringMemberParser_)
  77404. }
  77405. });
  77406. /**
  77407. * @const
  77408. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77409. * @private
  77410. */
  77411. ol.format.GMLBase.prototype.MULTIPOLYGON_PARSERS_ = Object({
  77412. 'http://www.opengis.net/gml' : {
  77413. 'polygonMember': ol.xml.makeArrayPusher(
  77414. ol.format.GMLBase.prototype.polygonMemberParser_),
  77415. 'polygonMembers': ol.xml.makeArrayPusher(
  77416. ol.format.GMLBase.prototype.polygonMemberParser_)
  77417. }
  77418. });
  77419. /**
  77420. * @const
  77421. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77422. * @private
  77423. */
  77424. ol.format.GMLBase.prototype.POINTMEMBER_PARSERS_ = Object({
  77425. 'http://www.opengis.net/gml' : {
  77426. 'Point': ol.xml.makeArrayPusher(
  77427. ol.format.GMLBase.prototype.readFlatCoordinatesFromNode_)
  77428. }
  77429. });
  77430. /**
  77431. * @const
  77432. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77433. * @private
  77434. */
  77435. ol.format.GMLBase.prototype.LINESTRINGMEMBER_PARSERS_ = Object({
  77436. 'http://www.opengis.net/gml' : {
  77437. 'LineString': ol.xml.makeArrayPusher(
  77438. ol.format.GMLBase.prototype.readLineString)
  77439. }
  77440. });
  77441. /**
  77442. * @const
  77443. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77444. * @private
  77445. */
  77446. ol.format.GMLBase.prototype.POLYGONMEMBER_PARSERS_ = Object({
  77447. 'http://www.opengis.net/gml' : {
  77448. 'Polygon': ol.xml.makeArrayPusher(
  77449. ol.format.GMLBase.prototype.readPolygon)
  77450. }
  77451. });
  77452. /**
  77453. * @const
  77454. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77455. * @protected
  77456. */
  77457. ol.format.GMLBase.prototype.RING_PARSERS = Object({
  77458. 'http://www.opengis.net/gml' : {
  77459. 'LinearRing': ol.xml.makeReplacer(
  77460. ol.format.GMLBase.prototype.readFlatLinearRing_)
  77461. }
  77462. });
  77463. /**
  77464. * @inheritDoc
  77465. */
  77466. ol.format.GMLBase.prototype.readGeometryFromNode =
  77467. function(node, opt_options) {
  77468. var geometry = this.readGeometryElement(node,
  77469. [this.getReadOptions(node, opt_options ? opt_options : {})]);
  77470. return geometry ? geometry : null;
  77471. };
  77472. /**
  77473. * Read all features from a GML FeatureCollection.
  77474. *
  77475. * @function
  77476. * @param {Document|Node|Object|string} source Source.
  77477. * @param {olx.format.ReadOptions=} opt_options Options.
  77478. * @return {Array.<ol.Feature>} Features.
  77479. * @api stable
  77480. */
  77481. ol.format.GMLBase.prototype.readFeatures;
  77482. /**
  77483. * @inheritDoc
  77484. */
  77485. ol.format.GMLBase.prototype.readFeaturesFromNode =
  77486. function(node, opt_options) {
  77487. var options = {
  77488. featureType: this.featureType,
  77489. featureNS: this.featureNS
  77490. };
  77491. if (opt_options) {
  77492. goog.object.extend(options, this.getReadOptions(node, opt_options));
  77493. }
  77494. return this.readFeaturesInternal(node, [options]);
  77495. };
  77496. /**
  77497. * @inheritDoc
  77498. */
  77499. ol.format.GMLBase.prototype.readProjectionFromNode = function(node) {
  77500. return ol.proj.get(this.srsName_ ? this.srsName_ :
  77501. node.firstElementChild.getAttribute('srsName'));
  77502. };
  77503. goog.provide('ol.format.XSD');
  77504. goog.require('goog.asserts');
  77505. goog.require('goog.string');
  77506. goog.require('ol');
  77507. goog.require('ol.xml');
  77508. /**
  77509. * @const
  77510. * @type {string}
  77511. */
  77512. ol.format.XSD.NAMESPACE_URI = 'http://www.w3.org/2001/XMLSchema';
  77513. /**
  77514. * @param {Node} node Node.
  77515. * @return {boolean|undefined} Boolean.
  77516. */
  77517. ol.format.XSD.readBoolean = function(node) {
  77518. var s = ol.xml.getAllTextContent(node, false);
  77519. return ol.format.XSD.readBooleanString(s);
  77520. };
  77521. /**
  77522. * @param {string} string String.
  77523. * @return {boolean|undefined} Boolean.
  77524. */
  77525. ol.format.XSD.readBooleanString = function(string) {
  77526. var m = /^\s*(true|1)|(false|0)\s*$/.exec(string);
  77527. if (m) {
  77528. return m[1] !== undefined || false;
  77529. } else {
  77530. return undefined;
  77531. }
  77532. };
  77533. /**
  77534. * @param {Node} node Node.
  77535. * @return {number|undefined} DateTime in seconds.
  77536. */
  77537. ol.format.XSD.readDateTime = function(node) {
  77538. var s = ol.xml.getAllTextContent(node, false);
  77539. var re =
  77540. /^\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(?:([+\-])(\d{2})(?::(\d{2}))?))\s*$/;
  77541. var m = re.exec(s);
  77542. if (m) {
  77543. var year = parseInt(m[1], 10);
  77544. var month = parseInt(m[2], 10) - 1;
  77545. var day = parseInt(m[3], 10);
  77546. var hour = parseInt(m[4], 10);
  77547. var minute = parseInt(m[5], 10);
  77548. var second = parseInt(m[6], 10);
  77549. var dateTime = Date.UTC(year, month, day, hour, minute, second) / 1000;
  77550. if (m[7] != 'Z') {
  77551. var sign = m[8] == '-' ? -1 : 1;
  77552. dateTime += sign * 60 * parseInt(m[9], 10);
  77553. if (m[10] !== undefined) {
  77554. dateTime += sign * 60 * 60 * parseInt(m[10], 10);
  77555. }
  77556. }
  77557. return dateTime;
  77558. } else {
  77559. return undefined;
  77560. }
  77561. };
  77562. /**
  77563. * @param {Node} node Node.
  77564. * @return {number|undefined} Decimal.
  77565. */
  77566. ol.format.XSD.readDecimal = function(node) {
  77567. var s = ol.xml.getAllTextContent(node, false);
  77568. return ol.format.XSD.readDecimalString(s);
  77569. };
  77570. /**
  77571. * @param {string} string String.
  77572. * @return {number|undefined} Decimal.
  77573. */
  77574. ol.format.XSD.readDecimalString = function(string) {
  77575. // FIXME check spec
  77576. var m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string);
  77577. if (m) {
  77578. return parseFloat(m[1]);
  77579. } else {
  77580. return undefined;
  77581. }
  77582. };
  77583. /**
  77584. * @param {Node} node Node.
  77585. * @return {number|undefined} Non negative integer.
  77586. */
  77587. ol.format.XSD.readNonNegativeInteger = function(node) {
  77588. var s = ol.xml.getAllTextContent(node, false);
  77589. return ol.format.XSD.readNonNegativeIntegerString(s);
  77590. };
  77591. /**
  77592. * @param {string} string String.
  77593. * @return {number|undefined} Non negative integer.
  77594. */
  77595. ol.format.XSD.readNonNegativeIntegerString = function(string) {
  77596. var m = /^\s*(\d+)\s*$/.exec(string);
  77597. if (m) {
  77598. return parseInt(m[1], 10);
  77599. } else {
  77600. return undefined;
  77601. }
  77602. };
  77603. /**
  77604. * @param {Node} node Node.
  77605. * @return {string|undefined} String.
  77606. */
  77607. ol.format.XSD.readString = function(node) {
  77608. return ol.xml.getAllTextContent(node, false).trim();
  77609. };
  77610. /**
  77611. * @param {Node} node Node to append a TextNode with the boolean to.
  77612. * @param {boolean} bool Boolean.
  77613. */
  77614. ol.format.XSD.writeBooleanTextNode = function(node, bool) {
  77615. ol.format.XSD.writeStringTextNode(node, (bool) ? '1' : '0');
  77616. };
  77617. /**
  77618. * @param {Node} node Node to append a TextNode with the dateTime to.
  77619. * @param {number} dateTime DateTime in seconds.
  77620. */
  77621. ol.format.XSD.writeDateTimeTextNode = function(node, dateTime) {
  77622. var date = new Date(dateTime * 1000);
  77623. var string = date.getUTCFullYear() + '-' +
  77624. goog.string.padNumber(date.getUTCMonth() + 1, 2) + '-' +
  77625. goog.string.padNumber(date.getUTCDate(), 2) + 'T' +
  77626. goog.string.padNumber(date.getUTCHours(), 2) + ':' +
  77627. goog.string.padNumber(date.getUTCMinutes(), 2) + ':' +
  77628. goog.string.padNumber(date.getUTCSeconds(), 2) + 'Z';
  77629. node.appendChild(ol.xml.DOCUMENT.createTextNode(string));
  77630. };
  77631. /**
  77632. * @param {Node} node Node to append a TextNode with the decimal to.
  77633. * @param {number} decimal Decimal.
  77634. */
  77635. ol.format.XSD.writeDecimalTextNode = function(node, decimal) {
  77636. var string = decimal.toPrecision();
  77637. node.appendChild(ol.xml.DOCUMENT.createTextNode(string));
  77638. };
  77639. /**
  77640. * @param {Node} node Node to append a TextNode with the decimal to.
  77641. * @param {number} nonNegativeInteger Non negative integer.
  77642. */
  77643. ol.format.XSD.writeNonNegativeIntegerTextNode =
  77644. function(node, nonNegativeInteger) {
  77645. goog.asserts.assert(nonNegativeInteger >= 0, 'value should be more than 0');
  77646. goog.asserts.assert(nonNegativeInteger == (nonNegativeInteger | 0),
  77647. 'value should be an integer value');
  77648. var string = nonNegativeInteger.toString();
  77649. node.appendChild(ol.xml.DOCUMENT.createTextNode(string));
  77650. };
  77651. /**
  77652. * @param {Node} node Node to append a TextNode with the string to.
  77653. * @param {string} string String.
  77654. */
  77655. ol.format.XSD.writeStringTextNode = function(node, string) {
  77656. node.appendChild(ol.xml.DOCUMENT.createTextNode(string));
  77657. };
  77658. goog.provide('ol.format.GML2');
  77659. goog.require('goog.asserts');
  77660. goog.require('goog.dom.NodeType');
  77661. goog.require('ol.extent');
  77662. goog.require('ol.format.GMLBase');
  77663. goog.require('ol.format.XSD');
  77664. goog.require('ol.proj');
  77665. goog.require('ol.xml');
  77666. /**
  77667. * @classdesc
  77668. * Feature format for reading and writing data in the GML format,
  77669. * version 2.1.2.
  77670. *
  77671. * @constructor
  77672. * @param {olx.format.GMLOptions=} opt_options Optional configuration object.
  77673. * @extends {ol.format.GMLBase}
  77674. * @api
  77675. */
  77676. ol.format.GML2 = function(opt_options) {
  77677. var options = /** @type {olx.format.GMLOptions} */
  77678. (opt_options ? opt_options : {});
  77679. goog.base(this, options);
  77680. this.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS][
  77681. 'featureMember'] =
  77682. ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readFeaturesInternal);
  77683. /**
  77684. * @inheritDoc
  77685. */
  77686. this.schemaLocation = options.schemaLocation ?
  77687. options.schemaLocation : ol.format.GML2.schemaLocation_;
  77688. };
  77689. goog.inherits(ol.format.GML2, ol.format.GMLBase);
  77690. /**
  77691. * @const
  77692. * @type {string}
  77693. * @private
  77694. */
  77695. ol.format.GML2.schemaLocation_ = ol.format.GMLBase.GMLNS +
  77696. ' http://schemas.opengis.net/gml/2.1.2/feature.xsd';
  77697. /**
  77698. * @param {Node} node Node.
  77699. * @param {Array.<*>} objectStack Object stack.
  77700. * @private
  77701. * @return {Array.<number>|undefined} Flat coordinates.
  77702. */
  77703. ol.format.GML2.prototype.readFlatCoordinates_ = function(node, objectStack) {
  77704. var s = ol.xml.getAllTextContent(node, false).replace(/^\s*|\s*$/g, '');
  77705. var context = objectStack[0];
  77706. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  77707. var containerSrs = context['srsName'];
  77708. var containerDimension = node.parentNode.getAttribute('srsDimension');
  77709. var axisOrientation = 'enu';
  77710. if (containerSrs) {
  77711. var proj = ol.proj.get(containerSrs);
  77712. axisOrientation = proj.getAxisOrientation();
  77713. }
  77714. var coords = s.split(/[\s,]+/);
  77715. // The "dimension" attribute is from the GML 3.0.1 spec.
  77716. var dim = 2;
  77717. if (node.getAttribute('srsDimension')) {
  77718. dim = ol.format.XSD.readNonNegativeIntegerString(
  77719. node.getAttribute('srsDimension'));
  77720. } else if (node.getAttribute('dimension')) {
  77721. dim = ol.format.XSD.readNonNegativeIntegerString(
  77722. node.getAttribute('dimension'));
  77723. } else if (containerDimension) {
  77724. dim = ol.format.XSD.readNonNegativeIntegerString(containerDimension);
  77725. }
  77726. var x, y, z;
  77727. var flatCoordinates = [];
  77728. for (var i = 0, ii = coords.length; i < ii; i += dim) {
  77729. x = parseFloat(coords[i]);
  77730. y = parseFloat(coords[i + 1]);
  77731. z = (dim === 3) ? parseFloat(coords[i + 2]) : 0;
  77732. if (axisOrientation.substr(0, 2) === 'en') {
  77733. flatCoordinates.push(x, y, z);
  77734. } else {
  77735. flatCoordinates.push(y, x, z);
  77736. }
  77737. }
  77738. return flatCoordinates;
  77739. };
  77740. /**
  77741. * @param {Node} node Node.
  77742. * @param {Array.<*>} objectStack Object stack.
  77743. * @private
  77744. * @return {ol.Extent|undefined} Envelope.
  77745. */
  77746. ol.format.GML2.prototype.readBox_ = function(node, objectStack) {
  77747. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77748. 'node.nodeType should be ELEMENT');
  77749. goog.asserts.assert(node.localName == 'Box', 'localName should be Box');
  77750. var flatCoordinates = ol.xml.pushParseAndPop(
  77751. /** @type {Array.<number>} */ ([null]),
  77752. this.BOX_PARSERS_, node, objectStack, this);
  77753. return ol.extent.createOrUpdate(flatCoordinates[1][0],
  77754. flatCoordinates[1][1], flatCoordinates[1][3],
  77755. flatCoordinates[1][4]);
  77756. };
  77757. /**
  77758. * @param {Node} node Node.
  77759. * @param {Array.<*>} objectStack Object stack.
  77760. * @private
  77761. */
  77762. ol.format.GML2.prototype.innerBoundaryIsParser_ =
  77763. function(node, objectStack) {
  77764. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77765. 'node.nodeType should be ELEMENT');
  77766. goog.asserts.assert(node.localName == 'innerBoundaryIs',
  77767. 'localName should be innerBoundaryIs');
  77768. var flatLinearRing = ol.xml.pushParseAndPop(
  77769. /** @type {Array.<number>|undefined} */ (undefined),
  77770. this.RING_PARSERS, node, objectStack, this);
  77771. if (flatLinearRing) {
  77772. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  77773. (objectStack[objectStack.length - 1]);
  77774. goog.asserts.assert(goog.isArray(flatLinearRings),
  77775. 'flatLinearRings should be an array');
  77776. goog.asserts.assert(flatLinearRings.length > 0,
  77777. 'flatLinearRings should have an array length larger than 0');
  77778. flatLinearRings.push(flatLinearRing);
  77779. }
  77780. };
  77781. /**
  77782. * @param {Node} node Node.
  77783. * @param {Array.<*>} objectStack Object stack.
  77784. * @private
  77785. */
  77786. ol.format.GML2.prototype.outerBoundaryIsParser_ =
  77787. function(node, objectStack) {
  77788. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77789. 'node.nodeType should be ELEMENT');
  77790. goog.asserts.assert(node.localName == 'outerBoundaryIs',
  77791. 'localName should be outerBoundaryIs');
  77792. var flatLinearRing = ol.xml.pushParseAndPop(
  77793. /** @type {Array.<number>|undefined} */ (undefined),
  77794. this.RING_PARSERS, node, objectStack, this);
  77795. if (flatLinearRing) {
  77796. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  77797. (objectStack[objectStack.length - 1]);
  77798. goog.asserts.assert(goog.isArray(flatLinearRings),
  77799. 'flatLinearRings should be an array');
  77800. goog.asserts.assert(flatLinearRings.length > 0,
  77801. 'flatLinearRings should have an array length larger than 0');
  77802. flatLinearRings[0] = flatLinearRing;
  77803. }
  77804. };
  77805. /**
  77806. * @const
  77807. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77808. * @private
  77809. */
  77810. ol.format.GML2.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_ = Object({
  77811. 'http://www.opengis.net/gml' : {
  77812. 'coordinates': ol.xml.makeReplacer(
  77813. ol.format.GML2.prototype.readFlatCoordinates_)
  77814. }
  77815. });
  77816. /**
  77817. * @const
  77818. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77819. * @private
  77820. */
  77821. ol.format.GML2.prototype.FLAT_LINEAR_RINGS_PARSERS_ = Object({
  77822. 'http://www.opengis.net/gml' : {
  77823. 'innerBoundaryIs': ol.format.GML2.prototype.innerBoundaryIsParser_,
  77824. 'outerBoundaryIs': ol.format.GML2.prototype.outerBoundaryIsParser_
  77825. }
  77826. });
  77827. /**
  77828. * @const
  77829. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77830. * @private
  77831. */
  77832. ol.format.GML2.prototype.BOX_PARSERS_ = Object({
  77833. 'http://www.opengis.net/gml' : {
  77834. 'coordinates': ol.xml.makeArrayPusher(
  77835. ol.format.GML2.prototype.readFlatCoordinates_)
  77836. }
  77837. });
  77838. /**
  77839. * @const
  77840. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  77841. * @private
  77842. */
  77843. ol.format.GML2.prototype.GEOMETRY_PARSERS_ = Object({
  77844. 'http://www.opengis.net/gml' : {
  77845. 'Point': ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPoint),
  77846. 'MultiPoint': ol.xml.makeReplacer(
  77847. ol.format.GMLBase.prototype.readMultiPoint),
  77848. 'LineString': ol.xml.makeReplacer(
  77849. ol.format.GMLBase.prototype.readLineString),
  77850. 'MultiLineString': ol.xml.makeReplacer(
  77851. ol.format.GMLBase.prototype.readMultiLineString),
  77852. 'LinearRing' : ol.xml.makeReplacer(
  77853. ol.format.GMLBase.prototype.readLinearRing),
  77854. 'Polygon': ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPolygon),
  77855. 'MultiPolygon': ol.xml.makeReplacer(
  77856. ol.format.GMLBase.prototype.readMultiPolygon),
  77857. 'Box': ol.xml.makeReplacer(ol.format.GML2.prototype.readBox_)
  77858. }
  77859. });
  77860. goog.provide('ol.format.GML');
  77861. goog.provide('ol.format.GML3');
  77862. goog.require('goog.array');
  77863. goog.require('goog.asserts');
  77864. goog.require('goog.dom.NodeType');
  77865. goog.require('goog.object');
  77866. goog.require('ol');
  77867. goog.require('ol.Feature');
  77868. goog.require('ol.extent');
  77869. goog.require('ol.format.Feature');
  77870. goog.require('ol.format.GMLBase');
  77871. goog.require('ol.format.XSD');
  77872. goog.require('ol.geom.Geometry');
  77873. goog.require('ol.geom.GeometryLayout');
  77874. goog.require('ol.geom.LineString');
  77875. goog.require('ol.geom.LinearRing');
  77876. goog.require('ol.geom.MultiLineString');
  77877. goog.require('ol.geom.MultiPolygon');
  77878. goog.require('ol.geom.Point');
  77879. goog.require('ol.geom.Polygon');
  77880. goog.require('ol.proj');
  77881. goog.require('ol.xml');
  77882. /**
  77883. * @classdesc
  77884. * Feature format for reading and writing data in the GML format
  77885. * version 3.1.1.
  77886. * Currently only supports GML 3.1.1 Simple Features profile.
  77887. *
  77888. * @constructor
  77889. * @param {olx.format.GMLOptions=} opt_options
  77890. * Optional configuration object.
  77891. * @extends {ol.format.GMLBase}
  77892. * @api
  77893. */
  77894. ol.format.GML3 = function(opt_options) {
  77895. var options = /** @type {olx.format.GMLOptions} */
  77896. (opt_options ? opt_options : {});
  77897. goog.base(this, options);
  77898. /**
  77899. * @private
  77900. * @type {boolean}
  77901. */
  77902. this.surface_ = options.surface !== undefined ? options.surface : false;
  77903. /**
  77904. * @private
  77905. * @type {boolean}
  77906. */
  77907. this.curve_ = options.curve !== undefined ? options.curve : false;
  77908. /**
  77909. * @private
  77910. * @type {boolean}
  77911. */
  77912. this.multiCurve_ = options.multiCurve !== undefined ?
  77913. options.multiCurve : true;
  77914. /**
  77915. * @private
  77916. * @type {boolean}
  77917. */
  77918. this.multiSurface_ = options.multiSurface !== undefined ?
  77919. options.multiSurface : true;
  77920. /**
  77921. * @inheritDoc
  77922. */
  77923. this.schemaLocation = options.schemaLocation ?
  77924. options.schemaLocation : ol.format.GML3.schemaLocation_;
  77925. };
  77926. goog.inherits(ol.format.GML3, ol.format.GMLBase);
  77927. /**
  77928. * @const
  77929. * @type {string}
  77930. * @private
  77931. */
  77932. ol.format.GML3.schemaLocation_ = ol.format.GMLBase.GMLNS +
  77933. ' http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/' +
  77934. '1.0.0/gmlsf.xsd';
  77935. /**
  77936. * @param {Node} node Node.
  77937. * @param {Array.<*>} objectStack Object stack.
  77938. * @private
  77939. * @return {ol.geom.MultiLineString|undefined} MultiLineString.
  77940. */
  77941. ol.format.GML3.prototype.readMultiCurve_ = function(node, objectStack) {
  77942. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77943. 'node.nodeType should be ELEMENT');
  77944. goog.asserts.assert(node.localName == 'MultiCurve',
  77945. 'localName should be MultiCurve');
  77946. var lineStrings = ol.xml.pushParseAndPop(
  77947. /** @type {Array.<ol.geom.LineString>} */ ([]),
  77948. this.MULTICURVE_PARSERS_, node, objectStack, this);
  77949. if (lineStrings) {
  77950. var multiLineString = new ol.geom.MultiLineString(null);
  77951. multiLineString.setLineStrings(lineStrings);
  77952. return multiLineString;
  77953. } else {
  77954. return undefined;
  77955. }
  77956. };
  77957. /**
  77958. * @param {Node} node Node.
  77959. * @param {Array.<*>} objectStack Object stack.
  77960. * @private
  77961. * @return {ol.geom.MultiPolygon|undefined} MultiPolygon.
  77962. */
  77963. ol.format.GML3.prototype.readMultiSurface_ = function(node, objectStack) {
  77964. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77965. 'node.nodeType should be ELEMENT');
  77966. goog.asserts.assert(node.localName == 'MultiSurface',
  77967. 'localName should be MultiSurface');
  77968. var polygons = ol.xml.pushParseAndPop(
  77969. /** @type {Array.<ol.geom.Polygon>} */ ([]),
  77970. this.MULTISURFACE_PARSERS_, node, objectStack, this);
  77971. if (polygons) {
  77972. var multiPolygon = new ol.geom.MultiPolygon(null);
  77973. multiPolygon.setPolygons(polygons);
  77974. return multiPolygon;
  77975. } else {
  77976. return undefined;
  77977. }
  77978. };
  77979. /**
  77980. * @param {Node} node Node.
  77981. * @param {Array.<*>} objectStack Object stack.
  77982. * @private
  77983. */
  77984. ol.format.GML3.prototype.curveMemberParser_ = function(node, objectStack) {
  77985. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77986. 'node.nodeType should be ELEMENT');
  77987. goog.asserts.assert(node.localName == 'curveMember' ||
  77988. node.localName == 'curveMembers',
  77989. 'localName should be curveMember or curveMembers');
  77990. ol.xml.parseNode(this.CURVEMEMBER_PARSERS_, node, objectStack, this);
  77991. };
  77992. /**
  77993. * @param {Node} node Node.
  77994. * @param {Array.<*>} objectStack Object stack.
  77995. * @private
  77996. */
  77997. ol.format.GML3.prototype.surfaceMemberParser_ = function(node, objectStack) {
  77998. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  77999. 'node.nodeType should be ELEMENT');
  78000. goog.asserts.assert(node.localName == 'surfaceMember' ||
  78001. node.localName == 'surfaceMembers',
  78002. 'localName should be surfaceMember or surfaceMembers');
  78003. ol.xml.parseNode(this.SURFACEMEMBER_PARSERS_,
  78004. node, objectStack, this);
  78005. };
  78006. /**
  78007. * @param {Node} node Node.
  78008. * @param {Array.<*>} objectStack Object stack.
  78009. * @private
  78010. * @return {Array.<(Array.<number>)>|undefined} flat coordinates.
  78011. */
  78012. ol.format.GML3.prototype.readPatch_ = function(node, objectStack) {
  78013. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78014. 'node.nodeType should be ELEMENT');
  78015. goog.asserts.assert(node.localName == 'patches',
  78016. 'localName should be patches');
  78017. return ol.xml.pushParseAndPop(
  78018. /** @type {Array.<Array.<number>>} */ ([null]),
  78019. this.PATCHES_PARSERS_, node, objectStack, this);
  78020. };
  78021. /**
  78022. * @param {Node} node Node.
  78023. * @param {Array.<*>} objectStack Object stack.
  78024. * @private
  78025. * @return {Array.<number>|undefined} flat coordinates.
  78026. */
  78027. ol.format.GML3.prototype.readSegment_ = function(node, objectStack) {
  78028. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78029. 'node.nodeType should be ELEMENT');
  78030. goog.asserts.assert(node.localName == 'segments',
  78031. 'localName should be segments');
  78032. return ol.xml.pushParseAndPop(
  78033. /** @type {Array.<number>} */ ([null]),
  78034. this.SEGMENTS_PARSERS_, node, objectStack, this);
  78035. };
  78036. /**
  78037. * @param {Node} node Node.
  78038. * @param {Array.<*>} objectStack Object stack.
  78039. * @private
  78040. * @return {Array.<(Array.<number>)>|undefined} flat coordinates.
  78041. */
  78042. ol.format.GML3.prototype.readPolygonPatch_ = function(node, objectStack) {
  78043. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78044. 'npde.nodeType should be ELEMENT');
  78045. goog.asserts.assert(node.localName == 'PolygonPatch',
  78046. 'localName should be PolygonPatch');
  78047. return ol.xml.pushParseAndPop(
  78048. /** @type {Array.<Array.<number>>} */ ([null]),
  78049. this.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack, this);
  78050. };
  78051. /**
  78052. * @param {Node} node Node.
  78053. * @param {Array.<*>} objectStack Object stack.
  78054. * @private
  78055. * @return {Array.<number>|undefined} flat coordinates.
  78056. */
  78057. ol.format.GML3.prototype.readLineStringSegment_ =
  78058. function(node, objectStack) {
  78059. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78060. 'node.nodeType should be ELEMENT');
  78061. goog.asserts.assert(node.localName == 'LineStringSegment',
  78062. 'localName should be LineStringSegment');
  78063. return ol.xml.pushParseAndPop(
  78064. /** @type {Array.<number>} */ ([null]),
  78065. this.GEOMETRY_FLAT_COORDINATES_PARSERS_,
  78066. node, objectStack, this);
  78067. };
  78068. /**
  78069. * @param {Node} node Node.
  78070. * @param {Array.<*>} objectStack Object stack.
  78071. * @private
  78072. */
  78073. ol.format.GML3.prototype.interiorParser_ = function(node, objectStack) {
  78074. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78075. 'node.nodeType should be ELEMENT');
  78076. goog.asserts.assert(node.localName == 'interior',
  78077. 'localName should be interior');
  78078. var flatLinearRing = ol.xml.pushParseAndPop(
  78079. /** @type {Array.<number>|undefined} */ (undefined),
  78080. this.RING_PARSERS, node, objectStack, this);
  78081. if (flatLinearRing) {
  78082. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  78083. (objectStack[objectStack.length - 1]);
  78084. goog.asserts.assert(goog.isArray(flatLinearRings),
  78085. 'flatLinearRings should be an array');
  78086. goog.asserts.assert(flatLinearRings.length > 0,
  78087. 'flatLinearRings should have an array length of 1 or more');
  78088. flatLinearRings.push(flatLinearRing);
  78089. }
  78090. };
  78091. /**
  78092. * @param {Node} node Node.
  78093. * @param {Array.<*>} objectStack Object stack.
  78094. * @private
  78095. */
  78096. ol.format.GML3.prototype.exteriorParser_ = function(node, objectStack) {
  78097. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78098. 'node.nodeType should be ELEMENT');
  78099. goog.asserts.assert(node.localName == 'exterior',
  78100. 'localName should be exterior');
  78101. var flatLinearRing = ol.xml.pushParseAndPop(
  78102. /** @type {Array.<number>|undefined} */ (undefined),
  78103. this.RING_PARSERS, node, objectStack, this);
  78104. if (flatLinearRing) {
  78105. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  78106. (objectStack[objectStack.length - 1]);
  78107. goog.asserts.assert(goog.isArray(flatLinearRings),
  78108. 'flatLinearRings should be an array');
  78109. goog.asserts.assert(flatLinearRings.length > 0,
  78110. 'flatLinearRings should have an array length of 1 or more');
  78111. flatLinearRings[0] = flatLinearRing;
  78112. }
  78113. };
  78114. /**
  78115. * @param {Node} node Node.
  78116. * @param {Array.<*>} objectStack Object stack.
  78117. * @private
  78118. * @return {ol.geom.Polygon|undefined} Polygon.
  78119. */
  78120. ol.format.GML3.prototype.readSurface_ = function(node, objectStack) {
  78121. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78122. 'node.nodeType should be ELEMENT');
  78123. goog.asserts.assert(node.localName == 'Surface',
  78124. 'localName should be Surface');
  78125. var flatLinearRings = ol.xml.pushParseAndPop(
  78126. /** @type {Array.<Array.<number>>} */ ([null]),
  78127. this.SURFACE_PARSERS_, node, objectStack, this);
  78128. if (flatLinearRings && flatLinearRings[0]) {
  78129. var polygon = new ol.geom.Polygon(null);
  78130. var flatCoordinates = flatLinearRings[0];
  78131. var ends = [flatCoordinates.length];
  78132. var i, ii;
  78133. for (i = 1, ii = flatLinearRings.length; i < ii; ++i) {
  78134. goog.array.extend(flatCoordinates, flatLinearRings[i]);
  78135. ends.push(flatCoordinates.length);
  78136. }
  78137. polygon.setFlatCoordinates(
  78138. ol.geom.GeometryLayout.XYZ, flatCoordinates, ends);
  78139. return polygon;
  78140. } else {
  78141. return undefined;
  78142. }
  78143. };
  78144. /**
  78145. * @param {Node} node Node.
  78146. * @param {Array.<*>} objectStack Object stack.
  78147. * @private
  78148. * @return {ol.geom.LineString|undefined} LineString.
  78149. */
  78150. ol.format.GML3.prototype.readCurve_ = function(node, objectStack) {
  78151. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78152. 'node.nodeType should be ELEMENT');
  78153. goog.asserts.assert(node.localName == 'Curve', 'localName should be Curve');
  78154. var flatCoordinates = ol.xml.pushParseAndPop(
  78155. /** @type {Array.<number>} */ ([null]),
  78156. this.CURVE_PARSERS_, node, objectStack, this);
  78157. if (flatCoordinates) {
  78158. var lineString = new ol.geom.LineString(null);
  78159. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  78160. return lineString;
  78161. } else {
  78162. return undefined;
  78163. }
  78164. };
  78165. /**
  78166. * @param {Node} node Node.
  78167. * @param {Array.<*>} objectStack Object stack.
  78168. * @private
  78169. * @return {ol.Extent|undefined} Envelope.
  78170. */
  78171. ol.format.GML3.prototype.readEnvelope_ = function(node, objectStack) {
  78172. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  78173. 'node.nodeType should be ELEMENT');
  78174. goog.asserts.assert(node.localName == 'Envelope',
  78175. 'localName should be Envelope');
  78176. var flatCoordinates = ol.xml.pushParseAndPop(
  78177. /** @type {Array.<number>} */ ([null]),
  78178. this.ENVELOPE_PARSERS_, node, objectStack, this);
  78179. return ol.extent.createOrUpdate(flatCoordinates[1][0],
  78180. flatCoordinates[1][1], flatCoordinates[2][0],
  78181. flatCoordinates[2][1]);
  78182. };
  78183. /**
  78184. * @param {Node} node Node.
  78185. * @param {Array.<*>} objectStack Object stack.
  78186. * @private
  78187. * @return {Array.<number>|undefined} Flat coordinates.
  78188. */
  78189. ol.format.GML3.prototype.readFlatPos_ = function(node, objectStack) {
  78190. var s = ol.xml.getAllTextContent(node, false);
  78191. var re = /^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/;
  78192. /** @type {Array.<number>} */
  78193. var flatCoordinates = [];
  78194. var m;
  78195. while ((m = re.exec(s))) {
  78196. flatCoordinates.push(parseFloat(m[1]));
  78197. s = s.substr(m[0].length);
  78198. }
  78199. if (s !== '') {
  78200. return undefined;
  78201. }
  78202. var context = objectStack[0];
  78203. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78204. var containerSrs = context['srsName'];
  78205. var axisOrientation = 'enu';
  78206. if (containerSrs) {
  78207. var proj = ol.proj.get(containerSrs);
  78208. axisOrientation = proj.getAxisOrientation();
  78209. }
  78210. if (axisOrientation === 'neu') {
  78211. var i, ii;
  78212. for (i = 0, ii = flatCoordinates.length; i < ii; i += 3) {
  78213. var y = flatCoordinates[i];
  78214. var x = flatCoordinates[i + 1];
  78215. flatCoordinates[i] = x;
  78216. flatCoordinates[i + 1] = y;
  78217. }
  78218. }
  78219. var len = flatCoordinates.length;
  78220. if (len == 2) {
  78221. flatCoordinates.push(0);
  78222. }
  78223. if (len === 0) {
  78224. return undefined;
  78225. }
  78226. return flatCoordinates;
  78227. };
  78228. /**
  78229. * @param {Node} node Node.
  78230. * @param {Array.<*>} objectStack Object stack.
  78231. * @private
  78232. * @return {Array.<number>|undefined} Flat coordinates.
  78233. */
  78234. ol.format.GML3.prototype.readFlatPosList_ = function(node, objectStack) {
  78235. var s = ol.xml.getAllTextContent(node, false).replace(/^\s*|\s*$/g, '');
  78236. var context = objectStack[0];
  78237. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78238. var containerSrs = context['srsName'];
  78239. var containerDimension = node.parentNode.getAttribute('srsDimension');
  78240. var axisOrientation = 'enu';
  78241. if (containerSrs) {
  78242. var proj = ol.proj.get(containerSrs);
  78243. axisOrientation = proj.getAxisOrientation();
  78244. }
  78245. var coords = s.split(/\s+/);
  78246. // The "dimension" attribute is from the GML 3.0.1 spec.
  78247. var dim = 2;
  78248. if (node.getAttribute('srsDimension')) {
  78249. dim = ol.format.XSD.readNonNegativeIntegerString(
  78250. node.getAttribute('srsDimension'));
  78251. } else if (node.getAttribute('dimension')) {
  78252. dim = ol.format.XSD.readNonNegativeIntegerString(
  78253. node.getAttribute('dimension'));
  78254. } else if (containerDimension) {
  78255. dim = ol.format.XSD.readNonNegativeIntegerString(containerDimension);
  78256. }
  78257. var x, y, z;
  78258. var flatCoordinates = [];
  78259. for (var i = 0, ii = coords.length; i < ii; i += dim) {
  78260. x = parseFloat(coords[i]);
  78261. y = parseFloat(coords[i + 1]);
  78262. z = (dim === 3) ? parseFloat(coords[i + 2]) : 0;
  78263. if (axisOrientation.substr(0, 2) === 'en') {
  78264. flatCoordinates.push(x, y, z);
  78265. } else {
  78266. flatCoordinates.push(y, x, z);
  78267. }
  78268. }
  78269. return flatCoordinates;
  78270. };
  78271. /**
  78272. * @const
  78273. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78274. * @private
  78275. */
  78276. ol.format.GML3.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS_ = Object({
  78277. 'http://www.opengis.net/gml' : {
  78278. 'pos': ol.xml.makeReplacer(ol.format.GML3.prototype.readFlatPos_),
  78279. 'posList': ol.xml.makeReplacer(ol.format.GML3.prototype.readFlatPosList_)
  78280. }
  78281. });
  78282. /**
  78283. * @const
  78284. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78285. * @private
  78286. */
  78287. ol.format.GML3.prototype.FLAT_LINEAR_RINGS_PARSERS_ = Object({
  78288. 'http://www.opengis.net/gml' : {
  78289. 'interior': ol.format.GML3.prototype.interiorParser_,
  78290. 'exterior': ol.format.GML3.prototype.exteriorParser_
  78291. }
  78292. });
  78293. /**
  78294. * @const
  78295. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78296. * @private
  78297. */
  78298. ol.format.GML3.prototype.GEOMETRY_PARSERS_ = Object({
  78299. 'http://www.opengis.net/gml' : {
  78300. 'Point': ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPoint),
  78301. 'MultiPoint': ol.xml.makeReplacer(
  78302. ol.format.GMLBase.prototype.readMultiPoint),
  78303. 'LineString': ol.xml.makeReplacer(
  78304. ol.format.GMLBase.prototype.readLineString),
  78305. 'MultiLineString': ol.xml.makeReplacer(
  78306. ol.format.GMLBase.prototype.readMultiLineString),
  78307. 'LinearRing' : ol.xml.makeReplacer(
  78308. ol.format.GMLBase.prototype.readLinearRing),
  78309. 'Polygon': ol.xml.makeReplacer(ol.format.GMLBase.prototype.readPolygon),
  78310. 'MultiPolygon': ol.xml.makeReplacer(
  78311. ol.format.GMLBase.prototype.readMultiPolygon),
  78312. 'Surface': ol.xml.makeReplacer(ol.format.GML3.prototype.readSurface_),
  78313. 'MultiSurface': ol.xml.makeReplacer(
  78314. ol.format.GML3.prototype.readMultiSurface_),
  78315. 'Curve': ol.xml.makeReplacer(ol.format.GML3.prototype.readCurve_),
  78316. 'MultiCurve': ol.xml.makeReplacer(
  78317. ol.format.GML3.prototype.readMultiCurve_),
  78318. 'Envelope': ol.xml.makeReplacer(ol.format.GML3.prototype.readEnvelope_)
  78319. }
  78320. });
  78321. /**
  78322. * @const
  78323. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78324. * @private
  78325. */
  78326. ol.format.GML3.prototype.MULTICURVE_PARSERS_ = Object({
  78327. 'http://www.opengis.net/gml' : {
  78328. 'curveMember': ol.xml.makeArrayPusher(
  78329. ol.format.GML3.prototype.curveMemberParser_),
  78330. 'curveMembers': ol.xml.makeArrayPusher(
  78331. ol.format.GML3.prototype.curveMemberParser_)
  78332. }
  78333. });
  78334. /**
  78335. * @const
  78336. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78337. * @private
  78338. */
  78339. ol.format.GML3.prototype.MULTISURFACE_PARSERS_ = Object({
  78340. 'http://www.opengis.net/gml' : {
  78341. 'surfaceMember': ol.xml.makeArrayPusher(
  78342. ol.format.GML3.prototype.surfaceMemberParser_),
  78343. 'surfaceMembers': ol.xml.makeArrayPusher(
  78344. ol.format.GML3.prototype.surfaceMemberParser_)
  78345. }
  78346. });
  78347. /**
  78348. * @const
  78349. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78350. * @private
  78351. */
  78352. ol.format.GML3.prototype.CURVEMEMBER_PARSERS_ = Object({
  78353. 'http://www.opengis.net/gml' : {
  78354. 'LineString': ol.xml.makeArrayPusher(
  78355. ol.format.GMLBase.prototype.readLineString),
  78356. 'Curve': ol.xml.makeArrayPusher(ol.format.GML3.prototype.readCurve_)
  78357. }
  78358. });
  78359. /**
  78360. * @const
  78361. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78362. * @private
  78363. */
  78364. ol.format.GML3.prototype.SURFACEMEMBER_PARSERS_ = Object({
  78365. 'http://www.opengis.net/gml' : {
  78366. 'Polygon': ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readPolygon),
  78367. 'Surface': ol.xml.makeArrayPusher(ol.format.GML3.prototype.readSurface_)
  78368. }
  78369. });
  78370. /**
  78371. * @const
  78372. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78373. * @private
  78374. */
  78375. ol.format.GML3.prototype.SURFACE_PARSERS_ = Object({
  78376. 'http://www.opengis.net/gml' : {
  78377. 'patches': ol.xml.makeReplacer(ol.format.GML3.prototype.readPatch_)
  78378. }
  78379. });
  78380. /**
  78381. * @const
  78382. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78383. * @private
  78384. */
  78385. ol.format.GML3.prototype.CURVE_PARSERS_ = Object({
  78386. 'http://www.opengis.net/gml' : {
  78387. 'segments': ol.xml.makeReplacer(ol.format.GML3.prototype.readSegment_)
  78388. }
  78389. });
  78390. /**
  78391. * @const
  78392. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78393. * @private
  78394. */
  78395. ol.format.GML3.prototype.ENVELOPE_PARSERS_ = Object({
  78396. 'http://www.opengis.net/gml' : {
  78397. 'lowerCorner': ol.xml.makeArrayPusher(
  78398. ol.format.GML3.prototype.readFlatPosList_),
  78399. 'upperCorner': ol.xml.makeArrayPusher(
  78400. ol.format.GML3.prototype.readFlatPosList_)
  78401. }
  78402. });
  78403. /**
  78404. * @const
  78405. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78406. * @private
  78407. */
  78408. ol.format.GML3.prototype.PATCHES_PARSERS_ = Object({
  78409. 'http://www.opengis.net/gml' : {
  78410. 'PolygonPatch': ol.xml.makeReplacer(
  78411. ol.format.GML3.prototype.readPolygonPatch_)
  78412. }
  78413. });
  78414. /**
  78415. * @const
  78416. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  78417. * @private
  78418. */
  78419. ol.format.GML3.prototype.SEGMENTS_PARSERS_ = Object({
  78420. 'http://www.opengis.net/gml' : {
  78421. 'LineStringSegment': ol.xml.makeReplacer(
  78422. ol.format.GML3.prototype.readLineStringSegment_)
  78423. }
  78424. });
  78425. /**
  78426. * @param {Node} node Node.
  78427. * @param {ol.geom.Point} value Point geometry.
  78428. * @param {Array.<*>} objectStack Node stack.
  78429. * @private
  78430. */
  78431. ol.format.GML3.prototype.writePos_ = function(node, value, objectStack) {
  78432. var context = objectStack[objectStack.length - 1];
  78433. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78434. var srsName = context['srsName'];
  78435. var axisOrientation = 'enu';
  78436. if (srsName) {
  78437. axisOrientation = ol.proj.get(srsName).getAxisOrientation();
  78438. }
  78439. var point = value.getCoordinates();
  78440. var coords;
  78441. // only 2d for simple features profile
  78442. if (axisOrientation.substr(0, 2) === 'en') {
  78443. coords = (point[0] + ' ' + point[1]);
  78444. } else {
  78445. coords = (point[1] + ' ' + point[0]);
  78446. }
  78447. ol.format.XSD.writeStringTextNode(node, coords);
  78448. };
  78449. /**
  78450. * @param {Array.<number>} point Point geometry.
  78451. * @param {string=} opt_srsName Optional srsName
  78452. * @return {string}
  78453. * @private
  78454. */
  78455. ol.format.GML3.prototype.getCoords_ = function(point, opt_srsName) {
  78456. var axisOrientation = 'enu';
  78457. if (opt_srsName) {
  78458. axisOrientation = ol.proj.get(opt_srsName).getAxisOrientation();
  78459. }
  78460. return ((axisOrientation.substr(0, 2) === 'en') ?
  78461. point[0] + ' ' + point[1] :
  78462. point[1] + ' ' + point[0]);
  78463. };
  78464. /**
  78465. * @param {Node} node Node.
  78466. * @param {ol.geom.LineString|ol.geom.LinearRing} value Geometry.
  78467. * @param {Array.<*>} objectStack Node stack.
  78468. * @private
  78469. */
  78470. ol.format.GML3.prototype.writePosList_ = function(node, value, objectStack) {
  78471. var context = objectStack[objectStack.length - 1];
  78472. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78473. var srsName = context['srsName'];
  78474. // only 2d for simple features profile
  78475. var points = value.getCoordinates();
  78476. var len = points.length;
  78477. var parts = new Array(len);
  78478. var point;
  78479. for (var i = 0; i < len; ++i) {
  78480. point = points[i];
  78481. parts[i] = this.getCoords_(point, srsName);
  78482. }
  78483. ol.format.XSD.writeStringTextNode(node, parts.join(' '));
  78484. };
  78485. /**
  78486. * @param {Node} node Node.
  78487. * @param {ol.geom.Point} geometry Point geometry.
  78488. * @param {Array.<*>} objectStack Node stack.
  78489. * @private
  78490. */
  78491. ol.format.GML3.prototype.writePoint_ = function(node, geometry, objectStack) {
  78492. var context = objectStack[objectStack.length - 1];
  78493. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78494. var srsName = context['srsName'];
  78495. if (srsName) {
  78496. node.setAttribute('srsName', srsName);
  78497. }
  78498. var pos = ol.xml.createElementNS(node.namespaceURI, 'pos');
  78499. node.appendChild(pos);
  78500. this.writePos_(pos, geometry, objectStack);
  78501. };
  78502. /**
  78503. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78504. * @private
  78505. */
  78506. ol.format.GML3.ENVELOPE_SERIALIZERS_ = {
  78507. 'http://www.opengis.net/gml': {
  78508. 'lowerCorner': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  78509. 'upperCorner': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)
  78510. }
  78511. };
  78512. /**
  78513. * @param {Node} node Node.
  78514. * @param {ol.Extent} extent Extent.
  78515. * @param {Array.<*>} objectStack Node stack.
  78516. */
  78517. ol.format.GML3.prototype.writeEnvelope = function(node, extent, objectStack) {
  78518. goog.asserts.assert(extent.length == 4, 'extent should have 4 items');
  78519. var context = objectStack[objectStack.length - 1];
  78520. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78521. var srsName = context['srsName'];
  78522. if (srsName) {
  78523. node.setAttribute('srsName', srsName);
  78524. }
  78525. var keys = ['lowerCorner', 'upperCorner'];
  78526. var values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]];
  78527. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  78528. ({node: node}), ol.format.GML3.ENVELOPE_SERIALIZERS_,
  78529. ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  78530. values,
  78531. objectStack, keys, this);
  78532. };
  78533. /**
  78534. * @param {Node} node Node.
  78535. * @param {ol.geom.LinearRing} geometry LinearRing geometry.
  78536. * @param {Array.<*>} objectStack Node stack.
  78537. * @private
  78538. */
  78539. ol.format.GML3.prototype.writeLinearRing_ =
  78540. function(node, geometry, objectStack) {
  78541. var context = objectStack[objectStack.length - 1];
  78542. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78543. var srsName = context['srsName'];
  78544. if (srsName) {
  78545. node.setAttribute('srsName', srsName);
  78546. }
  78547. var posList = ol.xml.createElementNS(node.namespaceURI, 'posList');
  78548. node.appendChild(posList);
  78549. this.writePosList_(posList, geometry, objectStack);
  78550. };
  78551. /**
  78552. * @param {*} value Value.
  78553. * @param {Array.<*>} objectStack Object stack.
  78554. * @param {string=} opt_nodeName Node name.
  78555. * @return {Node} Node.
  78556. * @private
  78557. */
  78558. ol.format.GML3.prototype.RING_NODE_FACTORY_ =
  78559. function(value, objectStack, opt_nodeName) {
  78560. var context = objectStack[objectStack.length - 1];
  78561. var parentNode = context.node;
  78562. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78563. var exteriorWritten = context['exteriorWritten'];
  78564. if (exteriorWritten === undefined) {
  78565. context['exteriorWritten'] = true;
  78566. }
  78567. return ol.xml.createElementNS(parentNode.namespaceURI,
  78568. exteriorWritten !== undefined ? 'interior' : 'exterior');
  78569. };
  78570. /**
  78571. * @param {Node} node Node.
  78572. * @param {ol.geom.Polygon} geometry Polygon geometry.
  78573. * @param {Array.<*>} objectStack Node stack.
  78574. * @private
  78575. */
  78576. ol.format.GML3.prototype.writeSurfaceOrPolygon_ =
  78577. function(node, geometry, objectStack) {
  78578. var context = objectStack[objectStack.length - 1];
  78579. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78580. var srsName = context['srsName'];
  78581. if (node.nodeName !== 'PolygonPatch' && srsName) {
  78582. node.setAttribute('srsName', srsName);
  78583. }
  78584. if (node.nodeName === 'Polygon' || node.nodeName === 'PolygonPatch') {
  78585. var rings = geometry.getLinearRings();
  78586. ol.xml.pushSerializeAndPop(
  78587. {node: node, srsName: srsName},
  78588. ol.format.GML3.RING_SERIALIZERS_,
  78589. this.RING_NODE_FACTORY_,
  78590. rings, objectStack, undefined, this);
  78591. } else if (node.nodeName === 'Surface') {
  78592. var patches = ol.xml.createElementNS(node.namespaceURI, 'patches');
  78593. node.appendChild(patches);
  78594. this.writeSurfacePatches_(
  78595. patches, geometry, objectStack);
  78596. }
  78597. };
  78598. /**
  78599. * @param {Node} node Node.
  78600. * @param {ol.geom.LineString} geometry LineString geometry.
  78601. * @param {Array.<*>} objectStack Node stack.
  78602. * @private
  78603. */
  78604. ol.format.GML3.prototype.writeCurveOrLineString_ =
  78605. function(node, geometry, objectStack) {
  78606. var context = objectStack[objectStack.length - 1];
  78607. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78608. var srsName = context['srsName'];
  78609. if (node.nodeName !== 'LineStringSegment' && srsName) {
  78610. node.setAttribute('srsName', srsName);
  78611. }
  78612. if (node.nodeName === 'LineString' ||
  78613. node.nodeName === 'LineStringSegment') {
  78614. var posList = ol.xml.createElementNS(node.namespaceURI, 'posList');
  78615. node.appendChild(posList);
  78616. this.writePosList_(posList, geometry, objectStack);
  78617. } else if (node.nodeName === 'Curve') {
  78618. var segments = ol.xml.createElementNS(node.namespaceURI, 'segments');
  78619. node.appendChild(segments);
  78620. this.writeCurveSegments_(segments,
  78621. geometry, objectStack);
  78622. }
  78623. };
  78624. /**
  78625. * @param {Node} node Node.
  78626. * @param {ol.geom.MultiPolygon} geometry MultiPolygon geometry.
  78627. * @param {Array.<*>} objectStack Node stack.
  78628. * @private
  78629. */
  78630. ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_ =
  78631. function(node, geometry, objectStack) {
  78632. var context = objectStack[objectStack.length - 1];
  78633. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78634. var srsName = context['srsName'];
  78635. var surface = context['surface'];
  78636. if (srsName) {
  78637. node.setAttribute('srsName', srsName);
  78638. }
  78639. var polygons = geometry.getPolygons();
  78640. ol.xml.pushSerializeAndPop({node: node, srsName: srsName, surface: surface},
  78641. ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_,
  78642. this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, polygons,
  78643. objectStack, undefined, this);
  78644. };
  78645. /**
  78646. * @param {Node} node Node.
  78647. * @param {ol.geom.MultiPoint} geometry MultiPoint geometry.
  78648. * @param {Array.<*>} objectStack Node stack.
  78649. * @private
  78650. */
  78651. ol.format.GML3.prototype.writeMultiPoint_ = function(node, geometry,
  78652. objectStack) {
  78653. var context = objectStack[objectStack.length - 1];
  78654. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78655. var srsName = context['srsName'];
  78656. if (srsName) {
  78657. node.setAttribute('srsName', srsName);
  78658. }
  78659. var points = geometry.getPoints();
  78660. ol.xml.pushSerializeAndPop({node: node, srsName: srsName},
  78661. ol.format.GML3.POINTMEMBER_SERIALIZERS_,
  78662. ol.xml.makeSimpleNodeFactory('pointMember'), points,
  78663. objectStack, undefined, this);
  78664. };
  78665. /**
  78666. * @param {Node} node Node.
  78667. * @param {ol.geom.MultiLineString} geometry MultiLineString geometry.
  78668. * @param {Array.<*>} objectStack Node stack.
  78669. * @private
  78670. */
  78671. ol.format.GML3.prototype.writeMultiCurveOrLineString_ =
  78672. function(node, geometry, objectStack) {
  78673. var context = objectStack[objectStack.length - 1];
  78674. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78675. var srsName = context['srsName'];
  78676. var curve = context['curve'];
  78677. if (srsName) {
  78678. node.setAttribute('srsName', srsName);
  78679. }
  78680. var lines = geometry.getLineStrings();
  78681. ol.xml.pushSerializeAndPop({node: node, srsName: srsName, curve: curve},
  78682. ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_,
  78683. this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_, lines,
  78684. objectStack, undefined, this);
  78685. };
  78686. /**
  78687. * @param {Node} node Node.
  78688. * @param {ol.geom.LinearRing} ring LinearRing geometry.
  78689. * @param {Array.<*>} objectStack Node stack.
  78690. * @private
  78691. */
  78692. ol.format.GML3.prototype.writeRing_ = function(node, ring, objectStack) {
  78693. var linearRing = ol.xml.createElementNS(node.namespaceURI, 'LinearRing');
  78694. node.appendChild(linearRing);
  78695. this.writeLinearRing_(linearRing, ring, objectStack);
  78696. };
  78697. /**
  78698. * @param {Node} node Node.
  78699. * @param {ol.geom.Polygon} polygon Polygon geometry.
  78700. * @param {Array.<*>} objectStack Node stack.
  78701. * @private
  78702. */
  78703. ol.format.GML3.prototype.writeSurfaceOrPolygonMember_ =
  78704. function(node, polygon, objectStack) {
  78705. var context = objectStack[objectStack.length - 1];
  78706. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78707. var child = this.GEOMETRY_NODE_FACTORY_(
  78708. polygon, objectStack);
  78709. if (child) {
  78710. node.appendChild(child);
  78711. this.writeSurfaceOrPolygon_(child, polygon, objectStack);
  78712. }
  78713. };
  78714. /**
  78715. * @param {Node} node Node.
  78716. * @param {ol.geom.Point} point Point geometry.
  78717. * @param {Array.<*>} objectStack Node stack.
  78718. * @private
  78719. */
  78720. ol.format.GML3.prototype.writePointMember_ =
  78721. function(node, point, objectStack) {
  78722. var child = ol.xml.createElementNS(node.namespaceURI, 'Point');
  78723. node.appendChild(child);
  78724. this.writePoint_(child, point, objectStack);
  78725. };
  78726. /**
  78727. * @param {Node} node Node.
  78728. * @param {ol.geom.LineString} line LineString geometry.
  78729. * @param {Array.<*>} objectStack Node stack.
  78730. * @private
  78731. */
  78732. ol.format.GML3.prototype.writeLineStringOrCurveMember_ =
  78733. function(node, line, objectStack) {
  78734. var context = objectStack[objectStack.length - 1];
  78735. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78736. var child = this.GEOMETRY_NODE_FACTORY_(line, objectStack);
  78737. if (child) {
  78738. node.appendChild(child);
  78739. this.writeCurveOrLineString_(child, line, objectStack);
  78740. }
  78741. };
  78742. /**
  78743. * @param {Node} node Node.
  78744. * @param {ol.geom.Polygon} polygon Polygon geometry.
  78745. * @param {Array.<*>} objectStack Node stack.
  78746. * @private
  78747. */
  78748. ol.format.GML3.prototype.writeSurfacePatches_ =
  78749. function(node, polygon, objectStack) {
  78750. var child = ol.xml.createElementNS(node.namespaceURI, 'PolygonPatch');
  78751. node.appendChild(child);
  78752. this.writeSurfaceOrPolygon_(child, polygon, objectStack);
  78753. };
  78754. /**
  78755. * @param {Node} node Node.
  78756. * @param {ol.geom.LineString} line LineString geometry.
  78757. * @param {Array.<*>} objectStack Node stack.
  78758. * @private
  78759. */
  78760. ol.format.GML3.prototype.writeCurveSegments_ =
  78761. function(node, line, objectStack) {
  78762. var child = ol.xml.createElementNS(node.namespaceURI,
  78763. 'LineStringSegment');
  78764. node.appendChild(child);
  78765. this.writeCurveOrLineString_(child, line, objectStack);
  78766. };
  78767. /**
  78768. * @param {Node} node Node.
  78769. * @param {ol.geom.Geometry|ol.Extent} geometry Geometry.
  78770. * @param {Array.<*>} objectStack Node stack.
  78771. */
  78772. ol.format.GML3.prototype.writeGeometryElement =
  78773. function(node, geometry, objectStack) {
  78774. var context = objectStack[objectStack.length - 1];
  78775. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78776. var item = goog.object.clone(context);
  78777. item.node = node;
  78778. var value;
  78779. if (goog.isArray(geometry)) {
  78780. if (context.dataProjection) {
  78781. value = ol.proj.transformExtent(
  78782. geometry, context.featureProjection, context.dataProjection);
  78783. } else {
  78784. value = geometry;
  78785. }
  78786. } else {
  78787. goog.asserts.assertInstanceof(geometry, ol.geom.Geometry,
  78788. 'geometry should be an ol.geom.Geometry');
  78789. value =
  78790. ol.format.Feature.transformWithOptions(geometry, true, context);
  78791. }
  78792. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  78793. (item), ol.format.GML3.GEOMETRY_SERIALIZERS_,
  78794. this.GEOMETRY_NODE_FACTORY_, [value],
  78795. objectStack, undefined, this);
  78796. };
  78797. /**
  78798. * @param {Node} node Node.
  78799. * @param {ol.Feature} feature Feature.
  78800. * @param {Array.<*>} objectStack Node stack.
  78801. */
  78802. ol.format.GML3.prototype.writeFeatureElement =
  78803. function(node, feature, objectStack) {
  78804. var fid = feature.getId();
  78805. if (fid) {
  78806. node.setAttribute('fid', fid);
  78807. }
  78808. var context = objectStack[objectStack.length - 1];
  78809. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78810. var featureNS = context['featureNS'];
  78811. var geometryName = feature.getGeometryName();
  78812. if (!context.serializers) {
  78813. context.serializers = {};
  78814. context.serializers[featureNS] = {};
  78815. }
  78816. var properties = feature.getProperties();
  78817. var keys = [], values = [];
  78818. for (var key in properties) {
  78819. var value = properties[key];
  78820. if (value !== null) {
  78821. keys.push(key);
  78822. values.push(value);
  78823. if (key == geometryName || value instanceof ol.geom.Geometry) {
  78824. if (!(key in context.serializers[featureNS])) {
  78825. context.serializers[featureNS][key] = ol.xml.makeChildAppender(
  78826. this.writeGeometryElement, this);
  78827. }
  78828. } else {
  78829. if (!(key in context.serializers[featureNS])) {
  78830. context.serializers[featureNS][key] = ol.xml.makeChildAppender(
  78831. ol.format.XSD.writeStringTextNode);
  78832. }
  78833. }
  78834. }
  78835. }
  78836. var item = goog.object.clone(context);
  78837. item.node = node;
  78838. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  78839. (item), context.serializers,
  78840. ol.xml.makeSimpleNodeFactory(undefined, featureNS),
  78841. values,
  78842. objectStack, keys);
  78843. };
  78844. /**
  78845. * @param {Node} node Node.
  78846. * @param {Array.<ol.Feature>} features Features.
  78847. * @param {Array.<*>} objectStack Node stack.
  78848. * @private
  78849. */
  78850. ol.format.GML3.prototype.writeFeatureMembers_ =
  78851. function(node, features, objectStack) {
  78852. var context = objectStack[objectStack.length - 1];
  78853. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78854. var featureType = context['featureType'];
  78855. var featureNS = context['featureNS'];
  78856. var serializers = {};
  78857. serializers[featureNS] = {};
  78858. serializers[featureNS][featureType] = ol.xml.makeChildAppender(
  78859. this.writeFeatureElement, this);
  78860. var item = goog.object.clone(context);
  78861. item.node = node;
  78862. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  78863. (item),
  78864. serializers,
  78865. ol.xml.makeSimpleNodeFactory(featureType, featureNS), features,
  78866. objectStack);
  78867. };
  78868. /**
  78869. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78870. * @private
  78871. */
  78872. ol.format.GML3.SURFACEORPOLYGONMEMBER_SERIALIZERS_ = {
  78873. 'http://www.opengis.net/gml': {
  78874. 'surfaceMember': ol.xml.makeChildAppender(
  78875. ol.format.GML3.prototype.writeSurfaceOrPolygonMember_),
  78876. 'polygonMember': ol.xml.makeChildAppender(
  78877. ol.format.GML3.prototype.writeSurfaceOrPolygonMember_)
  78878. }
  78879. };
  78880. /**
  78881. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78882. * @private
  78883. */
  78884. ol.format.GML3.POINTMEMBER_SERIALIZERS_ = {
  78885. 'http://www.opengis.net/gml': {
  78886. 'pointMember': ol.xml.makeChildAppender(
  78887. ol.format.GML3.prototype.writePointMember_)
  78888. }
  78889. };
  78890. /**
  78891. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78892. * @private
  78893. */
  78894. ol.format.GML3.LINESTRINGORCURVEMEMBER_SERIALIZERS_ = {
  78895. 'http://www.opengis.net/gml': {
  78896. 'lineStringMember': ol.xml.makeChildAppender(
  78897. ol.format.GML3.prototype.writeLineStringOrCurveMember_),
  78898. 'curveMember': ol.xml.makeChildAppender(
  78899. ol.format.GML3.prototype.writeLineStringOrCurveMember_)
  78900. }
  78901. };
  78902. /**
  78903. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78904. * @private
  78905. */
  78906. ol.format.GML3.RING_SERIALIZERS_ = {
  78907. 'http://www.opengis.net/gml': {
  78908. 'exterior': ol.xml.makeChildAppender(ol.format.GML3.prototype.writeRing_),
  78909. 'interior': ol.xml.makeChildAppender(ol.format.GML3.prototype.writeRing_)
  78910. }
  78911. };
  78912. /**
  78913. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  78914. * @private
  78915. */
  78916. ol.format.GML3.GEOMETRY_SERIALIZERS_ = {
  78917. 'http://www.opengis.net/gml': {
  78918. 'Curve': ol.xml.makeChildAppender(
  78919. ol.format.GML3.prototype.writeCurveOrLineString_),
  78920. 'MultiCurve': ol.xml.makeChildAppender(
  78921. ol.format.GML3.prototype.writeMultiCurveOrLineString_),
  78922. 'Point': ol.xml.makeChildAppender(ol.format.GML3.prototype.writePoint_),
  78923. 'MultiPoint': ol.xml.makeChildAppender(
  78924. ol.format.GML3.prototype.writeMultiPoint_),
  78925. 'LineString': ol.xml.makeChildAppender(
  78926. ol.format.GML3.prototype.writeCurveOrLineString_),
  78927. 'MultiLineString': ol.xml.makeChildAppender(
  78928. ol.format.GML3.prototype.writeMultiCurveOrLineString_),
  78929. 'LinearRing': ol.xml.makeChildAppender(
  78930. ol.format.GML3.prototype.writeLinearRing_),
  78931. 'Polygon': ol.xml.makeChildAppender(
  78932. ol.format.GML3.prototype.writeSurfaceOrPolygon_),
  78933. 'MultiPolygon': ol.xml.makeChildAppender(
  78934. ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),
  78935. 'Surface': ol.xml.makeChildAppender(
  78936. ol.format.GML3.prototype.writeSurfaceOrPolygon_),
  78937. 'MultiSurface': ol.xml.makeChildAppender(
  78938. ol.format.GML3.prototype.writeMultiSurfaceOrPolygon_),
  78939. 'Envelope': ol.xml.makeChildAppender(
  78940. ol.format.GML3.prototype.writeEnvelope)
  78941. }
  78942. };
  78943. /**
  78944. * @const
  78945. * @type {Object.<string, string>}
  78946. * @private
  78947. */
  78948. ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_ = {
  78949. 'MultiLineString': 'lineStringMember',
  78950. 'MultiCurve': 'curveMember',
  78951. 'MultiPolygon': 'polygonMember',
  78952. 'MultiSurface': 'surfaceMember'
  78953. };
  78954. /**
  78955. * @const
  78956. * @param {*} value Value.
  78957. * @param {Array.<*>} objectStack Object stack.
  78958. * @param {string=} opt_nodeName Node name.
  78959. * @return {Node|undefined} Node.
  78960. * @private
  78961. */
  78962. ol.format.GML3.prototype.MULTIGEOMETRY_MEMBER_NODE_FACTORY_ =
  78963. function(value, objectStack, opt_nodeName) {
  78964. var parentNode = objectStack[objectStack.length - 1].node;
  78965. goog.asserts.assert(ol.xml.isNode(parentNode),
  78966. 'parentNode should be a node');
  78967. return ol.xml.createElementNS('http://www.opengis.net/gml',
  78968. ol.format.GML3.MULTIGEOMETRY_TO_MEMBER_NODENAME_[parentNode.nodeName]);
  78969. };
  78970. /**
  78971. * @const
  78972. * @param {*} value Value.
  78973. * @param {Array.<*>} objectStack Object stack.
  78974. * @param {string=} opt_nodeName Node name.
  78975. * @return {Node|undefined} Node.
  78976. * @private
  78977. */
  78978. ol.format.GML3.prototype.GEOMETRY_NODE_FACTORY_ =
  78979. function(value, objectStack, opt_nodeName) {
  78980. var context = objectStack[objectStack.length - 1];
  78981. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  78982. var multiSurface = context['multiSurface'];
  78983. var surface = context['surface'];
  78984. var curve = context['curve'];
  78985. var multiCurve = context['multiCurve'];
  78986. var parentNode = objectStack[objectStack.length - 1].node;
  78987. goog.asserts.assert(ol.xml.isNode(parentNode),
  78988. 'parentNode should be a node');
  78989. var nodeName;
  78990. if (!goog.isArray(value)) {
  78991. goog.asserts.assertInstanceof(value, ol.geom.Geometry,
  78992. 'value should be an ol.geom.Geometry');
  78993. nodeName = value.getType();
  78994. if (nodeName === 'MultiPolygon' && multiSurface === true) {
  78995. nodeName = 'MultiSurface';
  78996. } else if (nodeName === 'Polygon' && surface === true) {
  78997. nodeName = 'Surface';
  78998. } else if (nodeName === 'LineString' && curve === true) {
  78999. nodeName = 'Curve';
  79000. } else if (nodeName === 'MultiLineString' && multiCurve === true) {
  79001. nodeName = 'MultiCurve';
  79002. }
  79003. } else {
  79004. nodeName = 'Envelope';
  79005. }
  79006. return ol.xml.createElementNS('http://www.opengis.net/gml',
  79007. nodeName);
  79008. };
  79009. /**
  79010. * Encode a geometry in GML 3.1.1 Simple Features.
  79011. *
  79012. * @param {ol.geom.Geometry} geometry Geometry.
  79013. * @param {olx.format.WriteOptions=} opt_options Options.
  79014. * @return {Node} Node.
  79015. * @api
  79016. */
  79017. ol.format.GML3.prototype.writeGeometryNode = function(geometry, opt_options) {
  79018. opt_options = this.adaptOptions(opt_options);
  79019. var geom = ol.xml.createElementNS('http://www.opengis.net/gml', 'geom');
  79020. var context = {node: geom, srsName: this.srsName,
  79021. curve: this.curve_, surface: this.surface_,
  79022. multiSurface: this.multiSurface_, multiCurve: this.multiCurve_};
  79023. if (opt_options) {
  79024. goog.object.extend(context, opt_options);
  79025. }
  79026. this.writeGeometryElement(geom, geometry, [context]);
  79027. return geom;
  79028. };
  79029. /**
  79030. * Encode an array of features in GML 3.1.1 Simple Features.
  79031. *
  79032. * @function
  79033. * @param {Array.<ol.Feature>} features Features.
  79034. * @param {olx.format.WriteOptions=} opt_options Options.
  79035. * @return {string} Result.
  79036. * @api stable
  79037. */
  79038. ol.format.GML3.prototype.writeFeatures;
  79039. /**
  79040. * Encode an array of features in the GML 3.1.1 format as an XML node.
  79041. *
  79042. * @param {Array.<ol.Feature>} features Features.
  79043. * @param {olx.format.WriteOptions=} opt_options Options.
  79044. * @return {Node} Node.
  79045. * @api
  79046. */
  79047. ol.format.GML3.prototype.writeFeaturesNode = function(features, opt_options) {
  79048. opt_options = this.adaptOptions(opt_options);
  79049. var node = ol.xml.createElementNS('http://www.opengis.net/gml',
  79050. 'featureMembers');
  79051. ol.xml.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance',
  79052. 'xsi:schemaLocation', this.schemaLocation);
  79053. var context = {
  79054. srsName: this.srsName,
  79055. curve: this.curve_,
  79056. surface: this.surface_,
  79057. multiSurface: this.multiSurface_,
  79058. multiCurve: this.multiCurve_,
  79059. featureNS: this.featureNS,
  79060. featureType: this.featureType
  79061. };
  79062. if (opt_options) {
  79063. goog.object.extend(context, opt_options);
  79064. }
  79065. this.writeFeatureMembers_(node, features, [context]);
  79066. return node;
  79067. };
  79068. /**
  79069. * @classdesc
  79070. * Feature format for reading and writing data in the GML format
  79071. * version 3.1.1.
  79072. * Currently only supports GML 3.1.1 Simple Features profile.
  79073. *
  79074. * @constructor
  79075. * @param {olx.format.GMLOptions=} opt_options
  79076. * Optional configuration object.
  79077. * @extends {ol.format.GMLBase}
  79078. * @api stable
  79079. */
  79080. ol.format.GML = ol.format.GML3;
  79081. /**
  79082. * Encode an array of features in GML 3.1.1 Simple Features.
  79083. *
  79084. * @function
  79085. * @param {Array.<ol.Feature>} features Features.
  79086. * @param {olx.format.WriteOptions=} opt_options Options.
  79087. * @return {string} Result.
  79088. * @api stable
  79089. */
  79090. ol.format.GML.prototype.writeFeatures;
  79091. /**
  79092. * Encode an array of features in the GML 3.1.1 format as an XML node.
  79093. *
  79094. * @function
  79095. * @param {Array.<ol.Feature>} features Features.
  79096. * @param {olx.format.WriteOptions=} opt_options Options.
  79097. * @return {Node} Node.
  79098. * @api
  79099. */
  79100. ol.format.GML.prototype.writeFeaturesNode;
  79101. goog.provide('ol.format.GPX');
  79102. goog.require('goog.asserts');
  79103. goog.require('goog.dom.NodeType');
  79104. goog.require('ol.Feature');
  79105. goog.require('ol.array');
  79106. goog.require('ol.format.Feature');
  79107. goog.require('ol.format.XMLFeature');
  79108. goog.require('ol.format.XSD');
  79109. goog.require('ol.geom.GeometryLayout');
  79110. goog.require('ol.geom.LineString');
  79111. goog.require('ol.geom.MultiLineString');
  79112. goog.require('ol.geom.Point');
  79113. goog.require('ol.proj');
  79114. goog.require('ol.xml');
  79115. /**
  79116. * @classdesc
  79117. * Feature format for reading and writing data in the GPX format.
  79118. *
  79119. * @constructor
  79120. * @extends {ol.format.XMLFeature}
  79121. * @param {olx.format.GPXOptions=} opt_options Options.
  79122. * @api stable
  79123. */
  79124. ol.format.GPX = function(opt_options) {
  79125. var options = opt_options ? opt_options : {};
  79126. goog.base(this);
  79127. /**
  79128. * @inheritDoc
  79129. */
  79130. this.defaultDataProjection = ol.proj.get('EPSG:4326');
  79131. /**
  79132. * @type {function(ol.Feature, Node)|undefined}
  79133. * @private
  79134. */
  79135. this.readExtensions_ = options.readExtensions;
  79136. };
  79137. goog.inherits(ol.format.GPX, ol.format.XMLFeature);
  79138. /**
  79139. * @const
  79140. * @private
  79141. * @type {Array.<string>}
  79142. */
  79143. ol.format.GPX.NAMESPACE_URIS_ = [
  79144. null,
  79145. 'http://www.topografix.com/GPX/1/0',
  79146. 'http://www.topografix.com/GPX/1/1'
  79147. ];
  79148. /**
  79149. * @param {Array.<number>} flatCoordinates Flat coordinates.
  79150. * @param {Node} node Node.
  79151. * @param {Object} values Values.
  79152. * @private
  79153. * @return {Array.<number>} Flat coordinates.
  79154. */
  79155. ol.format.GPX.appendCoordinate_ = function(flatCoordinates, node, values) {
  79156. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79157. 'node.nodeType should be ELEMENT');
  79158. flatCoordinates.push(
  79159. parseFloat(node.getAttribute('lon')),
  79160. parseFloat(node.getAttribute('lat')));
  79161. if ('ele' in values) {
  79162. flatCoordinates.push(/** @type {number} */ (values['ele']));
  79163. delete values['ele'];
  79164. } else {
  79165. flatCoordinates.push(0);
  79166. }
  79167. if ('time' in values) {
  79168. flatCoordinates.push(/** @type {number} */ (values['time']));
  79169. delete values['time'];
  79170. } else {
  79171. flatCoordinates.push(0);
  79172. }
  79173. return flatCoordinates;
  79174. };
  79175. /**
  79176. * @param {Node} node Node.
  79177. * @param {Array.<*>} objectStack Object stack.
  79178. * @private
  79179. */
  79180. ol.format.GPX.parseLink_ = function(node, objectStack) {
  79181. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79182. 'node.nodeType should be ELEMENT');
  79183. goog.asserts.assert(node.localName == 'link', 'localName should be link');
  79184. var values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  79185. var href = node.getAttribute('href');
  79186. if (href !== null) {
  79187. values['link'] = href;
  79188. }
  79189. ol.xml.parseNode(ol.format.GPX.LINK_PARSERS_, node, objectStack);
  79190. };
  79191. /**
  79192. * @param {Node} node Node.
  79193. * @param {Array.<*>} objectStack Object stack.
  79194. * @private
  79195. */
  79196. ol.format.GPX.parseExtensions_ = function(node, objectStack) {
  79197. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79198. 'node.nodeType should be ELEMENT');
  79199. goog.asserts.assert(node.localName == 'extensions',
  79200. 'localName should be extensions');
  79201. var values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  79202. values['extensionsNode_'] = node;
  79203. };
  79204. /**
  79205. * @param {Node} node Node.
  79206. * @param {Array.<*>} objectStack Object stack.
  79207. * @private
  79208. */
  79209. ol.format.GPX.parseRtePt_ = function(node, objectStack) {
  79210. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79211. 'node.nodeType should be ELEMENT');
  79212. goog.asserts.assert(node.localName == 'rtept', 'localName should be rtept');
  79213. var values = ol.xml.pushParseAndPop(
  79214. {}, ol.format.GPX.RTEPT_PARSERS_, node, objectStack);
  79215. if (values) {
  79216. var rteValues = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  79217. var flatCoordinates = /** @type {Array.<number>} */
  79218. (rteValues['flatCoordinates']);
  79219. ol.format.GPX.appendCoordinate_(flatCoordinates, node, values);
  79220. }
  79221. };
  79222. /**
  79223. * @param {Node} node Node.
  79224. * @param {Array.<*>} objectStack Object stack.
  79225. * @private
  79226. */
  79227. ol.format.GPX.parseTrkPt_ = function(node, objectStack) {
  79228. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79229. 'node.nodeType should be ELEMENT');
  79230. goog.asserts.assert(node.localName == 'trkpt', 'localName should be trkpt');
  79231. var values = ol.xml.pushParseAndPop(
  79232. {}, ol.format.GPX.TRKPT_PARSERS_, node, objectStack);
  79233. if (values) {
  79234. var trkValues = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  79235. var flatCoordinates = /** @type {Array.<number>} */
  79236. (trkValues['flatCoordinates']);
  79237. ol.format.GPX.appendCoordinate_(flatCoordinates, node, values);
  79238. }
  79239. };
  79240. /**
  79241. * @param {Node} node Node.
  79242. * @param {Array.<*>} objectStack Object stack.
  79243. * @private
  79244. */
  79245. ol.format.GPX.parseTrkSeg_ = function(node, objectStack) {
  79246. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79247. 'node.nodeType should be ELEMENT');
  79248. goog.asserts.assert(node.localName == 'trkseg',
  79249. 'localName should be trkseg');
  79250. var values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  79251. ol.xml.parseNode(ol.format.GPX.TRKSEG_PARSERS_, node, objectStack);
  79252. var flatCoordinates = /** @type {Array.<number>} */
  79253. (values['flatCoordinates']);
  79254. var ends = /** @type {Array.<number>} */ (values['ends']);
  79255. ends.push(flatCoordinates.length);
  79256. };
  79257. /**
  79258. * @param {Node} node Node.
  79259. * @param {Array.<*>} objectStack Object stack.
  79260. * @private
  79261. * @return {ol.Feature|undefined} Track.
  79262. */
  79263. ol.format.GPX.readRte_ = function(node, objectStack) {
  79264. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79265. 'node.nodeType should be ELEMENT');
  79266. goog.asserts.assert(node.localName == 'rte', 'localName should be rte');
  79267. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  79268. var values = ol.xml.pushParseAndPop({
  79269. 'flatCoordinates': []
  79270. }, ol.format.GPX.RTE_PARSERS_, node, objectStack);
  79271. if (!values) {
  79272. return undefined;
  79273. }
  79274. var flatCoordinates = /** @type {Array.<number>} */
  79275. (values['flatCoordinates']);
  79276. delete values['flatCoordinates'];
  79277. var geometry = new ol.geom.LineString(null);
  79278. geometry.setFlatCoordinates(ol.geom.GeometryLayout.XYZM, flatCoordinates);
  79279. ol.format.Feature.transformWithOptions(geometry, false, options);
  79280. var feature = new ol.Feature(geometry);
  79281. feature.setProperties(values);
  79282. return feature;
  79283. };
  79284. /**
  79285. * @param {Node} node Node.
  79286. * @param {Array.<*>} objectStack Object stack.
  79287. * @private
  79288. * @return {ol.Feature|undefined} Track.
  79289. */
  79290. ol.format.GPX.readTrk_ = function(node, objectStack) {
  79291. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79292. 'node.nodeType should be ELEMENT');
  79293. goog.asserts.assert(node.localName == 'trk', 'localName should be trk');
  79294. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  79295. var values = ol.xml.pushParseAndPop({
  79296. 'flatCoordinates': [],
  79297. 'ends': []
  79298. }, ol.format.GPX.TRK_PARSERS_, node, objectStack);
  79299. if (!values) {
  79300. return undefined;
  79301. }
  79302. var flatCoordinates = /** @type {Array.<number>} */
  79303. (values['flatCoordinates']);
  79304. delete values['flatCoordinates'];
  79305. var ends = /** @type {Array.<number>} */ (values['ends']);
  79306. delete values['ends'];
  79307. var geometry = new ol.geom.MultiLineString(null);
  79308. geometry.setFlatCoordinates(
  79309. ol.geom.GeometryLayout.XYZM, flatCoordinates, ends);
  79310. ol.format.Feature.transformWithOptions(geometry, false, options);
  79311. var feature = new ol.Feature(geometry);
  79312. feature.setProperties(values);
  79313. return feature;
  79314. };
  79315. /**
  79316. * @param {Node} node Node.
  79317. * @param {Array.<*>} objectStack Object stack.
  79318. * @private
  79319. * @return {ol.Feature|undefined} Waypoint.
  79320. */
  79321. ol.format.GPX.readWpt_ = function(node, objectStack) {
  79322. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79323. 'node.nodeType should be ELEMENT');
  79324. goog.asserts.assert(node.localName == 'wpt', 'localName should be wpt');
  79325. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  79326. var values = ol.xml.pushParseAndPop(
  79327. {}, ol.format.GPX.WPT_PARSERS_, node, objectStack);
  79328. if (!values) {
  79329. return undefined;
  79330. }
  79331. var coordinates = ol.format.GPX.appendCoordinate_([], node, values);
  79332. var geometry = new ol.geom.Point(
  79333. coordinates, ol.geom.GeometryLayout.XYZM);
  79334. ol.format.Feature.transformWithOptions(geometry, false, options);
  79335. var feature = new ol.Feature(geometry);
  79336. feature.setProperties(values);
  79337. return feature;
  79338. };
  79339. /**
  79340. * @const
  79341. * @type {Object.<string, function(Node, Array.<*>): (ol.Feature|undefined)>}
  79342. * @private
  79343. */
  79344. ol.format.GPX.FEATURE_READER_ = {
  79345. 'rte': ol.format.GPX.readRte_,
  79346. 'trk': ol.format.GPX.readTrk_,
  79347. 'wpt': ol.format.GPX.readWpt_
  79348. };
  79349. /**
  79350. * @const
  79351. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79352. * @private
  79353. */
  79354. ol.format.GPX.GPX_PARSERS_ = ol.xml.makeStructureNS(
  79355. ol.format.GPX.NAMESPACE_URIS_, {
  79356. 'rte': ol.xml.makeArrayPusher(ol.format.GPX.readRte_),
  79357. 'trk': ol.xml.makeArrayPusher(ol.format.GPX.readTrk_),
  79358. 'wpt': ol.xml.makeArrayPusher(ol.format.GPX.readWpt_)
  79359. });
  79360. /**
  79361. * @const
  79362. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79363. * @private
  79364. */
  79365. ol.format.GPX.LINK_PARSERS_ = ol.xml.makeStructureNS(
  79366. ol.format.GPX.NAMESPACE_URIS_, {
  79367. 'text':
  79368. ol.xml.makeObjectPropertySetter(ol.format.XSD.readString, 'linkText'),
  79369. 'type':
  79370. ol.xml.makeObjectPropertySetter(ol.format.XSD.readString, 'linkType')
  79371. });
  79372. /**
  79373. * @const
  79374. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79375. * @private
  79376. */
  79377. ol.format.GPX.RTE_PARSERS_ = ol.xml.makeStructureNS(
  79378. ol.format.GPX.NAMESPACE_URIS_, {
  79379. 'name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79380. 'cmt': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79381. 'desc': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79382. 'src': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79383. 'link': ol.format.GPX.parseLink_,
  79384. 'number':
  79385. ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),
  79386. 'extensions': ol.format.GPX.parseExtensions_,
  79387. 'type': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79388. 'rtept': ol.format.GPX.parseRtePt_
  79389. });
  79390. /**
  79391. * @const
  79392. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79393. * @private
  79394. */
  79395. ol.format.GPX.RTEPT_PARSERS_ = ol.xml.makeStructureNS(
  79396. ol.format.GPX.NAMESPACE_URIS_, {
  79397. 'ele': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79398. 'time': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime)
  79399. });
  79400. /**
  79401. * @const
  79402. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79403. * @private
  79404. */
  79405. ol.format.GPX.TRK_PARSERS_ = ol.xml.makeStructureNS(
  79406. ol.format.GPX.NAMESPACE_URIS_, {
  79407. 'name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79408. 'cmt': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79409. 'desc': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79410. 'src': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79411. 'link': ol.format.GPX.parseLink_,
  79412. 'number':
  79413. ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),
  79414. 'type': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79415. 'extensions': ol.format.GPX.parseExtensions_,
  79416. 'trkseg': ol.format.GPX.parseTrkSeg_
  79417. });
  79418. /**
  79419. * @const
  79420. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79421. * @private
  79422. */
  79423. ol.format.GPX.TRKSEG_PARSERS_ = ol.xml.makeStructureNS(
  79424. ol.format.GPX.NAMESPACE_URIS_, {
  79425. 'trkpt': ol.format.GPX.parseTrkPt_
  79426. });
  79427. /**
  79428. * @const
  79429. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79430. * @private
  79431. */
  79432. ol.format.GPX.TRKPT_PARSERS_ = ol.xml.makeStructureNS(
  79433. ol.format.GPX.NAMESPACE_URIS_, {
  79434. 'ele': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79435. 'time': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime)
  79436. });
  79437. /**
  79438. * @const
  79439. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  79440. * @private
  79441. */
  79442. ol.format.GPX.WPT_PARSERS_ = ol.xml.makeStructureNS(
  79443. ol.format.GPX.NAMESPACE_URIS_, {
  79444. 'ele': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79445. 'time': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDateTime),
  79446. 'magvar': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79447. 'geoidheight': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79448. 'name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79449. 'cmt': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79450. 'desc': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79451. 'src': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79452. 'link': ol.format.GPX.parseLink_,
  79453. 'sym': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79454. 'type': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79455. 'fix': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  79456. 'sat': ol.xml.makeObjectPropertySetter(
  79457. ol.format.XSD.readNonNegativeInteger),
  79458. 'hdop': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79459. 'vdop': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79460. 'pdop': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79461. 'ageofdgpsdata':
  79462. ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  79463. 'dgpsid':
  79464. ol.xml.makeObjectPropertySetter(ol.format.XSD.readNonNegativeInteger),
  79465. 'extensions': ol.format.GPX.parseExtensions_
  79466. });
  79467. /**
  79468. * @param {Array.<ol.Feature>} features
  79469. * @private
  79470. */
  79471. ol.format.GPX.prototype.handleReadExtensions_ = function(features) {
  79472. if (!features) {
  79473. features = [];
  79474. }
  79475. for (var i = 0, ii = features.length; i < ii; ++i) {
  79476. var feature = features[i];
  79477. if (this.readExtensions_) {
  79478. var extensionsNode = feature.get('extensionsNode_') || null;
  79479. this.readExtensions_(feature, extensionsNode);
  79480. }
  79481. feature.set('extensionsNode_', undefined);
  79482. }
  79483. };
  79484. /**
  79485. * Read the first feature from a GPX source.
  79486. *
  79487. * @function
  79488. * @param {Document|Node|Object|string} source Source.
  79489. * @param {olx.format.ReadOptions=} opt_options Read options.
  79490. * @return {ol.Feature} Feature.
  79491. * @api stable
  79492. */
  79493. ol.format.GPX.prototype.readFeature;
  79494. /**
  79495. * @inheritDoc
  79496. */
  79497. ol.format.GPX.prototype.readFeatureFromNode = function(node, opt_options) {
  79498. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79499. 'node.nodeType should be ELEMENT');
  79500. if (!ol.array.includes(ol.format.GPX.NAMESPACE_URIS_, node.namespaceURI)) {
  79501. return null;
  79502. }
  79503. var featureReader = ol.format.GPX.FEATURE_READER_[node.localName];
  79504. if (!featureReader) {
  79505. return null;
  79506. }
  79507. var feature = featureReader(node, [this.getReadOptions(node, opt_options)]);
  79508. if (!feature) {
  79509. return null;
  79510. }
  79511. this.handleReadExtensions_([feature]);
  79512. return feature;
  79513. };
  79514. /**
  79515. * Read all features from a GPX source.
  79516. *
  79517. * @function
  79518. * @param {Document|Node|Object|string} source Source.
  79519. * @param {olx.format.ReadOptions=} opt_options Read options.
  79520. * @return {Array.<ol.Feature>} Features.
  79521. * @api stable
  79522. */
  79523. ol.format.GPX.prototype.readFeatures;
  79524. /**
  79525. * @inheritDoc
  79526. */
  79527. ol.format.GPX.prototype.readFeaturesFromNode = function(node, opt_options) {
  79528. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  79529. 'node.nodeType should be ELEMENT');
  79530. if (!ol.array.includes(ol.format.GPX.NAMESPACE_URIS_, node.namespaceURI)) {
  79531. return [];
  79532. }
  79533. if (node.localName == 'gpx') {
  79534. var features = ol.xml.pushParseAndPop(
  79535. /** @type {Array.<ol.Feature>} */ ([]), ol.format.GPX.GPX_PARSERS_,
  79536. node, [this.getReadOptions(node, opt_options)]);
  79537. if (features) {
  79538. this.handleReadExtensions_(features);
  79539. return features;
  79540. } else {
  79541. return [];
  79542. }
  79543. }
  79544. return [];
  79545. };
  79546. /**
  79547. * Read the projection from a GPX source.
  79548. *
  79549. * @function
  79550. * @param {Document|Node|Object|string} source Source.
  79551. * @return {ol.proj.Projection} Projection.
  79552. * @api stable
  79553. */
  79554. ol.format.GPX.prototype.readProjection;
  79555. /**
  79556. * @param {Node} node Node.
  79557. * @param {string} value Value for the link's `href` attribute.
  79558. * @param {Array.<*>} objectStack Node stack.
  79559. * @private
  79560. */
  79561. ol.format.GPX.writeLink_ = function(node, value, objectStack) {
  79562. node.setAttribute('href', value);
  79563. var context = objectStack[objectStack.length - 1];
  79564. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  79565. var properties = context['properties'];
  79566. var link = [
  79567. properties['linkText'],
  79568. properties['linkType']
  79569. ];
  79570. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */ ({node: node}),
  79571. ol.format.GPX.LINK_SERIALIZERS_, ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  79572. link, objectStack, ol.format.GPX.LINK_SEQUENCE_);
  79573. };
  79574. /**
  79575. * @param {Node} node Node.
  79576. * @param {ol.Coordinate} coordinate Coordinate.
  79577. * @param {Array.<*>} objectStack Object stack.
  79578. * @private
  79579. */
  79580. ol.format.GPX.writeWptType_ = function(node, coordinate, objectStack) {
  79581. var context = objectStack[objectStack.length - 1];
  79582. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  79583. var parentNode = context.node;
  79584. goog.asserts.assert(ol.xml.isNode(parentNode),
  79585. 'parentNode should be an XML node');
  79586. var namespaceURI = parentNode.namespaceURI;
  79587. var properties = context['properties'];
  79588. //FIXME Projection handling
  79589. ol.xml.setAttributeNS(node, null, 'lat', coordinate[1]);
  79590. ol.xml.setAttributeNS(node, null, 'lon', coordinate[0]);
  79591. var geometryLayout = context['geometryLayout'];
  79592. /* jshint -W086 */
  79593. switch (geometryLayout) {
  79594. case ol.geom.GeometryLayout.XYZM:
  79595. if (coordinate[3] !== 0) {
  79596. properties['time'] = coordinate[3];
  79597. }
  79598. case ol.geom.GeometryLayout.XYZ:
  79599. if (coordinate[2] !== 0) {
  79600. properties['ele'] = coordinate[2];
  79601. }
  79602. break;
  79603. case ol.geom.GeometryLayout.XYM:
  79604. if (coordinate[2] !== 0) {
  79605. properties['time'] = coordinate[2];
  79606. }
  79607. }
  79608. /* jshint +W086 */
  79609. var orderedKeys = ol.format.GPX.WPT_TYPE_SEQUENCE_[namespaceURI];
  79610. var values = ol.xml.makeSequence(properties, orderedKeys);
  79611. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  79612. ({node: node, 'properties': properties}),
  79613. ol.format.GPX.WPT_TYPE_SERIALIZERS_, ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  79614. values, objectStack, orderedKeys);
  79615. };
  79616. /**
  79617. * @param {Node} node Node.
  79618. * @param {ol.Feature} feature Feature.
  79619. * @param {Array.<*>} objectStack Object stack.
  79620. * @private
  79621. */
  79622. ol.format.GPX.writeRte_ = function(node, feature, objectStack) {
  79623. var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]);
  79624. var properties = feature.getProperties();
  79625. var context = {node: node, 'properties': properties};
  79626. var geometry = feature.getGeometry();
  79627. if (geometry) {
  79628. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  79629. 'geometry should be an ol.geom.LineString');
  79630. geometry = /** @type {ol.geom.LineString} */
  79631. (ol.format.Feature.transformWithOptions(geometry, true, options));
  79632. context['geometryLayout'] = geometry.getLayout();
  79633. properties['rtept'] = geometry.getCoordinates();
  79634. }
  79635. var parentNode = objectStack[objectStack.length - 1].node;
  79636. var orderedKeys = ol.format.GPX.RTE_SEQUENCE_[parentNode.namespaceURI];
  79637. var values = ol.xml.makeSequence(properties, orderedKeys);
  79638. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */ (context),
  79639. ol.format.GPX.RTE_SERIALIZERS_, ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  79640. values, objectStack, orderedKeys);
  79641. };
  79642. /**
  79643. * @param {Node} node Node.
  79644. * @param {ol.Feature} feature Feature.
  79645. * @param {Array.<*>} objectStack Object stack.
  79646. * @private
  79647. */
  79648. ol.format.GPX.writeTrk_ = function(node, feature, objectStack) {
  79649. var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]);
  79650. var properties = feature.getProperties();
  79651. var context = {node: node, 'properties': properties};
  79652. var geometry = feature.getGeometry();
  79653. if (geometry) {
  79654. goog.asserts.assertInstanceof(geometry, ol.geom.MultiLineString,
  79655. 'geometry should be an ol.geom.MultiLineString');
  79656. geometry = /** @type {ol.geom.MultiLineString} */
  79657. (ol.format.Feature.transformWithOptions(geometry, true, options));
  79658. properties['trkseg'] = geometry.getLineStrings();
  79659. }
  79660. var parentNode = objectStack[objectStack.length - 1].node;
  79661. var orderedKeys = ol.format.GPX.TRK_SEQUENCE_[parentNode.namespaceURI];
  79662. var values = ol.xml.makeSequence(properties, orderedKeys);
  79663. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */ (context),
  79664. ol.format.GPX.TRK_SERIALIZERS_, ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  79665. values, objectStack, orderedKeys);
  79666. };
  79667. /**
  79668. * @param {Node} node Node.
  79669. * @param {ol.geom.LineString} lineString LineString.
  79670. * @param {Array.<*>} objectStack Object stack.
  79671. * @private
  79672. */
  79673. ol.format.GPX.writeTrkSeg_ = function(node, lineString, objectStack) {
  79674. var context = {node: node, 'geometryLayout': lineString.getLayout(),
  79675. 'properties': {}};
  79676. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */ (context),
  79677. ol.format.GPX.TRKSEG_SERIALIZERS_, ol.format.GPX.TRKSEG_NODE_FACTORY_,
  79678. lineString.getCoordinates(), objectStack);
  79679. };
  79680. /**
  79681. * @param {Node} node Node.
  79682. * @param {ol.Feature} feature Feature.
  79683. * @param {Array.<*>} objectStack Object stack.
  79684. * @private
  79685. */
  79686. ol.format.GPX.writeWpt_ = function(node, feature, objectStack) {
  79687. var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]);
  79688. var context = objectStack[objectStack.length - 1];
  79689. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  79690. context['properties'] = feature.getProperties();
  79691. var geometry = feature.getGeometry();
  79692. if (geometry) {
  79693. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  79694. 'geometry should be an ol.geom.Point');
  79695. geometry = /** @type {ol.geom.Point} */
  79696. (ol.format.Feature.transformWithOptions(geometry, true, options));
  79697. context['geometryLayout'] = geometry.getLayout();
  79698. ol.format.GPX.writeWptType_(node, geometry.getCoordinates(), objectStack);
  79699. }
  79700. };
  79701. /**
  79702. * @const
  79703. * @type {Array.<string>}
  79704. * @private
  79705. */
  79706. ol.format.GPX.LINK_SEQUENCE_ = ['text', 'type'];
  79707. /**
  79708. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79709. * @private
  79710. */
  79711. ol.format.GPX.LINK_SERIALIZERS_ = ol.xml.makeStructureNS(
  79712. ol.format.GPX.NAMESPACE_URIS_, {
  79713. 'text': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79714. 'type': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)
  79715. });
  79716. /**
  79717. * @const
  79718. * @type {Object.<string, Array.<string>>}
  79719. * @private
  79720. */
  79721. ol.format.GPX.RTE_SEQUENCE_ = ol.xml.makeStructureNS(
  79722. ol.format.GPX.NAMESPACE_URIS_, [
  79723. 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'rtept'
  79724. ]);
  79725. /**
  79726. * @const
  79727. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79728. * @private
  79729. */
  79730. ol.format.GPX.RTE_SERIALIZERS_ = ol.xml.makeStructureNS(
  79731. ol.format.GPX.NAMESPACE_URIS_, {
  79732. 'name': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79733. 'cmt': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79734. 'desc': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79735. 'src': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79736. 'link': ol.xml.makeChildAppender(ol.format.GPX.writeLink_),
  79737. 'number': ol.xml.makeChildAppender(
  79738. ol.format.XSD.writeNonNegativeIntegerTextNode),
  79739. 'type': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79740. 'rtept': ol.xml.makeArraySerializer(ol.xml.makeChildAppender(
  79741. ol.format.GPX.writeWptType_))
  79742. });
  79743. /**
  79744. * @const
  79745. * @type {Object.<string, Array.<string>>}
  79746. * @private
  79747. */
  79748. ol.format.GPX.TRK_SEQUENCE_ = ol.xml.makeStructureNS(
  79749. ol.format.GPX.NAMESPACE_URIS_, [
  79750. 'name', 'cmt', 'desc', 'src', 'link', 'number', 'type', 'trkseg'
  79751. ]);
  79752. /**
  79753. * @const
  79754. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79755. * @private
  79756. */
  79757. ol.format.GPX.TRK_SERIALIZERS_ = ol.xml.makeStructureNS(
  79758. ol.format.GPX.NAMESPACE_URIS_, {
  79759. 'name': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79760. 'cmt': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79761. 'desc': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79762. 'src': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79763. 'link': ol.xml.makeChildAppender(ol.format.GPX.writeLink_),
  79764. 'number': ol.xml.makeChildAppender(
  79765. ol.format.XSD.writeNonNegativeIntegerTextNode),
  79766. 'type': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79767. 'trkseg': ol.xml.makeArraySerializer(ol.xml.makeChildAppender(
  79768. ol.format.GPX.writeTrkSeg_))
  79769. });
  79770. /**
  79771. * @const
  79772. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  79773. * @private
  79774. */
  79775. ol.format.GPX.TRKSEG_NODE_FACTORY_ = ol.xml.makeSimpleNodeFactory('trkpt');
  79776. /**
  79777. * @const
  79778. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79779. * @private
  79780. */
  79781. ol.format.GPX.TRKSEG_SERIALIZERS_ = ol.xml.makeStructureNS(
  79782. ol.format.GPX.NAMESPACE_URIS_, {
  79783. 'trkpt': ol.xml.makeChildAppender(ol.format.GPX.writeWptType_)
  79784. });
  79785. /**
  79786. * @const
  79787. * @type {Object.<string, Array.<string>>}
  79788. * @private
  79789. */
  79790. ol.format.GPX.WPT_TYPE_SEQUENCE_ = ol.xml.makeStructureNS(
  79791. ol.format.GPX.NAMESPACE_URIS_, [
  79792. 'ele', 'time', 'magvar', 'geoidheight', 'name', 'cmt', 'desc', 'src',
  79793. 'link', 'sym', 'type', 'fix', 'sat', 'hdop', 'vdop', 'pdop',
  79794. 'ageofdgpsdata', 'dgpsid'
  79795. ]);
  79796. /**
  79797. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79798. * @private
  79799. */
  79800. ol.format.GPX.WPT_TYPE_SERIALIZERS_ = ol.xml.makeStructureNS(
  79801. ol.format.GPX.NAMESPACE_URIS_, {
  79802. 'ele': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  79803. 'time': ol.xml.makeChildAppender(ol.format.XSD.writeDateTimeTextNode),
  79804. 'magvar': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  79805. 'geoidheight': ol.xml.makeChildAppender(
  79806. ol.format.XSD.writeDecimalTextNode),
  79807. 'name': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79808. 'cmt': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79809. 'desc': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79810. 'src': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79811. 'link': ol.xml.makeChildAppender(ol.format.GPX.writeLink_),
  79812. 'sym': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79813. 'type': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79814. 'fix': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  79815. 'sat': ol.xml.makeChildAppender(
  79816. ol.format.XSD.writeNonNegativeIntegerTextNode),
  79817. 'hdop': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  79818. 'vdop': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  79819. 'pdop': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  79820. 'ageofdgpsdata': ol.xml.makeChildAppender(
  79821. ol.format.XSD.writeDecimalTextNode),
  79822. 'dgpsid': ol.xml.makeChildAppender(
  79823. ol.format.XSD.writeNonNegativeIntegerTextNode)
  79824. });
  79825. /**
  79826. * @const
  79827. * @type {Object.<string, string>}
  79828. * @private
  79829. */
  79830. ol.format.GPX.GEOMETRY_TYPE_TO_NODENAME_ = {
  79831. 'Point': 'wpt',
  79832. 'LineString': 'rte',
  79833. 'MultiLineString': 'trk'
  79834. };
  79835. /**
  79836. * @const
  79837. * @param {*} value Value.
  79838. * @param {Array.<*>} objectStack Object stack.
  79839. * @param {string=} opt_nodeName Node name.
  79840. * @return {Node|undefined} Node.
  79841. * @private
  79842. */
  79843. ol.format.GPX.GPX_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) {
  79844. goog.asserts.assertInstanceof(value, ol.Feature,
  79845. 'value should be an ol.Feature');
  79846. var geometry = value.getGeometry();
  79847. if (geometry) {
  79848. var parentNode = objectStack[objectStack.length - 1].node;
  79849. goog.asserts.assert(ol.xml.isNode(parentNode),
  79850. 'parentNode should be an XML node');
  79851. return ol.xml.createElementNS(parentNode.namespaceURI,
  79852. ol.format.GPX.GEOMETRY_TYPE_TO_NODENAME_[geometry.getType()]);
  79853. }
  79854. };
  79855. /**
  79856. * @const
  79857. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  79858. * @private
  79859. */
  79860. ol.format.GPX.GPX_SERIALIZERS_ = ol.xml.makeStructureNS(
  79861. ol.format.GPX.NAMESPACE_URIS_, {
  79862. 'rte': ol.xml.makeChildAppender(ol.format.GPX.writeRte_),
  79863. 'trk': ol.xml.makeChildAppender(ol.format.GPX.writeTrk_),
  79864. 'wpt': ol.xml.makeChildAppender(ol.format.GPX.writeWpt_)
  79865. });
  79866. /**
  79867. * Encode an array of features in the GPX format.
  79868. *
  79869. * @function
  79870. * @param {Array.<ol.Feature>} features Features.
  79871. * @param {olx.format.WriteOptions=} opt_options Write options.
  79872. * @return {string} Result.
  79873. * @api stable
  79874. */
  79875. ol.format.GPX.prototype.writeFeatures;
  79876. /**
  79877. * Encode an array of features in the GPX format as an XML node.
  79878. *
  79879. * @param {Array.<ol.Feature>} features Features.
  79880. * @param {olx.format.WriteOptions=} opt_options Options.
  79881. * @return {Node} Node.
  79882. * @api
  79883. */
  79884. ol.format.GPX.prototype.writeFeaturesNode = function(features, opt_options) {
  79885. opt_options = this.adaptOptions(opt_options);
  79886. //FIXME Serialize metadata
  79887. var gpx = ol.xml.createElementNS('http://www.topografix.com/GPX/1/1', 'gpx');
  79888. ol.xml.pushSerializeAndPop(/** @type {ol.xml.NodeStackItem} */
  79889. ({node: gpx}), ol.format.GPX.GPX_SERIALIZERS_,
  79890. ol.format.GPX.GPX_NODE_FACTORY_, features, [opt_options]);
  79891. return gpx;
  79892. };
  79893. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  79894. //
  79895. // Licensed under the Apache License, Version 2.0 (the "License");
  79896. // you may not use this file except in compliance with the License.
  79897. // You may obtain a copy of the License at
  79898. //
  79899. // http://www.apache.org/licenses/LICENSE-2.0
  79900. //
  79901. // Unless required by applicable law or agreed to in writing, software
  79902. // distributed under the License is distributed on an "AS-IS" BASIS,
  79903. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79904. // See the License for the specific language governing permissions and
  79905. // limitations under the License.
  79906. /**
  79907. * @fileoverview Utilities for string newlines.
  79908. * @author nnaze@google.com (Nathan Naze)
  79909. */
  79910. /**
  79911. * Namespace for string utilities
  79912. */
  79913. goog.provide('goog.string.newlines');
  79914. goog.provide('goog.string.newlines.Line');
  79915. goog.require('goog.array');
  79916. /**
  79917. * Splits a string into lines, properly handling universal newlines.
  79918. * @param {string} str String to split.
  79919. * @param {boolean=} opt_keepNewlines Whether to keep the newlines in the
  79920. * resulting strings. Defaults to false.
  79921. * @return {!Array<string>} String split into lines.
  79922. */
  79923. goog.string.newlines.splitLines = function(str, opt_keepNewlines) {
  79924. var lines = goog.string.newlines.getLines(str);
  79925. return goog.array.map(lines, function(line) {
  79926. return opt_keepNewlines ? line.getFullLine() : line.getContent();
  79927. });
  79928. };
  79929. /**
  79930. * Line metadata class that records the start/end indicies of lines
  79931. * in a string. Can be used to implement common newline use cases such as
  79932. * splitLines() or determining line/column of an index in a string.
  79933. * Also implements methods to get line contents.
  79934. *
  79935. * Indexes are expressed as string indicies into string.substring(), inclusive
  79936. * at the start, exclusive at the end.
  79937. *
  79938. * Create an array of these with goog.string.newlines.getLines().
  79939. * @param {string} string The original string.
  79940. * @param {number} startLineIndex The index of the start of the line.
  79941. * @param {number} endContentIndex The index of the end of the line, excluding
  79942. * newlines.
  79943. * @param {number} endLineIndex The index of the end of the line, index
  79944. * newlines.
  79945. * @constructor
  79946. * @struct
  79947. * @final
  79948. */
  79949. goog.string.newlines.Line = function(string, startLineIndex,
  79950. endContentIndex, endLineIndex) {
  79951. /**
  79952. * The original string.
  79953. * @type {string}
  79954. */
  79955. this.string = string;
  79956. /**
  79957. * Index of the start of the line.
  79958. * @type {number}
  79959. */
  79960. this.startLineIndex = startLineIndex;
  79961. /**
  79962. * Index of the end of the line, excluding any newline characters.
  79963. * Index is the first character after the line, suitable for
  79964. * String.substring().
  79965. * @type {number}
  79966. */
  79967. this.endContentIndex = endContentIndex;
  79968. /**
  79969. * Index of the end of the line, excluding any newline characters.
  79970. * Index is the first character after the line, suitable for
  79971. * String.substring().
  79972. * @type {number}
  79973. */
  79974. this.endLineIndex = endLineIndex;
  79975. };
  79976. /**
  79977. * @return {string} The content of the line, excluding any newline characters.
  79978. */
  79979. goog.string.newlines.Line.prototype.getContent = function() {
  79980. return this.string.substring(this.startLineIndex, this.endContentIndex);
  79981. };
  79982. /**
  79983. * @return {string} The full line, including any newline characters.
  79984. */
  79985. goog.string.newlines.Line.prototype.getFullLine = function() {
  79986. return this.string.substring(this.startLineIndex, this.endLineIndex);
  79987. };
  79988. /**
  79989. * @return {string} The newline characters, if any ('\n', \r', '\r\n', '', etc).
  79990. */
  79991. goog.string.newlines.Line.prototype.getNewline = function() {
  79992. return this.string.substring(this.endContentIndex, this.endLineIndex);
  79993. };
  79994. /**
  79995. * Splits a string into an array of line metadata.
  79996. * @param {string} str String to split.
  79997. * @return {!Array<!goog.string.newlines.Line>} Array of line metadata.
  79998. */
  79999. goog.string.newlines.getLines = function(str) {
  80000. // We use the constructor because literals are evaluated only once in
  80001. // < ES 3.1.
  80002. // See http://www.mail-archive.com/es-discuss@mozilla.org/msg01796.html
  80003. var re = RegExp('\r\n|\r|\n', 'g');
  80004. var sliceIndex = 0;
  80005. var result;
  80006. var lines = [];
  80007. while (result = re.exec(str)) {
  80008. var line = new goog.string.newlines.Line(
  80009. str, sliceIndex, result.index, result.index + result[0].length);
  80010. lines.push(line);
  80011. // remember where to start the slice from
  80012. sliceIndex = re.lastIndex;
  80013. }
  80014. // If the string does not end with a newline, add the last line.
  80015. if (sliceIndex < str.length) {
  80016. var line = new goog.string.newlines.Line(
  80017. str, sliceIndex, str.length, str.length);
  80018. lines.push(line);
  80019. }
  80020. return lines;
  80021. };
  80022. goog.provide('ol.format.TextFeature');
  80023. goog.require('goog.asserts');
  80024. goog.require('ol.format.Feature');
  80025. goog.require('ol.format.FormatType');
  80026. /**
  80027. * @classdesc
  80028. * Abstract base class; normally only used for creating subclasses and not
  80029. * instantiated in apps.
  80030. * Base class for text feature formats.
  80031. *
  80032. * @constructor
  80033. * @extends {ol.format.Feature}
  80034. */
  80035. ol.format.TextFeature = function() {
  80036. goog.base(this);
  80037. };
  80038. goog.inherits(ol.format.TextFeature, ol.format.Feature);
  80039. /**
  80040. * @param {Document|Node|Object|string} source Source.
  80041. * @private
  80042. * @return {string} Text.
  80043. */
  80044. ol.format.TextFeature.prototype.getText_ = function(source) {
  80045. if (goog.isString(source)) {
  80046. return source;
  80047. } else {
  80048. goog.asserts.fail();
  80049. return '';
  80050. }
  80051. };
  80052. /**
  80053. * @inheritDoc
  80054. */
  80055. ol.format.TextFeature.prototype.getType = function() {
  80056. return ol.format.FormatType.TEXT;
  80057. };
  80058. /**
  80059. * @inheritDoc
  80060. */
  80061. ol.format.TextFeature.prototype.readFeature = function(source, opt_options) {
  80062. return this.readFeatureFromText(
  80063. this.getText_(source), this.adaptOptions(opt_options));
  80064. };
  80065. /**
  80066. * @param {string} text Text.
  80067. * @param {olx.format.ReadOptions=} opt_options Read options.
  80068. * @protected
  80069. * @return {ol.Feature} Feature.
  80070. */
  80071. ol.format.TextFeature.prototype.readFeatureFromText = goog.abstractMethod;
  80072. /**
  80073. * @inheritDoc
  80074. */
  80075. ol.format.TextFeature.prototype.readFeatures = function(source, opt_options) {
  80076. return this.readFeaturesFromText(
  80077. this.getText_(source), this.adaptOptions(opt_options));
  80078. };
  80079. /**
  80080. * @param {string} text Text.
  80081. * @param {olx.format.ReadOptions=} opt_options Read options.
  80082. * @protected
  80083. * @return {Array.<ol.Feature>} Features.
  80084. */
  80085. ol.format.TextFeature.prototype.readFeaturesFromText = goog.abstractMethod;
  80086. /**
  80087. * @inheritDoc
  80088. */
  80089. ol.format.TextFeature.prototype.readGeometry = function(source, opt_options) {
  80090. return this.readGeometryFromText(
  80091. this.getText_(source), this.adaptOptions(opt_options));
  80092. };
  80093. /**
  80094. * @param {string} text Text.
  80095. * @param {olx.format.ReadOptions=} opt_options Read options.
  80096. * @protected
  80097. * @return {ol.geom.Geometry} Geometry.
  80098. */
  80099. ol.format.TextFeature.prototype.readGeometryFromText = goog.abstractMethod;
  80100. /**
  80101. * @inheritDoc
  80102. */
  80103. ol.format.TextFeature.prototype.readProjection = function(source) {
  80104. return this.readProjectionFromText(this.getText_(source));
  80105. };
  80106. /**
  80107. * @param {string} text Text.
  80108. * @protected
  80109. * @return {ol.proj.Projection} Projection.
  80110. */
  80111. ol.format.TextFeature.prototype.readProjectionFromText = function(text) {
  80112. return this.defaultDataProjection;
  80113. };
  80114. /**
  80115. * @inheritDoc
  80116. */
  80117. ol.format.TextFeature.prototype.writeFeature = function(feature, opt_options) {
  80118. return this.writeFeatureText(feature, this.adaptOptions(opt_options));
  80119. };
  80120. /**
  80121. * @param {ol.Feature} feature Features.
  80122. * @param {olx.format.WriteOptions=} opt_options Write options.
  80123. * @protected
  80124. * @return {string} Text.
  80125. */
  80126. ol.format.TextFeature.prototype.writeFeatureText = goog.abstractMethod;
  80127. /**
  80128. * @inheritDoc
  80129. */
  80130. ol.format.TextFeature.prototype.writeFeatures = function(
  80131. features, opt_options) {
  80132. return this.writeFeaturesText(features, this.adaptOptions(opt_options));
  80133. };
  80134. /**
  80135. * @param {Array.<ol.Feature>} features Features.
  80136. * @param {olx.format.WriteOptions=} opt_options Write options.
  80137. * @protected
  80138. * @return {string} Text.
  80139. */
  80140. ol.format.TextFeature.prototype.writeFeaturesText = goog.abstractMethod;
  80141. /**
  80142. * @inheritDoc
  80143. */
  80144. ol.format.TextFeature.prototype.writeGeometry = function(
  80145. geometry, opt_options) {
  80146. return this.writeGeometryText(geometry, this.adaptOptions(opt_options));
  80147. };
  80148. /**
  80149. * @param {ol.geom.Geometry} geometry Geometry.
  80150. * @param {olx.format.WriteOptions=} opt_options Write options.
  80151. * @protected
  80152. * @return {string} Text.
  80153. */
  80154. ol.format.TextFeature.prototype.writeGeometryText = goog.abstractMethod;
  80155. goog.provide('ol.format.IGC');
  80156. goog.provide('ol.format.IGCZ');
  80157. goog.require('goog.asserts');
  80158. goog.require('goog.string');
  80159. goog.require('goog.string.newlines');
  80160. goog.require('ol.Feature');
  80161. goog.require('ol.format.Feature');
  80162. goog.require('ol.format.TextFeature');
  80163. goog.require('ol.geom.GeometryLayout');
  80164. goog.require('ol.geom.LineString');
  80165. goog.require('ol.proj');
  80166. /**
  80167. * IGC altitude/z. One of 'barometric', 'gps', 'none'.
  80168. * @enum {string}
  80169. * @api
  80170. */
  80171. ol.format.IGCZ = {
  80172. BAROMETRIC: 'barometric',
  80173. GPS: 'gps',
  80174. NONE: 'none'
  80175. };
  80176. /**
  80177. * @classdesc
  80178. * Feature format for `*.igc` flight recording files.
  80179. *
  80180. * @constructor
  80181. * @extends {ol.format.TextFeature}
  80182. * @param {olx.format.IGCOptions=} opt_options Options.
  80183. * @api
  80184. */
  80185. ol.format.IGC = function(opt_options) {
  80186. var options = opt_options ? opt_options : {};
  80187. goog.base(this);
  80188. /**
  80189. * @inheritDoc
  80190. */
  80191. this.defaultDataProjection = ol.proj.get('EPSG:4326');
  80192. /**
  80193. * @private
  80194. * @type {ol.format.IGCZ}
  80195. */
  80196. this.altitudeMode_ = options.altitudeMode ?
  80197. options.altitudeMode : ol.format.IGCZ.NONE;
  80198. };
  80199. goog.inherits(ol.format.IGC, ol.format.TextFeature);
  80200. /**
  80201. * @const
  80202. * @type {Array.<string>}
  80203. * @private
  80204. */
  80205. ol.format.IGC.EXTENSIONS_ = ['.igc'];
  80206. /**
  80207. * @const
  80208. * @type {RegExp}
  80209. * @private
  80210. */
  80211. ol.format.IGC.B_RECORD_RE_ =
  80212. /^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/;
  80213. /**
  80214. * @const
  80215. * @type {RegExp}
  80216. * @private
  80217. */
  80218. ol.format.IGC.H_RECORD_RE_ = /^H.([A-Z]{3}).*?:(.*)/;
  80219. /**
  80220. * @const
  80221. * @type {RegExp}
  80222. * @private
  80223. */
  80224. ol.format.IGC.HFDTE_RECORD_RE_ = /^HFDTE(\d{2})(\d{2})(\d{2})/;
  80225. /**
  80226. * @inheritDoc
  80227. */
  80228. ol.format.IGC.prototype.getExtensions = function() {
  80229. return ol.format.IGC.EXTENSIONS_;
  80230. };
  80231. /**
  80232. * Read the feature from the IGC source.
  80233. *
  80234. * @function
  80235. * @param {Document|Node|Object|string} source Source.
  80236. * @param {olx.format.ReadOptions=} opt_options Read options.
  80237. * @return {ol.Feature} Feature.
  80238. * @api
  80239. */
  80240. ol.format.IGC.prototype.readFeature;
  80241. /**
  80242. * @inheritDoc
  80243. */
  80244. ol.format.IGC.prototype.readFeatureFromText = function(text, opt_options) {
  80245. var altitudeMode = this.altitudeMode_;
  80246. var lines = goog.string.newlines.splitLines(text);
  80247. /** @type {Object.<string, string>} */
  80248. var properties = {};
  80249. var flatCoordinates = [];
  80250. var year = 2000;
  80251. var month = 0;
  80252. var day = 1;
  80253. var i, ii;
  80254. for (i = 0, ii = lines.length; i < ii; ++i) {
  80255. var line = lines[i];
  80256. var m;
  80257. if (line.charAt(0) == 'B') {
  80258. m = ol.format.IGC.B_RECORD_RE_.exec(line);
  80259. if (m) {
  80260. var hour = parseInt(m[1], 10);
  80261. var minute = parseInt(m[2], 10);
  80262. var second = parseInt(m[3], 10);
  80263. var y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000;
  80264. if (m[6] == 'S') {
  80265. y = -y;
  80266. }
  80267. var x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000;
  80268. if (m[9] == 'W') {
  80269. x = -x;
  80270. }
  80271. flatCoordinates.push(x, y);
  80272. if (altitudeMode != ol.format.IGCZ.NONE) {
  80273. var z;
  80274. if (altitudeMode == ol.format.IGCZ.GPS) {
  80275. z = parseInt(m[11], 10);
  80276. } else if (altitudeMode == ol.format.IGCZ.BAROMETRIC) {
  80277. z = parseInt(m[12], 10);
  80278. } else {
  80279. goog.asserts.fail();
  80280. z = 0;
  80281. }
  80282. flatCoordinates.push(z);
  80283. }
  80284. var dateTime = Date.UTC(year, month, day, hour, minute, second);
  80285. flatCoordinates.push(dateTime / 1000);
  80286. }
  80287. } else if (line.charAt(0) == 'H') {
  80288. m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
  80289. if (m) {
  80290. day = parseInt(m[1], 10);
  80291. month = parseInt(m[2], 10) - 1;
  80292. year = 2000 + parseInt(m[3], 10);
  80293. } else {
  80294. m = ol.format.IGC.H_RECORD_RE_.exec(line);
  80295. if (m) {
  80296. properties[m[1]] = m[2].trim();
  80297. m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
  80298. }
  80299. }
  80300. }
  80301. }
  80302. if (flatCoordinates.length === 0) {
  80303. return null;
  80304. }
  80305. var lineString = new ol.geom.LineString(null);
  80306. var layout = altitudeMode == ol.format.IGCZ.NONE ?
  80307. ol.geom.GeometryLayout.XYM : ol.geom.GeometryLayout.XYZM;
  80308. lineString.setFlatCoordinates(layout, flatCoordinates);
  80309. var feature = new ol.Feature(ol.format.Feature.transformWithOptions(
  80310. lineString, false, opt_options));
  80311. feature.setProperties(properties);
  80312. return feature;
  80313. };
  80314. /**
  80315. * Read the feature from the source. As IGC sources contain a single
  80316. * feature, this will return the feature in an array.
  80317. *
  80318. * @function
  80319. * @param {Document|Node|Object|string} source Source.
  80320. * @param {olx.format.ReadOptions=} opt_options Read options.
  80321. * @return {Array.<ol.Feature>} Features.
  80322. * @api
  80323. */
  80324. ol.format.IGC.prototype.readFeatures;
  80325. /**
  80326. * @inheritDoc
  80327. */
  80328. ol.format.IGC.prototype.readFeaturesFromText = function(text, opt_options) {
  80329. var feature = this.readFeatureFromText(text, opt_options);
  80330. if (feature) {
  80331. return [feature];
  80332. } else {
  80333. return [];
  80334. }
  80335. };
  80336. /**
  80337. * Read the projection from the IGC source.
  80338. *
  80339. * @function
  80340. * @param {Document|Node|Object|string} source Source.
  80341. * @return {ol.proj.Projection} Projection.
  80342. * @api
  80343. */
  80344. ol.format.IGC.prototype.readProjection;
  80345. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  80346. //
  80347. // Licensed under the Apache License, Version 2.0 (the "License");
  80348. // you may not use this file except in compliance with the License.
  80349. // You may obtain a copy of the License at
  80350. //
  80351. // http://www.apache.org/licenses/LICENSE-2.0
  80352. //
  80353. // Unless required by applicable law or agreed to in writing, software
  80354. // distributed under the License is distributed on an "AS-IS" BASIS,
  80355. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  80356. // See the License for the specific language governing permissions and
  80357. // limitations under the License.
  80358. /**
  80359. * @fileoverview Class for parsing and formatting URIs.
  80360. *
  80361. * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to
  80362. * create a new instance of the goog.Uri object from Uri parts.
  80363. *
  80364. * e.g: <code>var myUri = new goog.Uri(window.location);</code>
  80365. *
  80366. * Implements RFC 3986 for parsing/formatting URIs.
  80367. * http://www.ietf.org/rfc/rfc3986.txt
  80368. *
  80369. * Some changes have been made to the interface (more like .NETs), though the
  80370. * internal representation is now of un-encoded parts, this will change the
  80371. * behavior slightly.
  80372. *
  80373. */
  80374. goog.provide('goog.Uri');
  80375. goog.provide('goog.Uri.QueryData');
  80376. goog.require('goog.array');
  80377. goog.require('goog.string');
  80378. goog.require('goog.structs');
  80379. goog.require('goog.structs.Map');
  80380. goog.require('goog.uri.utils');
  80381. goog.require('goog.uri.utils.ComponentIndex');
  80382. goog.require('goog.uri.utils.StandardQueryParam');
  80383. /**
  80384. * This class contains setters and getters for the parts of the URI.
  80385. * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part
  80386. * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the
  80387. * decoded path, <code>/foo bar</code>.
  80388. *
  80389. * Reserved characters (see RFC 3986 section 2.2) can be present in
  80390. * their percent-encoded form in scheme, domain, and path URI components and
  80391. * will not be auto-decoded. For example:
  80392. * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will
  80393. * return <code>relative/path%2fto/resource</code>.
  80394. *
  80395. * The constructor accepts an optional unparsed, raw URI string. The parser
  80396. * is relaxed, so special characters that aren't escaped but don't cause
  80397. * ambiguities will not cause parse failures.
  80398. *
  80399. * All setters return <code>this</code> and so may be chained, a la
  80400. * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.
  80401. *
  80402. * @param {*=} opt_uri Optional string URI to parse
  80403. * (use goog.Uri.create() to create a URI from parts), or if
  80404. * a goog.Uri is passed, a clone is created.
  80405. * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore
  80406. * the case of the parameter name.
  80407. *
  80408. * @throws URIError If opt_uri is provided and URI is malformed (that is,
  80409. * if decodeURIComponent fails on any of the URI components).
  80410. * @constructor
  80411. * @struct
  80412. */
  80413. goog.Uri = function(opt_uri, opt_ignoreCase) {
  80414. /**
  80415. * Scheme such as "http".
  80416. * @private {string}
  80417. */
  80418. this.scheme_ = '';
  80419. /**
  80420. * User credentials in the form "username:password".
  80421. * @private {string}
  80422. */
  80423. this.userInfo_ = '';
  80424. /**
  80425. * Domain part, e.g. "www.google.com".
  80426. * @private {string}
  80427. */
  80428. this.domain_ = '';
  80429. /**
  80430. * Port, e.g. 8080.
  80431. * @private {?number}
  80432. */
  80433. this.port_ = null;
  80434. /**
  80435. * Path, e.g. "/tests/img.png".
  80436. * @private {string}
  80437. */
  80438. this.path_ = '';
  80439. /**
  80440. * The fragment without the #.
  80441. * @private {string}
  80442. */
  80443. this.fragment_ = '';
  80444. /**
  80445. * Whether or not this Uri should be treated as Read Only.
  80446. * @private {boolean}
  80447. */
  80448. this.isReadOnly_ = false;
  80449. /**
  80450. * Whether or not to ignore case when comparing query params.
  80451. * @private {boolean}
  80452. */
  80453. this.ignoreCase_ = false;
  80454. /**
  80455. * Object representing query data.
  80456. * @private {!goog.Uri.QueryData}
  80457. */
  80458. this.queryData_;
  80459. // Parse in the uri string
  80460. var m;
  80461. if (opt_uri instanceof goog.Uri) {
  80462. this.ignoreCase_ = goog.isDef(opt_ignoreCase) ?
  80463. opt_ignoreCase : opt_uri.getIgnoreCase();
  80464. this.setScheme(opt_uri.getScheme());
  80465. this.setUserInfo(opt_uri.getUserInfo());
  80466. this.setDomain(opt_uri.getDomain());
  80467. this.setPort(opt_uri.getPort());
  80468. this.setPath(opt_uri.getPath());
  80469. this.setQueryData(opt_uri.getQueryData().clone());
  80470. this.setFragment(opt_uri.getFragment());
  80471. } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {
  80472. this.ignoreCase_ = !!opt_ignoreCase;
  80473. // Set the parts -- decoding as we do so.
  80474. // COMPATABILITY NOTE - In IE, unmatched fields may be empty strings,
  80475. // whereas in other browsers they will be undefined.
  80476. this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);
  80477. this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);
  80478. this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);
  80479. this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);
  80480. this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);
  80481. this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);
  80482. this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);
  80483. } else {
  80484. this.ignoreCase_ = !!opt_ignoreCase;
  80485. this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);
  80486. }
  80487. };
  80488. /**
  80489. * If true, we preserve the type of query parameters set programmatically.
  80490. *
  80491. * This means that if you set a parameter to a boolean, and then call
  80492. * getParameterValue, you will get a boolean back.
  80493. *
  80494. * If false, we will coerce parameters to strings, just as they would
  80495. * appear in real URIs.
  80496. *
  80497. * TODO(nicksantos): Remove this once people have time to fix all tests.
  80498. *
  80499. * @type {boolean}
  80500. */
  80501. goog.Uri.preserveParameterTypesCompatibilityFlag = false;
  80502. /**
  80503. * Parameter name added to stop caching.
  80504. * @type {string}
  80505. */
  80506. goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;
  80507. /**
  80508. * @return {string} The string form of the url.
  80509. * @override
  80510. */
  80511. goog.Uri.prototype.toString = function() {
  80512. var out = [];
  80513. var scheme = this.getScheme();
  80514. if (scheme) {
  80515. out.push(goog.Uri.encodeSpecialChars_(
  80516. scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), ':');
  80517. }
  80518. var domain = this.getDomain();
  80519. if (domain || scheme == 'file') {
  80520. out.push('//');
  80521. var userInfo = this.getUserInfo();
  80522. if (userInfo) {
  80523. out.push(goog.Uri.encodeSpecialChars_(
  80524. userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), '@');
  80525. }
  80526. out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));
  80527. var port = this.getPort();
  80528. if (port != null) {
  80529. out.push(':', String(port));
  80530. }
  80531. }
  80532. var path = this.getPath();
  80533. if (path) {
  80534. if (this.hasDomain() && path.charAt(0) != '/') {
  80535. out.push('/');
  80536. }
  80537. out.push(goog.Uri.encodeSpecialChars_(
  80538. path,
  80539. path.charAt(0) == '/' ?
  80540. goog.Uri.reDisallowedInAbsolutePath_ :
  80541. goog.Uri.reDisallowedInRelativePath_,
  80542. true));
  80543. }
  80544. var query = this.getEncodedQuery();
  80545. if (query) {
  80546. out.push('?', query);
  80547. }
  80548. var fragment = this.getFragment();
  80549. if (fragment) {
  80550. out.push('#', goog.Uri.encodeSpecialChars_(
  80551. fragment, goog.Uri.reDisallowedInFragment_));
  80552. }
  80553. return out.join('');
  80554. };
  80555. /**
  80556. * Resolves the given relative URI (a goog.Uri object), using the URI
  80557. * represented by this instance as the base URI.
  80558. *
  80559. * There are several kinds of relative URIs:<br>
  80560. * 1. foo - replaces the last part of the path, the whole query and fragment<br>
  80561. * 2. /foo - replaces the the path, the query and fragment<br>
  80562. * 3. //foo - replaces everything from the domain on. foo is a domain name<br>
  80563. * 4. ?foo - replace the query and fragment<br>
  80564. * 5. #foo - replace the fragment only
  80565. *
  80566. * Additionally, if relative URI has a non-empty path, all ".." and "."
  80567. * segments will be resolved, as described in RFC 3986.
  80568. *
  80569. * @param {!goog.Uri} relativeUri The relative URI to resolve.
  80570. * @return {!goog.Uri} The resolved URI.
  80571. */
  80572. goog.Uri.prototype.resolve = function(relativeUri) {
  80573. var absoluteUri = this.clone();
  80574. // we satisfy these conditions by looking for the first part of relativeUri
  80575. // that is not blank and applying defaults to the rest
  80576. var overridden = relativeUri.hasScheme();
  80577. if (overridden) {
  80578. absoluteUri.setScheme(relativeUri.getScheme());
  80579. } else {
  80580. overridden = relativeUri.hasUserInfo();
  80581. }
  80582. if (overridden) {
  80583. absoluteUri.setUserInfo(relativeUri.getUserInfo());
  80584. } else {
  80585. overridden = relativeUri.hasDomain();
  80586. }
  80587. if (overridden) {
  80588. absoluteUri.setDomain(relativeUri.getDomain());
  80589. } else {
  80590. overridden = relativeUri.hasPort();
  80591. }
  80592. var path = relativeUri.getPath();
  80593. if (overridden) {
  80594. absoluteUri.setPort(relativeUri.getPort());
  80595. } else {
  80596. overridden = relativeUri.hasPath();
  80597. if (overridden) {
  80598. // resolve path properly
  80599. if (path.charAt(0) != '/') {
  80600. // path is relative
  80601. if (this.hasDomain() && !this.hasPath()) {
  80602. // RFC 3986, section 5.2.3, case 1
  80603. path = '/' + path;
  80604. } else {
  80605. // RFC 3986, section 5.2.3, case 2
  80606. var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');
  80607. if (lastSlashIndex != -1) {
  80608. path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;
  80609. }
  80610. }
  80611. }
  80612. path = goog.Uri.removeDotSegments(path);
  80613. }
  80614. }
  80615. if (overridden) {
  80616. absoluteUri.setPath(path);
  80617. } else {
  80618. overridden = relativeUri.hasQuery();
  80619. }
  80620. if (overridden) {
  80621. absoluteUri.setQueryData(relativeUri.getDecodedQuery());
  80622. } else {
  80623. overridden = relativeUri.hasFragment();
  80624. }
  80625. if (overridden) {
  80626. absoluteUri.setFragment(relativeUri.getFragment());
  80627. }
  80628. return absoluteUri;
  80629. };
  80630. /**
  80631. * Clones the URI instance.
  80632. * @return {!goog.Uri} New instance of the URI object.
  80633. */
  80634. goog.Uri.prototype.clone = function() {
  80635. return new goog.Uri(this);
  80636. };
  80637. /**
  80638. * @return {string} The encoded scheme/protocol for the URI.
  80639. */
  80640. goog.Uri.prototype.getScheme = function() {
  80641. return this.scheme_;
  80642. };
  80643. /**
  80644. * Sets the scheme/protocol.
  80645. * @throws URIError If opt_decode is true and newScheme is malformed (that is,
  80646. * if decodeURIComponent fails).
  80647. * @param {string} newScheme New scheme value.
  80648. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80649. * @return {!goog.Uri} Reference to this URI object.
  80650. */
  80651. goog.Uri.prototype.setScheme = function(newScheme, opt_decode) {
  80652. this.enforceReadOnly();
  80653. this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) :
  80654. newScheme;
  80655. // remove an : at the end of the scheme so somebody can pass in
  80656. // window.location.protocol
  80657. if (this.scheme_) {
  80658. this.scheme_ = this.scheme_.replace(/:$/, '');
  80659. }
  80660. return this;
  80661. };
  80662. /**
  80663. * @return {boolean} Whether the scheme has been set.
  80664. */
  80665. goog.Uri.prototype.hasScheme = function() {
  80666. return !!this.scheme_;
  80667. };
  80668. /**
  80669. * @return {string} The decoded user info.
  80670. */
  80671. goog.Uri.prototype.getUserInfo = function() {
  80672. return this.userInfo_;
  80673. };
  80674. /**
  80675. * Sets the userInfo.
  80676. * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,
  80677. * if decodeURIComponent fails).
  80678. * @param {string} newUserInfo New userInfo value.
  80679. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80680. * @return {!goog.Uri} Reference to this URI object.
  80681. */
  80682. goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {
  80683. this.enforceReadOnly();
  80684. this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) :
  80685. newUserInfo;
  80686. return this;
  80687. };
  80688. /**
  80689. * @return {boolean} Whether the user info has been set.
  80690. */
  80691. goog.Uri.prototype.hasUserInfo = function() {
  80692. return !!this.userInfo_;
  80693. };
  80694. /**
  80695. * @return {string} The decoded domain.
  80696. */
  80697. goog.Uri.prototype.getDomain = function() {
  80698. return this.domain_;
  80699. };
  80700. /**
  80701. * Sets the domain.
  80702. * @throws URIError If opt_decode is true and newDomain is malformed (that is,
  80703. * if decodeURIComponent fails).
  80704. * @param {string} newDomain New domain value.
  80705. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80706. * @return {!goog.Uri} Reference to this URI object.
  80707. */
  80708. goog.Uri.prototype.setDomain = function(newDomain, opt_decode) {
  80709. this.enforceReadOnly();
  80710. this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) :
  80711. newDomain;
  80712. return this;
  80713. };
  80714. /**
  80715. * @return {boolean} Whether the domain has been set.
  80716. */
  80717. goog.Uri.prototype.hasDomain = function() {
  80718. return !!this.domain_;
  80719. };
  80720. /**
  80721. * @return {?number} The port number.
  80722. */
  80723. goog.Uri.prototype.getPort = function() {
  80724. return this.port_;
  80725. };
  80726. /**
  80727. * Sets the port number.
  80728. * @param {*} newPort Port number. Will be explicitly casted to a number.
  80729. * @return {!goog.Uri} Reference to this URI object.
  80730. */
  80731. goog.Uri.prototype.setPort = function(newPort) {
  80732. this.enforceReadOnly();
  80733. if (newPort) {
  80734. newPort = Number(newPort);
  80735. if (isNaN(newPort) || newPort < 0) {
  80736. throw Error('Bad port number ' + newPort);
  80737. }
  80738. this.port_ = newPort;
  80739. } else {
  80740. this.port_ = null;
  80741. }
  80742. return this;
  80743. };
  80744. /**
  80745. * @return {boolean} Whether the port has been set.
  80746. */
  80747. goog.Uri.prototype.hasPort = function() {
  80748. return this.port_ != null;
  80749. };
  80750. /**
  80751. * @return {string} The decoded path.
  80752. */
  80753. goog.Uri.prototype.getPath = function() {
  80754. return this.path_;
  80755. };
  80756. /**
  80757. * Sets the path.
  80758. * @throws URIError If opt_decode is true and newPath is malformed (that is,
  80759. * if decodeURIComponent fails).
  80760. * @param {string} newPath New path value.
  80761. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80762. * @return {!goog.Uri} Reference to this URI object.
  80763. */
  80764. goog.Uri.prototype.setPath = function(newPath, opt_decode) {
  80765. this.enforceReadOnly();
  80766. this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;
  80767. return this;
  80768. };
  80769. /**
  80770. * @return {boolean} Whether the path has been set.
  80771. */
  80772. goog.Uri.prototype.hasPath = function() {
  80773. return !!this.path_;
  80774. };
  80775. /**
  80776. * @return {boolean} Whether the query string has been set.
  80777. */
  80778. goog.Uri.prototype.hasQuery = function() {
  80779. return this.queryData_.toString() !== '';
  80780. };
  80781. /**
  80782. * Sets the query data.
  80783. * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.
  80784. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80785. * Applies only if queryData is a string.
  80786. * @return {!goog.Uri} Reference to this URI object.
  80787. */
  80788. goog.Uri.prototype.setQueryData = function(queryData, opt_decode) {
  80789. this.enforceReadOnly();
  80790. if (queryData instanceof goog.Uri.QueryData) {
  80791. this.queryData_ = queryData;
  80792. this.queryData_.setIgnoreCase(this.ignoreCase_);
  80793. } else {
  80794. if (!opt_decode) {
  80795. // QueryData accepts encoded query string, so encode it if
  80796. // opt_decode flag is not true.
  80797. queryData = goog.Uri.encodeSpecialChars_(queryData,
  80798. goog.Uri.reDisallowedInQuery_);
  80799. }
  80800. this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);
  80801. }
  80802. return this;
  80803. };
  80804. /**
  80805. * Sets the URI query.
  80806. * @param {string} newQuery New query value.
  80807. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80808. * @return {!goog.Uri} Reference to this URI object.
  80809. */
  80810. goog.Uri.prototype.setQuery = function(newQuery, opt_decode) {
  80811. return this.setQueryData(newQuery, opt_decode);
  80812. };
  80813. /**
  80814. * @return {string} The encoded URI query, not including the ?.
  80815. */
  80816. goog.Uri.prototype.getEncodedQuery = function() {
  80817. return this.queryData_.toString();
  80818. };
  80819. /**
  80820. * @return {string} The decoded URI query, not including the ?.
  80821. */
  80822. goog.Uri.prototype.getDecodedQuery = function() {
  80823. return this.queryData_.toDecodedString();
  80824. };
  80825. /**
  80826. * Returns the query data.
  80827. * @return {!goog.Uri.QueryData} QueryData object.
  80828. */
  80829. goog.Uri.prototype.getQueryData = function() {
  80830. return this.queryData_;
  80831. };
  80832. /**
  80833. * @return {string} The encoded URI query, not including the ?.
  80834. *
  80835. * Warning: This method, unlike other getter methods, returns encoded
  80836. * value, instead of decoded one.
  80837. */
  80838. goog.Uri.prototype.getQuery = function() {
  80839. return this.getEncodedQuery();
  80840. };
  80841. /**
  80842. * Sets the value of the named query parameters, clearing previous values for
  80843. * that key.
  80844. *
  80845. * @param {string} key The parameter to set.
  80846. * @param {*} value The new value.
  80847. * @return {!goog.Uri} Reference to this URI object.
  80848. */
  80849. goog.Uri.prototype.setParameterValue = function(key, value) {
  80850. this.enforceReadOnly();
  80851. this.queryData_.set(key, value);
  80852. return this;
  80853. };
  80854. /**
  80855. * Sets the values of the named query parameters, clearing previous values for
  80856. * that key. Not new values will currently be moved to the end of the query
  80857. * string.
  80858. *
  80859. * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])
  80860. * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>
  80861. *
  80862. * @param {string} key The parameter to set.
  80863. * @param {*} values The new values. If values is a single
  80864. * string then it will be treated as the sole value.
  80865. * @return {!goog.Uri} Reference to this URI object.
  80866. */
  80867. goog.Uri.prototype.setParameterValues = function(key, values) {
  80868. this.enforceReadOnly();
  80869. if (!goog.isArray(values)) {
  80870. values = [String(values)];
  80871. }
  80872. this.queryData_.setValues(key, values);
  80873. return this;
  80874. };
  80875. /**
  80876. * Returns the value<b>s</b> for a given cgi parameter as a list of decoded
  80877. * query parameter values.
  80878. * @param {string} name The parameter to get values for.
  80879. * @return {!Array<?>} The values for a given cgi parameter as a list of
  80880. * decoded query parameter values.
  80881. */
  80882. goog.Uri.prototype.getParameterValues = function(name) {
  80883. return this.queryData_.getValues(name);
  80884. };
  80885. /**
  80886. * Returns the first value for a given cgi parameter or undefined if the given
  80887. * parameter name does not appear in the query string.
  80888. * @param {string} paramName Unescaped parameter name.
  80889. * @return {string|undefined} The first value for a given cgi parameter or
  80890. * undefined if the given parameter name does not appear in the query
  80891. * string.
  80892. */
  80893. goog.Uri.prototype.getParameterValue = function(paramName) {
  80894. // NOTE(nicksantos): This type-cast is a lie when
  80895. // preserveParameterTypesCompatibilityFlag is set to true.
  80896. // But this should only be set to true in tests.
  80897. return /** @type {string|undefined} */ (this.queryData_.get(paramName));
  80898. };
  80899. /**
  80900. * @return {string} The URI fragment, not including the #.
  80901. */
  80902. goog.Uri.prototype.getFragment = function() {
  80903. return this.fragment_;
  80904. };
  80905. /**
  80906. * Sets the URI fragment.
  80907. * @throws URIError If opt_decode is true and newFragment is malformed (that is,
  80908. * if decodeURIComponent fails).
  80909. * @param {string} newFragment New fragment value.
  80910. * @param {boolean=} opt_decode Optional param for whether to decode new value.
  80911. * @return {!goog.Uri} Reference to this URI object.
  80912. */
  80913. goog.Uri.prototype.setFragment = function(newFragment, opt_decode) {
  80914. this.enforceReadOnly();
  80915. this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) :
  80916. newFragment;
  80917. return this;
  80918. };
  80919. /**
  80920. * @return {boolean} Whether the URI has a fragment set.
  80921. */
  80922. goog.Uri.prototype.hasFragment = function() {
  80923. return !!this.fragment_;
  80924. };
  80925. /**
  80926. * Returns true if this has the same domain as that of uri2.
  80927. * @param {!goog.Uri} uri2 The URI object to compare to.
  80928. * @return {boolean} true if same domain; false otherwise.
  80929. */
  80930. goog.Uri.prototype.hasSameDomainAs = function(uri2) {
  80931. return ((!this.hasDomain() && !uri2.hasDomain()) ||
  80932. this.getDomain() == uri2.getDomain()) &&
  80933. ((!this.hasPort() && !uri2.hasPort()) ||
  80934. this.getPort() == uri2.getPort());
  80935. };
  80936. /**
  80937. * Adds a random parameter to the Uri.
  80938. * @return {!goog.Uri} Reference to this Uri object.
  80939. */
  80940. goog.Uri.prototype.makeUnique = function() {
  80941. this.enforceReadOnly();
  80942. this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());
  80943. return this;
  80944. };
  80945. /**
  80946. * Removes the named query parameter.
  80947. *
  80948. * @param {string} key The parameter to remove.
  80949. * @return {!goog.Uri} Reference to this URI object.
  80950. */
  80951. goog.Uri.prototype.removeParameter = function(key) {
  80952. this.enforceReadOnly();
  80953. this.queryData_.remove(key);
  80954. return this;
  80955. };
  80956. /**
  80957. * Sets whether Uri is read only. If this goog.Uri is read-only,
  80958. * enforceReadOnly_ will be called at the start of any function that may modify
  80959. * this Uri.
  80960. * @param {boolean} isReadOnly whether this goog.Uri should be read only.
  80961. * @return {!goog.Uri} Reference to this Uri object.
  80962. */
  80963. goog.Uri.prototype.setReadOnly = function(isReadOnly) {
  80964. this.isReadOnly_ = isReadOnly;
  80965. return this;
  80966. };
  80967. /**
  80968. * @return {boolean} Whether the URI is read only.
  80969. */
  80970. goog.Uri.prototype.isReadOnly = function() {
  80971. return this.isReadOnly_;
  80972. };
  80973. /**
  80974. * Checks if this Uri has been marked as read only, and if so, throws an error.
  80975. * This should be called whenever any modifying function is called.
  80976. */
  80977. goog.Uri.prototype.enforceReadOnly = function() {
  80978. if (this.isReadOnly_) {
  80979. throw Error('Tried to modify a read-only Uri');
  80980. }
  80981. };
  80982. /**
  80983. * Sets whether to ignore case.
  80984. * NOTE: If there are already key/value pairs in the QueryData, and
  80985. * ignoreCase_ is set to false, the keys will all be lower-cased.
  80986. * @param {boolean} ignoreCase whether this goog.Uri should ignore case.
  80987. * @return {!goog.Uri} Reference to this Uri object.
  80988. */
  80989. goog.Uri.prototype.setIgnoreCase = function(ignoreCase) {
  80990. this.ignoreCase_ = ignoreCase;
  80991. if (this.queryData_) {
  80992. this.queryData_.setIgnoreCase(ignoreCase);
  80993. }
  80994. return this;
  80995. };
  80996. /**
  80997. * @return {boolean} Whether to ignore case.
  80998. */
  80999. goog.Uri.prototype.getIgnoreCase = function() {
  81000. return this.ignoreCase_;
  81001. };
  81002. //==============================================================================
  81003. // Static members
  81004. //==============================================================================
  81005. /**
  81006. * Creates a uri from the string form. Basically an alias of new goog.Uri().
  81007. * If a Uri object is passed to parse then it will return a clone of the object.
  81008. *
  81009. * @throws URIError If parsing the URI is malformed. The passed URI components
  81010. * should all be parseable by decodeURIComponent.
  81011. * @param {*} uri Raw URI string or instance of Uri
  81012. * object.
  81013. * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter
  81014. * names in #getParameterValue.
  81015. * @return {!goog.Uri} The new URI object.
  81016. */
  81017. goog.Uri.parse = function(uri, opt_ignoreCase) {
  81018. return uri instanceof goog.Uri ?
  81019. uri.clone() : new goog.Uri(uri, opt_ignoreCase);
  81020. };
  81021. /**
  81022. * Creates a new goog.Uri object from unencoded parts.
  81023. *
  81024. * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.
  81025. * @param {?string=} opt_userInfo username:password.
  81026. * @param {?string=} opt_domain www.google.com.
  81027. * @param {?number=} opt_port 9830.
  81028. * @param {?string=} opt_path /some/path/to/a/file.html.
  81029. * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.
  81030. * @param {?string=} opt_fragment The fragment without the #.
  81031. * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in
  81032. * #getParameterValue.
  81033. *
  81034. * @return {!goog.Uri} The new URI object.
  81035. */
  81036. goog.Uri.create = function(opt_scheme, opt_userInfo, opt_domain, opt_port,
  81037. opt_path, opt_query, opt_fragment, opt_ignoreCase) {
  81038. var uri = new goog.Uri(null, opt_ignoreCase);
  81039. // Only set the parts if they are defined and not empty strings.
  81040. opt_scheme && uri.setScheme(opt_scheme);
  81041. opt_userInfo && uri.setUserInfo(opt_userInfo);
  81042. opt_domain && uri.setDomain(opt_domain);
  81043. opt_port && uri.setPort(opt_port);
  81044. opt_path && uri.setPath(opt_path);
  81045. opt_query && uri.setQueryData(opt_query);
  81046. opt_fragment && uri.setFragment(opt_fragment);
  81047. return uri;
  81048. };
  81049. /**
  81050. * Resolves a relative Uri against a base Uri, accepting both strings and
  81051. * Uri objects.
  81052. *
  81053. * @param {*} base Base Uri.
  81054. * @param {*} rel Relative Uri.
  81055. * @return {!goog.Uri} Resolved uri.
  81056. */
  81057. goog.Uri.resolve = function(base, rel) {
  81058. if (!(base instanceof goog.Uri)) {
  81059. base = goog.Uri.parse(base);
  81060. }
  81061. if (!(rel instanceof goog.Uri)) {
  81062. rel = goog.Uri.parse(rel);
  81063. }
  81064. return base.resolve(rel);
  81065. };
  81066. /**
  81067. * Removes dot segments in given path component, as described in
  81068. * RFC 3986, section 5.2.4.
  81069. *
  81070. * @param {string} path A non-empty path component.
  81071. * @return {string} Path component with removed dot segments.
  81072. */
  81073. goog.Uri.removeDotSegments = function(path) {
  81074. if (path == '..' || path == '.') {
  81075. return '';
  81076. } else if (!goog.string.contains(path, './') &&
  81077. !goog.string.contains(path, '/.')) {
  81078. // This optimization detects uris which do not contain dot-segments,
  81079. // and as a consequence do not require any processing.
  81080. return path;
  81081. } else {
  81082. var leadingSlash = goog.string.startsWith(path, '/');
  81083. var segments = path.split('/');
  81084. var out = [];
  81085. for (var pos = 0; pos < segments.length; ) {
  81086. var segment = segments[pos++];
  81087. if (segment == '.') {
  81088. if (leadingSlash && pos == segments.length) {
  81089. out.push('');
  81090. }
  81091. } else if (segment == '..') {
  81092. if (out.length > 1 || out.length == 1 && out[0] != '') {
  81093. out.pop();
  81094. }
  81095. if (leadingSlash && pos == segments.length) {
  81096. out.push('');
  81097. }
  81098. } else {
  81099. out.push(segment);
  81100. leadingSlash = true;
  81101. }
  81102. }
  81103. return out.join('/');
  81104. }
  81105. };
  81106. /**
  81107. * Decodes a value or returns the empty string if it isn't defined or empty.
  81108. * @throws URIError If decodeURIComponent fails to decode val.
  81109. * @param {string|undefined} val Value to decode.
  81110. * @param {boolean=} opt_preserveReserved If true, restricted characters will
  81111. * not be decoded.
  81112. * @return {string} Decoded value.
  81113. * @private
  81114. */
  81115. goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {
  81116. // Don't use UrlDecode() here because val is not a query parameter.
  81117. if (!val) {
  81118. return '';
  81119. }
  81120. // decodeURI has the same output for '%2f' and '%252f'. We double encode %25
  81121. // so that we can distinguish between the 2 inputs. This is later undone by
  81122. // removeDoubleEncoding_.
  81123. return opt_preserveReserved ?
  81124. decodeURI(val.replace(/%25/g, '%2525')) : decodeURIComponent(val);
  81125. };
  81126. /**
  81127. * If unescapedPart is non null, then escapes any characters in it that aren't
  81128. * valid characters in a url and also escapes any special characters that
  81129. * appear in extra.
  81130. *
  81131. * @param {*} unescapedPart The string to encode.
  81132. * @param {RegExp} extra A character set of characters in [\01-\177].
  81133. * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent
  81134. * encoding.
  81135. * @return {?string} null iff unescapedPart == null.
  81136. * @private
  81137. */
  81138. goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra,
  81139. opt_removeDoubleEncoding) {
  81140. if (goog.isString(unescapedPart)) {
  81141. var encoded = encodeURI(unescapedPart).
  81142. replace(extra, goog.Uri.encodeChar_);
  81143. if (opt_removeDoubleEncoding) {
  81144. // encodeURI double-escapes %XX sequences used to represent restricted
  81145. // characters in some URI components, remove the double escaping here.
  81146. encoded = goog.Uri.removeDoubleEncoding_(encoded);
  81147. }
  81148. return encoded;
  81149. }
  81150. return null;
  81151. };
  81152. /**
  81153. * Converts a character in [\01-\177] to its unicode character equivalent.
  81154. * @param {string} ch One character string.
  81155. * @return {string} Encoded string.
  81156. * @private
  81157. */
  81158. goog.Uri.encodeChar_ = function(ch) {
  81159. var n = ch.charCodeAt(0);
  81160. return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);
  81161. };
  81162. /**
  81163. * Removes double percent-encoding from a string.
  81164. * @param {string} doubleEncodedString String
  81165. * @return {string} String with double encoding removed.
  81166. * @private
  81167. */
  81168. goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {
  81169. return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');
  81170. };
  81171. /**
  81172. * Regular expression for characters that are disallowed in the scheme or
  81173. * userInfo part of the URI.
  81174. * @type {RegExp}
  81175. * @private
  81176. */
  81177. goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g;
  81178. /**
  81179. * Regular expression for characters that are disallowed in a relative path.
  81180. * Colon is included due to RFC 3986 3.3.
  81181. * @type {RegExp}
  81182. * @private
  81183. */
  81184. goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g;
  81185. /**
  81186. * Regular expression for characters that are disallowed in an absolute path.
  81187. * @type {RegExp}
  81188. * @private
  81189. */
  81190. goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g;
  81191. /**
  81192. * Regular expression for characters that are disallowed in the query.
  81193. * @type {RegExp}
  81194. * @private
  81195. */
  81196. goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g;
  81197. /**
  81198. * Regular expression for characters that are disallowed in the fragment.
  81199. * @type {RegExp}
  81200. * @private
  81201. */
  81202. goog.Uri.reDisallowedInFragment_ = /#/g;
  81203. /**
  81204. * Checks whether two URIs have the same domain.
  81205. * @param {string} uri1String First URI string.
  81206. * @param {string} uri2String Second URI string.
  81207. * @return {boolean} true if the two URIs have the same domain; false otherwise.
  81208. */
  81209. goog.Uri.haveSameDomain = function(uri1String, uri2String) {
  81210. // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.
  81211. // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.
  81212. var pieces1 = goog.uri.utils.split(uri1String);
  81213. var pieces2 = goog.uri.utils.split(uri2String);
  81214. return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
  81215. pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
  81216. pieces1[goog.uri.utils.ComponentIndex.PORT] ==
  81217. pieces2[goog.uri.utils.ComponentIndex.PORT];
  81218. };
  81219. /**
  81220. * Class used to represent URI query parameters. It is essentially a hash of
  81221. * name-value pairs, though a name can be present more than once.
  81222. *
  81223. * Has the same interface as the collections in goog.structs.
  81224. *
  81225. * @param {?string=} opt_query Optional encoded query string to parse into
  81226. * the object.
  81227. * @param {goog.Uri=} opt_uri Optional uri object that should have its
  81228. * cache invalidated when this object updates. Deprecated -- this
  81229. * is no longer required.
  81230. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  81231. * name in #get.
  81232. * @constructor
  81233. * @struct
  81234. * @final
  81235. */
  81236. goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {
  81237. /**
  81238. * The map containing name/value or name/array-of-values pairs.
  81239. * May be null if it requires parsing from the query string.
  81240. *
  81241. * We need to use a Map because we cannot guarantee that the key names will
  81242. * not be problematic for IE.
  81243. *
  81244. * @private {goog.structs.Map<string, !Array<*>>}
  81245. */
  81246. this.keyMap_ = null;
  81247. /**
  81248. * The number of params, or null if it requires computing.
  81249. * @private {?number}
  81250. */
  81251. this.count_ = null;
  81252. /**
  81253. * Encoded query string, or null if it requires computing from the key map.
  81254. * @private {?string}
  81255. */
  81256. this.encodedQuery_ = opt_query || null;
  81257. /**
  81258. * If true, ignore the case of the parameter name in #get.
  81259. * @private {boolean}
  81260. */
  81261. this.ignoreCase_ = !!opt_ignoreCase;
  81262. };
  81263. /**
  81264. * If the underlying key map is not yet initialized, it parses the
  81265. * query string and fills the map with parsed data.
  81266. * @private
  81267. */
  81268. goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {
  81269. if (!this.keyMap_) {
  81270. this.keyMap_ = new goog.structs.Map();
  81271. this.count_ = 0;
  81272. if (this.encodedQuery_) {
  81273. var self = this;
  81274. goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {
  81275. self.add(goog.string.urlDecode(name), value);
  81276. });
  81277. }
  81278. }
  81279. };
  81280. /**
  81281. * Creates a new query data instance from a map of names and values.
  81282. *
  81283. * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter
  81284. * names to parameter value. If parameter value is an array, it is
  81285. * treated as if the key maps to each individual value in the
  81286. * array.
  81287. * @param {goog.Uri=} opt_uri URI object that should have its cache
  81288. * invalidated when this object updates.
  81289. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  81290. * name in #get.
  81291. * @return {!goog.Uri.QueryData} The populated query data instance.
  81292. */
  81293. goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {
  81294. var keys = goog.structs.getKeys(map);
  81295. if (typeof keys == 'undefined') {
  81296. throw Error('Keys are undefined');
  81297. }
  81298. var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);
  81299. var values = goog.structs.getValues(map);
  81300. for (var i = 0; i < keys.length; i++) {
  81301. var key = keys[i];
  81302. var value = values[i];
  81303. if (!goog.isArray(value)) {
  81304. queryData.add(key, value);
  81305. } else {
  81306. queryData.setValues(key, value);
  81307. }
  81308. }
  81309. return queryData;
  81310. };
  81311. /**
  81312. * Creates a new query data instance from parallel arrays of parameter names
  81313. * and values. Allows for duplicate parameter names. Throws an error if the
  81314. * lengths of the arrays differ.
  81315. *
  81316. * @param {!Array<string>} keys Parameter names.
  81317. * @param {!Array<?>} values Parameter values.
  81318. * @param {goog.Uri=} opt_uri URI object that should have its cache
  81319. * invalidated when this object updates.
  81320. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter
  81321. * name in #get.
  81322. * @return {!goog.Uri.QueryData} The populated query data instance.
  81323. */
  81324. goog.Uri.QueryData.createFromKeysValues = function(
  81325. keys, values, opt_uri, opt_ignoreCase) {
  81326. if (keys.length != values.length) {
  81327. throw Error('Mismatched lengths for keys/values');
  81328. }
  81329. var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);
  81330. for (var i = 0; i < keys.length; i++) {
  81331. queryData.add(keys[i], values[i]);
  81332. }
  81333. return queryData;
  81334. };
  81335. /**
  81336. * @return {?number} The number of parameters.
  81337. */
  81338. goog.Uri.QueryData.prototype.getCount = function() {
  81339. this.ensureKeyMapInitialized_();
  81340. return this.count_;
  81341. };
  81342. /**
  81343. * Adds a key value pair.
  81344. * @param {string} key Name.
  81345. * @param {*} value Value.
  81346. * @return {!goog.Uri.QueryData} Instance of this object.
  81347. */
  81348. goog.Uri.QueryData.prototype.add = function(key, value) {
  81349. this.ensureKeyMapInitialized_();
  81350. this.invalidateCache_();
  81351. key = this.getKeyName_(key);
  81352. var values = this.keyMap_.get(key);
  81353. if (!values) {
  81354. this.keyMap_.set(key, (values = []));
  81355. }
  81356. values.push(value);
  81357. this.count_++;
  81358. return this;
  81359. };
  81360. /**
  81361. * Removes all the params with the given key.
  81362. * @param {string} key Name.
  81363. * @return {boolean} Whether any parameter was removed.
  81364. */
  81365. goog.Uri.QueryData.prototype.remove = function(key) {
  81366. this.ensureKeyMapInitialized_();
  81367. key = this.getKeyName_(key);
  81368. if (this.keyMap_.containsKey(key)) {
  81369. this.invalidateCache_();
  81370. // Decrement parameter count.
  81371. this.count_ -= this.keyMap_.get(key).length;
  81372. return this.keyMap_.remove(key);
  81373. }
  81374. return false;
  81375. };
  81376. /**
  81377. * Clears the parameters.
  81378. */
  81379. goog.Uri.QueryData.prototype.clear = function() {
  81380. this.invalidateCache_();
  81381. this.keyMap_ = null;
  81382. this.count_ = 0;
  81383. };
  81384. /**
  81385. * @return {boolean} Whether we have any parameters.
  81386. */
  81387. goog.Uri.QueryData.prototype.isEmpty = function() {
  81388. this.ensureKeyMapInitialized_();
  81389. return this.count_ == 0;
  81390. };
  81391. /**
  81392. * Whether there is a parameter with the given name
  81393. * @param {string} key The parameter name to check for.
  81394. * @return {boolean} Whether there is a parameter with the given name.
  81395. */
  81396. goog.Uri.QueryData.prototype.containsKey = function(key) {
  81397. this.ensureKeyMapInitialized_();
  81398. key = this.getKeyName_(key);
  81399. return this.keyMap_.containsKey(key);
  81400. };
  81401. /**
  81402. * Whether there is a parameter with the given value.
  81403. * @param {*} value The value to check for.
  81404. * @return {boolean} Whether there is a parameter with the given value.
  81405. */
  81406. goog.Uri.QueryData.prototype.containsValue = function(value) {
  81407. // NOTE(arv): This solution goes through all the params even if it was the
  81408. // first param. We can get around this by not reusing code or by switching to
  81409. // iterators.
  81410. var vals = this.getValues();
  81411. return goog.array.contains(vals, value);
  81412. };
  81413. /**
  81414. * Returns all the keys of the parameters. If a key is used multiple times
  81415. * it will be included multiple times in the returned array
  81416. * @return {!Array<string>} All the keys of the parameters.
  81417. */
  81418. goog.Uri.QueryData.prototype.getKeys = function() {
  81419. this.ensureKeyMapInitialized_();
  81420. // We need to get the values to know how many keys to add.
  81421. var vals = /** @type {!Array<*>} */ (this.keyMap_.getValues());
  81422. var keys = this.keyMap_.getKeys();
  81423. var rv = [];
  81424. for (var i = 0; i < keys.length; i++) {
  81425. var val = vals[i];
  81426. for (var j = 0; j < val.length; j++) {
  81427. rv.push(keys[i]);
  81428. }
  81429. }
  81430. return rv;
  81431. };
  81432. /**
  81433. * Returns all the values of the parameters with the given name. If the query
  81434. * data has no such key this will return an empty array. If no key is given
  81435. * all values wil be returned.
  81436. * @param {string=} opt_key The name of the parameter to get the values for.
  81437. * @return {!Array<?>} All the values of the parameters with the given name.
  81438. */
  81439. goog.Uri.QueryData.prototype.getValues = function(opt_key) {
  81440. this.ensureKeyMapInitialized_();
  81441. var rv = [];
  81442. if (goog.isString(opt_key)) {
  81443. if (this.containsKey(opt_key)) {
  81444. rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));
  81445. }
  81446. } else {
  81447. // Return all values.
  81448. var values = this.keyMap_.getValues();
  81449. for (var i = 0; i < values.length; i++) {
  81450. rv = goog.array.concat(rv, values[i]);
  81451. }
  81452. }
  81453. return rv;
  81454. };
  81455. /**
  81456. * Sets a key value pair and removes all other keys with the same value.
  81457. *
  81458. * @param {string} key Name.
  81459. * @param {*} value Value.
  81460. * @return {!goog.Uri.QueryData} Instance of this object.
  81461. */
  81462. goog.Uri.QueryData.prototype.set = function(key, value) {
  81463. this.ensureKeyMapInitialized_();
  81464. this.invalidateCache_();
  81465. // TODO(chrishenry): This could be better written as
  81466. // this.remove(key), this.add(key, value), but that would reorder
  81467. // the key (since the key is first removed and then added at the
  81468. // end) and we would have to fix unit tests that depend on key
  81469. // ordering.
  81470. key = this.getKeyName_(key);
  81471. if (this.containsKey(key)) {
  81472. this.count_ -= this.keyMap_.get(key).length;
  81473. }
  81474. this.keyMap_.set(key, [value]);
  81475. this.count_++;
  81476. return this;
  81477. };
  81478. /**
  81479. * Returns the first value associated with the key. If the query data has no
  81480. * such key this will return undefined or the optional default.
  81481. * @param {string} key The name of the parameter to get the value for.
  81482. * @param {*=} opt_default The default value to return if the query data
  81483. * has no such key.
  81484. * @return {*} The first string value associated with the key, or opt_default
  81485. * if there's no value.
  81486. */
  81487. goog.Uri.QueryData.prototype.get = function(key, opt_default) {
  81488. var values = key ? this.getValues(key) : [];
  81489. if (goog.Uri.preserveParameterTypesCompatibilityFlag) {
  81490. return values.length > 0 ? values[0] : opt_default;
  81491. } else {
  81492. return values.length > 0 ? String(values[0]) : opt_default;
  81493. }
  81494. };
  81495. /**
  81496. * Sets the values for a key. If the key already exists, this will
  81497. * override all of the existing values that correspond to the key.
  81498. * @param {string} key The key to set values for.
  81499. * @param {!Array<?>} values The values to set.
  81500. */
  81501. goog.Uri.QueryData.prototype.setValues = function(key, values) {
  81502. this.remove(key);
  81503. if (values.length > 0) {
  81504. this.invalidateCache_();
  81505. this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));
  81506. this.count_ += values.length;
  81507. }
  81508. };
  81509. /**
  81510. * @return {string} Encoded query string.
  81511. * @override
  81512. */
  81513. goog.Uri.QueryData.prototype.toString = function() {
  81514. if (this.encodedQuery_) {
  81515. return this.encodedQuery_;
  81516. }
  81517. if (!this.keyMap_) {
  81518. return '';
  81519. }
  81520. var sb = [];
  81521. // In the past, we use this.getKeys() and this.getVals(), but that
  81522. // generates a lot of allocations as compared to simply iterating
  81523. // over the keys.
  81524. var keys = this.keyMap_.getKeys();
  81525. for (var i = 0; i < keys.length; i++) {
  81526. var key = keys[i];
  81527. var encodedKey = goog.string.urlEncode(key);
  81528. var val = this.getValues(key);
  81529. for (var j = 0; j < val.length; j++) {
  81530. var param = encodedKey;
  81531. // Ensure that null and undefined are encoded into the url as
  81532. // literal strings.
  81533. if (val[j] !== '') {
  81534. param += '=' + goog.string.urlEncode(val[j]);
  81535. }
  81536. sb.push(param);
  81537. }
  81538. }
  81539. return this.encodedQuery_ = sb.join('&');
  81540. };
  81541. /**
  81542. * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on
  81543. * any of the URI components).
  81544. * @return {string} Decoded query string.
  81545. */
  81546. goog.Uri.QueryData.prototype.toDecodedString = function() {
  81547. return goog.Uri.decodeOrEmpty_(this.toString());
  81548. };
  81549. /**
  81550. * Invalidate the cache.
  81551. * @private
  81552. */
  81553. goog.Uri.QueryData.prototype.invalidateCache_ = function() {
  81554. this.encodedQuery_ = null;
  81555. };
  81556. /**
  81557. * Removes all keys that are not in the provided list. (Modifies this object.)
  81558. * @param {Array<string>} keys The desired keys.
  81559. * @return {!goog.Uri.QueryData} a reference to this object.
  81560. */
  81561. goog.Uri.QueryData.prototype.filterKeys = function(keys) {
  81562. this.ensureKeyMapInitialized_();
  81563. this.keyMap_.forEach(
  81564. function(value, key) {
  81565. if (!goog.array.contains(keys, key)) {
  81566. this.remove(key);
  81567. }
  81568. }, this);
  81569. return this;
  81570. };
  81571. /**
  81572. * Clone the query data instance.
  81573. * @return {!goog.Uri.QueryData} New instance of the QueryData object.
  81574. */
  81575. goog.Uri.QueryData.prototype.clone = function() {
  81576. var rv = new goog.Uri.QueryData();
  81577. rv.encodedQuery_ = this.encodedQuery_;
  81578. if (this.keyMap_) {
  81579. rv.keyMap_ = this.keyMap_.clone();
  81580. rv.count_ = this.count_;
  81581. }
  81582. return rv;
  81583. };
  81584. /**
  81585. * Helper function to get the key name from a JavaScript object. Converts
  81586. * the object to a string, and to lower case if necessary.
  81587. * @private
  81588. * @param {*} arg The object to get a key name from.
  81589. * @return {string} valid key name which can be looked up in #keyMap_.
  81590. */
  81591. goog.Uri.QueryData.prototype.getKeyName_ = function(arg) {
  81592. var keyName = String(arg);
  81593. if (this.ignoreCase_) {
  81594. keyName = keyName.toLowerCase();
  81595. }
  81596. return keyName;
  81597. };
  81598. /**
  81599. * Ignore case in parameter names.
  81600. * NOTE: If there are already key/value pairs in the QueryData, and
  81601. * ignoreCase_ is set to false, the keys will all be lower-cased.
  81602. * @param {boolean} ignoreCase whether this goog.Uri should ignore case.
  81603. */
  81604. goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {
  81605. var resetKeys = ignoreCase && !this.ignoreCase_;
  81606. if (resetKeys) {
  81607. this.ensureKeyMapInitialized_();
  81608. this.invalidateCache_();
  81609. this.keyMap_.forEach(
  81610. function(value, key) {
  81611. var lowerCase = key.toLowerCase();
  81612. if (key != lowerCase) {
  81613. this.remove(key);
  81614. this.setValues(lowerCase, value);
  81615. }
  81616. }, this);
  81617. }
  81618. this.ignoreCase_ = ignoreCase;
  81619. };
  81620. /**
  81621. * Extends a query data object with another query data or map like object. This
  81622. * operates 'in-place', it does not create a new QueryData object.
  81623. *
  81624. * @param {...(goog.Uri.QueryData|goog.structs.Map<?, ?>|Object)} var_args
  81625. * The object from which key value pairs will be copied.
  81626. */
  81627. goog.Uri.QueryData.prototype.extend = function(var_args) {
  81628. for (var i = 0; i < arguments.length; i++) {
  81629. var data = arguments[i];
  81630. goog.structs.forEach(data,
  81631. /** @this {goog.Uri.QueryData} */
  81632. function(value, key) {
  81633. this.add(key, value);
  81634. }, this);
  81635. }
  81636. };
  81637. goog.provide('ol.style.Text');
  81638. goog.require('ol.style.Fill');
  81639. /**
  81640. * @classdesc
  81641. * Set text style for vector features.
  81642. *
  81643. * @constructor
  81644. * @param {olx.style.TextOptions=} opt_options Options.
  81645. * @api
  81646. */
  81647. ol.style.Text = function(opt_options) {
  81648. var options = opt_options || {};
  81649. /**
  81650. * @private
  81651. * @type {string|undefined}
  81652. */
  81653. this.font_ = options.font;
  81654. /**
  81655. * @private
  81656. * @type {number|undefined}
  81657. */
  81658. this.rotation_ = options.rotation;
  81659. /**
  81660. * @private
  81661. * @type {number|undefined}
  81662. */
  81663. this.scale_ = options.scale;
  81664. /**
  81665. * @private
  81666. * @type {string|undefined}
  81667. */
  81668. this.text_ = options.text;
  81669. /**
  81670. * @private
  81671. * @type {string|undefined}
  81672. */
  81673. this.textAlign_ = options.textAlign;
  81674. /**
  81675. * @private
  81676. * @type {string|undefined}
  81677. */
  81678. this.textBaseline_ = options.textBaseline;
  81679. /**
  81680. * @private
  81681. * @type {ol.style.Fill}
  81682. */
  81683. this.fill_ = options.fill !== undefined ? options.fill :
  81684. new ol.style.Fill({color: ol.style.Text.DEFAULT_FILL_COLOR_});
  81685. /**
  81686. * @private
  81687. * @type {ol.style.Stroke}
  81688. */
  81689. this.stroke_ = options.stroke !== undefined ? options.stroke : null;
  81690. /**
  81691. * @private
  81692. * @type {number}
  81693. */
  81694. this.offsetX_ = options.offsetX !== undefined ? options.offsetX : 0;
  81695. /**
  81696. * @private
  81697. * @type {number}
  81698. */
  81699. this.offsetY_ = options.offsetY !== undefined ? options.offsetY : 0;
  81700. };
  81701. /**
  81702. * The default fill color to use if no fill was set at construction time; a
  81703. * blackish `#333`.
  81704. *
  81705. * @const {string}
  81706. * @private
  81707. */
  81708. ol.style.Text.DEFAULT_FILL_COLOR_ = '#333';
  81709. /**
  81710. * Get the font name.
  81711. * @return {string|undefined} Font.
  81712. * @api
  81713. */
  81714. ol.style.Text.prototype.getFont = function() {
  81715. return this.font_;
  81716. };
  81717. /**
  81718. * Get the x-offset for the text.
  81719. * @return {number} Horizontal text offset.
  81720. * @api
  81721. */
  81722. ol.style.Text.prototype.getOffsetX = function() {
  81723. return this.offsetX_;
  81724. };
  81725. /**
  81726. * Get the y-offset for the text.
  81727. * @return {number} Vertical text offset.
  81728. * @api
  81729. */
  81730. ol.style.Text.prototype.getOffsetY = function() {
  81731. return this.offsetY_;
  81732. };
  81733. /**
  81734. * Get the fill style for the text.
  81735. * @return {ol.style.Fill} Fill style.
  81736. * @api
  81737. */
  81738. ol.style.Text.prototype.getFill = function() {
  81739. return this.fill_;
  81740. };
  81741. /**
  81742. * Get the text rotation.
  81743. * @return {number|undefined} Rotation.
  81744. * @api
  81745. */
  81746. ol.style.Text.prototype.getRotation = function() {
  81747. return this.rotation_;
  81748. };
  81749. /**
  81750. * Get the text scale.
  81751. * @return {number|undefined} Scale.
  81752. * @api
  81753. */
  81754. ol.style.Text.prototype.getScale = function() {
  81755. return this.scale_;
  81756. };
  81757. /**
  81758. * Get the stroke style for the text.
  81759. * @return {ol.style.Stroke} Stroke style.
  81760. * @api
  81761. */
  81762. ol.style.Text.prototype.getStroke = function() {
  81763. return this.stroke_;
  81764. };
  81765. /**
  81766. * Get the text to be rendered.
  81767. * @return {string|undefined} Text.
  81768. * @api
  81769. */
  81770. ol.style.Text.prototype.getText = function() {
  81771. return this.text_;
  81772. };
  81773. /**
  81774. * Get the text alignment.
  81775. * @return {string|undefined} Text align.
  81776. * @api
  81777. */
  81778. ol.style.Text.prototype.getTextAlign = function() {
  81779. return this.textAlign_;
  81780. };
  81781. /**
  81782. * Get the text baseline.
  81783. * @return {string|undefined} Text baseline.
  81784. * @api
  81785. */
  81786. ol.style.Text.prototype.getTextBaseline = function() {
  81787. return this.textBaseline_;
  81788. };
  81789. /**
  81790. * Set the font.
  81791. *
  81792. * @param {string|undefined} font Font.
  81793. * @api
  81794. */
  81795. ol.style.Text.prototype.setFont = function(font) {
  81796. this.font_ = font;
  81797. };
  81798. /**
  81799. * Set the x offset.
  81800. *
  81801. * @param {number} offsetX Horizontal text offset.
  81802. */
  81803. ol.style.Text.prototype.setOffsetX = function(offsetX) {
  81804. this.offsetX_ = offsetX;
  81805. };
  81806. /**
  81807. * Set the y offset.
  81808. *
  81809. * @param {number} offsetY Vertical text offset.
  81810. */
  81811. ol.style.Text.prototype.setOffsetY = function(offsetY) {
  81812. this.offsetY_ = offsetY;
  81813. };
  81814. /**
  81815. * Set the fill.
  81816. *
  81817. * @param {ol.style.Fill} fill Fill style.
  81818. * @api
  81819. */
  81820. ol.style.Text.prototype.setFill = function(fill) {
  81821. this.fill_ = fill;
  81822. };
  81823. /**
  81824. * Set the rotation.
  81825. *
  81826. * @param {number|undefined} rotation Rotation.
  81827. * @api
  81828. */
  81829. ol.style.Text.prototype.setRotation = function(rotation) {
  81830. this.rotation_ = rotation;
  81831. };
  81832. /**
  81833. * Set the scale.
  81834. *
  81835. * @param {number|undefined} scale Scale.
  81836. * @api
  81837. */
  81838. ol.style.Text.prototype.setScale = function(scale) {
  81839. this.scale_ = scale;
  81840. };
  81841. /**
  81842. * Set the stroke.
  81843. *
  81844. * @param {ol.style.Stroke} stroke Stroke style.
  81845. * @api
  81846. */
  81847. ol.style.Text.prototype.setStroke = function(stroke) {
  81848. this.stroke_ = stroke;
  81849. };
  81850. /**
  81851. * Set the text.
  81852. *
  81853. * @param {string|undefined} text Text.
  81854. * @api
  81855. */
  81856. ol.style.Text.prototype.setText = function(text) {
  81857. this.text_ = text;
  81858. };
  81859. /**
  81860. * Set the text alignment.
  81861. *
  81862. * @param {string|undefined} textAlign Text align.
  81863. * @api
  81864. */
  81865. ol.style.Text.prototype.setTextAlign = function(textAlign) {
  81866. this.textAlign_ = textAlign;
  81867. };
  81868. /**
  81869. * Set the text baseline.
  81870. *
  81871. * @param {string|undefined} textBaseline Text baseline.
  81872. * @api
  81873. */
  81874. ol.style.Text.prototype.setTextBaseline = function(textBaseline) {
  81875. this.textBaseline_ = textBaseline;
  81876. };
  81877. // FIXME http://earth.google.com/kml/1.0 namespace?
  81878. // FIXME why does node.getAttribute return an unknown type?
  81879. // FIXME text
  81880. // FIXME serialize arbitrary feature properties
  81881. // FIXME don't parse style if extractStyles is false
  81882. goog.provide('ol.format.KML');
  81883. goog.require('goog.Uri');
  81884. goog.require('goog.array');
  81885. goog.require('goog.asserts');
  81886. goog.require('goog.dom.NodeType');
  81887. goog.require('goog.math');
  81888. goog.require('ol');
  81889. goog.require('ol.Feature');
  81890. goog.require('ol.FeatureStyleFunction');
  81891. goog.require('ol.array');
  81892. goog.require('ol.color');
  81893. goog.require('ol.format.Feature');
  81894. goog.require('ol.format.XMLFeature');
  81895. goog.require('ol.format.XSD');
  81896. goog.require('ol.geom.Geometry');
  81897. goog.require('ol.geom.GeometryCollection');
  81898. goog.require('ol.geom.GeometryLayout');
  81899. goog.require('ol.geom.GeometryType');
  81900. goog.require('ol.geom.LineString');
  81901. goog.require('ol.geom.LinearRing');
  81902. goog.require('ol.geom.MultiLineString');
  81903. goog.require('ol.geom.MultiPoint');
  81904. goog.require('ol.geom.MultiPolygon');
  81905. goog.require('ol.geom.Point');
  81906. goog.require('ol.geom.Polygon');
  81907. goog.require('ol.proj');
  81908. goog.require('ol.style.Fill');
  81909. goog.require('ol.style.Icon');
  81910. goog.require('ol.style.IconAnchorUnits');
  81911. goog.require('ol.style.IconOrigin');
  81912. goog.require('ol.style.Image');
  81913. goog.require('ol.style.Stroke');
  81914. goog.require('ol.style.Style');
  81915. goog.require('ol.style.Text');
  81916. goog.require('ol.xml');
  81917. /**
  81918. * @typedef {{x: number, xunits: (ol.style.IconAnchorUnits|undefined),
  81919. * y: number, yunits: (ol.style.IconAnchorUnits|undefined)}}
  81920. */
  81921. ol.format.KMLVec2_;
  81922. /**
  81923. * @typedef {{flatCoordinates: Array.<number>,
  81924. * whens: Array.<number>}}
  81925. */
  81926. ol.format.KMLGxTrackObject_;
  81927. /**
  81928. * @classdesc
  81929. * Feature format for reading and writing data in the KML format.
  81930. *
  81931. * @constructor
  81932. * @extends {ol.format.XMLFeature}
  81933. * @param {olx.format.KMLOptions=} opt_options Options.
  81934. * @api stable
  81935. */
  81936. ol.format.KML = function(opt_options) {
  81937. var options = opt_options ? opt_options : {};
  81938. goog.base(this);
  81939. /**
  81940. * @inheritDoc
  81941. */
  81942. this.defaultDataProjection = ol.proj.get('EPSG:4326');
  81943. /**
  81944. * @private
  81945. * @type {Array.<ol.style.Style>}
  81946. */
  81947. this.defaultStyle_ = options.defaultStyle ?
  81948. options.defaultStyle : ol.format.KML.DEFAULT_STYLE_ARRAY_;
  81949. /**
  81950. * @private
  81951. * @type {boolean}
  81952. */
  81953. this.extractStyles_ = options.extractStyles !== undefined ?
  81954. options.extractStyles : true;
  81955. /**
  81956. * @private
  81957. * @type {Object.<string, (Array.<ol.style.Style>|string)>}
  81958. */
  81959. this.sharedStyles_ = {};
  81960. };
  81961. goog.inherits(ol.format.KML, ol.format.XMLFeature);
  81962. /**
  81963. * @const
  81964. * @type {Array.<string>}
  81965. * @private
  81966. */
  81967. ol.format.KML.EXTENSIONS_ = ['.kml'];
  81968. /**
  81969. * @const
  81970. * @type {Array.<string>}
  81971. * @private
  81972. */
  81973. ol.format.KML.GX_NAMESPACE_URIS_ = [
  81974. 'http://www.google.com/kml/ext/2.2'
  81975. ];
  81976. /**
  81977. * @const
  81978. * @type {Array.<string>}
  81979. * @private
  81980. */
  81981. ol.format.KML.NAMESPACE_URIS_ = [
  81982. null,
  81983. 'http://earth.google.com/kml/2.0',
  81984. 'http://earth.google.com/kml/2.1',
  81985. 'http://earth.google.com/kml/2.2',
  81986. 'http://www.opengis.net/kml/2.2'
  81987. ];
  81988. /**
  81989. * @const
  81990. * @type {string}
  81991. * @private
  81992. */
  81993. ol.format.KML.SCHEMA_LOCATION_ = 'http://www.opengis.net/kml/2.2 ' +
  81994. 'https://developers.google.com/kml/schema/kml22gx.xsd';
  81995. /**
  81996. * @const
  81997. * @type {ol.Color}
  81998. * @private
  81999. */
  82000. ol.format.KML.DEFAULT_COLOR_ = [255, 255, 255, 1];
  82001. /**
  82002. * @const
  82003. * @type {ol.style.Fill}
  82004. * @private
  82005. */
  82006. ol.format.KML.DEFAULT_FILL_STYLE_ = new ol.style.Fill({
  82007. color: ol.format.KML.DEFAULT_COLOR_
  82008. });
  82009. /**
  82010. * @const
  82011. * @type {ol.Size}
  82012. * @private
  82013. */
  82014. ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_ = [20, 2]; // FIXME maybe [8, 32] ?
  82015. /**
  82016. * @const
  82017. * @type {ol.style.IconAnchorUnits}
  82018. * @private
  82019. */
  82020. ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_ =
  82021. ol.style.IconAnchorUnits.PIXELS;
  82022. /**
  82023. * @const
  82024. * @type {ol.style.IconAnchorUnits}
  82025. * @private
  82026. */
  82027. ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_ =
  82028. ol.style.IconAnchorUnits.PIXELS;
  82029. /**
  82030. * @const
  82031. * @type {ol.Size}
  82032. * @private
  82033. */
  82034. ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_ = [64, 64];
  82035. /**
  82036. * @const
  82037. * @type {string}
  82038. * @private
  82039. */
  82040. ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_ =
  82041. 'https://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';
  82042. /**
  82043. * @const
  82044. * @type {ol.style.Image}
  82045. * @private
  82046. */
  82047. ol.format.KML.DEFAULT_IMAGE_STYLE_ = new ol.style.Icon({
  82048. anchor: ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_,
  82049. anchorOrigin: ol.style.IconOrigin.BOTTOM_LEFT,
  82050. anchorXUnits: ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_,
  82051. anchorYUnits: ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_,
  82052. crossOrigin: 'anonymous',
  82053. rotation: 0,
  82054. scale: 0.5,
  82055. size: ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_,
  82056. src: ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_
  82057. });
  82058. /**
  82059. * @const
  82060. * @type {ol.style.Stroke}
  82061. * @private
  82062. */
  82063. ol.format.KML.DEFAULT_STROKE_STYLE_ = new ol.style.Stroke({
  82064. color: ol.format.KML.DEFAULT_COLOR_,
  82065. width: 1
  82066. });
  82067. /**
  82068. * @const
  82069. * @type {ol.style.Text}
  82070. * @private
  82071. */
  82072. ol.format.KML.DEFAULT_TEXT_STYLE_ = new ol.style.Text({
  82073. font: 'normal 16px Helvetica',
  82074. fill: ol.format.KML.DEFAULT_FILL_STYLE_,
  82075. stroke: ol.format.KML.DEFAULT_STROKE_STYLE_,
  82076. scale: 1
  82077. });
  82078. /**
  82079. * @const
  82080. * @type {ol.style.Style}
  82081. * @private
  82082. */
  82083. ol.format.KML.DEFAULT_STYLE_ = new ol.style.Style({
  82084. fill: ol.format.KML.DEFAULT_FILL_STYLE_,
  82085. image: ol.format.KML.DEFAULT_IMAGE_STYLE_,
  82086. text: ol.format.KML.DEFAULT_TEXT_STYLE_,
  82087. stroke: ol.format.KML.DEFAULT_STROKE_STYLE_,
  82088. zIndex: 0
  82089. });
  82090. /**
  82091. * @const
  82092. * @type {Array.<ol.style.Style>}
  82093. * @private
  82094. */
  82095. ol.format.KML.DEFAULT_STYLE_ARRAY_ = [ol.format.KML.DEFAULT_STYLE_];
  82096. /**
  82097. * @const
  82098. * @type {Object.<string, ol.style.IconAnchorUnits>}
  82099. * @private
  82100. */
  82101. ol.format.KML.ICON_ANCHOR_UNITS_MAP_ = {
  82102. 'fraction': ol.style.IconAnchorUnits.FRACTION,
  82103. 'pixels': ol.style.IconAnchorUnits.PIXELS
  82104. };
  82105. /**
  82106. * @param {Array.<ol.style.Style>|undefined} style Style.
  82107. * @param {string} styleUrl Style URL.
  82108. * @param {Array.<ol.style.Style>} defaultStyle Default style.
  82109. * @param {Object.<string, (Array.<ol.style.Style>|string)>} sharedStyles
  82110. * Shared styles.
  82111. * @return {ol.FeatureStyleFunction} Feature style function.
  82112. * @private
  82113. */
  82114. ol.format.KML.createFeatureStyleFunction_ = function(
  82115. style, styleUrl, defaultStyle, sharedStyles) {
  82116. return (
  82117. /**
  82118. * @param {number} resolution Resolution.
  82119. * @return {Array.<ol.style.Style>} Style.
  82120. * @this {ol.Feature}
  82121. */
  82122. function(resolution) {
  82123. if (style) {
  82124. return style;
  82125. }
  82126. if (styleUrl) {
  82127. return ol.format.KML.findStyle_(styleUrl, defaultStyle, sharedStyles);
  82128. }
  82129. return defaultStyle;
  82130. });
  82131. };
  82132. /**
  82133. * @param {Array.<ol.style.Style>|string|undefined} styleValue Style value.
  82134. * @param {Array.<ol.style.Style>} defaultStyle Default style.
  82135. * @param {Object.<string, (Array.<ol.style.Style>|string)>} sharedStyles
  82136. * Shared styles.
  82137. * @return {Array.<ol.style.Style>} Style.
  82138. * @private
  82139. */
  82140. ol.format.KML.findStyle_ = function(styleValue, defaultStyle, sharedStyles) {
  82141. if (goog.isArray(styleValue)) {
  82142. return styleValue;
  82143. } else if (goog.isString(styleValue)) {
  82144. // KML files in the wild occasionally forget the leading `#` on styleUrls
  82145. // defined in the same document. Add a leading `#` if it enables to find
  82146. // a style.
  82147. if (!(styleValue in sharedStyles) && ('#' + styleValue in sharedStyles)) {
  82148. styleValue = '#' + styleValue;
  82149. }
  82150. return ol.format.KML.findStyle_(
  82151. sharedStyles[styleValue], defaultStyle, sharedStyles);
  82152. } else {
  82153. return defaultStyle;
  82154. }
  82155. };
  82156. /**
  82157. * @param {Node} node Node.
  82158. * @private
  82159. * @return {ol.Color|undefined} Color.
  82160. */
  82161. ol.format.KML.readColor_ = function(node) {
  82162. var s = ol.xml.getAllTextContent(node, false);
  82163. // The KML specification states that colors should not include a leading `#`
  82164. // but we tolerate them.
  82165. var m = /^\s*#?\s*([0-9A-Fa-f]{8})\s*$/.exec(s);
  82166. if (m) {
  82167. var hexColor = m[1];
  82168. return [
  82169. parseInt(hexColor.substr(6, 2), 16),
  82170. parseInt(hexColor.substr(4, 2), 16),
  82171. parseInt(hexColor.substr(2, 2), 16),
  82172. parseInt(hexColor.substr(0, 2), 16) / 255
  82173. ];
  82174. } else {
  82175. return undefined;
  82176. }
  82177. };
  82178. /**
  82179. * @param {Node} node Node.
  82180. * @private
  82181. * @return {Array.<number>|undefined} Flat coordinates.
  82182. */
  82183. ol.format.KML.readFlatCoordinates_ = function(node) {
  82184. var s = ol.xml.getAllTextContent(node, false);
  82185. var flatCoordinates = [];
  82186. // The KML specification states that coordinate tuples should not include
  82187. // spaces, but we tolerate them.
  82188. var re =
  82189. /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)(?:\s*,\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?))?\s*/i;
  82190. var m;
  82191. while ((m = re.exec(s))) {
  82192. var x = parseFloat(m[1]);
  82193. var y = parseFloat(m[2]);
  82194. var z = m[3] ? parseFloat(m[3]) : 0;
  82195. flatCoordinates.push(x, y, z);
  82196. s = s.substr(m[0].length);
  82197. }
  82198. if (s !== '') {
  82199. return undefined;
  82200. }
  82201. return flatCoordinates;
  82202. };
  82203. /**
  82204. * @param {Node} node Node.
  82205. * @private
  82206. * @return {string|undefined} Style URL.
  82207. */
  82208. ol.format.KML.readStyleUrl_ = function(node) {
  82209. var s = ol.xml.getAllTextContent(node, false).trim();
  82210. if (node.baseURI) {
  82211. return goog.Uri.resolve(node.baseURI, s).toString();
  82212. } else {
  82213. return s;
  82214. }
  82215. };
  82216. /**
  82217. * @param {Node} node Node.
  82218. * @private
  82219. * @return {string} URI.
  82220. */
  82221. ol.format.KML.readURI_ = function(node) {
  82222. var s = ol.xml.getAllTextContent(node, false);
  82223. if (node.baseURI) {
  82224. return goog.Uri.resolve(node.baseURI, s.trim()).toString();
  82225. } else {
  82226. return s.trim();
  82227. }
  82228. };
  82229. /**
  82230. * @param {Node} node Node.
  82231. * @private
  82232. * @return {ol.format.KMLVec2_} Vec2.
  82233. */
  82234. ol.format.KML.readVec2_ = function(node) {
  82235. var xunits = node.getAttribute('xunits');
  82236. var yunits = node.getAttribute('yunits');
  82237. return {
  82238. x: parseFloat(node.getAttribute('x')),
  82239. xunits: ol.format.KML.ICON_ANCHOR_UNITS_MAP_[xunits],
  82240. y: parseFloat(node.getAttribute('y')),
  82241. yunits: ol.format.KML.ICON_ANCHOR_UNITS_MAP_[yunits]
  82242. };
  82243. };
  82244. /**
  82245. * @param {Node} node Node.
  82246. * @private
  82247. * @return {number|undefined} Scale.
  82248. */
  82249. ol.format.KML.readScale_ = function(node) {
  82250. var number = ol.format.XSD.readDecimal(node);
  82251. if (number !== undefined) {
  82252. return Math.sqrt(number);
  82253. } else {
  82254. return undefined;
  82255. }
  82256. };
  82257. /**
  82258. * @param {Node} node Node.
  82259. * @param {Array.<*>} objectStack Object stack.
  82260. * @private
  82261. * @return {Array.<ol.style.Style>|string|undefined} StyleMap.
  82262. */
  82263. ol.format.KML.readStyleMapValue_ = function(node, objectStack) {
  82264. return ol.xml.pushParseAndPop(
  82265. /** @type {Array.<ol.style.Style>|string|undefined} */ (undefined),
  82266. ol.format.KML.STYLE_MAP_PARSERS_, node, objectStack);
  82267. };
  82268. /**
  82269. * @param {Node} node Node.
  82270. * @param {Array.<*>} objectStack Object stack.
  82271. * @private
  82272. */
  82273. ol.format.KML.IconStyleParser_ = function(node, objectStack) {
  82274. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82275. 'node.nodeType should be an ELEMENT');
  82276. goog.asserts.assert(node.localName == 'IconStyle',
  82277. 'localName should be IconStyle');
  82278. // FIXME refreshMode
  82279. // FIXME refreshInterval
  82280. // FIXME viewRefreshTime
  82281. // FIXME viewBoundScale
  82282. // FIXME viewFormat
  82283. // FIXME httpQuery
  82284. var object = ol.xml.pushParseAndPop(
  82285. {}, ol.format.KML.ICON_STYLE_PARSERS_, node, objectStack);
  82286. if (!object) {
  82287. return;
  82288. }
  82289. var styleObject = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  82290. goog.asserts.assert(goog.isObject(styleObject),
  82291. 'styleObject should be an Object');
  82292. var IconObject = 'Icon' in object ? object['Icon'] : {};
  82293. var src;
  82294. var href = /** @type {string|undefined} */
  82295. (IconObject['href']);
  82296. if (href) {
  82297. src = href;
  82298. } else {
  82299. src = ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_;
  82300. }
  82301. var anchor, anchorXUnits, anchorYUnits;
  82302. var hotSpot = /** @type {ol.format.KMLVec2_|undefined} */
  82303. (object['hotSpot']);
  82304. if (hotSpot) {
  82305. anchor = [hotSpot.x, hotSpot.y];
  82306. anchorXUnits = hotSpot.xunits;
  82307. anchorYUnits = hotSpot.yunits;
  82308. } else if (src === ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_) {
  82309. anchor = ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_;
  82310. anchorXUnits = ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS_;
  82311. anchorYUnits = ol.format.KML.DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS_;
  82312. } else if (/^http:\/\/maps\.(?:google|gstatic)\.com\//.test(src)) {
  82313. anchor = [0.5, 0];
  82314. anchorXUnits = ol.style.IconAnchorUnits.FRACTION;
  82315. anchorYUnits = ol.style.IconAnchorUnits.FRACTION;
  82316. }
  82317. var offset;
  82318. var x = /** @type {number|undefined} */
  82319. (IconObject['x']);
  82320. var y = /** @type {number|undefined} */
  82321. (IconObject['y']);
  82322. if (x !== undefined && y !== undefined) {
  82323. offset = [x, y];
  82324. }
  82325. var size;
  82326. var w = /** @type {number|undefined} */
  82327. (IconObject['w']);
  82328. var h = /** @type {number|undefined} */
  82329. (IconObject['h']);
  82330. if (w !== undefined && h !== undefined) {
  82331. size = [w, h];
  82332. }
  82333. var rotation;
  82334. var heading = /** @type {number} */
  82335. (object['heading']);
  82336. if (heading !== undefined) {
  82337. rotation = goog.math.toRadians(heading);
  82338. }
  82339. var scale = /** @type {number|undefined} */
  82340. (object['scale']);
  82341. if (src == ol.format.KML.DEFAULT_IMAGE_STYLE_SRC_) {
  82342. size = ol.format.KML.DEFAULT_IMAGE_STYLE_SIZE_;
  82343. }
  82344. var imageStyle = new ol.style.Icon({
  82345. anchor: anchor,
  82346. anchorOrigin: ol.style.IconOrigin.BOTTOM_LEFT,
  82347. anchorXUnits: anchorXUnits,
  82348. anchorYUnits: anchorYUnits,
  82349. crossOrigin: 'anonymous', // FIXME should this be configurable?
  82350. offset: offset,
  82351. offsetOrigin: ol.style.IconOrigin.BOTTOM_LEFT,
  82352. rotation: rotation,
  82353. scale: scale,
  82354. size: size,
  82355. src: src
  82356. });
  82357. styleObject['imageStyle'] = imageStyle;
  82358. };
  82359. /**
  82360. * @param {Node} node Node.
  82361. * @param {Array.<*>} objectStack Object stack.
  82362. * @private
  82363. */
  82364. ol.format.KML.LabelStyleParser_ = function(node, objectStack) {
  82365. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82366. 'node.nodeType should be ELEMENT');
  82367. goog.asserts.assert(node.localName == 'LabelStyle',
  82368. 'localName should be LabelStyle');
  82369. // FIXME colorMode
  82370. var object = ol.xml.pushParseAndPop(
  82371. {}, ol.format.KML.LABEL_STYLE_PARSERS_, node, objectStack);
  82372. if (!object) {
  82373. return;
  82374. }
  82375. var styleObject = objectStack[objectStack.length - 1];
  82376. goog.asserts.assert(goog.isObject(styleObject),
  82377. 'styleObject should be an Object');
  82378. var textStyle = new ol.style.Text({
  82379. fill: new ol.style.Fill({
  82380. color: /** @type {ol.Color} */
  82381. ('color' in object ? object['color'] : ol.format.KML.DEFAULT_COLOR_)
  82382. }),
  82383. scale: /** @type {number|undefined} */
  82384. (object['scale'])
  82385. });
  82386. styleObject['textStyle'] = textStyle;
  82387. };
  82388. /**
  82389. * @param {Node} node Node.
  82390. * @param {Array.<*>} objectStack Object stack.
  82391. * @private
  82392. */
  82393. ol.format.KML.LineStyleParser_ = function(node, objectStack) {
  82394. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82395. 'node.nodeType should be ELEMENT');
  82396. goog.asserts.assert(node.localName == 'LineStyle',
  82397. 'localName should be LineStyle');
  82398. // FIXME colorMode
  82399. // FIXME gx:outerColor
  82400. // FIXME gx:outerWidth
  82401. // FIXME gx:physicalWidth
  82402. // FIXME gx:labelVisibility
  82403. var object = ol.xml.pushParseAndPop(
  82404. {}, ol.format.KML.LINE_STYLE_PARSERS_, node, objectStack);
  82405. if (!object) {
  82406. return;
  82407. }
  82408. var styleObject = objectStack[objectStack.length - 1];
  82409. goog.asserts.assert(goog.isObject(styleObject),
  82410. 'styleObject should be an Object');
  82411. var strokeStyle = new ol.style.Stroke({
  82412. color: /** @type {ol.Color} */
  82413. ('color' in object ? object['color'] : ol.format.KML.DEFAULT_COLOR_),
  82414. width: /** @type {number} */ ('width' in object ? object['width'] : 1)
  82415. });
  82416. styleObject['strokeStyle'] = strokeStyle;
  82417. };
  82418. /**
  82419. * @param {Node} node Node.
  82420. * @param {Array.<*>} objectStack Object stack.
  82421. * @private
  82422. */
  82423. ol.format.KML.PolyStyleParser_ = function(node, objectStack) {
  82424. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82425. 'node.nodeType should be ELEMENT');
  82426. goog.asserts.assert(node.localName == 'PolyStyle',
  82427. 'localName should be PolyStyle');
  82428. // FIXME colorMode
  82429. var object = ol.xml.pushParseAndPop(
  82430. {}, ol.format.KML.POLY_STYLE_PARSERS_, node, objectStack);
  82431. if (!object) {
  82432. return;
  82433. }
  82434. var styleObject = objectStack[objectStack.length - 1];
  82435. goog.asserts.assert(goog.isObject(styleObject),
  82436. 'styleObject should be an Object');
  82437. var fillStyle = new ol.style.Fill({
  82438. color: /** @type {ol.Color} */
  82439. ('color' in object ? object['color'] : ol.format.KML.DEFAULT_COLOR_)
  82440. });
  82441. styleObject['fillStyle'] = fillStyle;
  82442. var fill = /** @type {boolean|undefined} */ (object['fill']);
  82443. if (fill !== undefined) {
  82444. styleObject['fill'] = fill;
  82445. }
  82446. var outline =
  82447. /** @type {boolean|undefined} */ (object['outline']);
  82448. if (outline !== undefined) {
  82449. styleObject['outline'] = outline;
  82450. }
  82451. };
  82452. /**
  82453. * @param {Node} node Node.
  82454. * @param {Array.<*>} objectStack Object stack.
  82455. * @private
  82456. * @return {Array.<number>} LinearRing flat coordinates.
  82457. */
  82458. ol.format.KML.readFlatLinearRing_ = function(node, objectStack) {
  82459. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82460. 'node.nodeType should be ELEMENT');
  82461. goog.asserts.assert(node.localName == 'LinearRing',
  82462. 'localName should be LinearRing');
  82463. return /** @type {Array.<number>} */ (ol.xml.pushParseAndPop(
  82464. null, ol.format.KML.FLAT_LINEAR_RING_PARSERS_, node, objectStack));
  82465. };
  82466. /**
  82467. * @param {Node} node Node.
  82468. * @param {Array.<*>} objectStack Object stack.
  82469. * @private
  82470. */
  82471. ol.format.KML.gxCoordParser_ = function(node, objectStack) {
  82472. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82473. 'node.nodeType should be ELEMENT');
  82474. goog.asserts.assert(ol.array.includes(
  82475. ol.format.KML.GX_NAMESPACE_URIS_, node.namespaceURI),
  82476. 'namespaceURI of the node should be known to the KML parser');
  82477. goog.asserts.assert(node.localName == 'coord', 'localName should be coord');
  82478. var gxTrackObject = /** @type {ol.format.KMLGxTrackObject_} */
  82479. (objectStack[objectStack.length - 1]);
  82480. goog.asserts.assert(goog.isObject(gxTrackObject),
  82481. 'gxTrackObject should be an Object');
  82482. var flatCoordinates = gxTrackObject.flatCoordinates;
  82483. var s = ol.xml.getAllTextContent(node, false);
  82484. var re =
  82485. /^\s*([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s*$/i;
  82486. var m = re.exec(s);
  82487. if (m) {
  82488. var x = parseFloat(m[1]);
  82489. var y = parseFloat(m[2]);
  82490. var z = parseFloat(m[3]);
  82491. flatCoordinates.push(x, y, z, 0);
  82492. } else {
  82493. flatCoordinates.push(0, 0, 0, 0);
  82494. }
  82495. };
  82496. /**
  82497. * @param {Node} node Node.
  82498. * @param {Array.<*>} objectStack Object stack.
  82499. * @private
  82500. * @return {ol.geom.MultiLineString|undefined} MultiLineString.
  82501. */
  82502. ol.format.KML.readGxMultiTrack_ = function(node, objectStack) {
  82503. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82504. 'node.nodeType should be ELEMENT');
  82505. goog.asserts.assert(ol.array.includes(
  82506. ol.format.KML.GX_NAMESPACE_URIS_, node.namespaceURI),
  82507. 'namespaceURI of the node should be known to the KML parser');
  82508. goog.asserts.assert(node.localName == 'MultiTrack',
  82509. 'localName should be MultiTrack');
  82510. var lineStrings = ol.xml.pushParseAndPop(
  82511. /** @type {Array.<ol.geom.LineString>} */ ([]),
  82512. ol.format.KML.GX_MULTITRACK_GEOMETRY_PARSERS_, node, objectStack);
  82513. if (!lineStrings) {
  82514. return undefined;
  82515. }
  82516. var multiLineString = new ol.geom.MultiLineString(null);
  82517. multiLineString.setLineStrings(lineStrings);
  82518. return multiLineString;
  82519. };
  82520. /**
  82521. * @param {Node} node Node.
  82522. * @param {Array.<*>} objectStack Object stack.
  82523. * @private
  82524. * @return {ol.geom.LineString|undefined} LineString.
  82525. */
  82526. ol.format.KML.readGxTrack_ = function(node, objectStack) {
  82527. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82528. 'node.nodeType should be ELEMENT');
  82529. goog.asserts.assert(ol.array.includes(
  82530. ol.format.KML.GX_NAMESPACE_URIS_, node.namespaceURI),
  82531. 'namespaceURI of the node should be known to the KML parser');
  82532. goog.asserts.assert(node.localName == 'Track', 'localName should be Track');
  82533. var gxTrackObject = ol.xml.pushParseAndPop(
  82534. /** @type {ol.format.KMLGxTrackObject_} */ ({
  82535. flatCoordinates: [],
  82536. whens: []
  82537. }), ol.format.KML.GX_TRACK_PARSERS_, node, objectStack);
  82538. if (!gxTrackObject) {
  82539. return undefined;
  82540. }
  82541. var flatCoordinates = gxTrackObject.flatCoordinates;
  82542. var whens = gxTrackObject.whens;
  82543. goog.asserts.assert(flatCoordinates.length / 4 == whens.length,
  82544. 'the length of the flatCoordinates array divided by 4 should be the ' +
  82545. 'length of the whens array');
  82546. var i, ii;
  82547. for (i = 0, ii = Math.min(flatCoordinates.length, whens.length); i < ii;
  82548. ++i) {
  82549. flatCoordinates[4 * i + 3] = whens[i];
  82550. }
  82551. var lineString = new ol.geom.LineString(null);
  82552. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZM, flatCoordinates);
  82553. return lineString;
  82554. };
  82555. /**
  82556. * @param {Node} node Node.
  82557. * @param {Array.<*>} objectStack Object stack.
  82558. * @private
  82559. * @return {Object} Icon object.
  82560. */
  82561. ol.format.KML.readIcon_ = function(node, objectStack) {
  82562. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82563. 'node.nodeType should be ELEMENT');
  82564. goog.asserts.assert(node.localName == 'Icon', 'localName should be Icon');
  82565. var iconObject = ol.xml.pushParseAndPop(
  82566. {}, ol.format.KML.ICON_PARSERS_, node, objectStack);
  82567. if (iconObject) {
  82568. return iconObject;
  82569. } else {
  82570. return null;
  82571. }
  82572. };
  82573. /**
  82574. * @param {Node} node Node.
  82575. * @param {Array.<*>} objectStack Object stack.
  82576. * @private
  82577. * @return {Array.<number>} Flat coordinates.
  82578. */
  82579. ol.format.KML.readFlatCoordinatesFromNode_ = function(node, objectStack) {
  82580. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82581. 'node.nodeType should be ELEMENT');
  82582. return /** @type {Array.<number>} */ (ol.xml.pushParseAndPop(null,
  82583. ol.format.KML.GEOMETRY_FLAT_COORDINATES_PARSERS_, node, objectStack));
  82584. };
  82585. /**
  82586. * @param {Node} node Node.
  82587. * @param {Array.<*>} objectStack Object stack.
  82588. * @private
  82589. * @return {ol.geom.LineString|undefined} LineString.
  82590. */
  82591. ol.format.KML.readLineString_ = function(node, objectStack) {
  82592. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82593. 'node.nodeType should be ELEMENT');
  82594. goog.asserts.assert(node.localName == 'LineString',
  82595. 'localName should be LineString');
  82596. var properties = ol.xml.pushParseAndPop(/** @type {Object<string,*>} */ ({}),
  82597. ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node,
  82598. objectStack);
  82599. var flatCoordinates =
  82600. ol.format.KML.readFlatCoordinatesFromNode_(node, objectStack);
  82601. if (flatCoordinates) {
  82602. var lineString = new ol.geom.LineString(null);
  82603. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  82604. lineString.setProperties(properties);
  82605. return lineString;
  82606. } else {
  82607. return undefined;
  82608. }
  82609. };
  82610. /**
  82611. * @param {Node} node Node.
  82612. * @param {Array.<*>} objectStack Object stack.
  82613. * @private
  82614. * @return {ol.geom.Polygon|undefined} Polygon.
  82615. */
  82616. ol.format.KML.readLinearRing_ = function(node, objectStack) {
  82617. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82618. 'node.nodeType should be ELEMENT');
  82619. goog.asserts.assert(node.localName == 'LinearRing',
  82620. 'localName should be LinearRing');
  82621. var properties = ol.xml.pushParseAndPop(/** @type {Object<string,*>} */ ({}),
  82622. ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node,
  82623. objectStack);
  82624. var flatCoordinates =
  82625. ol.format.KML.readFlatCoordinatesFromNode_(node, objectStack);
  82626. if (flatCoordinates) {
  82627. var polygon = new ol.geom.Polygon(null);
  82628. polygon.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates,
  82629. [flatCoordinates.length]);
  82630. polygon.setProperties(properties);
  82631. return polygon;
  82632. } else {
  82633. return undefined;
  82634. }
  82635. };
  82636. /**
  82637. * @param {Node} node Node.
  82638. * @param {Array.<*>} objectStack Object stack.
  82639. * @private
  82640. * @return {ol.geom.Geometry} Geometry.
  82641. */
  82642. ol.format.KML.readMultiGeometry_ = function(node, objectStack) {
  82643. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82644. 'node.nodeType should be ELEMENT');
  82645. goog.asserts.assert(node.localName == 'MultiGeometry',
  82646. 'localName should be MultiGeometry');
  82647. var geometries = ol.xml.pushParseAndPop(
  82648. /** @type {Array.<ol.geom.Geometry>} */ ([]),
  82649. ol.format.KML.MULTI_GEOMETRY_PARSERS_, node, objectStack);
  82650. if (!geometries) {
  82651. return null;
  82652. }
  82653. if (geometries.length === 0) {
  82654. return new ol.geom.GeometryCollection(geometries);
  82655. }
  82656. var homogeneous = true;
  82657. var type = geometries[0].getType();
  82658. var geometry, i, ii;
  82659. for (i = 1, ii = geometries.length; i < ii; ++i) {
  82660. geometry = geometries[i];
  82661. if (geometry.getType() != type) {
  82662. homogeneous = false;
  82663. break;
  82664. }
  82665. }
  82666. if (homogeneous) {
  82667. /** @type {ol.geom.GeometryLayout} */
  82668. var layout;
  82669. /** @type {Array.<number>} */
  82670. var flatCoordinates;
  82671. if (type == ol.geom.GeometryType.POINT) {
  82672. var point = geometries[0];
  82673. goog.asserts.assertInstanceof(point, ol.geom.Point,
  82674. 'point should be an ol.geom.Point');
  82675. layout = point.getLayout();
  82676. flatCoordinates = point.getFlatCoordinates();
  82677. for (i = 1, ii = geometries.length; i < ii; ++i) {
  82678. geometry = geometries[i];
  82679. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  82680. 'geometry should be an ol.geom.Point');
  82681. goog.asserts.assert(geometry.getLayout() == layout,
  82682. 'geometry layout should be consistent');
  82683. goog.array.extend(flatCoordinates, geometry.getFlatCoordinates());
  82684. }
  82685. var multiPoint = new ol.geom.MultiPoint(null);
  82686. multiPoint.setFlatCoordinates(layout, flatCoordinates);
  82687. ol.format.KML.setCommonGeometryProperties_(multiPoint, geometries);
  82688. return multiPoint;
  82689. } else if (type == ol.geom.GeometryType.LINE_STRING) {
  82690. var multiLineString = new ol.geom.MultiLineString(null);
  82691. multiLineString.setLineStrings(geometries);
  82692. ol.format.KML.setCommonGeometryProperties_(multiLineString, geometries);
  82693. return multiLineString;
  82694. } else if (type == ol.geom.GeometryType.POLYGON) {
  82695. var multiPolygon = new ol.geom.MultiPolygon(null);
  82696. multiPolygon.setPolygons(geometries);
  82697. ol.format.KML.setCommonGeometryProperties_(multiPolygon, geometries);
  82698. return multiPolygon;
  82699. } else if (type == ol.geom.GeometryType.GEOMETRY_COLLECTION) {
  82700. return new ol.geom.GeometryCollection(geometries);
  82701. } else {
  82702. goog.asserts.fail('Unexpected type: ' + type);
  82703. return null;
  82704. }
  82705. } else {
  82706. return new ol.geom.GeometryCollection(geometries);
  82707. }
  82708. };
  82709. /**
  82710. * @param {Node} node Node.
  82711. * @param {Array.<*>} objectStack Object stack.
  82712. * @private
  82713. * @return {ol.geom.Point|undefined} Point.
  82714. */
  82715. ol.format.KML.readPoint_ = function(node, objectStack) {
  82716. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82717. 'node.nodeType should be ELEMENT');
  82718. goog.asserts.assert(node.localName == 'Point', 'localName should be Point');
  82719. var properties = ol.xml.pushParseAndPop(/** @type {Object<string,*>} */ ({}),
  82720. ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node,
  82721. objectStack);
  82722. var flatCoordinates =
  82723. ol.format.KML.readFlatCoordinatesFromNode_(node, objectStack);
  82724. if (flatCoordinates) {
  82725. var point = new ol.geom.Point(null);
  82726. goog.asserts.assert(flatCoordinates.length == 3,
  82727. 'flatCoordinates should have a length of 3');
  82728. point.setFlatCoordinates(ol.geom.GeometryLayout.XYZ, flatCoordinates);
  82729. point.setProperties(properties);
  82730. return point;
  82731. } else {
  82732. return undefined;
  82733. }
  82734. };
  82735. /**
  82736. * @param {Node} node Node.
  82737. * @param {Array.<*>} objectStack Object stack.
  82738. * @private
  82739. * @return {ol.geom.Polygon|undefined} Polygon.
  82740. */
  82741. ol.format.KML.readPolygon_ = function(node, objectStack) {
  82742. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82743. 'node.nodeType should be ELEMENT');
  82744. goog.asserts.assert(node.localName == 'Polygon',
  82745. 'localName should be Polygon');
  82746. var properties = ol.xml.pushParseAndPop(/** @type {Object<string,*>} */ ({}),
  82747. ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_, node,
  82748. objectStack);
  82749. var flatLinearRings = ol.xml.pushParseAndPop(
  82750. /** @type {Array.<Array.<number>>} */ ([null]),
  82751. ol.format.KML.FLAT_LINEAR_RINGS_PARSERS_, node, objectStack);
  82752. if (flatLinearRings && flatLinearRings[0]) {
  82753. var polygon = new ol.geom.Polygon(null);
  82754. var flatCoordinates = flatLinearRings[0];
  82755. var ends = [flatCoordinates.length];
  82756. var i, ii;
  82757. for (i = 1, ii = flatLinearRings.length; i < ii; ++i) {
  82758. goog.array.extend(flatCoordinates, flatLinearRings[i]);
  82759. ends.push(flatCoordinates.length);
  82760. }
  82761. polygon.setFlatCoordinates(
  82762. ol.geom.GeometryLayout.XYZ, flatCoordinates, ends);
  82763. polygon.setProperties(properties);
  82764. return polygon;
  82765. } else {
  82766. return undefined;
  82767. }
  82768. };
  82769. /**
  82770. * @param {Node} node Node.
  82771. * @param {Array.<*>} objectStack Object stack.
  82772. * @private
  82773. * @return {Array.<ol.style.Style>} Style.
  82774. */
  82775. ol.format.KML.readStyle_ = function(node, objectStack) {
  82776. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82777. 'node.nodeType should be ELEMENT');
  82778. goog.asserts.assert(node.localName == 'Style', 'localName should be Style');
  82779. var styleObject = ol.xml.pushParseAndPop(
  82780. {}, ol.format.KML.STYLE_PARSERS_, node, objectStack);
  82781. if (!styleObject) {
  82782. return null;
  82783. }
  82784. var fillStyle = /** @type {ol.style.Fill} */
  82785. ('fillStyle' in styleObject ?
  82786. styleObject['fillStyle'] : ol.format.KML.DEFAULT_FILL_STYLE_);
  82787. var fill = /** @type {boolean|undefined} */ (styleObject['fill']);
  82788. if (fill !== undefined && !fill) {
  82789. fillStyle = null;
  82790. }
  82791. var imageStyle = /** @type {ol.style.Image} */
  82792. ('imageStyle' in styleObject ?
  82793. styleObject['imageStyle'] : ol.format.KML.DEFAULT_IMAGE_STYLE_);
  82794. var textStyle = /** @type {ol.style.Text} */
  82795. ('textStyle' in styleObject ?
  82796. styleObject['textStyle'] : ol.format.KML.DEFAULT_TEXT_STYLE_);
  82797. var strokeStyle = /** @type {ol.style.Stroke} */
  82798. ('strokeStyle' in styleObject ?
  82799. styleObject['strokeStyle'] : ol.format.KML.DEFAULT_STROKE_STYLE_);
  82800. var outline = /** @type {boolean|undefined} */
  82801. (styleObject['outline']);
  82802. if (outline !== undefined && !outline) {
  82803. strokeStyle = null;
  82804. }
  82805. return [new ol.style.Style({
  82806. fill: fillStyle,
  82807. image: imageStyle,
  82808. stroke: strokeStyle,
  82809. text: textStyle,
  82810. zIndex: undefined // FIXME
  82811. })];
  82812. };
  82813. /**
  82814. * Reads an array of geometries and creates arrays for common geometry
  82815. * properties. Then sets them to the multi geometry.
  82816. * @param {ol.geom.MultiPoint|ol.geom.MultiLineString|ol.geom.MultiPolygon}
  82817. * multiGeometry
  82818. * @param {Array.<ol.geom.Geometry>} geometries
  82819. * @private
  82820. */
  82821. ol.format.KML.setCommonGeometryProperties_ = function(multiGeometry,
  82822. geometries) {
  82823. var ii = geometries.length;
  82824. var extrudes = new Array(geometries.length);
  82825. var altitudeModes = new Array(geometries.length);
  82826. var geometry, i, hasExtrude, hasAltitudeMode;
  82827. hasExtrude = hasAltitudeMode = false;
  82828. for (i = 0; i < ii; ++i) {
  82829. geometry = geometries[i];
  82830. extrudes[i] = geometry.get('extrude');
  82831. altitudeModes[i] = geometry.get('altitudeMode');
  82832. hasExtrude = hasExtrude || extrudes[i] !== undefined;
  82833. hasAltitudeMode = hasAltitudeMode || altitudeModes[i];
  82834. }
  82835. if (hasExtrude) {
  82836. multiGeometry.set('extrude', extrudes);
  82837. }
  82838. if (hasAltitudeMode) {
  82839. multiGeometry.set('altitudeMode', altitudeModes);
  82840. }
  82841. };
  82842. /**
  82843. * @param {Node} node Node.
  82844. * @param {Array.<*>} objectStack Object stack.
  82845. * @private
  82846. */
  82847. ol.format.KML.DataParser_ = function(node, objectStack) {
  82848. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82849. 'node.nodeType should be ELEMENT');
  82850. goog.asserts.assert(node.localName == 'Data', 'localName should be Data');
  82851. var name = node.getAttribute('name');
  82852. if (name !== null) {
  82853. var data = ol.xml.pushParseAndPop(
  82854. undefined, ol.format.KML.DATA_PARSERS_, node, objectStack);
  82855. if (data) {
  82856. var featureObject =
  82857. /** @type {Object} */ (objectStack[objectStack.length - 1]);
  82858. goog.asserts.assert(goog.isObject(featureObject),
  82859. 'featureObject should be an Object');
  82860. featureObject[name] = data;
  82861. }
  82862. }
  82863. };
  82864. /**
  82865. * @param {Node} node Node.
  82866. * @param {Array.<*>} objectStack Object stack.
  82867. * @private
  82868. */
  82869. ol.format.KML.ExtendedDataParser_ = function(node, objectStack) {
  82870. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82871. 'node.nodeType should be ELEMENT');
  82872. goog.asserts.assert(node.localName == 'ExtendedData',
  82873. 'localName should be ExtendedData');
  82874. ol.xml.parseNode(ol.format.KML.EXTENDED_DATA_PARSERS_, node, objectStack);
  82875. };
  82876. /**
  82877. * @param {Node} node Node.
  82878. * @param {Array.<*>} objectStack Object stack.
  82879. * @private
  82880. */
  82881. ol.format.KML.PairDataParser_ = function(node, objectStack) {
  82882. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82883. 'node.nodeType should be ELEMENT');
  82884. goog.asserts.assert(node.localName == 'Pair', 'localName should be Pair');
  82885. var pairObject = ol.xml.pushParseAndPop(
  82886. {}, ol.format.KML.PAIR_PARSERS_, node, objectStack);
  82887. if (!pairObject) {
  82888. return;
  82889. }
  82890. var key = /** @type {string|undefined} */
  82891. (pairObject['key']);
  82892. if (key && key == 'normal') {
  82893. var styleUrl = /** @type {string|undefined} */
  82894. (pairObject['styleUrl']);
  82895. if (styleUrl) {
  82896. objectStack[objectStack.length - 1] = styleUrl;
  82897. }
  82898. var Style = /** @type {ol.style.Style} */
  82899. (pairObject['Style']);
  82900. if (Style) {
  82901. objectStack[objectStack.length - 1] = Style;
  82902. }
  82903. }
  82904. };
  82905. /**
  82906. * @param {Node} node Node.
  82907. * @param {Array.<*>} objectStack Object stack.
  82908. * @private
  82909. */
  82910. ol.format.KML.PlacemarkStyleMapParser_ = function(node, objectStack) {
  82911. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82912. 'node.nodeType should be ELEMENT');
  82913. goog.asserts.assert(node.localName == 'StyleMap',
  82914. 'localName should be StyleMap');
  82915. var styleMapValue = ol.format.KML.readStyleMapValue_(node, objectStack);
  82916. if (!styleMapValue) {
  82917. return;
  82918. }
  82919. var placemarkObject = objectStack[objectStack.length - 1];
  82920. goog.asserts.assert(goog.isObject(placemarkObject),
  82921. 'placemarkObject should be an Object');
  82922. if (goog.isArray(styleMapValue)) {
  82923. placemarkObject['Style'] = styleMapValue;
  82924. } else if (goog.isString(styleMapValue)) {
  82925. placemarkObject['styleUrl'] = styleMapValue;
  82926. } else {
  82927. goog.asserts.fail('styleMapValue has an unknown type');
  82928. }
  82929. };
  82930. /**
  82931. * @param {Node} node Node.
  82932. * @param {Array.<*>} objectStack Object stack.
  82933. * @private
  82934. */
  82935. ol.format.KML.SchemaDataParser_ = function(node, objectStack) {
  82936. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82937. 'node.nodeType should be ELEMENT');
  82938. goog.asserts.assert(node.localName == 'SchemaData',
  82939. 'localName should be SchemaData');
  82940. ol.xml.parseNode(ol.format.KML.SCHEMA_DATA_PARSERS_, node, objectStack);
  82941. };
  82942. /**
  82943. * @param {Node} node Node.
  82944. * @param {Array.<*>} objectStack Object stack.
  82945. * @private
  82946. */
  82947. ol.format.KML.SimpleDataParser_ = function(node, objectStack) {
  82948. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82949. 'node.nodeType should be ELEMENT');
  82950. goog.asserts.assert(node.localName == 'SimpleData',
  82951. 'localName should be SimpleData');
  82952. var name = node.getAttribute('name');
  82953. if (name !== null) {
  82954. var data = ol.format.XSD.readString(node);
  82955. var featureObject =
  82956. /** @type {Object} */ (objectStack[objectStack.length - 1]);
  82957. featureObject[name] = data;
  82958. }
  82959. };
  82960. /**
  82961. * @param {Node} node Node.
  82962. * @param {Array.<*>} objectStack Object stack.
  82963. * @private
  82964. */
  82965. ol.format.KML.innerBoundaryIsParser_ = function(node, objectStack) {
  82966. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82967. 'node.nodeType should be ELEMENT');
  82968. goog.asserts.assert(node.localName == 'innerBoundaryIs',
  82969. 'localName should be innerBoundaryIs');
  82970. var flatLinearRing = ol.xml.pushParseAndPop(
  82971. /** @type {Array.<number>|undefined} */ (undefined),
  82972. ol.format.KML.INNER_BOUNDARY_IS_PARSERS_, node, objectStack);
  82973. if (flatLinearRing) {
  82974. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  82975. (objectStack[objectStack.length - 1]);
  82976. goog.asserts.assert(goog.isArray(flatLinearRings),
  82977. 'flatLinearRings should be an array');
  82978. goog.asserts.assert(flatLinearRings.length > 0,
  82979. 'flatLinearRings array should not be empty');
  82980. flatLinearRings.push(flatLinearRing);
  82981. }
  82982. };
  82983. /**
  82984. * @param {Node} node Node.
  82985. * @param {Array.<*>} objectStack Object stack.
  82986. * @private
  82987. */
  82988. ol.format.KML.outerBoundaryIsParser_ = function(node, objectStack) {
  82989. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  82990. 'node.nodeType should be ELEMENT');
  82991. goog.asserts.assert(node.localName == 'outerBoundaryIs',
  82992. 'localName should be outerBoundaryIs');
  82993. var flatLinearRing = ol.xml.pushParseAndPop(
  82994. /** @type {Array.<number>|undefined} */ (undefined),
  82995. ol.format.KML.OUTER_BOUNDARY_IS_PARSERS_, node, objectStack);
  82996. if (flatLinearRing) {
  82997. var flatLinearRings = /** @type {Array.<Array.<number>>} */
  82998. (objectStack[objectStack.length - 1]);
  82999. goog.asserts.assert(goog.isArray(flatLinearRings),
  83000. 'flatLinearRings should be an array');
  83001. goog.asserts.assert(flatLinearRings.length > 0,
  83002. 'flatLinearRings array should not be empty');
  83003. flatLinearRings[0] = flatLinearRing;
  83004. }
  83005. };
  83006. /**
  83007. * @param {Node} node Node.
  83008. * @param {Array.<*>} objectStack Object stack.
  83009. * @private
  83010. */
  83011. ol.format.KML.LinkParser_ = function(node, objectStack) {
  83012. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83013. 'node.nodeType should be ELEMENT');
  83014. goog.asserts.assert(node.localName == 'Link', 'localName should be Link');
  83015. ol.xml.parseNode(ol.format.KML.LINK_PARSERS_, node, objectStack);
  83016. };
  83017. /**
  83018. * @param {Node} node Node.
  83019. * @param {Array.<*>} objectStack Object stack.
  83020. * @private
  83021. */
  83022. ol.format.KML.whenParser_ = function(node, objectStack) {
  83023. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83024. 'node.nodeType should be ELEMENT');
  83025. goog.asserts.assert(node.localName == 'when', 'localName should be when');
  83026. var gxTrackObject = /** @type {ol.format.KMLGxTrackObject_} */
  83027. (objectStack[objectStack.length - 1]);
  83028. goog.asserts.assert(goog.isObject(gxTrackObject),
  83029. 'gxTrackObject should be an Object');
  83030. var whens = gxTrackObject.whens;
  83031. var s = ol.xml.getAllTextContent(node, false);
  83032. var re =
  83033. /^\s*(\d{4})($|-(\d{2})($|-(\d{2})($|T(\d{2}):(\d{2}):(\d{2})(Z|(?:([+\-])(\d{2})(?::(\d{2}))?)))))\s*$/;
  83034. var m = re.exec(s);
  83035. if (m) {
  83036. var year = parseInt(m[1], 10);
  83037. var month = m[3] ? parseInt(m[3], 10) - 1 : 0;
  83038. var day = m[5] ? parseInt(m[5], 10) : 1;
  83039. var hour = m[7] ? parseInt(m[7], 10) : 0;
  83040. var minute = m[8] ? parseInt(m[8], 10) : 0;
  83041. var second = m[9] ? parseInt(m[9], 10) : 0;
  83042. var when = Date.UTC(year, month, day, hour, minute, second);
  83043. if (m[10] && m[10] != 'Z') {
  83044. var sign = m[11] == '-' ? -1 : 1;
  83045. when += sign * 60 * parseInt(m[12], 10);
  83046. if (m[13]) {
  83047. when += sign * 60 * 60 * parseInt(m[13], 10);
  83048. }
  83049. }
  83050. whens.push(when);
  83051. } else {
  83052. whens.push(0);
  83053. }
  83054. };
  83055. /**
  83056. * @const
  83057. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83058. * @private
  83059. */
  83060. ol.format.KML.DATA_PARSERS_ = ol.xml.makeStructureNS(
  83061. ol.format.KML.NAMESPACE_URIS_, {
  83062. 'value': ol.xml.makeReplacer(ol.format.XSD.readString)
  83063. });
  83064. /**
  83065. * @const
  83066. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83067. * @private
  83068. */
  83069. ol.format.KML.EXTENDED_DATA_PARSERS_ = ol.xml.makeStructureNS(
  83070. ol.format.KML.NAMESPACE_URIS_, {
  83071. 'Data': ol.format.KML.DataParser_,
  83072. 'SchemaData': ol.format.KML.SchemaDataParser_
  83073. });
  83074. /**
  83075. * @const
  83076. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83077. * @private
  83078. */
  83079. ol.format.KML.EXTRUDE_AND_ALTITUDE_MODE_PARSERS_ = ol.xml.makeStructureNS(
  83080. ol.format.KML.NAMESPACE_URIS_, {
  83081. 'extrude': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
  83082. 'altitudeMode': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)
  83083. });
  83084. /**
  83085. * @const
  83086. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83087. * @private
  83088. */
  83089. ol.format.KML.FLAT_LINEAR_RING_PARSERS_ = ol.xml.makeStructureNS(
  83090. ol.format.KML.NAMESPACE_URIS_, {
  83091. 'coordinates': ol.xml.makeReplacer(ol.format.KML.readFlatCoordinates_)
  83092. });
  83093. /**
  83094. * @const
  83095. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83096. * @private
  83097. */
  83098. ol.format.KML.FLAT_LINEAR_RINGS_PARSERS_ = ol.xml.makeStructureNS(
  83099. ol.format.KML.NAMESPACE_URIS_, {
  83100. 'innerBoundaryIs': ol.format.KML.innerBoundaryIsParser_,
  83101. 'outerBoundaryIs': ol.format.KML.outerBoundaryIsParser_
  83102. });
  83103. /**
  83104. * @const
  83105. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83106. * @private
  83107. */
  83108. ol.format.KML.GX_TRACK_PARSERS_ = ol.xml.makeStructureNS(
  83109. ol.format.KML.NAMESPACE_URIS_, {
  83110. 'when': ol.format.KML.whenParser_
  83111. }, ol.xml.makeStructureNS(
  83112. ol.format.KML.GX_NAMESPACE_URIS_, {
  83113. 'coord': ol.format.KML.gxCoordParser_
  83114. }));
  83115. /**
  83116. * @const
  83117. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83118. * @private
  83119. */
  83120. ol.format.KML.GEOMETRY_FLAT_COORDINATES_PARSERS_ = ol.xml.makeStructureNS(
  83121. ol.format.KML.NAMESPACE_URIS_, {
  83122. 'coordinates': ol.xml.makeReplacer(ol.format.KML.readFlatCoordinates_)
  83123. });
  83124. /**
  83125. * @const
  83126. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83127. * @private
  83128. */
  83129. ol.format.KML.ICON_PARSERS_ = ol.xml.makeStructureNS(
  83130. ol.format.KML.NAMESPACE_URIS_, {
  83131. 'href': ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_)
  83132. }, ol.xml.makeStructureNS(
  83133. ol.format.KML.GX_NAMESPACE_URIS_, {
  83134. 'x': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  83135. 'y': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  83136. 'w': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  83137. 'h': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)
  83138. }));
  83139. /**
  83140. * @const
  83141. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83142. * @private
  83143. */
  83144. ol.format.KML.ICON_STYLE_PARSERS_ = ol.xml.makeStructureNS(
  83145. ol.format.KML.NAMESPACE_URIS_, {
  83146. 'Icon': ol.xml.makeObjectPropertySetter(ol.format.KML.readIcon_),
  83147. 'heading': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal),
  83148. 'hotSpot': ol.xml.makeObjectPropertySetter(ol.format.KML.readVec2_),
  83149. 'scale': ol.xml.makeObjectPropertySetter(ol.format.KML.readScale_)
  83150. });
  83151. /**
  83152. * @const
  83153. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83154. * @private
  83155. */
  83156. ol.format.KML.INNER_BOUNDARY_IS_PARSERS_ = ol.xml.makeStructureNS(
  83157. ol.format.KML.NAMESPACE_URIS_, {
  83158. 'LinearRing': ol.xml.makeReplacer(ol.format.KML.readFlatLinearRing_)
  83159. });
  83160. /**
  83161. * @const
  83162. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83163. * @private
  83164. */
  83165. ol.format.KML.LABEL_STYLE_PARSERS_ = ol.xml.makeStructureNS(
  83166. ol.format.KML.NAMESPACE_URIS_, {
  83167. 'color': ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),
  83168. 'scale': ol.xml.makeObjectPropertySetter(ol.format.KML.readScale_)
  83169. });
  83170. /**
  83171. * @const
  83172. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83173. * @private
  83174. */
  83175. ol.format.KML.LINE_STYLE_PARSERS_ = ol.xml.makeStructureNS(
  83176. ol.format.KML.NAMESPACE_URIS_, {
  83177. 'color': ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),
  83178. 'width': ol.xml.makeObjectPropertySetter(ol.format.XSD.readDecimal)
  83179. });
  83180. /**
  83181. * @const
  83182. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83183. * @private
  83184. */
  83185. ol.format.KML.MULTI_GEOMETRY_PARSERS_ = ol.xml.makeStructureNS(
  83186. ol.format.KML.NAMESPACE_URIS_, {
  83187. 'LineString': ol.xml.makeArrayPusher(ol.format.KML.readLineString_),
  83188. 'LinearRing': ol.xml.makeArrayPusher(ol.format.KML.readLinearRing_),
  83189. 'MultiGeometry': ol.xml.makeArrayPusher(ol.format.KML.readMultiGeometry_),
  83190. 'Point': ol.xml.makeArrayPusher(ol.format.KML.readPoint_),
  83191. 'Polygon': ol.xml.makeArrayPusher(ol.format.KML.readPolygon_)
  83192. });
  83193. /**
  83194. * @const
  83195. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83196. * @private
  83197. */
  83198. ol.format.KML.GX_MULTITRACK_GEOMETRY_PARSERS_ = ol.xml.makeStructureNS(
  83199. ol.format.KML.GX_NAMESPACE_URIS_, {
  83200. 'Track': ol.xml.makeArrayPusher(ol.format.KML.readGxTrack_)
  83201. });
  83202. /**
  83203. * @const
  83204. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83205. * @private
  83206. */
  83207. ol.format.KML.NETWORK_LINK_PARSERS_ = ol.xml.makeStructureNS(
  83208. ol.format.KML.NAMESPACE_URIS_, {
  83209. 'ExtendedData': ol.format.KML.ExtendedDataParser_,
  83210. 'Link': ol.format.KML.LinkParser_,
  83211. 'address': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83212. 'description': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83213. 'name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83214. 'open': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
  83215. 'phoneNumber': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83216. 'visibility': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)
  83217. });
  83218. /**
  83219. * @const
  83220. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83221. * @private
  83222. */
  83223. ol.format.KML.LINK_PARSERS_ = ol.xml.makeStructureNS(
  83224. ol.format.KML.NAMESPACE_URIS_, {
  83225. 'href': ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_)
  83226. });
  83227. /**
  83228. * @const
  83229. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83230. * @private
  83231. */
  83232. ol.format.KML.OUTER_BOUNDARY_IS_PARSERS_ = ol.xml.makeStructureNS(
  83233. ol.format.KML.NAMESPACE_URIS_, {
  83234. 'LinearRing': ol.xml.makeReplacer(ol.format.KML.readFlatLinearRing_)
  83235. });
  83236. /**
  83237. * @const
  83238. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83239. * @private
  83240. */
  83241. ol.format.KML.PAIR_PARSERS_ = ol.xml.makeStructureNS(
  83242. ol.format.KML.NAMESPACE_URIS_, {
  83243. 'Style': ol.xml.makeObjectPropertySetter(ol.format.KML.readStyle_),
  83244. 'key': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83245. 'styleUrl': ol.xml.makeObjectPropertySetter(ol.format.KML.readStyleUrl_)
  83246. });
  83247. /**
  83248. * @const
  83249. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83250. * @private
  83251. */
  83252. ol.format.KML.PLACEMARK_PARSERS_ = ol.xml.makeStructureNS(
  83253. ol.format.KML.NAMESPACE_URIS_, {
  83254. 'ExtendedData': ol.format.KML.ExtendedDataParser_,
  83255. 'MultiGeometry': ol.xml.makeObjectPropertySetter(
  83256. ol.format.KML.readMultiGeometry_, 'geometry'),
  83257. 'LineString': ol.xml.makeObjectPropertySetter(
  83258. ol.format.KML.readLineString_, 'geometry'),
  83259. 'LinearRing': ol.xml.makeObjectPropertySetter(
  83260. ol.format.KML.readLinearRing_, 'geometry'),
  83261. 'Point': ol.xml.makeObjectPropertySetter(
  83262. ol.format.KML.readPoint_, 'geometry'),
  83263. 'Polygon': ol.xml.makeObjectPropertySetter(
  83264. ol.format.KML.readPolygon_, 'geometry'),
  83265. 'Style': ol.xml.makeObjectPropertySetter(ol.format.KML.readStyle_),
  83266. 'StyleMap': ol.format.KML.PlacemarkStyleMapParser_,
  83267. 'address': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83268. 'description': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83269. 'name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83270. 'open': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
  83271. 'phoneNumber': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  83272. 'styleUrl': ol.xml.makeObjectPropertySetter(ol.format.KML.readURI_),
  83273. 'visibility': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)
  83274. }, ol.xml.makeStructureNS(
  83275. ol.format.KML.GX_NAMESPACE_URIS_, {
  83276. 'MultiTrack': ol.xml.makeObjectPropertySetter(
  83277. ol.format.KML.readGxMultiTrack_, 'geometry'),
  83278. 'Track': ol.xml.makeObjectPropertySetter(
  83279. ol.format.KML.readGxTrack_, 'geometry')
  83280. }
  83281. ));
  83282. /**
  83283. * @const
  83284. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83285. * @private
  83286. */
  83287. ol.format.KML.POLY_STYLE_PARSERS_ = ol.xml.makeStructureNS(
  83288. ol.format.KML.NAMESPACE_URIS_, {
  83289. 'color': ol.xml.makeObjectPropertySetter(ol.format.KML.readColor_),
  83290. 'fill': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean),
  83291. 'outline': ol.xml.makeObjectPropertySetter(ol.format.XSD.readBoolean)
  83292. });
  83293. /**
  83294. * @const
  83295. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83296. * @private
  83297. */
  83298. ol.format.KML.SCHEMA_DATA_PARSERS_ = ol.xml.makeStructureNS(
  83299. ol.format.KML.NAMESPACE_URIS_, {
  83300. 'SimpleData': ol.format.KML.SimpleDataParser_
  83301. });
  83302. /**
  83303. * @const
  83304. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83305. * @private
  83306. */
  83307. ol.format.KML.STYLE_PARSERS_ = ol.xml.makeStructureNS(
  83308. ol.format.KML.NAMESPACE_URIS_, {
  83309. 'IconStyle': ol.format.KML.IconStyleParser_,
  83310. 'LabelStyle': ol.format.KML.LabelStyleParser_,
  83311. 'LineStyle': ol.format.KML.LineStyleParser_,
  83312. 'PolyStyle': ol.format.KML.PolyStyleParser_
  83313. });
  83314. /**
  83315. * @const
  83316. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  83317. * @private
  83318. */
  83319. ol.format.KML.STYLE_MAP_PARSERS_ = ol.xml.makeStructureNS(
  83320. ol.format.KML.NAMESPACE_URIS_, {
  83321. 'Pair': ol.format.KML.PairDataParser_
  83322. });
  83323. /**
  83324. * @inheritDoc
  83325. */
  83326. ol.format.KML.prototype.getExtensions = function() {
  83327. return ol.format.KML.EXTENSIONS_;
  83328. };
  83329. /**
  83330. * @param {Node} node Node.
  83331. * @param {Array.<*>} objectStack Object stack.
  83332. * @private
  83333. * @return {Array.<ol.Feature>|undefined} Features.
  83334. */
  83335. ol.format.KML.prototype.readDocumentOrFolder_ = function(node, objectStack) {
  83336. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83337. 'node.nodeType should be ELEMENT');
  83338. var localName = ol.xml.getLocalName(node);
  83339. goog.asserts.assert(localName == 'Document' || localName == 'Folder',
  83340. 'localName should be Document or Folder');
  83341. // FIXME use scope somehow
  83342. var parsersNS = ol.xml.makeStructureNS(
  83343. ol.format.KML.NAMESPACE_URIS_, {
  83344. 'Document': ol.xml.makeArrayExtender(this.readDocumentOrFolder_, this),
  83345. 'Folder': ol.xml.makeArrayExtender(this.readDocumentOrFolder_, this),
  83346. 'Placemark': ol.xml.makeArrayPusher(this.readPlacemark_, this),
  83347. 'Style': goog.bind(this.readSharedStyle_, this),
  83348. 'StyleMap': goog.bind(this.readSharedStyleMap_, this)
  83349. });
  83350. var features = ol.xml.pushParseAndPop(/** @type {Array.<ol.Feature>} */ ([]),
  83351. parsersNS, node, objectStack, this);
  83352. if (features) {
  83353. return features;
  83354. } else {
  83355. return undefined;
  83356. }
  83357. };
  83358. /**
  83359. * @param {Node} node Node.
  83360. * @param {Array.<*>} objectStack Object stack.
  83361. * @private
  83362. * @return {ol.Feature|undefined} Feature.
  83363. */
  83364. ol.format.KML.prototype.readPlacemark_ = function(node, objectStack) {
  83365. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83366. 'node.nodeType should be ELEMENT');
  83367. goog.asserts.assert(node.localName == 'Placemark',
  83368. 'localName should be Placemark');
  83369. var object = ol.xml.pushParseAndPop({'geometry': null},
  83370. ol.format.KML.PLACEMARK_PARSERS_, node, objectStack);
  83371. if (!object) {
  83372. return undefined;
  83373. }
  83374. var feature = new ol.Feature();
  83375. var id = node.getAttribute('id');
  83376. if (id !== null) {
  83377. feature.setId(id);
  83378. }
  83379. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  83380. var geometry = object['geometry'];
  83381. if (geometry) {
  83382. ol.format.Feature.transformWithOptions(geometry, false, options);
  83383. }
  83384. feature.setGeometry(geometry);
  83385. delete object['geometry'];
  83386. if (this.extractStyles_) {
  83387. var style = object['Style'];
  83388. var styleUrl = object['styleUrl'];
  83389. var styleFunction = ol.format.KML.createFeatureStyleFunction_(
  83390. style, styleUrl, this.defaultStyle_, this.sharedStyles_);
  83391. feature.setStyle(styleFunction);
  83392. }
  83393. delete object['Style'];
  83394. // we do not remove the styleUrl property from the object, so it
  83395. // gets stored on feature when setProperties is called
  83396. feature.setProperties(object);
  83397. return feature;
  83398. };
  83399. /**
  83400. * @param {Node} node Node.
  83401. * @param {Array.<*>} objectStack Object stack.
  83402. * @private
  83403. */
  83404. ol.format.KML.prototype.readSharedStyle_ = function(node, objectStack) {
  83405. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83406. 'node.nodeType should be ELEMENT');
  83407. goog.asserts.assert(node.localName == 'Style', 'localName should be Style');
  83408. var id = node.getAttribute('id');
  83409. if (id !== null) {
  83410. var style = ol.format.KML.readStyle_(node, objectStack);
  83411. if (style) {
  83412. var styleUri;
  83413. if (node.baseURI) {
  83414. styleUri = goog.Uri.resolve(node.baseURI, '#' + id).toString();
  83415. } else {
  83416. styleUri = '#' + id;
  83417. }
  83418. this.sharedStyles_[styleUri] = style;
  83419. }
  83420. }
  83421. };
  83422. /**
  83423. * @param {Node} node Node.
  83424. * @param {Array.<*>} objectStack Object stack.
  83425. * @private
  83426. */
  83427. ol.format.KML.prototype.readSharedStyleMap_ = function(node, objectStack) {
  83428. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83429. 'node.nodeType should be ELEMENT');
  83430. goog.asserts.assert(node.localName == 'StyleMap',
  83431. 'localName should be StyleMap');
  83432. var id = node.getAttribute('id');
  83433. if (id === null) {
  83434. return;
  83435. }
  83436. var styleMapValue = ol.format.KML.readStyleMapValue_(node, objectStack);
  83437. if (!styleMapValue) {
  83438. return;
  83439. }
  83440. var styleUri;
  83441. if (node.baseURI) {
  83442. styleUri = goog.Uri.resolve(node.baseURI, '#' + id).toString();
  83443. } else {
  83444. styleUri = '#' + id;
  83445. }
  83446. this.sharedStyles_[styleUri] = styleMapValue;
  83447. };
  83448. /**
  83449. * Read the first feature from a KML source.
  83450. *
  83451. * @function
  83452. * @param {Document|Node|Object|string} source Source.
  83453. * @param {olx.format.ReadOptions=} opt_options Read options.
  83454. * @return {ol.Feature} Feature.
  83455. * @api stable
  83456. */
  83457. ol.format.KML.prototype.readFeature;
  83458. /**
  83459. * @inheritDoc
  83460. */
  83461. ol.format.KML.prototype.readFeatureFromNode = function(node, opt_options) {
  83462. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83463. 'node.nodeType should be ELEMENT');
  83464. if (!ol.array.includes(ol.format.KML.NAMESPACE_URIS_, node.namespaceURI)) {
  83465. return null;
  83466. }
  83467. goog.asserts.assert(node.localName == 'Placemark',
  83468. 'localName should be Placemark');
  83469. var feature = this.readPlacemark_(
  83470. node, [this.getReadOptions(node, opt_options)]);
  83471. if (feature) {
  83472. return feature;
  83473. } else {
  83474. return null;
  83475. }
  83476. };
  83477. /**
  83478. * Read all features from a KML source.
  83479. *
  83480. * @function
  83481. * @param {Document|Node|Object|string} source Source.
  83482. * @param {olx.format.ReadOptions=} opt_options Read options.
  83483. * @return {Array.<ol.Feature>} Features.
  83484. * @api stable
  83485. */
  83486. ol.format.KML.prototype.readFeatures;
  83487. /**
  83488. * @inheritDoc
  83489. */
  83490. ol.format.KML.prototype.readFeaturesFromNode = function(node, opt_options) {
  83491. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  83492. 'node.nodeType should be ELEMENT');
  83493. if (!ol.array.includes(ol.format.KML.NAMESPACE_URIS_, node.namespaceURI)) {
  83494. return [];
  83495. }
  83496. var features;
  83497. var localName = ol.xml.getLocalName(node);
  83498. if (localName == 'Document' || localName == 'Folder') {
  83499. features = this.readDocumentOrFolder_(
  83500. node, [this.getReadOptions(node, opt_options)]);
  83501. if (features) {
  83502. return features;
  83503. } else {
  83504. return [];
  83505. }
  83506. } else if (localName == 'Placemark') {
  83507. var feature = this.readPlacemark_(
  83508. node, [this.getReadOptions(node, opt_options)]);
  83509. if (feature) {
  83510. return [feature];
  83511. } else {
  83512. return [];
  83513. }
  83514. } else if (localName == 'kml') {
  83515. features = [];
  83516. var n;
  83517. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  83518. var fs = this.readFeaturesFromNode(n, opt_options);
  83519. if (fs) {
  83520. goog.array.extend(features, fs);
  83521. }
  83522. }
  83523. return features;
  83524. } else {
  83525. return [];
  83526. }
  83527. };
  83528. /**
  83529. * Read the name of the KML.
  83530. *
  83531. * @param {Document|Node|string} source Souce.
  83532. * @return {string|undefined} Name.
  83533. * @api stable
  83534. */
  83535. ol.format.KML.prototype.readName = function(source) {
  83536. if (ol.xml.isDocument(source)) {
  83537. return this.readNameFromDocument(/** @type {Document} */ (source));
  83538. } else if (ol.xml.isNode(source)) {
  83539. return this.readNameFromNode(/** @type {Node} */ (source));
  83540. } else if (goog.isString(source)) {
  83541. var doc = ol.xml.parse(source);
  83542. return this.readNameFromDocument(doc);
  83543. } else {
  83544. goog.asserts.fail('Unknown type for source');
  83545. return undefined;
  83546. }
  83547. };
  83548. /**
  83549. * @param {Document} doc Document.
  83550. * @return {string|undefined} Name.
  83551. */
  83552. ol.format.KML.prototype.readNameFromDocument = function(doc) {
  83553. var n;
  83554. for (n = doc.firstChild; n; n = n.nextSibling) {
  83555. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  83556. var name = this.readNameFromNode(n);
  83557. if (name) {
  83558. return name;
  83559. }
  83560. }
  83561. }
  83562. return undefined;
  83563. };
  83564. /**
  83565. * @param {Node} node Node.
  83566. * @return {string|undefined} Name.
  83567. */
  83568. ol.format.KML.prototype.readNameFromNode = function(node) {
  83569. var n;
  83570. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  83571. if (ol.array.includes(ol.format.KML.NAMESPACE_URIS_, n.namespaceURI) &&
  83572. n.localName == 'name') {
  83573. return ol.format.XSD.readString(n);
  83574. }
  83575. }
  83576. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  83577. var localName = ol.xml.getLocalName(n);
  83578. if (ol.array.includes(ol.format.KML.NAMESPACE_URIS_, n.namespaceURI) &&
  83579. (localName == 'Document' ||
  83580. localName == 'Folder' ||
  83581. localName == 'Placemark' ||
  83582. localName == 'kml')) {
  83583. var name = this.readNameFromNode(n);
  83584. if (name) {
  83585. return name;
  83586. }
  83587. }
  83588. }
  83589. return undefined;
  83590. };
  83591. /**
  83592. * Read the network links of the KML.
  83593. *
  83594. * @param {Document|Node|string} source Source.
  83595. * @return {Array.<Object>} Network links.
  83596. * @api
  83597. */
  83598. ol.format.KML.prototype.readNetworkLinks = function(source) {
  83599. var networkLinks = [];
  83600. if (ol.xml.isDocument(source)) {
  83601. goog.array.extend(networkLinks, this.readNetworkLinksFromDocument(
  83602. /** @type {Document} */ (source)));
  83603. } else if (ol.xml.isNode(source)) {
  83604. goog.array.extend(networkLinks, this.readNetworkLinksFromNode(
  83605. /** @type {Node} */ (source)));
  83606. } else if (goog.isString(source)) {
  83607. var doc = ol.xml.parse(source);
  83608. goog.array.extend(networkLinks, this.readNetworkLinksFromDocument(doc));
  83609. } else {
  83610. goog.asserts.fail('unknown type for source');
  83611. }
  83612. return networkLinks;
  83613. };
  83614. /**
  83615. * @param {Document} doc Document.
  83616. * @return {Array.<Object>} Network links.
  83617. */
  83618. ol.format.KML.prototype.readNetworkLinksFromDocument = function(doc) {
  83619. var n, networkLinks = [];
  83620. for (n = doc.firstChild; n; n = n.nextSibling) {
  83621. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  83622. goog.array.extend(networkLinks, this.readNetworkLinksFromNode(n));
  83623. }
  83624. }
  83625. return networkLinks;
  83626. };
  83627. /**
  83628. * @param {Node} node Node.
  83629. * @return {Array.<Object>} Network links.
  83630. */
  83631. ol.format.KML.prototype.readNetworkLinksFromNode = function(node) {
  83632. var n, networkLinks = [];
  83633. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  83634. if (ol.array.includes(ol.format.KML.NAMESPACE_URIS_, n.namespaceURI) &&
  83635. n.localName == 'NetworkLink') {
  83636. var obj = ol.xml.pushParseAndPop({}, ol.format.KML.NETWORK_LINK_PARSERS_,
  83637. n, []);
  83638. networkLinks.push(obj);
  83639. }
  83640. }
  83641. for (n = node.firstElementChild; n; n = n.nextElementSibling) {
  83642. var localName = ol.xml.getLocalName(n);
  83643. if (ol.array.includes(ol.format.KML.NAMESPACE_URIS_, n.namespaceURI) &&
  83644. (localName == 'Document' ||
  83645. localName == 'Folder' ||
  83646. localName == 'kml')) {
  83647. goog.array.extend(networkLinks, this.readNetworkLinksFromNode(n));
  83648. }
  83649. }
  83650. return networkLinks;
  83651. };
  83652. /**
  83653. * Read the projection from a KML source.
  83654. *
  83655. * @function
  83656. * @param {Document|Node|Object|string} source Source.
  83657. * @return {ol.proj.Projection} Projection.
  83658. * @api stable
  83659. */
  83660. ol.format.KML.prototype.readProjection;
  83661. /**
  83662. * @param {Node} node Node to append a TextNode with the color to.
  83663. * @param {ol.Color|string} color Color.
  83664. * @private
  83665. */
  83666. ol.format.KML.writeColorTextNode_ = function(node, color) {
  83667. var rgba = ol.color.asArray(color);
  83668. var opacity = (rgba.length == 4) ? rgba[3] : 1;
  83669. var abgr = [opacity * 255, rgba[2], rgba[1], rgba[0]];
  83670. var i;
  83671. for (i = 0; i < 4; ++i) {
  83672. var hex = parseInt(abgr[i], 10).toString(16);
  83673. abgr[i] = (hex.length == 1) ? '0' + hex : hex;
  83674. }
  83675. ol.format.XSD.writeStringTextNode(node, abgr.join(''));
  83676. };
  83677. /**
  83678. * @param {Node} node Node to append a TextNode with the coordinates to.
  83679. * @param {Array.<number>} coordinates Coordinates.
  83680. * @param {Array.<*>} objectStack Object stack.
  83681. * @private
  83682. */
  83683. ol.format.KML.writeCoordinatesTextNode_ =
  83684. function(node, coordinates, objectStack) {
  83685. var context = objectStack[objectStack.length - 1];
  83686. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  83687. var layout = context['layout'];
  83688. var stride = context['stride'];
  83689. var dimension;
  83690. if (layout == ol.geom.GeometryLayout.XY ||
  83691. layout == ol.geom.GeometryLayout.XYM) {
  83692. dimension = 2;
  83693. } else if (layout == ol.geom.GeometryLayout.XYZ ||
  83694. layout == ol.geom.GeometryLayout.XYZM) {
  83695. dimension = 3;
  83696. } else {
  83697. goog.asserts.fail('Unknown geometry layout');
  83698. }
  83699. var d, i;
  83700. var ii = coordinates.length;
  83701. var text = '';
  83702. if (ii > 0) {
  83703. text += coordinates[0];
  83704. for (d = 1; d < dimension; ++d) {
  83705. text += ',' + coordinates[d];
  83706. }
  83707. for (i = stride; i < ii; i += stride) {
  83708. text += ' ' + coordinates[i];
  83709. for (d = 1; d < dimension; ++d) {
  83710. text += ',' + coordinates[i + d];
  83711. }
  83712. }
  83713. }
  83714. ol.format.XSD.writeStringTextNode(node, text);
  83715. };
  83716. /**
  83717. * @param {Node} node Node.
  83718. * @param {Array.<ol.Feature>} features Features.
  83719. * @param {Array.<*>} objectStack Object stack.
  83720. * @private
  83721. */
  83722. ol.format.KML.writeDocument_ = function(node, features, objectStack) {
  83723. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83724. ol.xml.pushSerializeAndPop(context, ol.format.KML.DOCUMENT_SERIALIZERS_,
  83725. ol.format.KML.DOCUMENT_NODE_FACTORY_, features, objectStack);
  83726. };
  83727. /**
  83728. * @param {Node} node Node.
  83729. * @param {Object} icon Icon object.
  83730. * @param {Array.<*>} objectStack Object stack.
  83731. * @private
  83732. */
  83733. ol.format.KML.writeIcon_ = function(node, icon, objectStack) {
  83734. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83735. var parentNode = objectStack[objectStack.length - 1].node;
  83736. var orderedKeys = ol.format.KML.ICON_SEQUENCE_[parentNode.namespaceURI];
  83737. var values = ol.xml.makeSequence(icon, orderedKeys);
  83738. ol.xml.pushSerializeAndPop(context,
  83739. ol.format.KML.ICON_SERIALIZERS_, ol.xml.OBJECT_PROPERTY_NODE_FACTORY,
  83740. values, objectStack, orderedKeys);
  83741. orderedKeys =
  83742. ol.format.KML.ICON_SEQUENCE_[ol.format.KML.GX_NAMESPACE_URIS_[0]];
  83743. values = ol.xml.makeSequence(icon, orderedKeys);
  83744. ol.xml.pushSerializeAndPop(context, ol.format.KML.ICON_SERIALIZERS_,
  83745. ol.format.KML.GX_NODE_FACTORY_, values, objectStack, orderedKeys);
  83746. };
  83747. /**
  83748. * @param {Node} node Node.
  83749. * @param {ol.style.Icon} style Icon style.
  83750. * @param {Array.<*>} objectStack Object stack.
  83751. * @private
  83752. */
  83753. ol.format.KML.writeIconStyle_ = function(node, style, objectStack) {
  83754. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83755. var properties = {};
  83756. var src = style.getSrc();
  83757. var size = style.getSize();
  83758. var iconImageSize = style.getImageSize();
  83759. var iconProperties = {
  83760. 'href': src
  83761. };
  83762. if (size) {
  83763. iconProperties['w'] = size[0];
  83764. iconProperties['h'] = size[1];
  83765. var anchor = style.getAnchor(); // top-left
  83766. var origin = style.getOrigin(); // top-left
  83767. if (origin && iconImageSize && origin[0] !== 0 && origin[1] !== size[1]) {
  83768. iconProperties['x'] = origin[0];
  83769. iconProperties['y'] = iconImageSize[1] - (origin[1] + size[1]);
  83770. }
  83771. if (anchor && anchor[0] !== 0 && anchor[1] !== size[1]) {
  83772. var /** @type {ol.format.KMLVec2_} */ hotSpot = {
  83773. x: anchor[0],
  83774. xunits: ol.style.IconAnchorUnits.PIXELS,
  83775. y: size[1] - anchor[1],
  83776. yunits: ol.style.IconAnchorUnits.PIXELS
  83777. };
  83778. properties['hotSpot'] = hotSpot;
  83779. }
  83780. }
  83781. properties['Icon'] = iconProperties;
  83782. var scale = style.getScale();
  83783. if (scale !== 1) {
  83784. properties['scale'] = scale;
  83785. }
  83786. var rotation = style.getRotation();
  83787. if (rotation !== 0) {
  83788. properties['heading'] = rotation; // 0-360
  83789. }
  83790. var parentNode = objectStack[objectStack.length - 1].node;
  83791. var orderedKeys = ol.format.KML.ICON_STYLE_SEQUENCE_[parentNode.namespaceURI];
  83792. var values = ol.xml.makeSequence(properties, orderedKeys);
  83793. ol.xml.pushSerializeAndPop(context, ol.format.KML.ICON_STYLE_SERIALIZERS_,
  83794. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
  83795. };
  83796. /**
  83797. * @param {Node} node Node.
  83798. * @param {ol.style.Text} style style.
  83799. * @param {Array.<*>} objectStack Object stack.
  83800. * @private
  83801. */
  83802. ol.format.KML.writeLabelStyle_ = function(node, style, objectStack) {
  83803. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83804. var properties = {};
  83805. var fill = style.getFill();
  83806. if (fill) {
  83807. properties['color'] = fill.getColor();
  83808. }
  83809. var scale = style.getScale();
  83810. if (scale && scale !== 1) {
  83811. properties['scale'] = scale;
  83812. }
  83813. var parentNode = objectStack[objectStack.length - 1].node;
  83814. var orderedKeys =
  83815. ol.format.KML.LABEL_STYLE_SEQUENCE_[parentNode.namespaceURI];
  83816. var values = ol.xml.makeSequence(properties, orderedKeys);
  83817. ol.xml.pushSerializeAndPop(context, ol.format.KML.LABEL_STYLE_SERIALIZERS_,
  83818. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
  83819. };
  83820. /**
  83821. * @param {Node} node Node.
  83822. * @param {ol.style.Stroke} style style.
  83823. * @param {Array.<*>} objectStack Object stack.
  83824. * @private
  83825. */
  83826. ol.format.KML.writeLineStyle_ = function(node, style, objectStack) {
  83827. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83828. var properties = {
  83829. 'color': style.getColor(),
  83830. 'width': style.getWidth()
  83831. };
  83832. var parentNode = objectStack[objectStack.length - 1].node;
  83833. var orderedKeys = ol.format.KML.LINE_STYLE_SEQUENCE_[parentNode.namespaceURI];
  83834. var values = ol.xml.makeSequence(properties, orderedKeys);
  83835. ol.xml.pushSerializeAndPop(context, ol.format.KML.LINE_STYLE_SERIALIZERS_,
  83836. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
  83837. };
  83838. /**
  83839. * @param {Node} node Node.
  83840. * @param {ol.geom.Geometry} geometry Geometry.
  83841. * @param {Array.<*>} objectStack Object stack.
  83842. * @private
  83843. */
  83844. ol.format.KML.writeMultiGeometry_ =
  83845. function(node, geometry, objectStack) {
  83846. goog.asserts.assert(
  83847. (geometry instanceof ol.geom.MultiPoint) ||
  83848. (geometry instanceof ol.geom.MultiLineString) ||
  83849. (geometry instanceof ol.geom.MultiPolygon),
  83850. 'geometry should be one of: ol.geom.MultiPoint, ' +
  83851. 'ol.geom.MultiLineString or ol.geom.MultiPolygon');
  83852. /** @type {ol.xml.NodeStackItem} */
  83853. var context = {node: node};
  83854. var type = geometry.getType();
  83855. /** @type {Array.<ol.geom.Geometry>} */
  83856. var geometries;
  83857. /** @type {function(*, Array.<*>, string=): (Node|undefined)} */
  83858. var factory;
  83859. if (type == ol.geom.GeometryType.MULTI_POINT) {
  83860. geometries =
  83861. (/** @type {ol.geom.MultiPoint} */ (geometry)).getPoints();
  83862. factory = ol.format.KML.POINT_NODE_FACTORY_;
  83863. } else if (type == ol.geom.GeometryType.MULTI_LINE_STRING) {
  83864. geometries =
  83865. (/** @type {ol.geom.MultiLineString} */ (geometry)).getLineStrings();
  83866. factory = ol.format.KML.LINE_STRING_NODE_FACTORY_;
  83867. } else if (type == ol.geom.GeometryType.MULTI_POLYGON) {
  83868. geometries =
  83869. (/** @type {ol.geom.MultiPolygon} */ (geometry)).getPolygons();
  83870. factory = ol.format.KML.POLYGON_NODE_FACTORY_;
  83871. } else {
  83872. goog.asserts.fail('Unknown geometry type: ' + type);
  83873. }
  83874. ol.xml.pushSerializeAndPop(context,
  83875. ol.format.KML.MULTI_GEOMETRY_SERIALIZERS_, factory,
  83876. geometries, objectStack);
  83877. };
  83878. /**
  83879. * @param {Node} node Node.
  83880. * @param {ol.geom.LinearRing} linearRing Linear ring.
  83881. * @param {Array.<*>} objectStack Object stack.
  83882. * @private
  83883. */
  83884. ol.format.KML.writeBoundaryIs_ = function(node, linearRing, objectStack) {
  83885. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83886. ol.xml.pushSerializeAndPop(context,
  83887. ol.format.KML.BOUNDARY_IS_SERIALIZERS_,
  83888. ol.format.KML.LINEAR_RING_NODE_FACTORY_, [linearRing], objectStack);
  83889. };
  83890. /**
  83891. * FIXME currently we do serialize arbitrary/custom feature properties
  83892. * (ExtendedData).
  83893. * @param {Node} node Node.
  83894. * @param {ol.Feature} feature Feature.
  83895. * @param {Array.<*>} objectStack Object stack.
  83896. * @private
  83897. */
  83898. ol.format.KML.writePlacemark_ = function(node, feature, objectStack) {
  83899. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83900. // set id
  83901. if (feature.getId()) {
  83902. node.setAttribute('id', feature.getId());
  83903. }
  83904. // serialize properties (properties unknown to KML are not serialized)
  83905. var properties = feature.getProperties();
  83906. var styleFunction = feature.getStyleFunction();
  83907. if (styleFunction) {
  83908. // FIXME the styles returned by the style function are supposed to be
  83909. // resolution-independent here
  83910. var styles = styleFunction.call(feature, 0);
  83911. if (styles && styles.length > 0) {
  83912. properties['Style'] = styles[0];
  83913. var textStyle = styles[0].getText();
  83914. if (textStyle) {
  83915. properties['name'] = textStyle.getText();
  83916. }
  83917. }
  83918. }
  83919. var parentNode = objectStack[objectStack.length - 1].node;
  83920. var orderedKeys = ol.format.KML.PLACEMARK_SEQUENCE_[parentNode.namespaceURI];
  83921. var values = ol.xml.makeSequence(properties, orderedKeys);
  83922. ol.xml.pushSerializeAndPop(context, ol.format.KML.PLACEMARK_SERIALIZERS_,
  83923. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
  83924. // serialize geometry
  83925. var options = /** @type {olx.format.WriteOptions} */ (objectStack[0]);
  83926. var geometry = feature.getGeometry();
  83927. if (geometry) {
  83928. geometry =
  83929. ol.format.Feature.transformWithOptions(geometry, true, options);
  83930. }
  83931. ol.xml.pushSerializeAndPop(context, ol.format.KML.PLACEMARK_SERIALIZERS_,
  83932. ol.format.KML.GEOMETRY_NODE_FACTORY_, [geometry], objectStack);
  83933. };
  83934. /**
  83935. * @param {Node} node Node.
  83936. * @param {ol.geom.SimpleGeometry} geometry Geometry.
  83937. * @param {Array.<*>} objectStack Object stack.
  83938. * @private
  83939. */
  83940. ol.format.KML.writePrimitiveGeometry_ = function(node, geometry, objectStack) {
  83941. goog.asserts.assert(
  83942. (geometry instanceof ol.geom.Point) ||
  83943. (geometry instanceof ol.geom.LineString) ||
  83944. (geometry instanceof ol.geom.LinearRing),
  83945. 'geometry should be one of ol.geom.Point, ol.geom.LineString ' +
  83946. 'or ol.geom.LinearRing');
  83947. var flatCoordinates = geometry.getFlatCoordinates();
  83948. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83949. context['layout'] = geometry.getLayout();
  83950. context['stride'] = geometry.getStride();
  83951. ol.xml.pushSerializeAndPop(context,
  83952. ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_,
  83953. ol.format.KML.COORDINATES_NODE_FACTORY_,
  83954. [flatCoordinates], objectStack);
  83955. };
  83956. /**
  83957. * @param {Node} node Node.
  83958. * @param {ol.geom.Polygon} polygon Polygon.
  83959. * @param {Array.<*>} objectStack Object stack.
  83960. * @private
  83961. */
  83962. ol.format.KML.writePolygon_ = function(node, polygon, objectStack) {
  83963. goog.asserts.assertInstanceof(polygon, ol.geom.Polygon,
  83964. 'polygon should be an ol.geom.Polygon');
  83965. var linearRings = polygon.getLinearRings();
  83966. goog.asserts.assert(linearRings.length > 0,
  83967. 'linearRings should not be empty');
  83968. var outerRing = linearRings.shift();
  83969. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83970. // inner rings
  83971. ol.xml.pushSerializeAndPop(context,
  83972. ol.format.KML.POLYGON_SERIALIZERS_,
  83973. ol.format.KML.INNER_BOUNDARY_NODE_FACTORY_,
  83974. linearRings, objectStack);
  83975. // outer ring
  83976. ol.xml.pushSerializeAndPop(context,
  83977. ol.format.KML.POLYGON_SERIALIZERS_,
  83978. ol.format.KML.OUTER_BOUNDARY_NODE_FACTORY_,
  83979. [outerRing], objectStack);
  83980. };
  83981. /**
  83982. * @param {Node} node Node.
  83983. * @param {ol.style.Fill} style Style.
  83984. * @param {Array.<*>} objectStack Object stack.
  83985. * @private
  83986. */
  83987. ol.format.KML.writePolyStyle_ = function(node, style, objectStack) {
  83988. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  83989. ol.xml.pushSerializeAndPop(context, ol.format.KML.POLY_STYLE_SERIALIZERS_,
  83990. ol.format.KML.COLOR_NODE_FACTORY_, [style.getColor()], objectStack);
  83991. };
  83992. /**
  83993. * @param {Node} node Node to append a TextNode with the scale to.
  83994. * @param {number|undefined} scale Scale.
  83995. * @private
  83996. */
  83997. ol.format.KML.writeScaleTextNode_ = function(node, scale) {
  83998. ol.format.XSD.writeDecimalTextNode(node, scale * scale);
  83999. };
  84000. /**
  84001. * @param {Node} node Node.
  84002. * @param {ol.style.Style} style Style.
  84003. * @param {Array.<*>} objectStack Object stack.
  84004. * @private
  84005. */
  84006. ol.format.KML.writeStyle_ = function(node, style, objectStack) {
  84007. var /** @type {ol.xml.NodeStackItem} */ context = {node: node};
  84008. var properties = {};
  84009. var fillStyle = style.getFill();
  84010. var strokeStyle = style.getStroke();
  84011. var imageStyle = style.getImage();
  84012. var textStyle = style.getText();
  84013. if (imageStyle) {
  84014. properties['IconStyle'] = imageStyle;
  84015. }
  84016. if (textStyle) {
  84017. properties['LabelStyle'] = textStyle;
  84018. }
  84019. if (strokeStyle) {
  84020. properties['LineStyle'] = strokeStyle;
  84021. }
  84022. if (fillStyle) {
  84023. properties['PolyStyle'] = fillStyle;
  84024. }
  84025. var parentNode = objectStack[objectStack.length - 1].node;
  84026. var orderedKeys = ol.format.KML.STYLE_SEQUENCE_[parentNode.namespaceURI];
  84027. var values = ol.xml.makeSequence(properties, orderedKeys);
  84028. ol.xml.pushSerializeAndPop(context, ol.format.KML.STYLE_SERIALIZERS_,
  84029. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, objectStack, orderedKeys);
  84030. };
  84031. /**
  84032. * @param {Node} node Node to append a TextNode with the Vec2 to.
  84033. * @param {ol.format.KMLVec2_} vec2 Vec2.
  84034. * @private
  84035. */
  84036. ol.format.KML.writeVec2_ = function(node, vec2) {
  84037. node.setAttribute('x', vec2.x);
  84038. node.setAttribute('y', vec2.y);
  84039. node.setAttribute('xunits', vec2.xunits);
  84040. node.setAttribute('yunits', vec2.yunits);
  84041. };
  84042. /**
  84043. * @const
  84044. * @type {Object.<string, Array.<string>>}
  84045. * @private
  84046. */
  84047. ol.format.KML.KML_SEQUENCE_ = ol.xml.makeStructureNS(
  84048. ol.format.KML.NAMESPACE_URIS_, [
  84049. 'Document', 'Placemark'
  84050. ]);
  84051. /**
  84052. * @const
  84053. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84054. * @private
  84055. */
  84056. ol.format.KML.KML_SERIALIZERS_ = ol.xml.makeStructureNS(
  84057. ol.format.KML.NAMESPACE_URIS_, {
  84058. 'Document': ol.xml.makeChildAppender(ol.format.KML.writeDocument_),
  84059. 'Placemark': ol.xml.makeChildAppender(ol.format.KML.writePlacemark_)
  84060. });
  84061. /**
  84062. * @const
  84063. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84064. * @private
  84065. */
  84066. ol.format.KML.DOCUMENT_SERIALIZERS_ = ol.xml.makeStructureNS(
  84067. ol.format.KML.NAMESPACE_URIS_, {
  84068. 'Placemark': ol.xml.makeChildAppender(ol.format.KML.writePlacemark_)
  84069. });
  84070. /**
  84071. * @const
  84072. * @type {Object.<string, string>}
  84073. * @private
  84074. */
  84075. ol.format.KML.GEOMETRY_TYPE_TO_NODENAME_ = {
  84076. 'Point': 'Point',
  84077. 'LineString': 'LineString',
  84078. 'LinearRing': 'LinearRing',
  84079. 'Polygon': 'Polygon',
  84080. 'MultiPoint': 'MultiGeometry',
  84081. 'MultiLineString': 'MultiGeometry',
  84082. 'MultiPolygon': 'MultiGeometry'
  84083. };
  84084. /**
  84085. * @const
  84086. * @type {Object.<string, Array.<string>>}
  84087. * @private
  84088. */
  84089. ol.format.KML.ICON_SEQUENCE_ = ol.xml.makeStructureNS(
  84090. ol.format.KML.NAMESPACE_URIS_, [
  84091. 'href'
  84092. ],
  84093. ol.xml.makeStructureNS(
  84094. ol.format.KML.GX_NAMESPACE_URIS_, [
  84095. 'x', 'y', 'w', 'h'
  84096. ]));
  84097. /**
  84098. * @const
  84099. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84100. * @private
  84101. */
  84102. ol.format.KML.ICON_SERIALIZERS_ = ol.xml.makeStructureNS(
  84103. ol.format.KML.NAMESPACE_URIS_, {
  84104. 'href': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)
  84105. }, ol.xml.makeStructureNS(
  84106. ol.format.KML.GX_NAMESPACE_URIS_, {
  84107. 'x': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  84108. 'y': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  84109. 'w': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  84110. 'h': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode)
  84111. }));
  84112. /**
  84113. * @const
  84114. * @type {Object.<string, Array.<string>>}
  84115. * @private
  84116. */
  84117. ol.format.KML.ICON_STYLE_SEQUENCE_ = ol.xml.makeStructureNS(
  84118. ol.format.KML.NAMESPACE_URIS_, [
  84119. 'scale', 'heading', 'Icon', 'hotSpot'
  84120. ]);
  84121. /**
  84122. * @const
  84123. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84124. * @private
  84125. */
  84126. ol.format.KML.ICON_STYLE_SERIALIZERS_ = ol.xml.makeStructureNS(
  84127. ol.format.KML.NAMESPACE_URIS_, {
  84128. 'Icon': ol.xml.makeChildAppender(ol.format.KML.writeIcon_),
  84129. 'heading': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode),
  84130. 'hotSpot': ol.xml.makeChildAppender(ol.format.KML.writeVec2_),
  84131. 'scale': ol.xml.makeChildAppender(ol.format.KML.writeScaleTextNode_)
  84132. });
  84133. /**
  84134. * @const
  84135. * @type {Object.<string, Array.<string>>}
  84136. * @private
  84137. */
  84138. ol.format.KML.LABEL_STYLE_SEQUENCE_ = ol.xml.makeStructureNS(
  84139. ol.format.KML.NAMESPACE_URIS_, [
  84140. 'color', 'scale'
  84141. ]);
  84142. /**
  84143. * @const
  84144. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84145. * @private
  84146. */
  84147. ol.format.KML.LABEL_STYLE_SERIALIZERS_ = ol.xml.makeStructureNS(
  84148. ol.format.KML.NAMESPACE_URIS_, {
  84149. 'color': ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_),
  84150. 'scale': ol.xml.makeChildAppender(ol.format.KML.writeScaleTextNode_)
  84151. });
  84152. /**
  84153. * @const
  84154. * @type {Object.<string, Array.<string>>}
  84155. * @private
  84156. */
  84157. ol.format.KML.LINE_STYLE_SEQUENCE_ = ol.xml.makeStructureNS(
  84158. ol.format.KML.NAMESPACE_URIS_, [
  84159. 'color', 'width'
  84160. ]);
  84161. /**
  84162. * @const
  84163. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84164. * @private
  84165. */
  84166. ol.format.KML.LINE_STYLE_SERIALIZERS_ = ol.xml.makeStructureNS(
  84167. ol.format.KML.NAMESPACE_URIS_, {
  84168. 'color': ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_),
  84169. 'width': ol.xml.makeChildAppender(ol.format.XSD.writeDecimalTextNode)
  84170. });
  84171. /**
  84172. * @const
  84173. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84174. * @private
  84175. */
  84176. ol.format.KML.BOUNDARY_IS_SERIALIZERS_ = ol.xml.makeStructureNS(
  84177. ol.format.KML.NAMESPACE_URIS_, {
  84178. 'LinearRing': ol.xml.makeChildAppender(
  84179. ol.format.KML.writePrimitiveGeometry_)
  84180. });
  84181. /**
  84182. * @const
  84183. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84184. * @private
  84185. */
  84186. ol.format.KML.MULTI_GEOMETRY_SERIALIZERS_ = ol.xml.makeStructureNS(
  84187. ol.format.KML.NAMESPACE_URIS_, {
  84188. 'LineString': ol.xml.makeChildAppender(
  84189. ol.format.KML.writePrimitiveGeometry_),
  84190. 'Point': ol.xml.makeChildAppender(
  84191. ol.format.KML.writePrimitiveGeometry_),
  84192. 'Polygon': ol.xml.makeChildAppender(ol.format.KML.writePolygon_)
  84193. });
  84194. /**
  84195. * @const
  84196. * @type {Object.<string, Array.<string>>}
  84197. * @private
  84198. */
  84199. ol.format.KML.PLACEMARK_SEQUENCE_ = ol.xml.makeStructureNS(
  84200. ol.format.KML.NAMESPACE_URIS_, [
  84201. 'name', 'open', 'visibility', 'address', 'phoneNumber', 'description',
  84202. 'styleUrl', 'Style'
  84203. ]);
  84204. /**
  84205. * @const
  84206. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84207. * @private
  84208. */
  84209. ol.format.KML.PLACEMARK_SERIALIZERS_ = ol.xml.makeStructureNS(
  84210. ol.format.KML.NAMESPACE_URIS_, {
  84211. 'MultiGeometry': ol.xml.makeChildAppender(
  84212. ol.format.KML.writeMultiGeometry_),
  84213. 'LineString': ol.xml.makeChildAppender(
  84214. ol.format.KML.writePrimitiveGeometry_),
  84215. 'LinearRing': ol.xml.makeChildAppender(
  84216. ol.format.KML.writePrimitiveGeometry_),
  84217. 'Point': ol.xml.makeChildAppender(
  84218. ol.format.KML.writePrimitiveGeometry_),
  84219. 'Polygon': ol.xml.makeChildAppender(ol.format.KML.writePolygon_),
  84220. 'Style': ol.xml.makeChildAppender(ol.format.KML.writeStyle_),
  84221. 'address': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  84222. 'description': ol.xml.makeChildAppender(
  84223. ol.format.XSD.writeStringTextNode),
  84224. 'name': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  84225. 'open': ol.xml.makeChildAppender(ol.format.XSD.writeBooleanTextNode),
  84226. 'phoneNumber': ol.xml.makeChildAppender(
  84227. ol.format.XSD.writeStringTextNode),
  84228. 'styleUrl': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode),
  84229. 'visibility': ol.xml.makeChildAppender(
  84230. ol.format.XSD.writeBooleanTextNode)
  84231. });
  84232. /**
  84233. * @const
  84234. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84235. * @private
  84236. */
  84237. ol.format.KML.PRIMITIVE_GEOMETRY_SERIALIZERS_ = ol.xml.makeStructureNS(
  84238. ol.format.KML.NAMESPACE_URIS_, {
  84239. 'coordinates': ol.xml.makeChildAppender(
  84240. ol.format.KML.writeCoordinatesTextNode_)
  84241. });
  84242. /**
  84243. * @const
  84244. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84245. * @private
  84246. */
  84247. ol.format.KML.POLYGON_SERIALIZERS_ = ol.xml.makeStructureNS(
  84248. ol.format.KML.NAMESPACE_URIS_, {
  84249. 'outerBoundaryIs': ol.xml.makeChildAppender(
  84250. ol.format.KML.writeBoundaryIs_),
  84251. 'innerBoundaryIs': ol.xml.makeChildAppender(
  84252. ol.format.KML.writeBoundaryIs_)
  84253. });
  84254. /**
  84255. * @const
  84256. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84257. * @private
  84258. */
  84259. ol.format.KML.POLY_STYLE_SERIALIZERS_ = ol.xml.makeStructureNS(
  84260. ol.format.KML.NAMESPACE_URIS_, {
  84261. 'color': ol.xml.makeChildAppender(ol.format.KML.writeColorTextNode_)
  84262. });
  84263. /**
  84264. * @const
  84265. * @type {Object.<string, Array.<string>>}
  84266. * @private
  84267. */
  84268. ol.format.KML.STYLE_SEQUENCE_ = ol.xml.makeStructureNS(
  84269. ol.format.KML.NAMESPACE_URIS_, [
  84270. 'IconStyle', 'LabelStyle', 'LineStyle', 'PolyStyle'
  84271. ]);
  84272. /**
  84273. * @const
  84274. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  84275. * @private
  84276. */
  84277. ol.format.KML.STYLE_SERIALIZERS_ = ol.xml.makeStructureNS(
  84278. ol.format.KML.NAMESPACE_URIS_, {
  84279. 'IconStyle': ol.xml.makeChildAppender(ol.format.KML.writeIconStyle_),
  84280. 'LabelStyle': ol.xml.makeChildAppender(ol.format.KML.writeLabelStyle_),
  84281. 'LineStyle': ol.xml.makeChildAppender(ol.format.KML.writeLineStyle_),
  84282. 'PolyStyle': ol.xml.makeChildAppender(ol.format.KML.writePolyStyle_)
  84283. });
  84284. /**
  84285. * @const
  84286. * @param {*} value Value.
  84287. * @param {Array.<*>} objectStack Object stack.
  84288. * @param {string=} opt_nodeName Node name.
  84289. * @return {Node|undefined} Node.
  84290. * @private
  84291. */
  84292. ol.format.KML.GX_NODE_FACTORY_ = function(value, objectStack, opt_nodeName) {
  84293. return ol.xml.createElementNS(ol.format.KML.GX_NAMESPACE_URIS_[0],
  84294. 'gx:' + opt_nodeName);
  84295. };
  84296. /**
  84297. * @const
  84298. * @param {*} value Value.
  84299. * @param {Array.<*>} objectStack Object stack.
  84300. * @param {string=} opt_nodeName Node name.
  84301. * @return {Node|undefined} Node.
  84302. * @private
  84303. */
  84304. ol.format.KML.DOCUMENT_NODE_FACTORY_ = function(value, objectStack,
  84305. opt_nodeName) {
  84306. goog.asserts.assertInstanceof(value, ol.Feature,
  84307. 'value should be an ol.Feature');
  84308. var parentNode = objectStack[objectStack.length - 1].node;
  84309. goog.asserts.assert(ol.xml.isNode(parentNode),
  84310. 'parentNode should be an XML node');
  84311. return ol.xml.createElementNS(parentNode.namespaceURI, 'Placemark');
  84312. };
  84313. /**
  84314. * @const
  84315. * @param {*} value Value.
  84316. * @param {Array.<*>} objectStack Object stack.
  84317. * @param {string=} opt_nodeName Node name.
  84318. * @return {Node|undefined} Node.
  84319. * @private
  84320. */
  84321. ol.format.KML.GEOMETRY_NODE_FACTORY_ = function(value, objectStack,
  84322. opt_nodeName) {
  84323. if (value) {
  84324. goog.asserts.assertInstanceof(value, ol.geom.Geometry,
  84325. 'value should be an ol.geom.Geometry');
  84326. var parentNode = objectStack[objectStack.length - 1].node;
  84327. goog.asserts.assert(ol.xml.isNode(parentNode),
  84328. 'parentNode should be an XML node');
  84329. return ol.xml.createElementNS(parentNode.namespaceURI,
  84330. ol.format.KML.GEOMETRY_TYPE_TO_NODENAME_[value.getType()]);
  84331. }
  84332. };
  84333. /**
  84334. * A factory for creating coordinates nodes.
  84335. * @const
  84336. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84337. * @private
  84338. */
  84339. ol.format.KML.COLOR_NODE_FACTORY_ = ol.xml.makeSimpleNodeFactory('color');
  84340. /**
  84341. * A factory for creating coordinates nodes.
  84342. * @const
  84343. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84344. * @private
  84345. */
  84346. ol.format.KML.COORDINATES_NODE_FACTORY_ =
  84347. ol.xml.makeSimpleNodeFactory('coordinates');
  84348. /**
  84349. * A factory for creating innerBoundaryIs nodes.
  84350. * @const
  84351. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84352. * @private
  84353. */
  84354. ol.format.KML.INNER_BOUNDARY_NODE_FACTORY_ =
  84355. ol.xml.makeSimpleNodeFactory('innerBoundaryIs');
  84356. /**
  84357. * A factory for creating Point nodes.
  84358. * @const
  84359. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84360. * @private
  84361. */
  84362. ol.format.KML.POINT_NODE_FACTORY_ =
  84363. ol.xml.makeSimpleNodeFactory('Point');
  84364. /**
  84365. * A factory for creating LineString nodes.
  84366. * @const
  84367. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84368. * @private
  84369. */
  84370. ol.format.KML.LINE_STRING_NODE_FACTORY_ =
  84371. ol.xml.makeSimpleNodeFactory('LineString');
  84372. /**
  84373. * A factory for creating LinearRing nodes.
  84374. * @const
  84375. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84376. * @private
  84377. */
  84378. ol.format.KML.LINEAR_RING_NODE_FACTORY_ =
  84379. ol.xml.makeSimpleNodeFactory('LinearRing');
  84380. /**
  84381. * A factory for creating Polygon nodes.
  84382. * @const
  84383. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84384. * @private
  84385. */
  84386. ol.format.KML.POLYGON_NODE_FACTORY_ =
  84387. ol.xml.makeSimpleNodeFactory('Polygon');
  84388. /**
  84389. * A factory for creating outerBoundaryIs nodes.
  84390. * @const
  84391. * @type {function(*, Array.<*>, string=): (Node|undefined)}
  84392. * @private
  84393. */
  84394. ol.format.KML.OUTER_BOUNDARY_NODE_FACTORY_ =
  84395. ol.xml.makeSimpleNodeFactory('outerBoundaryIs');
  84396. /**
  84397. * Encode an array of features in the KML format.
  84398. *
  84399. * @function
  84400. * @param {Array.<ol.Feature>} features Features.
  84401. * @param {olx.format.WriteOptions=} opt_options Options.
  84402. * @return {string} Result.
  84403. * @api stable
  84404. */
  84405. ol.format.KML.prototype.writeFeatures;
  84406. /**
  84407. * Encode an array of features in the KML format as an XML node.
  84408. *
  84409. * @param {Array.<ol.Feature>} features Features.
  84410. * @param {olx.format.WriteOptions=} opt_options Options.
  84411. * @return {Node} Node.
  84412. * @api
  84413. */
  84414. ol.format.KML.prototype.writeFeaturesNode = function(features, opt_options) {
  84415. opt_options = this.adaptOptions(opt_options);
  84416. var kml = ol.xml.createElementNS(ol.format.KML.NAMESPACE_URIS_[4], 'kml');
  84417. var xmlnsUri = 'http://www.w3.org/2000/xmlns/';
  84418. var xmlSchemaInstanceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  84419. ol.xml.setAttributeNS(kml, xmlnsUri, 'xmlns:gx',
  84420. ol.format.KML.GX_NAMESPACE_URIS_[0]);
  84421. ol.xml.setAttributeNS(kml, xmlnsUri, 'xmlns:xsi', xmlSchemaInstanceUri);
  84422. ol.xml.setAttributeNS(kml, xmlSchemaInstanceUri, 'xsi:schemaLocation',
  84423. ol.format.KML.SCHEMA_LOCATION_);
  84424. var /** @type {ol.xml.NodeStackItem} */ context = {node: kml};
  84425. var properties = {};
  84426. if (features.length > 1) {
  84427. properties['Document'] = features;
  84428. } else if (features.length == 1) {
  84429. properties['Placemark'] = features[0];
  84430. }
  84431. var orderedKeys = ol.format.KML.KML_SEQUENCE_[kml.namespaceURI];
  84432. var values = ol.xml.makeSequence(properties, orderedKeys);
  84433. ol.xml.pushSerializeAndPop(context, ol.format.KML.KML_SERIALIZERS_,
  84434. ol.xml.OBJECT_PROPERTY_NODE_FACTORY, values, [opt_options], orderedKeys);
  84435. return kml;
  84436. };
  84437. // FIXME add typedef for stack state objects
  84438. goog.provide('ol.format.OSMXML');
  84439. goog.require('goog.array');
  84440. goog.require('goog.asserts');
  84441. goog.require('goog.dom.NodeType');
  84442. goog.require('goog.object');
  84443. goog.require('ol.Feature');
  84444. goog.require('ol.format.Feature');
  84445. goog.require('ol.format.XMLFeature');
  84446. goog.require('ol.geom.GeometryLayout');
  84447. goog.require('ol.geom.LineString');
  84448. goog.require('ol.geom.Point');
  84449. goog.require('ol.geom.Polygon');
  84450. goog.require('ol.proj');
  84451. goog.require('ol.xml');
  84452. /**
  84453. * @classdesc
  84454. * Feature format for reading data in the
  84455. * [OSMXML format](http://wiki.openstreetmap.org/wiki/OSM_XML).
  84456. *
  84457. * @constructor
  84458. * @extends {ol.format.XMLFeature}
  84459. * @api stable
  84460. */
  84461. ol.format.OSMXML = function() {
  84462. goog.base(this);
  84463. /**
  84464. * @inheritDoc
  84465. */
  84466. this.defaultDataProjection = ol.proj.get('EPSG:4326');
  84467. };
  84468. goog.inherits(ol.format.OSMXML, ol.format.XMLFeature);
  84469. /**
  84470. * @const
  84471. * @type {Array.<string>}
  84472. * @private
  84473. */
  84474. ol.format.OSMXML.EXTENSIONS_ = ['.osm'];
  84475. /**
  84476. * @inheritDoc
  84477. */
  84478. ol.format.OSMXML.prototype.getExtensions = function() {
  84479. return ol.format.OSMXML.EXTENSIONS_;
  84480. };
  84481. /**
  84482. * @param {Node} node Node.
  84483. * @param {Array.<*>} objectStack Object stack.
  84484. * @private
  84485. */
  84486. ol.format.OSMXML.readNode_ = function(node, objectStack) {
  84487. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84488. 'node.nodeType should be ELEMENT');
  84489. goog.asserts.assert(node.localName == 'node', 'localName should be node');
  84490. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  84491. var state = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  84492. var id = node.getAttribute('id');
  84493. var coordinates = /** @type {Array.<number>} */ ([
  84494. parseFloat(node.getAttribute('lon')),
  84495. parseFloat(node.getAttribute('lat'))
  84496. ]);
  84497. state.nodes[id] = coordinates;
  84498. var values = ol.xml.pushParseAndPop({
  84499. tags: {}
  84500. }, ol.format.OSMXML.NODE_PARSERS_, node, objectStack);
  84501. if (!goog.object.isEmpty(values.tags)) {
  84502. var geometry = new ol.geom.Point(coordinates);
  84503. ol.format.Feature.transformWithOptions(geometry, false, options);
  84504. var feature = new ol.Feature(geometry);
  84505. feature.setId(id);
  84506. feature.setProperties(values.tags);
  84507. state.features.push(feature);
  84508. }
  84509. };
  84510. /**
  84511. * @param {Node} node Node.
  84512. * @param {Array.<*>} objectStack Object stack.
  84513. * @private
  84514. */
  84515. ol.format.OSMXML.readWay_ = function(node, objectStack) {
  84516. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84517. 'node.nodeType should be ELEMENT');
  84518. goog.asserts.assert(node.localName == 'way', 'localName should be way');
  84519. var options = /** @type {olx.format.ReadOptions} */ (objectStack[0]);
  84520. var id = node.getAttribute('id');
  84521. var values = ol.xml.pushParseAndPop({
  84522. ndrefs: [],
  84523. tags: {}
  84524. }, ol.format.OSMXML.WAY_PARSERS_, node, objectStack);
  84525. var state = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  84526. var flatCoordinates = /** @type {Array.<number>} */ ([]);
  84527. for (var i = 0, ii = values.ndrefs.length; i < ii; i++) {
  84528. var point = state.nodes[values.ndrefs[i]];
  84529. goog.array.extend(flatCoordinates, point);
  84530. }
  84531. var geometry;
  84532. if (values.ndrefs[0] == values.ndrefs[values.ndrefs.length - 1]) {
  84533. // closed way
  84534. geometry = new ol.geom.Polygon(null);
  84535. geometry.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates,
  84536. [flatCoordinates.length]);
  84537. } else {
  84538. geometry = new ol.geom.LineString(null);
  84539. geometry.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  84540. }
  84541. ol.format.Feature.transformWithOptions(geometry, false, options);
  84542. var feature = new ol.Feature(geometry);
  84543. feature.setId(id);
  84544. feature.setProperties(values.tags);
  84545. state.features.push(feature);
  84546. };
  84547. /**
  84548. * @param {Node} node Node.
  84549. * @param {Array.<*>} objectStack Object stack.
  84550. * @private
  84551. * @return {ol.Feature|undefined} Track.
  84552. */
  84553. ol.format.OSMXML.readNd_ = function(node, objectStack) {
  84554. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84555. 'node.nodeType should be ELEMENT');
  84556. goog.asserts.assert(node.localName == 'nd', 'localName should be nd');
  84557. var values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  84558. values.ndrefs.push(node.getAttribute('ref'));
  84559. };
  84560. /**
  84561. * @param {Node} node Node.
  84562. * @param {Array.<*>} objectStack Object stack.
  84563. * @private
  84564. * @return {ol.Feature|undefined} Track.
  84565. */
  84566. ol.format.OSMXML.readTag_ = function(node, objectStack) {
  84567. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84568. 'node.nodeType should be ELEMENT');
  84569. goog.asserts.assert(node.localName == 'tag', 'localName should be tag');
  84570. var values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
  84571. values.tags[node.getAttribute('k')] = node.getAttribute('v');
  84572. };
  84573. /**
  84574. * @const
  84575. * @private
  84576. * @type {Array.<string>}
  84577. */
  84578. ol.format.OSMXML.NAMESPACE_URIS_ = [
  84579. null
  84580. ];
  84581. /**
  84582. * @const
  84583. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84584. * @private
  84585. */
  84586. ol.format.OSMXML.WAY_PARSERS_ = ol.xml.makeStructureNS(
  84587. ol.format.OSMXML.NAMESPACE_URIS_, {
  84588. 'nd': ol.format.OSMXML.readNd_,
  84589. 'tag': ol.format.OSMXML.readTag_
  84590. });
  84591. /**
  84592. * @const
  84593. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84594. * @private
  84595. */
  84596. ol.format.OSMXML.PARSERS_ = ol.xml.makeStructureNS(
  84597. ol.format.OSMXML.NAMESPACE_URIS_, {
  84598. 'node': ol.format.OSMXML.readNode_,
  84599. 'way': ol.format.OSMXML.readWay_
  84600. });
  84601. /**
  84602. * @const
  84603. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84604. * @private
  84605. */
  84606. ol.format.OSMXML.NODE_PARSERS_ = ol.xml.makeStructureNS(
  84607. ol.format.OSMXML.NAMESPACE_URIS_, {
  84608. 'tag': ol.format.OSMXML.readTag_
  84609. });
  84610. /**
  84611. * Read all features from an OSM source.
  84612. *
  84613. * @function
  84614. * @param {Document|Node|Object|string} source Source.
  84615. * @param {olx.format.ReadOptions=} opt_options Read options.
  84616. * @return {Array.<ol.Feature>} Features.
  84617. * @api stable
  84618. */
  84619. ol.format.OSMXML.prototype.readFeatures;
  84620. /**
  84621. * @inheritDoc
  84622. */
  84623. ol.format.OSMXML.prototype.readFeaturesFromNode = function(node, opt_options) {
  84624. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84625. 'node.nodeType should be ELEMENT');
  84626. var options = this.getReadOptions(node, opt_options);
  84627. if (node.localName == 'osm') {
  84628. var state = ol.xml.pushParseAndPop({
  84629. nodes: {},
  84630. features: []
  84631. }, ol.format.OSMXML.PARSERS_, node, [options]);
  84632. if (state.features) {
  84633. return state.features;
  84634. }
  84635. }
  84636. return [];
  84637. };
  84638. /**
  84639. * Read the projection from an OSM source.
  84640. *
  84641. * @function
  84642. * @param {Document|Node|Object|string} source Source.
  84643. * @return {ol.proj.Projection} Projection.
  84644. * @api stable
  84645. */
  84646. ol.format.OSMXML.prototype.readProjection;
  84647. goog.provide('ol.format.XLink');
  84648. /**
  84649. * @const
  84650. * @type {string}
  84651. */
  84652. ol.format.XLink.NAMESPACE_URI = 'http://www.w3.org/1999/xlink';
  84653. /**
  84654. * @param {Node} node Node.
  84655. * @return {boolean|undefined} Boolean.
  84656. */
  84657. ol.format.XLink.readHref = function(node) {
  84658. return node.getAttributeNS(ol.format.XLink.NAMESPACE_URI, 'href');
  84659. };
  84660. goog.provide('ol.format.XML');
  84661. goog.require('goog.asserts');
  84662. goog.require('ol.xml');
  84663. /**
  84664. * @classdesc
  84665. * Generic format for reading non-feature XML data
  84666. *
  84667. * @constructor
  84668. */
  84669. ol.format.XML = function() {
  84670. };
  84671. /**
  84672. * @param {Document|Node|string} source Source.
  84673. * @return {Object}
  84674. */
  84675. ol.format.XML.prototype.read = function(source) {
  84676. if (ol.xml.isDocument(source)) {
  84677. return this.readFromDocument(/** @type {Document} */ (source));
  84678. } else if (ol.xml.isNode(source)) {
  84679. return this.readFromNode(/** @type {Node} */ (source));
  84680. } else if (goog.isString(source)) {
  84681. var doc = ol.xml.parse(source);
  84682. return this.readFromDocument(doc);
  84683. } else {
  84684. goog.asserts.fail();
  84685. return null;
  84686. }
  84687. };
  84688. /**
  84689. * @param {Document} doc Document.
  84690. * @return {Object}
  84691. */
  84692. ol.format.XML.prototype.readFromDocument = goog.abstractMethod;
  84693. /**
  84694. * @param {Node} node Node.
  84695. * @return {Object}
  84696. */
  84697. ol.format.XML.prototype.readFromNode = goog.abstractMethod;
  84698. goog.provide('ol.format.OWS');
  84699. goog.require('goog.asserts');
  84700. goog.require('goog.dom.NodeType');
  84701. goog.require('ol.format.XLink');
  84702. goog.require('ol.format.XML');
  84703. goog.require('ol.format.XSD');
  84704. goog.require('ol.xml');
  84705. /**
  84706. * @constructor
  84707. * @extends {ol.format.XML}
  84708. */
  84709. ol.format.OWS = function() {
  84710. goog.base(this);
  84711. };
  84712. goog.inherits(ol.format.OWS, ol.format.XML);
  84713. /**
  84714. * @param {Document} doc Document.
  84715. * @return {Object} OWS object.
  84716. */
  84717. ol.format.OWS.prototype.readFromDocument = function(doc) {
  84718. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  84719. 'doc.nodeType should be DOCUMENT');
  84720. for (var n = doc.firstChild; n; n = n.nextSibling) {
  84721. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  84722. return this.readFromNode(n);
  84723. }
  84724. }
  84725. return null;
  84726. };
  84727. /**
  84728. * @param {Node} node Node.
  84729. * @return {Object} OWS object.
  84730. */
  84731. ol.format.OWS.prototype.readFromNode = function(node) {
  84732. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84733. 'node.nodeType should be ELEMENT');
  84734. var owsObject = ol.xml.pushParseAndPop({},
  84735. ol.format.OWS.PARSERS_, node, []);
  84736. return owsObject ? owsObject : null;
  84737. };
  84738. /**
  84739. * @param {Node} node Node.
  84740. * @param {Array.<*>} objectStack Object stack.
  84741. * @private
  84742. * @return {Object|undefined}
  84743. */
  84744. ol.format.OWS.readAddress_ = function(node, objectStack) {
  84745. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84746. 'node.nodeType should be ELEMENT');
  84747. goog.asserts.assert(node.localName == 'Address',
  84748. 'localName should be Address');
  84749. return ol.xml.pushParseAndPop({},
  84750. ol.format.OWS.ADDRESS_PARSERS_, node, objectStack);
  84751. };
  84752. /**
  84753. * @param {Node} node Node.
  84754. * @param {Array.<*>} objectStack Object stack.
  84755. * @private
  84756. * @return {Object|undefined}
  84757. */
  84758. ol.format.OWS.readAllowedValues_ = function(node, objectStack) {
  84759. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84760. 'node.nodeType should be ELEMENT');
  84761. goog.asserts.assert(node.localName == 'AllowedValues',
  84762. 'localName should be AllowedValues');
  84763. return ol.xml.pushParseAndPop({},
  84764. ol.format.OWS.ALLOWED_VALUES_PARSERS_, node, objectStack);
  84765. };
  84766. /**
  84767. * @param {Node} node Node.
  84768. * @param {Array.<*>} objectStack Object stack.
  84769. * @private
  84770. * @return {Object|undefined}
  84771. */
  84772. ol.format.OWS.readConstraint_ = function(node, objectStack) {
  84773. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84774. 'node.nodeType should be ELEMENT');
  84775. goog.asserts.assert(node.localName == 'Constraint',
  84776. 'localName should be Constraint');
  84777. var name = node.getAttribute('name');
  84778. if (!name) {
  84779. return undefined;
  84780. }
  84781. return ol.xml.pushParseAndPop({'name': name},
  84782. ol.format.OWS.CONSTRAINT_PARSERS_, node,
  84783. objectStack);
  84784. };
  84785. /**
  84786. * @param {Node} node Node.
  84787. * @param {Array.<*>} objectStack Object stack.
  84788. * @private
  84789. * @return {Object|undefined}
  84790. */
  84791. ol.format.OWS.readContactInfo_ = function(node, objectStack) {
  84792. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84793. 'node.nodeType should be ELEMENT');
  84794. goog.asserts.assert(node.localName == 'ContactInfo',
  84795. 'localName should be ContactInfo');
  84796. return ol.xml.pushParseAndPop({},
  84797. ol.format.OWS.CONTACT_INFO_PARSERS_, node, objectStack);
  84798. };
  84799. /**
  84800. * @param {Node} node Node.
  84801. * @param {Array.<*>} objectStack Object stack.
  84802. * @private
  84803. * @return {Object|undefined}
  84804. */
  84805. ol.format.OWS.readDcp_ = function(node, objectStack) {
  84806. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84807. 'node.nodeType should be ELEMENT');
  84808. goog.asserts.assert(node.localName == 'DCP', 'localName should be DCP');
  84809. return ol.xml.pushParseAndPop({},
  84810. ol.format.OWS.DCP_PARSERS_, node, objectStack);
  84811. };
  84812. /**
  84813. * @param {Node} node Node.
  84814. * @param {Array.<*>} objectStack Object stack.
  84815. * @private
  84816. * @return {Object|undefined}
  84817. */
  84818. ol.format.OWS.readGet_ = function(node, objectStack) {
  84819. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84820. 'node.nodeType should be ELEMENT');
  84821. goog.asserts.assert(node.localName == 'Get', 'localName should be Get');
  84822. var href = ol.format.XLink.readHref(node);
  84823. if (!href) {
  84824. return undefined;
  84825. }
  84826. return ol.xml.pushParseAndPop({'href': href},
  84827. ol.format.OWS.REQUEST_METHOD_PARSERS_, node, objectStack);
  84828. };
  84829. /**
  84830. * @param {Node} node Node.
  84831. * @param {Array.<*>} objectStack Object stack.
  84832. * @private
  84833. * @return {Object|undefined}
  84834. */
  84835. ol.format.OWS.readHttp_ = function(node, objectStack) {
  84836. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84837. 'node.nodeType should be ELEMENT');
  84838. goog.asserts.assert(node.localName == 'HTTP', 'localName should be HTTP');
  84839. return ol.xml.pushParseAndPop({}, ol.format.OWS.HTTP_PARSERS_,
  84840. node, objectStack);
  84841. };
  84842. /**
  84843. * @param {Node} node Node.
  84844. * @param {Array.<*>} objectStack Object stack.
  84845. * @private
  84846. * @return {Object|undefined}
  84847. */
  84848. ol.format.OWS.readOperation_ = function(node, objectStack) {
  84849. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84850. 'node.nodeType should be ELEMENT');
  84851. goog.asserts.assert(node.localName == 'Operation',
  84852. 'localName should be Operation');
  84853. var name = node.getAttribute('name');
  84854. var value = ol.xml.pushParseAndPop({},
  84855. ol.format.OWS.OPERATION_PARSERS_, node, objectStack);
  84856. if (!value) {
  84857. return undefined;
  84858. }
  84859. var object = /** @type {Object} */
  84860. (objectStack[objectStack.length - 1]);
  84861. goog.asserts.assert(goog.isObject(object), 'object should be an Object');
  84862. object[name] = value;
  84863. };
  84864. /**
  84865. * @param {Node} node Node.
  84866. * @param {Array.<*>} objectStack Object stack.
  84867. * @private
  84868. * @return {Object|undefined}
  84869. */
  84870. ol.format.OWS.readOperationsMetadata_ = function(node,
  84871. objectStack) {
  84872. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84873. 'node.nodeType should be ELEMENT');
  84874. goog.asserts.assert(node.localName == 'OperationsMetadata',
  84875. 'localName should be OperationsMetadata');
  84876. return ol.xml.pushParseAndPop({},
  84877. ol.format.OWS.OPERATIONS_METADATA_PARSERS_, node,
  84878. objectStack);
  84879. };
  84880. /**
  84881. * @param {Node} node Node.
  84882. * @param {Array.<*>} objectStack Object stack.
  84883. * @private
  84884. * @return {Object|undefined}
  84885. */
  84886. ol.format.OWS.readPhone_ = function(node, objectStack) {
  84887. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84888. 'node.nodeType should be ELEMENT');
  84889. goog.asserts.assert(node.localName == 'Phone', 'localName should be Phone');
  84890. return ol.xml.pushParseAndPop({},
  84891. ol.format.OWS.PHONE_PARSERS_, node, objectStack);
  84892. };
  84893. /**
  84894. * @param {Node} node Node.
  84895. * @param {Array.<*>} objectStack Object stack.
  84896. * @private
  84897. * @return {Object|undefined}
  84898. */
  84899. ol.format.OWS.readServiceIdentification_ = function(node,
  84900. objectStack) {
  84901. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84902. 'node.nodeType should be ELEMENT');
  84903. goog.asserts.assert(node.localName == 'ServiceIdentification',
  84904. 'localName should be ServiceIdentification');
  84905. return ol.xml.pushParseAndPop(
  84906. {}, ol.format.OWS.SERVICE_IDENTIFICATION_PARSERS_, node,
  84907. objectStack);
  84908. };
  84909. /**
  84910. * @param {Node} node Node.
  84911. * @param {Array.<*>} objectStack Object stack.
  84912. * @private
  84913. * @return {Object|undefined}
  84914. */
  84915. ol.format.OWS.readServiceContact_ = function(node, objectStack) {
  84916. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84917. 'node.nodeType should be ELEMENT');
  84918. goog.asserts.assert(node.localName == 'ServiceContact',
  84919. 'localName should be ServiceContact');
  84920. return ol.xml.pushParseAndPop(
  84921. {}, ol.format.OWS.SERVICE_CONTACT_PARSERS_, node,
  84922. objectStack);
  84923. };
  84924. /**
  84925. * @param {Node} node Node.
  84926. * @param {Array.<*>} objectStack Object stack.
  84927. * @private
  84928. * @return {Object|undefined}
  84929. */
  84930. ol.format.OWS.readServiceProvider_ = function(node, objectStack) {
  84931. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84932. 'node.nodeType should be ELEMENT');
  84933. goog.asserts.assert(node.localName == 'ServiceProvider',
  84934. 'localName should be ServiceProvider');
  84935. return ol.xml.pushParseAndPop(
  84936. {}, ol.format.OWS.SERVICE_PROVIDER_PARSERS_, node,
  84937. objectStack);
  84938. };
  84939. /**
  84940. * @param {Node} node Node.
  84941. * @param {Array.<*>} objectStack Object stack.
  84942. * @private
  84943. * @return {string|undefined}
  84944. */
  84945. ol.format.OWS.readValue_ = function(node, objectStack) {
  84946. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  84947. 'node.nodeType should be ELEMENT');
  84948. goog.asserts.assert(node.localName == 'Value', 'localName should be Value');
  84949. return ol.format.XSD.readString(node);
  84950. };
  84951. /**
  84952. * @const
  84953. * @type {Array.<string>}
  84954. * @private
  84955. */
  84956. ol.format.OWS.NAMESPACE_URIS_ = [
  84957. null,
  84958. 'http://www.opengis.net/ows/1.1'
  84959. ];
  84960. /**
  84961. * @const
  84962. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84963. * @private
  84964. */
  84965. ol.format.OWS.PARSERS_ = ol.xml.makeStructureNS(
  84966. ol.format.OWS.NAMESPACE_URIS_, {
  84967. 'ServiceIdentification': ol.xml.makeObjectPropertySetter(
  84968. ol.format.OWS.readServiceIdentification_),
  84969. 'ServiceProvider': ol.xml.makeObjectPropertySetter(
  84970. ol.format.OWS.readServiceProvider_),
  84971. 'OperationsMetadata': ol.xml.makeObjectPropertySetter(
  84972. ol.format.OWS.readOperationsMetadata_)
  84973. });
  84974. /**
  84975. * @const
  84976. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84977. * @private
  84978. */
  84979. ol.format.OWS.ADDRESS_PARSERS_ = ol.xml.makeStructureNS(
  84980. ol.format.OWS.NAMESPACE_URIS_, {
  84981. 'DeliveryPoint': ol.xml.makeObjectPropertySetter(
  84982. ol.format.XSD.readString),
  84983. 'City': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  84984. 'AdministrativeArea': ol.xml.makeObjectPropertySetter(
  84985. ol.format.XSD.readString),
  84986. 'PostalCode': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  84987. 'Country': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  84988. 'ElectronicMailAddress': ol.xml.makeObjectPropertySetter(
  84989. ol.format.XSD.readString)
  84990. });
  84991. /**
  84992. * @const
  84993. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  84994. * @private
  84995. */
  84996. ol.format.OWS.ALLOWED_VALUES_PARSERS_ = ol.xml.makeStructureNS(
  84997. ol.format.OWS.NAMESPACE_URIS_, {
  84998. 'Value': ol.xml.makeObjectPropertyPusher(ol.format.OWS.readValue_)
  84999. });
  85000. /**
  85001. * @const
  85002. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85003. * @private
  85004. */
  85005. ol.format.OWS.CONSTRAINT_PARSERS_ = ol.xml.makeStructureNS(
  85006. ol.format.OWS.NAMESPACE_URIS_, {
  85007. 'AllowedValues': ol.xml.makeObjectPropertySetter(
  85008. ol.format.OWS.readAllowedValues_)
  85009. });
  85010. /**
  85011. * @const
  85012. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85013. * @private
  85014. */
  85015. ol.format.OWS.CONTACT_INFO_PARSERS_ = ol.xml.makeStructureNS(
  85016. ol.format.OWS.NAMESPACE_URIS_, {
  85017. 'Phone': ol.xml.makeObjectPropertySetter(ol.format.OWS.readPhone_),
  85018. 'Address': ol.xml.makeObjectPropertySetter(ol.format.OWS.readAddress_)
  85019. });
  85020. /**
  85021. * @const
  85022. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85023. * @private
  85024. */
  85025. ol.format.OWS.DCP_PARSERS_ = ol.xml.makeStructureNS(
  85026. ol.format.OWS.NAMESPACE_URIS_, {
  85027. 'HTTP': ol.xml.makeObjectPropertySetter(ol.format.OWS.readHttp_)
  85028. });
  85029. /**
  85030. * @const
  85031. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85032. * @private
  85033. */
  85034. ol.format.OWS.HTTP_PARSERS_ = ol.xml.makeStructureNS(
  85035. ol.format.OWS.NAMESPACE_URIS_, {
  85036. 'Get': ol.xml.makeObjectPropertyPusher(ol.format.OWS.readGet_),
  85037. 'Post': undefined // TODO
  85038. });
  85039. /**
  85040. * @const
  85041. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85042. * @private
  85043. */
  85044. ol.format.OWS.OPERATION_PARSERS_ = ol.xml.makeStructureNS(
  85045. ol.format.OWS.NAMESPACE_URIS_, {
  85046. 'DCP': ol.xml.makeObjectPropertySetter(ol.format.OWS.readDcp_)
  85047. });
  85048. /**
  85049. * @const
  85050. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85051. * @private
  85052. */
  85053. ol.format.OWS.OPERATIONS_METADATA_PARSERS_ = ol.xml.makeStructureNS(
  85054. ol.format.OWS.NAMESPACE_URIS_, {
  85055. 'Operation': ol.format.OWS.readOperation_
  85056. });
  85057. /**
  85058. * @const
  85059. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85060. * @private
  85061. */
  85062. ol.format.OWS.PHONE_PARSERS_ = ol.xml.makeStructureNS(
  85063. ol.format.OWS.NAMESPACE_URIS_, {
  85064. 'Voice': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  85065. 'Facsimile': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)
  85066. });
  85067. /**
  85068. * @const
  85069. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85070. * @private
  85071. */
  85072. ol.format.OWS.REQUEST_METHOD_PARSERS_ = ol.xml.makeStructureNS(
  85073. ol.format.OWS.NAMESPACE_URIS_, {
  85074. 'Constraint': ol.xml.makeObjectPropertyPusher(
  85075. ol.format.OWS.readConstraint_)
  85076. });
  85077. /**
  85078. * @const
  85079. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85080. * @private
  85081. */
  85082. ol.format.OWS.SERVICE_CONTACT_PARSERS_ =
  85083. ol.xml.makeStructureNS(
  85084. ol.format.OWS.NAMESPACE_URIS_, {
  85085. 'IndividualName': ol.xml.makeObjectPropertySetter(
  85086. ol.format.XSD.readString),
  85087. 'PositionName': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  85088. 'ContactInfo': ol.xml.makeObjectPropertySetter(
  85089. ol.format.OWS.readContactInfo_)
  85090. });
  85091. /**
  85092. * @const
  85093. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85094. * @private
  85095. */
  85096. ol.format.OWS.SERVICE_IDENTIFICATION_PARSERS_ =
  85097. ol.xml.makeStructureNS(
  85098. ol.format.OWS.NAMESPACE_URIS_, {
  85099. 'Title': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  85100. 'ServiceTypeVersion': ol.xml.makeObjectPropertySetter(
  85101. ol.format.XSD.readString),
  85102. 'ServiceType': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)
  85103. });
  85104. /**
  85105. * @const
  85106. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  85107. * @private
  85108. */
  85109. ol.format.OWS.SERVICE_PROVIDER_PARSERS_ =
  85110. ol.xml.makeStructureNS(
  85111. ol.format.OWS.NAMESPACE_URIS_, {
  85112. 'ProviderName': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  85113. 'ProviderSite': ol.xml.makeObjectPropertySetter(ol.format.XLink.readHref),
  85114. 'ServiceContact': ol.xml.makeObjectPropertySetter(
  85115. ol.format.OWS.readServiceContact_)
  85116. });
  85117. goog.provide('ol.geom.flat.flip');
  85118. goog.require('goog.asserts');
  85119. /**
  85120. * @param {Array.<number>} flatCoordinates Flat coordinates.
  85121. * @param {number} offset Offset.
  85122. * @param {number} end End.
  85123. * @param {number} stride Stride.
  85124. * @param {Array.<number>=} opt_dest Destination.
  85125. * @param {number=} opt_destOffset Destination offset.
  85126. * @return {Array.<number>} Flat coordinates.
  85127. */
  85128. ol.geom.flat.flip.flipXY =
  85129. function(flatCoordinates, offset, end, stride, opt_dest, opt_destOffset) {
  85130. var dest, destOffset;
  85131. if (opt_dest !== undefined) {
  85132. dest = opt_dest;
  85133. destOffset = opt_destOffset !== undefined ? opt_destOffset : 0;
  85134. } else {
  85135. goog.asserts.assert(opt_destOffset === undefined,
  85136. 'opt_destOffSet should be defined');
  85137. dest = [];
  85138. destOffset = 0;
  85139. }
  85140. var j, k;
  85141. for (j = offset; j < end; ) {
  85142. var x = flatCoordinates[j++];
  85143. dest[destOffset++] = flatCoordinates[j++];
  85144. dest[destOffset++] = x;
  85145. for (k = 2; k < stride; ++k) {
  85146. dest[destOffset++] = flatCoordinates[j++];
  85147. }
  85148. }
  85149. dest.length = destOffset;
  85150. return dest;
  85151. };
  85152. goog.provide('ol.format.Polyline');
  85153. goog.require('goog.asserts');
  85154. goog.require('ol.Feature');
  85155. goog.require('ol.format.Feature');
  85156. goog.require('ol.format.TextFeature');
  85157. goog.require('ol.geom.GeometryLayout');
  85158. goog.require('ol.geom.LineString');
  85159. goog.require('ol.geom.SimpleGeometry');
  85160. goog.require('ol.geom.flat.flip');
  85161. goog.require('ol.geom.flat.inflate');
  85162. goog.require('ol.proj');
  85163. /**
  85164. * @classdesc
  85165. * Feature format for reading and writing data in the Encoded
  85166. * Polyline Algorithm Format.
  85167. *
  85168. * @constructor
  85169. * @extends {ol.format.TextFeature}
  85170. * @param {olx.format.PolylineOptions=} opt_options
  85171. * Optional configuration object.
  85172. * @api stable
  85173. */
  85174. ol.format.Polyline = function(opt_options) {
  85175. var options = opt_options ? opt_options : {};
  85176. goog.base(this);
  85177. /**
  85178. * @inheritDoc
  85179. */
  85180. this.defaultDataProjection = ol.proj.get('EPSG:4326');
  85181. /**
  85182. * @private
  85183. * @type {number}
  85184. */
  85185. this.factor_ = options.factor ? options.factor : 1e5;
  85186. /**
  85187. * @private
  85188. * @type {ol.geom.GeometryLayout}
  85189. */
  85190. this.geometryLayout_ = options.geometryLayout ?
  85191. options.geometryLayout : ol.geom.GeometryLayout.XY;
  85192. };
  85193. goog.inherits(ol.format.Polyline, ol.format.TextFeature);
  85194. /**
  85195. * Encode a list of n-dimensional points and return an encoded string
  85196. *
  85197. * Attention: This function will modify the passed array!
  85198. *
  85199. * @param {Array.<number>} numbers A list of n-dimensional points.
  85200. * @param {number} stride The number of dimension of the points in the list.
  85201. * @param {number=} opt_factor The factor by which the numbers will be
  85202. * multiplied. The remaining decimal places will get rounded away.
  85203. * Default is `1e5`.
  85204. * @return {string} The encoded string.
  85205. * @api
  85206. */
  85207. ol.format.Polyline.encodeDeltas = function(numbers, stride, opt_factor) {
  85208. var factor = opt_factor ? opt_factor : 1e5;
  85209. var d;
  85210. var lastNumbers = new Array(stride);
  85211. for (d = 0; d < stride; ++d) {
  85212. lastNumbers[d] = 0;
  85213. }
  85214. var i, ii;
  85215. for (i = 0, ii = numbers.length; i < ii;) {
  85216. for (d = 0; d < stride; ++d, ++i) {
  85217. var num = numbers[i];
  85218. var delta = num - lastNumbers[d];
  85219. lastNumbers[d] = num;
  85220. numbers[i] = delta;
  85221. }
  85222. }
  85223. return ol.format.Polyline.encodeFloats(numbers, factor);
  85224. };
  85225. /**
  85226. * Decode a list of n-dimensional points from an encoded string
  85227. *
  85228. * @param {string} encoded An encoded string.
  85229. * @param {number} stride The number of dimension of the points in the
  85230. * encoded string.
  85231. * @param {number=} opt_factor The factor by which the resulting numbers will
  85232. * be divided. Default is `1e5`.
  85233. * @return {Array.<number>} A list of n-dimensional points.
  85234. * @api
  85235. */
  85236. ol.format.Polyline.decodeDeltas = function(encoded, stride, opt_factor) {
  85237. var factor = opt_factor ? opt_factor : 1e5;
  85238. var d;
  85239. /** @type {Array.<number>} */
  85240. var lastNumbers = new Array(stride);
  85241. for (d = 0; d < stride; ++d) {
  85242. lastNumbers[d] = 0;
  85243. }
  85244. var numbers = ol.format.Polyline.decodeFloats(encoded, factor);
  85245. var i, ii;
  85246. for (i = 0, ii = numbers.length; i < ii;) {
  85247. for (d = 0; d < stride; ++d, ++i) {
  85248. lastNumbers[d] += numbers[i];
  85249. numbers[i] = lastNumbers[d];
  85250. }
  85251. }
  85252. return numbers;
  85253. };
  85254. /**
  85255. * Encode a list of floating point numbers and return an encoded string
  85256. *
  85257. * Attention: This function will modify the passed array!
  85258. *
  85259. * @param {Array.<number>} numbers A list of floating point numbers.
  85260. * @param {number=} opt_factor The factor by which the numbers will be
  85261. * multiplied. The remaining decimal places will get rounded away.
  85262. * Default is `1e5`.
  85263. * @return {string} The encoded string.
  85264. * @api
  85265. */
  85266. ol.format.Polyline.encodeFloats = function(numbers, opt_factor) {
  85267. var factor = opt_factor ? opt_factor : 1e5;
  85268. var i, ii;
  85269. for (i = 0, ii = numbers.length; i < ii; ++i) {
  85270. numbers[i] = Math.round(numbers[i] * factor);
  85271. }
  85272. return ol.format.Polyline.encodeSignedIntegers(numbers);
  85273. };
  85274. /**
  85275. * Decode a list of floating point numbers from an encoded string
  85276. *
  85277. * @param {string} encoded An encoded string.
  85278. * @param {number=} opt_factor The factor by which the result will be divided.
  85279. * Default is `1e5`.
  85280. * @return {Array.<number>} A list of floating point numbers.
  85281. * @api
  85282. */
  85283. ol.format.Polyline.decodeFloats = function(encoded, opt_factor) {
  85284. var factor = opt_factor ? opt_factor : 1e5;
  85285. var numbers = ol.format.Polyline.decodeSignedIntegers(encoded);
  85286. var i, ii;
  85287. for (i = 0, ii = numbers.length; i < ii; ++i) {
  85288. numbers[i] /= factor;
  85289. }
  85290. return numbers;
  85291. };
  85292. /**
  85293. * Encode a list of signed integers and return an encoded string
  85294. *
  85295. * Attention: This function will modify the passed array!
  85296. *
  85297. * @param {Array.<number>} numbers A list of signed integers.
  85298. * @return {string} The encoded string.
  85299. */
  85300. ol.format.Polyline.encodeSignedIntegers = function(numbers) {
  85301. var i, ii;
  85302. for (i = 0, ii = numbers.length; i < ii; ++i) {
  85303. var num = numbers[i];
  85304. numbers[i] = (num < 0) ? ~(num << 1) : (num << 1);
  85305. }
  85306. return ol.format.Polyline.encodeUnsignedIntegers(numbers);
  85307. };
  85308. /**
  85309. * Decode a list of signed integers from an encoded string
  85310. *
  85311. * @param {string} encoded An encoded string.
  85312. * @return {Array.<number>} A list of signed integers.
  85313. */
  85314. ol.format.Polyline.decodeSignedIntegers = function(encoded) {
  85315. var numbers = ol.format.Polyline.decodeUnsignedIntegers(encoded);
  85316. var i, ii;
  85317. for (i = 0, ii = numbers.length; i < ii; ++i) {
  85318. var num = numbers[i];
  85319. numbers[i] = (num & 1) ? ~(num >> 1) : (num >> 1);
  85320. }
  85321. return numbers;
  85322. };
  85323. /**
  85324. * Encode a list of unsigned integers and return an encoded string
  85325. *
  85326. * @param {Array.<number>} numbers A list of unsigned integers.
  85327. * @return {string} The encoded string.
  85328. */
  85329. ol.format.Polyline.encodeUnsignedIntegers = function(numbers) {
  85330. var encoded = '';
  85331. var i, ii;
  85332. for (i = 0, ii = numbers.length; i < ii; ++i) {
  85333. encoded += ol.format.Polyline.encodeUnsignedInteger(numbers[i]);
  85334. }
  85335. return encoded;
  85336. };
  85337. /**
  85338. * Decode a list of unsigned integers from an encoded string
  85339. *
  85340. * @param {string} encoded An encoded string.
  85341. * @return {Array.<number>} A list of unsigned integers.
  85342. */
  85343. ol.format.Polyline.decodeUnsignedIntegers = function(encoded) {
  85344. var numbers = [];
  85345. var current = 0;
  85346. var shift = 0;
  85347. var i, ii;
  85348. for (i = 0, ii = encoded.length; i < ii; ++i) {
  85349. var b = encoded.charCodeAt(i) - 63;
  85350. current |= (b & 0x1f) << shift;
  85351. if (b < 0x20) {
  85352. numbers.push(current);
  85353. current = 0;
  85354. shift = 0;
  85355. } else {
  85356. shift += 5;
  85357. }
  85358. }
  85359. return numbers;
  85360. };
  85361. /**
  85362. * Encode one single unsigned integer and return an encoded string
  85363. *
  85364. * @param {number} num Unsigned integer that should be encoded.
  85365. * @return {string} The encoded string.
  85366. */
  85367. ol.format.Polyline.encodeUnsignedInteger = function(num) {
  85368. var value, encoded = '';
  85369. while (num >= 0x20) {
  85370. value = (0x20 | (num & 0x1f)) + 63;
  85371. encoded += String.fromCharCode(value);
  85372. num >>= 5;
  85373. }
  85374. value = num + 63;
  85375. encoded += String.fromCharCode(value);
  85376. return encoded;
  85377. };
  85378. /**
  85379. * Read the feature from the Polyline source. The coordinates are assumed to be
  85380. * in two dimensions and in latitude, longitude order.
  85381. *
  85382. * @function
  85383. * @param {Document|Node|Object|string} source Source.
  85384. * @param {olx.format.ReadOptions=} opt_options Read options.
  85385. * @return {ol.Feature} Feature.
  85386. * @api stable
  85387. */
  85388. ol.format.Polyline.prototype.readFeature;
  85389. /**
  85390. * @inheritDoc
  85391. */
  85392. ol.format.Polyline.prototype.readFeatureFromText = function(text, opt_options) {
  85393. var geometry = this.readGeometryFromText(text, opt_options);
  85394. return new ol.Feature(geometry);
  85395. };
  85396. /**
  85397. * Read the feature from the source. As Polyline sources contain a single
  85398. * feature, this will return the feature in an array.
  85399. *
  85400. * @function
  85401. * @param {Document|Node|Object|string} source Source.
  85402. * @param {olx.format.ReadOptions=} opt_options Read options.
  85403. * @return {Array.<ol.Feature>} Features.
  85404. * @api stable
  85405. */
  85406. ol.format.Polyline.prototype.readFeatures;
  85407. /**
  85408. * @inheritDoc
  85409. */
  85410. ol.format.Polyline.prototype.readFeaturesFromText =
  85411. function(text, opt_options) {
  85412. var feature = this.readFeatureFromText(text, opt_options);
  85413. return [feature];
  85414. };
  85415. /**
  85416. * Read the geometry from the source.
  85417. *
  85418. * @function
  85419. * @param {Document|Node|Object|string} source Source.
  85420. * @param {olx.format.ReadOptions=} opt_options Read options.
  85421. * @return {ol.geom.Geometry} Geometry.
  85422. * @api stable
  85423. */
  85424. ol.format.Polyline.prototype.readGeometry;
  85425. /**
  85426. * @inheritDoc
  85427. */
  85428. ol.format.Polyline.prototype.readGeometryFromText =
  85429. function(text, opt_options) {
  85430. var stride = ol.geom.SimpleGeometry.getStrideForLayout(this.geometryLayout_);
  85431. var flatCoordinates = ol.format.Polyline.decodeDeltas(
  85432. text, stride, this.factor_);
  85433. ol.geom.flat.flip.flipXY(
  85434. flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates);
  85435. var coordinates = ol.geom.flat.inflate.coordinates(
  85436. flatCoordinates, 0, flatCoordinates.length, stride);
  85437. return /** @type {ol.geom.Geometry} */ (
  85438. ol.format.Feature.transformWithOptions(
  85439. new ol.geom.LineString(coordinates, this.geometryLayout_), false,
  85440. this.adaptOptions(opt_options)));
  85441. };
  85442. /**
  85443. * Read the projection from a Polyline source.
  85444. *
  85445. * @function
  85446. * @param {Document|Node|Object|string} source Source.
  85447. * @return {ol.proj.Projection} Projection.
  85448. * @api stable
  85449. */
  85450. ol.format.Polyline.prototype.readProjection;
  85451. /**
  85452. * @inheritDoc
  85453. */
  85454. ol.format.Polyline.prototype.writeFeatureText = function(feature, opt_options) {
  85455. var geometry = feature.getGeometry();
  85456. if (geometry) {
  85457. return this.writeGeometryText(geometry, opt_options);
  85458. } else {
  85459. goog.asserts.fail('geometry needs to be defined');
  85460. return '';
  85461. }
  85462. };
  85463. /**
  85464. * @inheritDoc
  85465. */
  85466. ol.format.Polyline.prototype.writeFeaturesText =
  85467. function(features, opt_options) {
  85468. goog.asserts.assert(features.length == 1,
  85469. 'features array should have 1 item');
  85470. return this.writeFeatureText(features[0], opt_options);
  85471. };
  85472. /**
  85473. * Write a single geometry in Polyline format.
  85474. *
  85475. * @function
  85476. * @param {ol.geom.Geometry} geometry Geometry.
  85477. * @param {olx.format.WriteOptions=} opt_options Write options.
  85478. * @return {string} Geometry.
  85479. * @api stable
  85480. */
  85481. ol.format.Polyline.prototype.writeGeometry;
  85482. /**
  85483. * @inheritDoc
  85484. */
  85485. ol.format.Polyline.prototype.writeGeometryText =
  85486. function(geometry, opt_options) {
  85487. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  85488. 'geometry should be an ol.geom.LineString');
  85489. geometry = /** @type {ol.geom.LineString} */
  85490. (ol.format.Feature.transformWithOptions(
  85491. geometry, true, this.adaptOptions(opt_options)));
  85492. var flatCoordinates = geometry.getFlatCoordinates();
  85493. var stride = geometry.getStride();
  85494. ol.geom.flat.flip.flipXY(
  85495. flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates);
  85496. return ol.format.Polyline.encodeDeltas(flatCoordinates, stride, this.factor_);
  85497. };
  85498. goog.provide('ol.format.TopoJSON');
  85499. goog.require('goog.asserts');
  85500. goog.require('goog.object');
  85501. goog.require('ol.Feature');
  85502. goog.require('ol.format.Feature');
  85503. goog.require('ol.format.JSONFeature');
  85504. goog.require('ol.geom.LineString');
  85505. goog.require('ol.geom.MultiLineString');
  85506. goog.require('ol.geom.MultiPoint');
  85507. goog.require('ol.geom.MultiPolygon');
  85508. goog.require('ol.geom.Point');
  85509. goog.require('ol.geom.Polygon');
  85510. goog.require('ol.proj');
  85511. /**
  85512. * @classdesc
  85513. * Feature format for reading and writing data in the TopoJSON format.
  85514. *
  85515. * @constructor
  85516. * @extends {ol.format.JSONFeature}
  85517. * @param {olx.format.TopoJSONOptions=} opt_options Options.
  85518. * @api stable
  85519. */
  85520. ol.format.TopoJSON = function(opt_options) {
  85521. var options = opt_options ? opt_options : {};
  85522. goog.base(this);
  85523. /**
  85524. * @inheritDoc
  85525. */
  85526. this.defaultDataProjection = ol.proj.get(
  85527. options.defaultDataProjection ?
  85528. options.defaultDataProjection : 'EPSG:4326');
  85529. };
  85530. goog.inherits(ol.format.TopoJSON, ol.format.JSONFeature);
  85531. /**
  85532. * @const {Array.<string>}
  85533. * @private
  85534. */
  85535. ol.format.TopoJSON.EXTENSIONS_ = ['.topojson'];
  85536. /**
  85537. * Concatenate arcs into a coordinate array.
  85538. * @param {Array.<number>} indices Indices of arcs to concatenate. Negative
  85539. * values indicate arcs need to be reversed.
  85540. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs (already
  85541. * transformed).
  85542. * @return {Array.<ol.Coordinate>} Coordinates array.
  85543. * @private
  85544. */
  85545. ol.format.TopoJSON.concatenateArcs_ = function(indices, arcs) {
  85546. /** @type {Array.<ol.Coordinate>} */
  85547. var coordinates = [];
  85548. var index, arc;
  85549. var i, ii;
  85550. var j, jj;
  85551. for (i = 0, ii = indices.length; i < ii; ++i) {
  85552. index = indices[i];
  85553. if (i > 0) {
  85554. // splicing together arcs, discard last point
  85555. coordinates.pop();
  85556. }
  85557. if (index >= 0) {
  85558. // forward arc
  85559. arc = arcs[index];
  85560. } else {
  85561. // reverse arc
  85562. arc = arcs[~index].slice().reverse();
  85563. }
  85564. coordinates.push.apply(coordinates, arc);
  85565. }
  85566. // provide fresh copies of coordinate arrays
  85567. for (j = 0, jj = coordinates.length; j < jj; ++j) {
  85568. coordinates[j] = coordinates[j].slice();
  85569. }
  85570. return coordinates;
  85571. };
  85572. /**
  85573. * Create a point from a TopoJSON geometry object.
  85574. *
  85575. * @param {TopoJSONGeometry} object TopoJSON object.
  85576. * @param {Array.<number>} scale Scale for each dimension.
  85577. * @param {Array.<number>} translate Translation for each dimension.
  85578. * @return {ol.geom.Point} Geometry.
  85579. * @private
  85580. */
  85581. ol.format.TopoJSON.readPointGeometry_ = function(object, scale, translate) {
  85582. var coordinates = object.coordinates;
  85583. if (scale && translate) {
  85584. ol.format.TopoJSON.transformVertex_(coordinates, scale, translate);
  85585. }
  85586. return new ol.geom.Point(coordinates);
  85587. };
  85588. /**
  85589. * Create a multi-point from a TopoJSON geometry object.
  85590. *
  85591. * @param {TopoJSONGeometry} object TopoJSON object.
  85592. * @param {Array.<number>} scale Scale for each dimension.
  85593. * @param {Array.<number>} translate Translation for each dimension.
  85594. * @return {ol.geom.MultiPoint} Geometry.
  85595. * @private
  85596. */
  85597. ol.format.TopoJSON.readMultiPointGeometry_ = function(object, scale,
  85598. translate) {
  85599. var coordinates = object.coordinates;
  85600. var i, ii;
  85601. if (scale && translate) {
  85602. for (i = 0, ii = coordinates.length; i < ii; ++i) {
  85603. ol.format.TopoJSON.transformVertex_(coordinates[i], scale, translate);
  85604. }
  85605. }
  85606. return new ol.geom.MultiPoint(coordinates);
  85607. };
  85608. /**
  85609. * Create a linestring from a TopoJSON geometry object.
  85610. *
  85611. * @param {TopoJSONGeometry} object TopoJSON object.
  85612. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85613. * @return {ol.geom.LineString} Geometry.
  85614. * @private
  85615. */
  85616. ol.format.TopoJSON.readLineStringGeometry_ = function(object, arcs) {
  85617. var coordinates = ol.format.TopoJSON.concatenateArcs_(object.arcs, arcs);
  85618. return new ol.geom.LineString(coordinates);
  85619. };
  85620. /**
  85621. * Create a multi-linestring from a TopoJSON geometry object.
  85622. *
  85623. * @param {TopoJSONGeometry} object TopoJSON object.
  85624. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85625. * @return {ol.geom.MultiLineString} Geometry.
  85626. * @private
  85627. */
  85628. ol.format.TopoJSON.readMultiLineStringGeometry_ = function(object, arcs) {
  85629. var coordinates = [];
  85630. var i, ii;
  85631. for (i = 0, ii = object.arcs.length; i < ii; ++i) {
  85632. coordinates[i] = ol.format.TopoJSON.concatenateArcs_(object.arcs[i], arcs);
  85633. }
  85634. return new ol.geom.MultiLineString(coordinates);
  85635. };
  85636. /**
  85637. * Create a polygon from a TopoJSON geometry object.
  85638. *
  85639. * @param {TopoJSONGeometry} object TopoJSON object.
  85640. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85641. * @return {ol.geom.Polygon} Geometry.
  85642. * @private
  85643. */
  85644. ol.format.TopoJSON.readPolygonGeometry_ = function(object, arcs) {
  85645. var coordinates = [];
  85646. var i, ii;
  85647. for (i = 0, ii = object.arcs.length; i < ii; ++i) {
  85648. coordinates[i] = ol.format.TopoJSON.concatenateArcs_(object.arcs[i], arcs);
  85649. }
  85650. return new ol.geom.Polygon(coordinates);
  85651. };
  85652. /**
  85653. * Create a multi-polygon from a TopoJSON geometry object.
  85654. *
  85655. * @param {TopoJSONGeometry} object TopoJSON object.
  85656. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85657. * @return {ol.geom.MultiPolygon} Geometry.
  85658. * @private
  85659. */
  85660. ol.format.TopoJSON.readMultiPolygonGeometry_ = function(object, arcs) {
  85661. var coordinates = [];
  85662. var polyArray, ringCoords, j, jj;
  85663. var i, ii;
  85664. for (i = 0, ii = object.arcs.length; i < ii; ++i) {
  85665. // for each polygon
  85666. polyArray = object.arcs[i];
  85667. ringCoords = [];
  85668. for (j = 0, jj = polyArray.length; j < jj; ++j) {
  85669. // for each ring
  85670. ringCoords[j] = ol.format.TopoJSON.concatenateArcs_(polyArray[j], arcs);
  85671. }
  85672. coordinates[i] = ringCoords;
  85673. }
  85674. return new ol.geom.MultiPolygon(coordinates);
  85675. };
  85676. /**
  85677. * @inheritDoc
  85678. */
  85679. ol.format.TopoJSON.prototype.getExtensions = function() {
  85680. return ol.format.TopoJSON.EXTENSIONS_;
  85681. };
  85682. /**
  85683. * Create features from a TopoJSON GeometryCollection object.
  85684. *
  85685. * @param {TopoJSONGeometryCollection} collection TopoJSON Geometry
  85686. * object.
  85687. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85688. * @param {Array.<number>} scale Scale for each dimension.
  85689. * @param {Array.<number>} translate Translation for each dimension.
  85690. * @param {olx.format.ReadOptions=} opt_options Read options.
  85691. * @return {Array.<ol.Feature>} Array of features.
  85692. * @private
  85693. */
  85694. ol.format.TopoJSON.readFeaturesFromGeometryCollection_ = function(
  85695. collection, arcs, scale, translate, opt_options) {
  85696. var geometries = collection.geometries;
  85697. var features = [];
  85698. var i, ii;
  85699. for (i = 0, ii = geometries.length; i < ii; ++i) {
  85700. features[i] = ol.format.TopoJSON.readFeatureFromGeometry_(
  85701. geometries[i], arcs, scale, translate, opt_options);
  85702. }
  85703. return features;
  85704. };
  85705. /**
  85706. * Create a feature from a TopoJSON geometry object.
  85707. *
  85708. * @param {TopoJSONGeometry} object TopoJSON geometry object.
  85709. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85710. * @param {Array.<number>} scale Scale for each dimension.
  85711. * @param {Array.<number>} translate Translation for each dimension.
  85712. * @param {olx.format.ReadOptions=} opt_options Read options.
  85713. * @return {ol.Feature} Feature.
  85714. * @private
  85715. */
  85716. ol.format.TopoJSON.readFeatureFromGeometry_ = function(object, arcs,
  85717. scale, translate, opt_options) {
  85718. var geometry;
  85719. var type = object.type;
  85720. var geometryReader = ol.format.TopoJSON.GEOMETRY_READERS_[type];
  85721. goog.asserts.assert(geometryReader, 'geometryReader should be defined');
  85722. if ((type === 'Point') || (type === 'MultiPoint')) {
  85723. geometry = geometryReader(object, scale, translate);
  85724. } else {
  85725. geometry = geometryReader(object, arcs);
  85726. }
  85727. var feature = new ol.Feature();
  85728. feature.setGeometry(/** @type {ol.geom.Geometry} */ (
  85729. ol.format.Feature.transformWithOptions(geometry, false, opt_options)));
  85730. if (object.id) {
  85731. feature.setId(object.id);
  85732. }
  85733. if (object.properties) {
  85734. feature.setProperties(object.properties);
  85735. }
  85736. return feature;
  85737. };
  85738. /**
  85739. * Read all features from a TopoJSON source.
  85740. *
  85741. * @function
  85742. * @param {Document|Node|Object|string} source Source.
  85743. * @return {Array.<ol.Feature>} Features.
  85744. * @api stable
  85745. */
  85746. ol.format.TopoJSON.prototype.readFeatures;
  85747. /**
  85748. * @inheritDoc
  85749. */
  85750. ol.format.TopoJSON.prototype.readFeaturesFromObject = function(
  85751. object, opt_options) {
  85752. if (object.type == 'Topology') {
  85753. var topoJSONTopology = /** @type {TopoJSONTopology} */ (object);
  85754. var transform, scale = null, translate = null;
  85755. if (topoJSONTopology.transform) {
  85756. transform = topoJSONTopology.transform;
  85757. scale = transform.scale;
  85758. translate = transform.translate;
  85759. }
  85760. var arcs = topoJSONTopology.arcs;
  85761. if (transform) {
  85762. ol.format.TopoJSON.transformArcs_(arcs, scale, translate);
  85763. }
  85764. /** @type {Array.<ol.Feature>} */
  85765. var features = [];
  85766. var topoJSONFeatures = goog.object.getValues(topoJSONTopology.objects);
  85767. var i, ii;
  85768. var feature;
  85769. for (i = 0, ii = topoJSONFeatures.length; i < ii; ++i) {
  85770. if (topoJSONFeatures[i].type === 'GeometryCollection') {
  85771. feature = /** @type {TopoJSONGeometryCollection} */
  85772. (topoJSONFeatures[i]);
  85773. features.push.apply(features,
  85774. ol.format.TopoJSON.readFeaturesFromGeometryCollection_(
  85775. feature, arcs, scale, translate, opt_options));
  85776. } else {
  85777. feature = /** @type {TopoJSONGeometry} */
  85778. (topoJSONFeatures[i]);
  85779. features.push(ol.format.TopoJSON.readFeatureFromGeometry_(
  85780. feature, arcs, scale, translate, opt_options));
  85781. }
  85782. }
  85783. return features;
  85784. } else {
  85785. return [];
  85786. }
  85787. };
  85788. /**
  85789. * Apply a linear transform to array of arcs. The provided array of arcs is
  85790. * modified in place.
  85791. *
  85792. * @param {Array.<Array.<ol.Coordinate>>} arcs Array of arcs.
  85793. * @param {Array.<number>} scale Scale for each dimension.
  85794. * @param {Array.<number>} translate Translation for each dimension.
  85795. * @private
  85796. */
  85797. ol.format.TopoJSON.transformArcs_ = function(arcs, scale, translate) {
  85798. var i, ii;
  85799. for (i = 0, ii = arcs.length; i < ii; ++i) {
  85800. ol.format.TopoJSON.transformArc_(arcs[i], scale, translate);
  85801. }
  85802. };
  85803. /**
  85804. * Apply a linear transform to an arc. The provided arc is modified in place.
  85805. *
  85806. * @param {Array.<ol.Coordinate>} arc Arc.
  85807. * @param {Array.<number>} scale Scale for each dimension.
  85808. * @param {Array.<number>} translate Translation for each dimension.
  85809. * @private
  85810. */
  85811. ol.format.TopoJSON.transformArc_ = function(arc, scale, translate) {
  85812. var x = 0;
  85813. var y = 0;
  85814. var vertex;
  85815. var i, ii;
  85816. for (i = 0, ii = arc.length; i < ii; ++i) {
  85817. vertex = arc[i];
  85818. x += vertex[0];
  85819. y += vertex[1];
  85820. vertex[0] = x;
  85821. vertex[1] = y;
  85822. ol.format.TopoJSON.transformVertex_(vertex, scale, translate);
  85823. }
  85824. };
  85825. /**
  85826. * Apply a linear transform to a vertex. The provided vertex is modified in
  85827. * place.
  85828. *
  85829. * @param {ol.Coordinate} vertex Vertex.
  85830. * @param {Array.<number>} scale Scale for each dimension.
  85831. * @param {Array.<number>} translate Translation for each dimension.
  85832. * @private
  85833. */
  85834. ol.format.TopoJSON.transformVertex_ = function(vertex, scale, translate) {
  85835. vertex[0] = vertex[0] * scale[0] + translate[0];
  85836. vertex[1] = vertex[1] * scale[1] + translate[1];
  85837. };
  85838. /**
  85839. * Read the projection from a TopoJSON source.
  85840. *
  85841. * @function
  85842. * @param {Document|Node|Object|string} object Source.
  85843. * @return {ol.proj.Projection} Projection.
  85844. * @api stable
  85845. */
  85846. ol.format.TopoJSON.prototype.readProjection = function(object) {
  85847. return this.defaultDataProjection;
  85848. };
  85849. /**
  85850. * @const
  85851. * @private
  85852. * @type {Object.<string, function(TopoJSONGeometry, Array, ...Array): ol.geom.Geometry>}
  85853. */
  85854. ol.format.TopoJSON.GEOMETRY_READERS_ = {
  85855. 'Point': ol.format.TopoJSON.readPointGeometry_,
  85856. 'LineString': ol.format.TopoJSON.readLineStringGeometry_,
  85857. 'Polygon': ol.format.TopoJSON.readPolygonGeometry_,
  85858. 'MultiPoint': ol.format.TopoJSON.readMultiPointGeometry_,
  85859. 'MultiLineString': ol.format.TopoJSON.readMultiLineStringGeometry_,
  85860. 'MultiPolygon': ol.format.TopoJSON.readMultiPolygonGeometry_
  85861. };
  85862. goog.provide('ol.format.WFS');
  85863. goog.require('goog.asserts');
  85864. goog.require('goog.dom.NodeType');
  85865. goog.require('goog.object');
  85866. goog.require('ol');
  85867. goog.require('ol.format.GML3');
  85868. goog.require('ol.format.GMLBase');
  85869. goog.require('ol.format.XMLFeature');
  85870. goog.require('ol.format.XSD');
  85871. goog.require('ol.geom.Geometry');
  85872. goog.require('ol.proj');
  85873. goog.require('ol.xml');
  85874. /**
  85875. * @classdesc
  85876. * Feature format for reading and writing data in the WFS format.
  85877. * By default, supports WFS version 1.1.0. You can pass a GML format
  85878. * as option if you want to read a WFS that contains GML2 (WFS 1.0.0).
  85879. * Also see {@link ol.format.GMLBase} which is used by this format.
  85880. *
  85881. * @constructor
  85882. * @param {olx.format.WFSOptions=} opt_options
  85883. * Optional configuration object.
  85884. * @extends {ol.format.XMLFeature}
  85885. * @api stable
  85886. */
  85887. ol.format.WFS = function(opt_options) {
  85888. var options = opt_options ? opt_options : {};
  85889. /**
  85890. * @private
  85891. * @type {Array.<string>|string|undefined}
  85892. */
  85893. this.featureType_ = options.featureType;
  85894. /**
  85895. * @private
  85896. * @type {Object.<string, string>|string|undefined}
  85897. */
  85898. this.featureNS_ = options.featureNS;
  85899. /**
  85900. * @private
  85901. * @type {ol.format.GMLBase}
  85902. */
  85903. this.gmlFormat_ = options.gmlFormat ?
  85904. options.gmlFormat : new ol.format.GML3();
  85905. /**
  85906. * @private
  85907. * @type {string}
  85908. */
  85909. this.schemaLocation_ = options.schemaLocation ?
  85910. options.schemaLocation : ol.format.WFS.SCHEMA_LOCATION;
  85911. goog.base(this);
  85912. };
  85913. goog.inherits(ol.format.WFS, ol.format.XMLFeature);
  85914. /**
  85915. * @const
  85916. * @type {string}
  85917. */
  85918. ol.format.WFS.FEATURE_PREFIX = 'feature';
  85919. /**
  85920. * @const
  85921. * @type {string}
  85922. */
  85923. ol.format.WFS.XMLNS = 'http://www.w3.org/2000/xmlns/';
  85924. /**
  85925. * Number of features; bounds/extent.
  85926. * @typedef {{numberOfFeatures: number,
  85927. * bounds: ol.Extent}}
  85928. * @api stable
  85929. */
  85930. ol.format.WFS.FeatureCollectionMetadata;
  85931. /**
  85932. * Total deleted; total inserted; total updated; array of insert ids.
  85933. * @typedef {{totalDeleted: number,
  85934. * totalInserted: number,
  85935. * totalUpdated: number,
  85936. * insertIds: Array.<string>}}
  85937. * @api stable
  85938. */
  85939. ol.format.WFS.TransactionResponse;
  85940. /**
  85941. * @const
  85942. * @type {string}
  85943. */
  85944. ol.format.WFS.SCHEMA_LOCATION = 'http://www.opengis.net/wfs ' +
  85945. 'http://schemas.opengis.net/wfs/1.1.0/wfs.xsd';
  85946. /**
  85947. * Read all features from a WFS FeatureCollection.
  85948. *
  85949. * @function
  85950. * @param {Document|Node|Object|string} source Source.
  85951. * @param {olx.format.ReadOptions=} opt_options Read options.
  85952. * @return {Array.<ol.Feature>} Features.
  85953. * @api stable
  85954. */
  85955. ol.format.WFS.prototype.readFeatures;
  85956. /**
  85957. * @inheritDoc
  85958. */
  85959. ol.format.WFS.prototype.readFeaturesFromNode = function(node, opt_options) {
  85960. var context = {
  85961. 'featureType': this.featureType_,
  85962. 'featureNS': this.featureNS_
  85963. };
  85964. goog.object.extend(context, this.getReadOptions(node,
  85965. opt_options ? opt_options : {}));
  85966. var objectStack = [context];
  85967. this.gmlFormat_.FEATURE_COLLECTION_PARSERS[ol.format.GMLBase.GMLNS][
  85968. 'featureMember'] =
  85969. ol.xml.makeArrayPusher(ol.format.GMLBase.prototype.readFeaturesInternal);
  85970. var features = ol.xml.pushParseAndPop([],
  85971. this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node,
  85972. objectStack, this.gmlFormat_);
  85973. if (!features) {
  85974. features = [];
  85975. }
  85976. return features;
  85977. };
  85978. /**
  85979. * Read transaction response of the source.
  85980. *
  85981. * @param {Document|Node|Object|string} source Source.
  85982. * @return {ol.format.WFS.TransactionResponse|undefined} Transaction response.
  85983. * @api stable
  85984. */
  85985. ol.format.WFS.prototype.readTransactionResponse = function(source) {
  85986. if (ol.xml.isDocument(source)) {
  85987. return this.readTransactionResponseFromDocument(
  85988. /** @type {Document} */ (source));
  85989. } else if (ol.xml.isNode(source)) {
  85990. return this.readTransactionResponseFromNode(/** @type {Node} */ (source));
  85991. } else if (goog.isString(source)) {
  85992. var doc = ol.xml.parse(source);
  85993. return this.readTransactionResponseFromDocument(doc);
  85994. } else {
  85995. goog.asserts.fail('Unknown source type');
  85996. return undefined;
  85997. }
  85998. };
  85999. /**
  86000. * Read feature collection metadata of the source.
  86001. *
  86002. * @param {Document|Node|Object|string} source Source.
  86003. * @return {ol.format.WFS.FeatureCollectionMetadata|undefined}
  86004. * FeatureCollection metadata.
  86005. * @api stable
  86006. */
  86007. ol.format.WFS.prototype.readFeatureCollectionMetadata = function(source) {
  86008. if (ol.xml.isDocument(source)) {
  86009. return this.readFeatureCollectionMetadataFromDocument(
  86010. /** @type {Document} */ (source));
  86011. } else if (ol.xml.isNode(source)) {
  86012. return this.readFeatureCollectionMetadataFromNode(
  86013. /** @type {Node} */ (source));
  86014. } else if (goog.isString(source)) {
  86015. var doc = ol.xml.parse(source);
  86016. return this.readFeatureCollectionMetadataFromDocument(doc);
  86017. } else {
  86018. goog.asserts.fail('Unknown source type');
  86019. return undefined;
  86020. }
  86021. };
  86022. /**
  86023. * @param {Document} doc Document.
  86024. * @return {ol.format.WFS.FeatureCollectionMetadata|undefined}
  86025. * FeatureCollection metadata.
  86026. */
  86027. ol.format.WFS.prototype.readFeatureCollectionMetadataFromDocument =
  86028. function(doc) {
  86029. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  86030. 'doc.nodeType should be DOCUMENT');
  86031. for (var n = doc.firstChild; n; n = n.nextSibling) {
  86032. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  86033. return this.readFeatureCollectionMetadataFromNode(n);
  86034. }
  86035. }
  86036. return undefined;
  86037. };
  86038. /**
  86039. * @const
  86040. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  86041. * @private
  86042. */
  86043. ol.format.WFS.FEATURE_COLLECTION_PARSERS_ = {
  86044. 'http://www.opengis.net/gml': {
  86045. 'boundedBy': ol.xml.makeObjectPropertySetter(
  86046. ol.format.GMLBase.prototype.readGeometryElement, 'bounds')
  86047. }
  86048. };
  86049. /**
  86050. * @param {Node} node Node.
  86051. * @return {ol.format.WFS.FeatureCollectionMetadata|undefined}
  86052. * FeatureCollection metadata.
  86053. */
  86054. ol.format.WFS.prototype.readFeatureCollectionMetadataFromNode = function(node) {
  86055. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  86056. 'node.nodeType should be ELEMENT');
  86057. goog.asserts.assert(node.localName == 'FeatureCollection',
  86058. 'localName should be FeatureCollection');
  86059. var result = {};
  86060. var value = ol.format.XSD.readNonNegativeIntegerString(
  86061. node.getAttribute('numberOfFeatures'));
  86062. result['numberOfFeatures'] = value;
  86063. return ol.xml.pushParseAndPop(
  86064. /** @type {ol.format.WFS.FeatureCollectionMetadata} */ (result),
  86065. ol.format.WFS.FEATURE_COLLECTION_PARSERS_, node, [], this.gmlFormat_);
  86066. };
  86067. /**
  86068. * @const
  86069. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  86070. * @private
  86071. */
  86072. ol.format.WFS.TRANSACTION_SUMMARY_PARSERS_ = {
  86073. 'http://www.opengis.net/wfs': {
  86074. 'totalInserted': ol.xml.makeObjectPropertySetter(
  86075. ol.format.XSD.readNonNegativeInteger),
  86076. 'totalUpdated': ol.xml.makeObjectPropertySetter(
  86077. ol.format.XSD.readNonNegativeInteger),
  86078. 'totalDeleted': ol.xml.makeObjectPropertySetter(
  86079. ol.format.XSD.readNonNegativeInteger)
  86080. }
  86081. };
  86082. /**
  86083. * @param {Node} node Node.
  86084. * @param {Array.<*>} objectStack Object stack.
  86085. * @return {Object|undefined} Transaction Summary.
  86086. * @private
  86087. */
  86088. ol.format.WFS.readTransactionSummary_ = function(node, objectStack) {
  86089. return ol.xml.pushParseAndPop(
  86090. {}, ol.format.WFS.TRANSACTION_SUMMARY_PARSERS_, node, objectStack);
  86091. };
  86092. /**
  86093. * @const
  86094. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  86095. * @private
  86096. */
  86097. ol.format.WFS.OGC_FID_PARSERS_ = {
  86098. 'http://www.opengis.net/ogc': {
  86099. 'FeatureId': ol.xml.makeArrayPusher(function(node, objectStack) {
  86100. return node.getAttribute('fid');
  86101. })
  86102. }
  86103. };
  86104. /**
  86105. * @param {Node} node Node.
  86106. * @param {Array.<*>} objectStack Object stack.
  86107. * @private
  86108. */
  86109. ol.format.WFS.fidParser_ = function(node, objectStack) {
  86110. ol.xml.parseNode(ol.format.WFS.OGC_FID_PARSERS_, node, objectStack);
  86111. };
  86112. /**
  86113. * @const
  86114. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  86115. * @private
  86116. */
  86117. ol.format.WFS.INSERT_RESULTS_PARSERS_ = {
  86118. 'http://www.opengis.net/wfs': {
  86119. 'Feature': ol.format.WFS.fidParser_
  86120. }
  86121. };
  86122. /**
  86123. * @param {Node} node Node.
  86124. * @param {Array.<*>} objectStack Object stack.
  86125. * @return {Array.<string>|undefined} Insert results.
  86126. * @private
  86127. */
  86128. ol.format.WFS.readInsertResults_ = function(node, objectStack) {
  86129. return ol.xml.pushParseAndPop(
  86130. [], ol.format.WFS.INSERT_RESULTS_PARSERS_, node, objectStack);
  86131. };
  86132. /**
  86133. * @const
  86134. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  86135. * @private
  86136. */
  86137. ol.format.WFS.TRANSACTION_RESPONSE_PARSERS_ = {
  86138. 'http://www.opengis.net/wfs': {
  86139. 'TransactionSummary': ol.xml.makeObjectPropertySetter(
  86140. ol.format.WFS.readTransactionSummary_, 'transactionSummary'),
  86141. 'InsertResults': ol.xml.makeObjectPropertySetter(
  86142. ol.format.WFS.readInsertResults_, 'insertIds')
  86143. }
  86144. };
  86145. /**
  86146. * @param {Document} doc Document.
  86147. * @return {ol.format.WFS.TransactionResponse|undefined} Transaction response.
  86148. */
  86149. ol.format.WFS.prototype.readTransactionResponseFromDocument = function(doc) {
  86150. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  86151. 'doc.nodeType should be DOCUMENT');
  86152. for (var n = doc.firstChild; n; n = n.nextSibling) {
  86153. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  86154. return this.readTransactionResponseFromNode(n);
  86155. }
  86156. }
  86157. return undefined;
  86158. };
  86159. /**
  86160. * @param {Node} node Node.
  86161. * @return {ol.format.WFS.TransactionResponse|undefined} Transaction response.
  86162. */
  86163. ol.format.WFS.prototype.readTransactionResponseFromNode = function(node) {
  86164. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  86165. 'node.nodeType should be ELEMENT');
  86166. goog.asserts.assert(node.localName == 'TransactionResponse',
  86167. 'localName should be TransactionResponse');
  86168. return ol.xml.pushParseAndPop(
  86169. /** @type {ol.format.WFS.TransactionResponse} */({}),
  86170. ol.format.WFS.TRANSACTION_RESPONSE_PARSERS_, node, []);
  86171. };
  86172. /**
  86173. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  86174. * @private
  86175. */
  86176. ol.format.WFS.QUERY_SERIALIZERS_ = {
  86177. 'http://www.opengis.net/wfs': {
  86178. 'PropertyName': ol.xml.makeChildAppender(ol.format.XSD.writeStringTextNode)
  86179. }
  86180. };
  86181. /**
  86182. * @param {Node} node Node.
  86183. * @param {ol.Feature} feature Feature.
  86184. * @param {Array.<*>} objectStack Node stack.
  86185. * @private
  86186. */
  86187. ol.format.WFS.writeFeature_ = function(node, feature, objectStack) {
  86188. var context = objectStack[objectStack.length - 1];
  86189. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86190. var featureType = context['featureType'];
  86191. var featureNS = context['featureNS'];
  86192. var child = ol.xml.createElementNS(featureNS, featureType);
  86193. node.appendChild(child);
  86194. ol.format.GML3.prototype.writeFeatureElement(child, feature, objectStack);
  86195. };
  86196. /**
  86197. * @param {Node} node Node.
  86198. * @param {number|string} fid Feature identifier.
  86199. * @param {Array.<*>} objectStack Node stack.
  86200. * @private
  86201. */
  86202. ol.format.WFS.writeOgcFidFilter_ = function(node, fid, objectStack) {
  86203. var filter = ol.xml.createElementNS('http://www.opengis.net/ogc', 'Filter');
  86204. var child = ol.xml.createElementNS('http://www.opengis.net/ogc', 'FeatureId');
  86205. filter.appendChild(child);
  86206. child.setAttribute('fid', fid);
  86207. node.appendChild(filter);
  86208. };
  86209. /**
  86210. * @param {Node} node Node.
  86211. * @param {ol.Feature} feature Feature.
  86212. * @param {Array.<*>} objectStack Node stack.
  86213. * @private
  86214. */
  86215. ol.format.WFS.writeDelete_ = function(node, feature, objectStack) {
  86216. var context = objectStack[objectStack.length - 1];
  86217. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86218. var featureType = context['featureType'];
  86219. var featurePrefix = context['featurePrefix'];
  86220. featurePrefix = featurePrefix ? featurePrefix :
  86221. ol.format.WFS.FEATURE_PREFIX;
  86222. var featureNS = context['featureNS'];
  86223. node.setAttribute('typeName', featurePrefix + ':' + featureType);
  86224. ol.xml.setAttributeNS(node, ol.format.WFS.XMLNS, 'xmlns:' + featurePrefix,
  86225. featureNS);
  86226. var fid = feature.getId();
  86227. if (fid) {
  86228. ol.format.WFS.writeOgcFidFilter_(node, fid, objectStack);
  86229. }
  86230. };
  86231. /**
  86232. * @param {Node} node Node.
  86233. * @param {ol.Feature} feature Feature.
  86234. * @param {Array.<*>} objectStack Node stack.
  86235. * @private
  86236. */
  86237. ol.format.WFS.writeUpdate_ = function(node, feature, objectStack) {
  86238. var context = objectStack[objectStack.length - 1];
  86239. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86240. var featureType = context['featureType'];
  86241. var featurePrefix = context['featurePrefix'];
  86242. featurePrefix = featurePrefix ? featurePrefix :
  86243. ol.format.WFS.FEATURE_PREFIX;
  86244. var featureNS = context['featureNS'];
  86245. node.setAttribute('typeName', featurePrefix + ':' + featureType);
  86246. ol.xml.setAttributeNS(node, ol.format.WFS.XMLNS, 'xmlns:' + featurePrefix,
  86247. featureNS);
  86248. var fid = feature.getId();
  86249. if (fid) {
  86250. var keys = feature.getKeys();
  86251. var values = [];
  86252. for (var i = 0, ii = keys.length; i < ii; i++) {
  86253. var value = feature.get(keys[i]);
  86254. if (value !== undefined) {
  86255. values.push({name: keys[i], value: value});
  86256. }
  86257. }
  86258. ol.xml.pushSerializeAndPop({node: node, srsName:
  86259. context['srsName']},
  86260. ol.format.WFS.TRANSACTION_SERIALIZERS_,
  86261. ol.xml.makeSimpleNodeFactory('Property'), values,
  86262. objectStack);
  86263. ol.format.WFS.writeOgcFidFilter_(node, fid, objectStack);
  86264. }
  86265. };
  86266. /**
  86267. * @param {Node} node Node.
  86268. * @param {Object} pair Property name and value.
  86269. * @param {Array.<*>} objectStack Node stack.
  86270. * @private
  86271. */
  86272. ol.format.WFS.writeProperty_ = function(node, pair, objectStack) {
  86273. var name = ol.xml.createElementNS('http://www.opengis.net/wfs', 'Name');
  86274. node.appendChild(name);
  86275. ol.format.XSD.writeStringTextNode(name, pair.name);
  86276. if (pair.value !== undefined && pair.value !== null) {
  86277. var value = ol.xml.createElementNS('http://www.opengis.net/wfs', 'Value');
  86278. node.appendChild(value);
  86279. if (pair.value instanceof ol.geom.Geometry) {
  86280. ol.format.GML3.prototype.writeGeometryElement(value,
  86281. pair.value, objectStack);
  86282. } else {
  86283. ol.format.XSD.writeStringTextNode(value, pair.value);
  86284. }
  86285. }
  86286. };
  86287. /**
  86288. * @param {Node} node Node.
  86289. * @param {{vendorId: string, safeToIgnore: boolean, value: string}}
  86290. * nativeElement The native element.
  86291. * @param {Array.<*>} objectStack Node stack.
  86292. * @private
  86293. */
  86294. ol.format.WFS.writeNative_ = function(node, nativeElement, objectStack) {
  86295. if (nativeElement.vendorId) {
  86296. node.setAttribute('vendorId', nativeElement.vendorId);
  86297. }
  86298. if (nativeElement.safeToIgnore !== undefined) {
  86299. node.setAttribute('safeToIgnore', nativeElement.safeToIgnore);
  86300. }
  86301. if (nativeElement.value !== undefined) {
  86302. ol.format.XSD.writeStringTextNode(node, nativeElement.value);
  86303. }
  86304. };
  86305. /**
  86306. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  86307. * @private
  86308. */
  86309. ol.format.WFS.TRANSACTION_SERIALIZERS_ = {
  86310. 'http://www.opengis.net/wfs': {
  86311. 'Insert': ol.xml.makeChildAppender(ol.format.WFS.writeFeature_),
  86312. 'Update': ol.xml.makeChildAppender(ol.format.WFS.writeUpdate_),
  86313. 'Delete': ol.xml.makeChildAppender(ol.format.WFS.writeDelete_),
  86314. 'Property': ol.xml.makeChildAppender(ol.format.WFS.writeProperty_),
  86315. 'Native': ol.xml.makeChildAppender(ol.format.WFS.writeNative_)
  86316. }
  86317. };
  86318. /**
  86319. * @param {Node} node Node.
  86320. * @param {string} featureType Feature type.
  86321. * @param {Array.<*>} objectStack Node stack.
  86322. * @private
  86323. */
  86324. ol.format.WFS.writeQuery_ = function(node, featureType, objectStack) {
  86325. var context = objectStack[objectStack.length - 1];
  86326. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86327. var featurePrefix = context['featurePrefix'];
  86328. var featureNS = context['featureNS'];
  86329. var propertyNames = context['propertyNames'];
  86330. var srsName = context['srsName'];
  86331. var prefix = featurePrefix ? featurePrefix + ':' : '';
  86332. node.setAttribute('typeName', prefix + featureType);
  86333. if (srsName) {
  86334. node.setAttribute('srsName', srsName);
  86335. }
  86336. if (featureNS) {
  86337. ol.xml.setAttributeNS(node, ol.format.WFS.XMLNS, 'xmlns:' + featurePrefix,
  86338. featureNS);
  86339. }
  86340. var item = goog.object.clone(context);
  86341. item.node = node;
  86342. ol.xml.pushSerializeAndPop(item,
  86343. ol.format.WFS.QUERY_SERIALIZERS_,
  86344. ol.xml.makeSimpleNodeFactory('PropertyName'), propertyNames,
  86345. objectStack);
  86346. var bbox = context['bbox'];
  86347. if (bbox) {
  86348. var child = ol.xml.createElementNS('http://www.opengis.net/ogc', 'Filter');
  86349. ol.format.WFS.writeOgcBBOX_(child, bbox, objectStack);
  86350. node.appendChild(child);
  86351. }
  86352. };
  86353. /**
  86354. * @param {Node} node Node.
  86355. * @param {string} value PropertyName value.
  86356. * @param {Array.<*>} objectStack Node stack.
  86357. * @private
  86358. */
  86359. ol.format.WFS.writeOgcPropertyName_ = function(node, value, objectStack) {
  86360. var property = ol.xml.createElementNS('http://www.opengis.net/ogc',
  86361. 'PropertyName');
  86362. ol.format.XSD.writeStringTextNode(property, value);
  86363. node.appendChild(property);
  86364. };
  86365. /**
  86366. * @param {Node} node Node.
  86367. * @param {ol.Extent} bbox Bounding box.
  86368. * @param {Array.<*>} objectStack Node stack.
  86369. * @private
  86370. */
  86371. ol.format.WFS.writeOgcBBOX_ = function(node, bbox, objectStack) {
  86372. var context = objectStack[objectStack.length - 1];
  86373. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86374. var geometryName = context['geometryName'];
  86375. var bboxNode = ol.xml.createElementNS('http://www.opengis.net/ogc', 'BBOX');
  86376. node.appendChild(bboxNode);
  86377. ol.format.WFS.writeOgcPropertyName_(bboxNode, geometryName, objectStack);
  86378. ol.format.GML3.prototype.writeGeometryElement(bboxNode, bbox, objectStack);
  86379. };
  86380. /**
  86381. * @type {Object.<string, Object.<string, ol.xml.Serializer>>}
  86382. * @private
  86383. */
  86384. ol.format.WFS.GETFEATURE_SERIALIZERS_ = {
  86385. 'http://www.opengis.net/wfs': {
  86386. 'Query': ol.xml.makeChildAppender(
  86387. ol.format.WFS.writeQuery_)
  86388. }
  86389. };
  86390. /**
  86391. * @param {Node} node Node.
  86392. * @param {Array.<{string}>} featureTypes Feature types.
  86393. * @param {Array.<*>} objectStack Node stack.
  86394. * @private
  86395. */
  86396. ol.format.WFS.writeGetFeature_ = function(node, featureTypes, objectStack) {
  86397. var context = objectStack[objectStack.length - 1];
  86398. goog.asserts.assert(goog.isObject(context), 'context should be an Object');
  86399. var item = goog.object.clone(context);
  86400. item.node = node;
  86401. ol.xml.pushSerializeAndPop(item,
  86402. ol.format.WFS.GETFEATURE_SERIALIZERS_,
  86403. ol.xml.makeSimpleNodeFactory('Query'), featureTypes,
  86404. objectStack);
  86405. };
  86406. /**
  86407. * Encode format as WFS `GetFeature` and return the Node.
  86408. *
  86409. * @param {olx.format.WFSWriteGetFeatureOptions} options Options.
  86410. * @return {Node} Result.
  86411. * @api stable
  86412. */
  86413. ol.format.WFS.prototype.writeGetFeature = function(options) {
  86414. var node = ol.xml.createElementNS('http://www.opengis.net/wfs',
  86415. 'GetFeature');
  86416. node.setAttribute('service', 'WFS');
  86417. node.setAttribute('version', '1.1.0');
  86418. if (options) {
  86419. if (options.handle) {
  86420. node.setAttribute('handle', options.handle);
  86421. }
  86422. if (options.outputFormat) {
  86423. node.setAttribute('outputFormat', options.outputFormat);
  86424. }
  86425. if (options.maxFeatures !== undefined) {
  86426. node.setAttribute('maxFeatures', options.maxFeatures);
  86427. }
  86428. if (options.resultType) {
  86429. node.setAttribute('resultType', options.resultType);
  86430. }
  86431. if (options.startIndex !== undefined) {
  86432. node.setAttribute('startIndex', options.startIndex);
  86433. }
  86434. if (options.count !== undefined) {
  86435. node.setAttribute('count', options.count);
  86436. }
  86437. }
  86438. ol.xml.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance',
  86439. 'xsi:schemaLocation', this.schemaLocation_);
  86440. var context = {
  86441. node: node,
  86442. srsName: options.srsName,
  86443. featureNS: options.featureNS ? options.featureNS : this.featureNS_,
  86444. featurePrefix: options.featurePrefix,
  86445. geometryName: options.geometryName,
  86446. bbox: options.bbox,
  86447. propertyNames: options.propertyNames ? options.propertyNames : []
  86448. };
  86449. goog.asserts.assert(goog.isArray(options.featureTypes),
  86450. 'options.featureTypes should be an array');
  86451. ol.format.WFS.writeGetFeature_(node, options.featureTypes, [context]);
  86452. return node;
  86453. };
  86454. /**
  86455. * Encode format as WFS `Transaction` and return the Node.
  86456. *
  86457. * @param {Array.<ol.Feature>} inserts The features to insert.
  86458. * @param {Array.<ol.Feature>} updates The features to update.
  86459. * @param {Array.<ol.Feature>} deletes The features to delete.
  86460. * @param {olx.format.WFSWriteTransactionOptions} options Write options.
  86461. * @return {Node} Result.
  86462. * @api stable
  86463. */
  86464. ol.format.WFS.prototype.writeTransaction = function(inserts, updates, deletes,
  86465. options) {
  86466. var objectStack = [];
  86467. var node = ol.xml.createElementNS('http://www.opengis.net/wfs',
  86468. 'Transaction');
  86469. node.setAttribute('service', 'WFS');
  86470. node.setAttribute('version', '1.1.0');
  86471. var baseObj, obj;
  86472. if (options) {
  86473. baseObj = options.gmlOptions ? options.gmlOptions : {};
  86474. if (options.handle) {
  86475. node.setAttribute('handle', options.handle);
  86476. }
  86477. }
  86478. ol.xml.setAttributeNS(node, 'http://www.w3.org/2001/XMLSchema-instance',
  86479. 'xsi:schemaLocation', this.schemaLocation_);
  86480. if (inserts) {
  86481. obj = {node: node, featureNS: options.featureNS,
  86482. featureType: options.featureType, featurePrefix: options.featurePrefix};
  86483. goog.object.extend(obj, baseObj);
  86484. ol.xml.pushSerializeAndPop(obj,
  86485. ol.format.WFS.TRANSACTION_SERIALIZERS_,
  86486. ol.xml.makeSimpleNodeFactory('Insert'), inserts,
  86487. objectStack);
  86488. }
  86489. if (updates) {
  86490. obj = {node: node, featureNS: options.featureNS,
  86491. featureType: options.featureType, featurePrefix: options.featurePrefix};
  86492. goog.object.extend(obj, baseObj);
  86493. ol.xml.pushSerializeAndPop(obj,
  86494. ol.format.WFS.TRANSACTION_SERIALIZERS_,
  86495. ol.xml.makeSimpleNodeFactory('Update'), updates,
  86496. objectStack);
  86497. }
  86498. if (deletes) {
  86499. ol.xml.pushSerializeAndPop({node: node, featureNS: options.featureNS,
  86500. featureType: options.featureType, featurePrefix: options.featurePrefix},
  86501. ol.format.WFS.TRANSACTION_SERIALIZERS_,
  86502. ol.xml.makeSimpleNodeFactory('Delete'), deletes,
  86503. objectStack);
  86504. }
  86505. if (options.nativeElements) {
  86506. ol.xml.pushSerializeAndPop({node: node, featureNS: options.featureNS,
  86507. featureType: options.featureType, featurePrefix: options.featurePrefix},
  86508. ol.format.WFS.TRANSACTION_SERIALIZERS_,
  86509. ol.xml.makeSimpleNodeFactory('Native'), options.nativeElements,
  86510. objectStack);
  86511. }
  86512. return node;
  86513. };
  86514. /**
  86515. * Read the projection from a WFS source.
  86516. *
  86517. * @function
  86518. * @param {Document|Node|Object|string} source Source.
  86519. * @return {?ol.proj.Projection} Projection.
  86520. * @api stable
  86521. */
  86522. ol.format.WFS.prototype.readProjection;
  86523. /**
  86524. * @inheritDoc
  86525. */
  86526. ol.format.WFS.prototype.readProjectionFromDocument = function(doc) {
  86527. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  86528. 'doc.nodeType should be a DOCUMENT');
  86529. for (var n = doc.firstChild; n; n = n.nextSibling) {
  86530. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  86531. return this.readProjectionFromNode(n);
  86532. }
  86533. }
  86534. return null;
  86535. };
  86536. /**
  86537. * @inheritDoc
  86538. */
  86539. ol.format.WFS.prototype.readProjectionFromNode = function(node) {
  86540. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  86541. 'node.nodeType should be ELEMENT');
  86542. goog.asserts.assert(node.localName == 'FeatureCollection',
  86543. 'localName should be FeatureCollection');
  86544. if (node.firstElementChild &&
  86545. node.firstElementChild.firstElementChild) {
  86546. node = node.firstElementChild.firstElementChild;
  86547. for (var n = node.firstElementChild; n; n = n.nextElementSibling) {
  86548. if (!(n.childNodes.length === 0 ||
  86549. (n.childNodes.length === 1 &&
  86550. n.firstChild.nodeType === 3))) {
  86551. var objectStack = [{}];
  86552. this.gmlFormat_.readGeometryElement(n, objectStack);
  86553. return ol.proj.get(objectStack.pop().srsName);
  86554. }
  86555. }
  86556. }
  86557. return null;
  86558. };
  86559. goog.provide('ol.format.WKT');
  86560. goog.require('goog.asserts');
  86561. goog.require('ol');
  86562. goog.require('ol.Feature');
  86563. goog.require('ol.format.Feature');
  86564. goog.require('ol.format.TextFeature');
  86565. goog.require('ol.geom.Geometry');
  86566. goog.require('ol.geom.GeometryCollection');
  86567. goog.require('ol.geom.GeometryType');
  86568. goog.require('ol.geom.LineString');
  86569. goog.require('ol.geom.MultiLineString');
  86570. goog.require('ol.geom.MultiPoint');
  86571. goog.require('ol.geom.MultiPolygon');
  86572. goog.require('ol.geom.Point');
  86573. goog.require('ol.geom.Polygon');
  86574. /**
  86575. * @classdesc
  86576. * Geometry format for reading and writing data in the `WellKnownText` (WKT)
  86577. * format.
  86578. *
  86579. * @constructor
  86580. * @extends {ol.format.TextFeature}
  86581. * @param {olx.format.WKTOptions=} opt_options Options.
  86582. * @api stable
  86583. */
  86584. ol.format.WKT = function(opt_options) {
  86585. var options = opt_options ? opt_options : {};
  86586. goog.base(this);
  86587. /**
  86588. * Split GeometryCollection into multiple features.
  86589. * @type {boolean}
  86590. * @private
  86591. */
  86592. this.splitCollection_ = options.splitCollection !== undefined ?
  86593. options.splitCollection : false;
  86594. };
  86595. goog.inherits(ol.format.WKT, ol.format.TextFeature);
  86596. /**
  86597. * @const
  86598. * @type {string}
  86599. */
  86600. ol.format.WKT.EMPTY = 'EMPTY';
  86601. /**
  86602. * @param {ol.geom.Point} geom Point geometry.
  86603. * @return {string} Coordinates part of Point as WKT.
  86604. * @private
  86605. */
  86606. ol.format.WKT.encodePointGeometry_ = function(geom) {
  86607. var coordinates = geom.getCoordinates();
  86608. if (coordinates.length === 0) {
  86609. return '';
  86610. }
  86611. return coordinates[0] + ' ' + coordinates[1];
  86612. };
  86613. /**
  86614. * @param {ol.geom.MultiPoint} geom MultiPoint geometry.
  86615. * @return {string} Coordinates part of MultiPoint as WKT.
  86616. * @private
  86617. */
  86618. ol.format.WKT.encodeMultiPointGeometry_ = function(geom) {
  86619. var array = [];
  86620. var components = geom.getPoints();
  86621. for (var i = 0, ii = components.length; i < ii; ++i) {
  86622. array.push('(' + ol.format.WKT.encodePointGeometry_(components[i]) + ')');
  86623. }
  86624. return array.join(',');
  86625. };
  86626. /**
  86627. * @param {ol.geom.GeometryCollection} geom GeometryCollection geometry.
  86628. * @return {string} Coordinates part of GeometryCollection as WKT.
  86629. * @private
  86630. */
  86631. ol.format.WKT.encodeGeometryCollectionGeometry_ = function(geom) {
  86632. var array = [];
  86633. var geoms = geom.getGeometries();
  86634. for (var i = 0, ii = geoms.length; i < ii; ++i) {
  86635. array.push(ol.format.WKT.encode_(geoms[i]));
  86636. }
  86637. return array.join(',');
  86638. };
  86639. /**
  86640. * @param {ol.geom.LineString|ol.geom.LinearRing} geom LineString geometry.
  86641. * @return {string} Coordinates part of LineString as WKT.
  86642. * @private
  86643. */
  86644. ol.format.WKT.encodeLineStringGeometry_ = function(geom) {
  86645. var coordinates = geom.getCoordinates();
  86646. var array = [];
  86647. for (var i = 0, ii = coordinates.length; i < ii; ++i) {
  86648. array.push(coordinates[i][0] + ' ' + coordinates[i][1]);
  86649. }
  86650. return array.join(',');
  86651. };
  86652. /**
  86653. * @param {ol.geom.MultiLineString} geom MultiLineString geometry.
  86654. * @return {string} Coordinates part of MultiLineString as WKT.
  86655. * @private
  86656. */
  86657. ol.format.WKT.encodeMultiLineStringGeometry_ = function(geom) {
  86658. var array = [];
  86659. var components = geom.getLineStrings();
  86660. for (var i = 0, ii = components.length; i < ii; ++i) {
  86661. array.push('(' + ol.format.WKT.encodeLineStringGeometry_(
  86662. components[i]) + ')');
  86663. }
  86664. return array.join(',');
  86665. };
  86666. /**
  86667. * @param {ol.geom.Polygon} geom Polygon geometry.
  86668. * @return {string} Coordinates part of Polygon as WKT.
  86669. * @private
  86670. */
  86671. ol.format.WKT.encodePolygonGeometry_ = function(geom) {
  86672. var array = [];
  86673. var rings = geom.getLinearRings();
  86674. for (var i = 0, ii = rings.length; i < ii; ++i) {
  86675. array.push('(' + ol.format.WKT.encodeLineStringGeometry_(
  86676. rings[i]) + ')');
  86677. }
  86678. return array.join(',');
  86679. };
  86680. /**
  86681. * @param {ol.geom.MultiPolygon} geom MultiPolygon geometry.
  86682. * @return {string} Coordinates part of MultiPolygon as WKT.
  86683. * @private
  86684. */
  86685. ol.format.WKT.encodeMultiPolygonGeometry_ = function(geom) {
  86686. var array = [];
  86687. var components = geom.getPolygons();
  86688. for (var i = 0, ii = components.length; i < ii; ++i) {
  86689. array.push('(' + ol.format.WKT.encodePolygonGeometry_(
  86690. components[i]) + ')');
  86691. }
  86692. return array.join(',');
  86693. };
  86694. /**
  86695. * Encode a geometry as WKT.
  86696. * @param {ol.geom.Geometry} geom The geometry to encode.
  86697. * @return {string} WKT string for the geometry.
  86698. * @private
  86699. */
  86700. ol.format.WKT.encode_ = function(geom) {
  86701. var type = geom.getType();
  86702. var geometryEncoder = ol.format.WKT.GeometryEncoder_[type];
  86703. goog.asserts.assert(geometryEncoder, 'geometryEncoder should be defined');
  86704. var enc = geometryEncoder(geom);
  86705. type = type.toUpperCase();
  86706. if (enc.length === 0) {
  86707. return type + ' ' + ol.format.WKT.EMPTY;
  86708. }
  86709. return type + '(' + enc + ')';
  86710. };
  86711. /**
  86712. * @const
  86713. * @type {Object.<string, function(ol.geom.Geometry): string>}
  86714. * @private
  86715. */
  86716. ol.format.WKT.GeometryEncoder_ = {
  86717. 'Point': ol.format.WKT.encodePointGeometry_,
  86718. 'LineString': ol.format.WKT.encodeLineStringGeometry_,
  86719. 'Polygon': ol.format.WKT.encodePolygonGeometry_,
  86720. 'MultiPoint': ol.format.WKT.encodeMultiPointGeometry_,
  86721. 'MultiLineString': ol.format.WKT.encodeMultiLineStringGeometry_,
  86722. 'MultiPolygon': ol.format.WKT.encodeMultiPolygonGeometry_,
  86723. 'GeometryCollection': ol.format.WKT.encodeGeometryCollectionGeometry_
  86724. };
  86725. /**
  86726. * Parse a WKT string.
  86727. * @param {string} wkt WKT string.
  86728. * @return {ol.geom.Geometry|ol.geom.GeometryCollection|undefined}
  86729. * The geometry created.
  86730. * @private
  86731. */
  86732. ol.format.WKT.prototype.parse_ = function(wkt) {
  86733. var lexer = new ol.format.WKT.Lexer(wkt);
  86734. var parser = new ol.format.WKT.Parser(lexer);
  86735. return parser.parse();
  86736. };
  86737. /**
  86738. * Read a feature from a WKT source.
  86739. *
  86740. * @function
  86741. * @param {Document|Node|Object|string} source Source.
  86742. * @param {olx.format.ReadOptions=} opt_options Read options.
  86743. * @return {ol.Feature} Feature.
  86744. * @api stable
  86745. */
  86746. ol.format.WKT.prototype.readFeature;
  86747. /**
  86748. * @inheritDoc
  86749. */
  86750. ol.format.WKT.prototype.readFeatureFromText = function(text, opt_options) {
  86751. var geom = this.readGeometryFromText(text, opt_options);
  86752. if (geom) {
  86753. var feature = new ol.Feature();
  86754. feature.setGeometry(geom);
  86755. return feature;
  86756. }
  86757. return null;
  86758. };
  86759. /**
  86760. * Read all features from a WKT source.
  86761. *
  86762. * @function
  86763. * @param {Document|Node|Object|string} source Source.
  86764. * @param {olx.format.ReadOptions=} opt_options Read options.
  86765. * @return {Array.<ol.Feature>} Features.
  86766. * @api stable
  86767. */
  86768. ol.format.WKT.prototype.readFeatures;
  86769. /**
  86770. * @inheritDoc
  86771. */
  86772. ol.format.WKT.prototype.readFeaturesFromText = function(text, opt_options) {
  86773. var geometries = [];
  86774. var geometry = this.readGeometryFromText(text, opt_options);
  86775. if (this.splitCollection_ &&
  86776. geometry.getType() == ol.geom.GeometryType.GEOMETRY_COLLECTION) {
  86777. geometries = (/** @type {ol.geom.GeometryCollection} */ (geometry))
  86778. .getGeometriesArray();
  86779. } else {
  86780. geometries = [geometry];
  86781. }
  86782. var feature, features = [];
  86783. for (var i = 0, ii = geometries.length; i < ii; ++i) {
  86784. feature = new ol.Feature();
  86785. feature.setGeometry(geometries[i]);
  86786. features.push(feature);
  86787. }
  86788. return features;
  86789. };
  86790. /**
  86791. * Read a single geometry from a WKT source.
  86792. *
  86793. * @function
  86794. * @param {Document|Node|Object|string} source Source.
  86795. * @param {olx.format.ReadOptions=} opt_options Read options.
  86796. * @return {ol.geom.Geometry} Geometry.
  86797. * @api stable
  86798. */
  86799. ol.format.WKT.prototype.readGeometry;
  86800. /**
  86801. * @inheritDoc
  86802. */
  86803. ol.format.WKT.prototype.readGeometryFromText = function(text, opt_options) {
  86804. var geometry = this.parse_(text);
  86805. if (geometry) {
  86806. return /** @type {ol.geom.Geometry} */ (
  86807. ol.format.Feature.transformWithOptions(geometry, false, opt_options));
  86808. } else {
  86809. return null;
  86810. }
  86811. };
  86812. /**
  86813. * Encode a feature as a WKT string.
  86814. *
  86815. * @function
  86816. * @param {ol.Feature} feature Feature.
  86817. * @param {olx.format.WriteOptions=} opt_options Write options.
  86818. * @return {string} WKT string.
  86819. * @api stable
  86820. */
  86821. ol.format.WKT.prototype.writeFeature;
  86822. /**
  86823. * @inheritDoc
  86824. */
  86825. ol.format.WKT.prototype.writeFeatureText = function(feature, opt_options) {
  86826. var geometry = feature.getGeometry();
  86827. if (geometry) {
  86828. return this.writeGeometryText(geometry, opt_options);
  86829. }
  86830. return '';
  86831. };
  86832. /**
  86833. * Encode an array of features as a WKT string.
  86834. *
  86835. * @function
  86836. * @param {Array.<ol.Feature>} features Features.
  86837. * @param {olx.format.WriteOptions=} opt_options Write options.
  86838. * @return {string} WKT string.
  86839. * @api stable
  86840. */
  86841. ol.format.WKT.prototype.writeFeatures;
  86842. /**
  86843. * @inheritDoc
  86844. */
  86845. ol.format.WKT.prototype.writeFeaturesText = function(features, opt_options) {
  86846. if (features.length == 1) {
  86847. return this.writeFeatureText(features[0], opt_options);
  86848. }
  86849. var geometries = [];
  86850. for (var i = 0, ii = features.length; i < ii; ++i) {
  86851. geometries.push(features[i].getGeometry());
  86852. }
  86853. var collection = new ol.geom.GeometryCollection(geometries);
  86854. return this.writeGeometryText(collection, opt_options);
  86855. };
  86856. /**
  86857. * Write a single geometry as a WKT string.
  86858. *
  86859. * @function
  86860. * @param {ol.geom.Geometry} geometry Geometry.
  86861. * @return {string} WKT string.
  86862. * @api stable
  86863. */
  86864. ol.format.WKT.prototype.writeGeometry;
  86865. /**
  86866. * @inheritDoc
  86867. */
  86868. ol.format.WKT.prototype.writeGeometryText = function(geometry, opt_options) {
  86869. return ol.format.WKT.encode_(/** @type {ol.geom.Geometry} */ (
  86870. ol.format.Feature.transformWithOptions(geometry, true, opt_options)));
  86871. };
  86872. /**
  86873. * @typedef {{type: number, value: (number|string|undefined), position: number}}
  86874. */
  86875. ol.format.WKT.Token;
  86876. /**
  86877. * @const
  86878. * @enum {number}
  86879. */
  86880. ol.format.WKT.TokenType = {
  86881. TEXT: 1,
  86882. LEFT_PAREN: 2,
  86883. RIGHT_PAREN: 3,
  86884. NUMBER: 4,
  86885. COMMA: 5,
  86886. EOF: 6
  86887. };
  86888. /**
  86889. * Class to tokenize a WKT string.
  86890. * @param {string} wkt WKT string.
  86891. * @constructor
  86892. * @protected
  86893. */
  86894. ol.format.WKT.Lexer = function(wkt) {
  86895. /**
  86896. * @type {string}
  86897. */
  86898. this.wkt = wkt;
  86899. /**
  86900. * @type {number}
  86901. * @private
  86902. */
  86903. this.index_ = -1;
  86904. };
  86905. /**
  86906. * @param {string} c Character.
  86907. * @return {boolean} Whether the character is alphabetic.
  86908. * @private
  86909. */
  86910. ol.format.WKT.Lexer.prototype.isAlpha_ = function(c) {
  86911. return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
  86912. };
  86913. /**
  86914. * @param {string} c Character.
  86915. * @param {boolean=} opt_decimal Whether the string number
  86916. * contains a dot, i.e. is a decimal number.
  86917. * @return {boolean} Whether the character is numeric.
  86918. * @private
  86919. */
  86920. ol.format.WKT.Lexer.prototype.isNumeric_ = function(c, opt_decimal) {
  86921. var decimal = opt_decimal !== undefined ? opt_decimal : false;
  86922. return c >= '0' && c <= '9' || c == '.' && !decimal;
  86923. };
  86924. /**
  86925. * @param {string} c Character.
  86926. * @return {boolean} Whether the character is whitespace.
  86927. * @private
  86928. */
  86929. ol.format.WKT.Lexer.prototype.isWhiteSpace_ = function(c) {
  86930. return c == ' ' || c == '\t' || c == '\r' || c == '\n';
  86931. };
  86932. /**
  86933. * @return {string} Next string character.
  86934. * @private
  86935. */
  86936. ol.format.WKT.Lexer.prototype.nextChar_ = function() {
  86937. return this.wkt.charAt(++this.index_);
  86938. };
  86939. /**
  86940. * Fetch and return the next token.
  86941. * @return {!ol.format.WKT.Token} Next string token.
  86942. */
  86943. ol.format.WKT.Lexer.prototype.nextToken = function() {
  86944. var c = this.nextChar_();
  86945. var token = {position: this.index_, value: c};
  86946. if (c == '(') {
  86947. token.type = ol.format.WKT.TokenType.LEFT_PAREN;
  86948. } else if (c == ',') {
  86949. token.type = ol.format.WKT.TokenType.COMMA;
  86950. } else if (c == ')') {
  86951. token.type = ol.format.WKT.TokenType.RIGHT_PAREN;
  86952. } else if (this.isNumeric_(c) || c == '-') {
  86953. token.type = ol.format.WKT.TokenType.NUMBER;
  86954. token.value = this.readNumber_();
  86955. } else if (this.isAlpha_(c)) {
  86956. token.type = ol.format.WKT.TokenType.TEXT;
  86957. token.value = this.readText_();
  86958. } else if (this.isWhiteSpace_(c)) {
  86959. return this.nextToken();
  86960. } else if (c === '') {
  86961. token.type = ol.format.WKT.TokenType.EOF;
  86962. } else {
  86963. throw new Error('Unexpected character: ' + c);
  86964. }
  86965. return token;
  86966. };
  86967. /**
  86968. * @return {number} Numeric token value.
  86969. * @private
  86970. */
  86971. ol.format.WKT.Lexer.prototype.readNumber_ = function() {
  86972. var c, index = this.index_;
  86973. var decimal = false;
  86974. var scientificNotation = false;
  86975. do {
  86976. if (c == '.') {
  86977. decimal = true;
  86978. } else if (c == 'e' || c == 'E') {
  86979. scientificNotation = true;
  86980. }
  86981. c = this.nextChar_();
  86982. } while (
  86983. this.isNumeric_(c, decimal) ||
  86984. // if we haven't detected a scientific number before, 'e' or 'E'
  86985. // hint that we should continue to read
  86986. !scientificNotation && (c == 'e' || c == 'E') ||
  86987. // once we know that we have a scientific number, both '-' and '+'
  86988. // are allowed
  86989. scientificNotation && (c == '-' || c == '+')
  86990. );
  86991. return parseFloat(this.wkt.substring(index, this.index_--));
  86992. };
  86993. /**
  86994. * @return {string} String token value.
  86995. * @private
  86996. */
  86997. ol.format.WKT.Lexer.prototype.readText_ = function() {
  86998. var c, index = this.index_;
  86999. do {
  87000. c = this.nextChar_();
  87001. } while (this.isAlpha_(c));
  87002. return this.wkt.substring(index, this.index_--).toUpperCase();
  87003. };
  87004. /**
  87005. * Class to parse the tokens from the WKT string.
  87006. * @param {ol.format.WKT.Lexer} lexer
  87007. * @constructor
  87008. * @protected
  87009. */
  87010. ol.format.WKT.Parser = function(lexer) {
  87011. /**
  87012. * @type {ol.format.WKT.Lexer}
  87013. * @private
  87014. */
  87015. this.lexer_ = lexer;
  87016. /**
  87017. * @type {ol.format.WKT.Token}
  87018. * @private
  87019. */
  87020. this.token_;
  87021. /**
  87022. * @type {number}
  87023. * @private
  87024. */
  87025. this.dimension_ = 2;
  87026. };
  87027. /**
  87028. * Fetch the next token form the lexer and replace the active token.
  87029. * @private
  87030. */
  87031. ol.format.WKT.Parser.prototype.consume_ = function() {
  87032. this.token_ = this.lexer_.nextToken();
  87033. };
  87034. /**
  87035. * If the given type matches the current token, consume it.
  87036. * @param {ol.format.WKT.TokenType.<number>} type Token type.
  87037. * @return {boolean} Whether the token matches the given type.
  87038. */
  87039. ol.format.WKT.Parser.prototype.match = function(type) {
  87040. var isMatch = this.token_.type == type;
  87041. if (isMatch) {
  87042. this.consume_();
  87043. }
  87044. return isMatch;
  87045. };
  87046. /**
  87047. * Try to parse the tokens provided by the lexer.
  87048. * @return {ol.geom.Geometry|ol.geom.GeometryCollection} The geometry.
  87049. */
  87050. ol.format.WKT.Parser.prototype.parse = function() {
  87051. this.consume_();
  87052. var geometry = this.parseGeometry_();
  87053. goog.asserts.assert(this.token_.type == ol.format.WKT.TokenType.EOF,
  87054. 'token type should be end of file');
  87055. return geometry;
  87056. };
  87057. /**
  87058. * @return {!(ol.geom.Geometry|ol.geom.GeometryCollection)} The geometry.
  87059. * @private
  87060. */
  87061. ol.format.WKT.Parser.prototype.parseGeometry_ = function() {
  87062. var token = this.token_;
  87063. if (this.match(ol.format.WKT.TokenType.TEXT)) {
  87064. var geomType = token.value;
  87065. if (geomType == ol.geom.GeometryType.GEOMETRY_COLLECTION.toUpperCase()) {
  87066. var geometries = this.parseGeometryCollectionText_();
  87067. return new ol.geom.GeometryCollection(geometries);
  87068. } else {
  87069. var parser = ol.format.WKT.Parser.GeometryParser_[geomType];
  87070. var ctor = ol.format.WKT.Parser.GeometryConstructor_[geomType];
  87071. if (!parser || !ctor) {
  87072. throw new Error('Invalid geometry type: ' + geomType);
  87073. }
  87074. var coordinates = parser.call(this);
  87075. return new ctor(coordinates);
  87076. }
  87077. }
  87078. throw new Error(this.formatErrorMessage_());
  87079. };
  87080. /**
  87081. * @return {!Array.<ol.geom.Geometry>} A collection of geometries.
  87082. * @private
  87083. */
  87084. ol.format.WKT.Parser.prototype.parseGeometryCollectionText_ = function() {
  87085. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87086. var geometries = [];
  87087. do {
  87088. geometries.push(this.parseGeometry_());
  87089. } while (this.match(ol.format.WKT.TokenType.COMMA));
  87090. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87091. return geometries;
  87092. }
  87093. } else if (this.isEmptyGeometry_()) {
  87094. return [];
  87095. }
  87096. throw new Error(this.formatErrorMessage_());
  87097. };
  87098. /**
  87099. * @return {Array.<number>} All values in a point.
  87100. * @private
  87101. */
  87102. ol.format.WKT.Parser.prototype.parsePointText_ = function() {
  87103. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87104. var coordinates = this.parsePoint_();
  87105. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87106. return coordinates;
  87107. }
  87108. } else if (this.isEmptyGeometry_()) {
  87109. return null;
  87110. }
  87111. throw new Error(this.formatErrorMessage_());
  87112. };
  87113. /**
  87114. * @return {!Array.<!Array.<number>>} All points in a linestring.
  87115. * @private
  87116. */
  87117. ol.format.WKT.Parser.prototype.parseLineStringText_ = function() {
  87118. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87119. var coordinates = this.parsePointList_();
  87120. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87121. return coordinates;
  87122. }
  87123. } else if (this.isEmptyGeometry_()) {
  87124. return [];
  87125. }
  87126. throw new Error(this.formatErrorMessage_());
  87127. };
  87128. /**
  87129. * @return {!Array.<!Array.<number>>} All points in a polygon.
  87130. * @private
  87131. */
  87132. ol.format.WKT.Parser.prototype.parsePolygonText_ = function() {
  87133. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87134. var coordinates = this.parseLineStringTextList_();
  87135. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87136. return coordinates;
  87137. }
  87138. } else if (this.isEmptyGeometry_()) {
  87139. return [];
  87140. }
  87141. throw new Error(this.formatErrorMessage_());
  87142. };
  87143. /**
  87144. * @return {!Array.<!Array.<number>>} All points in a multipoint.
  87145. * @private
  87146. */
  87147. ol.format.WKT.Parser.prototype.parseMultiPointText_ = function() {
  87148. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87149. var coordinates;
  87150. if (this.token_.type == ol.format.WKT.TokenType.LEFT_PAREN) {
  87151. coordinates = this.parsePointTextList_();
  87152. } else {
  87153. coordinates = this.parsePointList_();
  87154. }
  87155. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87156. return coordinates;
  87157. }
  87158. } else if (this.isEmptyGeometry_()) {
  87159. return [];
  87160. }
  87161. throw new Error(this.formatErrorMessage_());
  87162. };
  87163. /**
  87164. * @return {!Array.<!Array.<number>>} All linestring points
  87165. * in a multilinestring.
  87166. * @private
  87167. */
  87168. ol.format.WKT.Parser.prototype.parseMultiLineStringText_ = function() {
  87169. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87170. var coordinates = this.parseLineStringTextList_();
  87171. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87172. return coordinates;
  87173. }
  87174. } else if (this.isEmptyGeometry_()) {
  87175. return [];
  87176. }
  87177. throw new Error(this.formatErrorMessage_());
  87178. };
  87179. /**
  87180. * @return {!Array.<!Array.<number>>} All polygon points in a multipolygon.
  87181. * @private
  87182. */
  87183. ol.format.WKT.Parser.prototype.parseMultiPolygonText_ = function() {
  87184. if (this.match(ol.format.WKT.TokenType.LEFT_PAREN)) {
  87185. var coordinates = this.parsePolygonTextList_();
  87186. if (this.match(ol.format.WKT.TokenType.RIGHT_PAREN)) {
  87187. return coordinates;
  87188. }
  87189. } else if (this.isEmptyGeometry_()) {
  87190. return [];
  87191. }
  87192. throw new Error(this.formatErrorMessage_());
  87193. };
  87194. /**
  87195. * @return {!Array.<number>} A point.
  87196. * @private
  87197. */
  87198. ol.format.WKT.Parser.prototype.parsePoint_ = function() {
  87199. var coordinates = [];
  87200. for (var i = 0; i < this.dimension_; ++i) {
  87201. var token = this.token_;
  87202. if (this.match(ol.format.WKT.TokenType.NUMBER)) {
  87203. coordinates.push(token.value);
  87204. } else {
  87205. break;
  87206. }
  87207. }
  87208. if (coordinates.length == this.dimension_) {
  87209. return coordinates;
  87210. }
  87211. throw new Error(this.formatErrorMessage_());
  87212. };
  87213. /**
  87214. * @return {!Array.<!Array.<number>>} An array of points.
  87215. * @private
  87216. */
  87217. ol.format.WKT.Parser.prototype.parsePointList_ = function() {
  87218. var coordinates = [this.parsePoint_()];
  87219. while (this.match(ol.format.WKT.TokenType.COMMA)) {
  87220. coordinates.push(this.parsePoint_());
  87221. }
  87222. return coordinates;
  87223. };
  87224. /**
  87225. * @return {!Array.<!Array.<number>>} An array of points.
  87226. * @private
  87227. */
  87228. ol.format.WKT.Parser.prototype.parsePointTextList_ = function() {
  87229. var coordinates = [this.parsePointText_()];
  87230. while (this.match(ol.format.WKT.TokenType.COMMA)) {
  87231. coordinates.push(this.parsePointText_());
  87232. }
  87233. return coordinates;
  87234. };
  87235. /**
  87236. * @return {!Array.<!Array.<number>>} An array of points.
  87237. * @private
  87238. */
  87239. ol.format.WKT.Parser.prototype.parseLineStringTextList_ = function() {
  87240. var coordinates = [this.parseLineStringText_()];
  87241. while (this.match(ol.format.WKT.TokenType.COMMA)) {
  87242. coordinates.push(this.parseLineStringText_());
  87243. }
  87244. return coordinates;
  87245. };
  87246. /**
  87247. * @return {!Array.<!Array.<number>>} An array of points.
  87248. * @private
  87249. */
  87250. ol.format.WKT.Parser.prototype.parsePolygonTextList_ = function() {
  87251. var coordinates = [this.parsePolygonText_()];
  87252. while (this.match(ol.format.WKT.TokenType.COMMA)) {
  87253. coordinates.push(this.parsePolygonText_());
  87254. }
  87255. return coordinates;
  87256. };
  87257. /**
  87258. * @return {boolean} Whether the token implies an empty geometry.
  87259. * @private
  87260. */
  87261. ol.format.WKT.Parser.prototype.isEmptyGeometry_ = function() {
  87262. var isEmpty = this.token_.type == ol.format.WKT.TokenType.TEXT &&
  87263. this.token_.value == ol.format.WKT.EMPTY;
  87264. if (isEmpty) {
  87265. this.consume_();
  87266. }
  87267. return isEmpty;
  87268. };
  87269. /**
  87270. * Create an error message for an unexpected token error.
  87271. * @return {string} Error message.
  87272. * @private
  87273. */
  87274. ol.format.WKT.Parser.prototype.formatErrorMessage_ = function() {
  87275. return 'Unexpected `' + this.token_.value + '` at position ' +
  87276. this.token_.position + ' in `' + this.lexer_.wkt + '`';
  87277. };
  87278. /**
  87279. * @enum {function (new:ol.geom.Geometry, Array, ol.geom.GeometryLayout.<string>=)}
  87280. * @private
  87281. */
  87282. ol.format.WKT.Parser.GeometryConstructor_ = {
  87283. 'POINT': ol.geom.Point,
  87284. 'LINESTRING': ol.geom.LineString,
  87285. 'POLYGON': ol.geom.Polygon,
  87286. 'MULTIPOINT': ol.geom.MultiPoint,
  87287. 'MULTILINESTRING': ol.geom.MultiLineString,
  87288. 'MULTIPOLYGON': ol.geom.MultiPolygon
  87289. };
  87290. /**
  87291. * @enum {(function(): Array)}
  87292. * @private
  87293. */
  87294. ol.format.WKT.Parser.GeometryParser_ = {
  87295. 'POINT': ol.format.WKT.Parser.prototype.parsePointText_,
  87296. 'LINESTRING': ol.format.WKT.Parser.prototype.parseLineStringText_,
  87297. 'POLYGON': ol.format.WKT.Parser.prototype.parsePolygonText_,
  87298. 'MULTIPOINT': ol.format.WKT.Parser.prototype.parseMultiPointText_,
  87299. 'MULTILINESTRING': ol.format.WKT.Parser.prototype.parseMultiLineStringText_,
  87300. 'MULTIPOLYGON': ol.format.WKT.Parser.prototype.parseMultiPolygonText_
  87301. };
  87302. goog.provide('ol.format.WMSCapabilities');
  87303. goog.require('goog.asserts');
  87304. goog.require('goog.dom.NodeType');
  87305. goog.require('goog.object');
  87306. goog.require('ol');
  87307. goog.require('ol.format.XLink');
  87308. goog.require('ol.format.XML');
  87309. goog.require('ol.format.XSD');
  87310. goog.require('ol.xml');
  87311. /**
  87312. * @classdesc
  87313. * Format for reading WMS capabilities data
  87314. *
  87315. * @constructor
  87316. * @extends {ol.format.XML}
  87317. * @api
  87318. */
  87319. ol.format.WMSCapabilities = function() {
  87320. goog.base(this);
  87321. /**
  87322. * @type {string|undefined}
  87323. */
  87324. this.version = undefined;
  87325. };
  87326. goog.inherits(ol.format.WMSCapabilities, ol.format.XML);
  87327. /**
  87328. * Read a WMS capabilities document.
  87329. *
  87330. * @function
  87331. * @param {Document|Node|string} source The XML source.
  87332. * @return {Object} An object representing the WMS capabilities.
  87333. * @api
  87334. */
  87335. ol.format.WMSCapabilities.prototype.read;
  87336. /**
  87337. * @param {Document} doc Document.
  87338. * @return {Object} WMS Capability object.
  87339. */
  87340. ol.format.WMSCapabilities.prototype.readFromDocument = function(doc) {
  87341. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  87342. 'doc.nodeType should be DOCUMENT');
  87343. for (var n = doc.firstChild; n; n = n.nextSibling) {
  87344. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  87345. return this.readFromNode(n);
  87346. }
  87347. }
  87348. return null;
  87349. };
  87350. /**
  87351. * @param {Node} node Node.
  87352. * @return {Object} WMS Capability object.
  87353. */
  87354. ol.format.WMSCapabilities.prototype.readFromNode = function(node) {
  87355. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87356. 'node.nodeType should be ELEMENT');
  87357. goog.asserts.assert(node.localName == 'WMS_Capabilities' ||
  87358. node.localName == 'WMT_MS_Capabilities',
  87359. 'localName should be WMS_Capabilities or WMT_MS_Capabilities');
  87360. this.version = node.getAttribute('version').trim();
  87361. goog.asserts.assertString(this.version, 'this.version should be a string');
  87362. var wmsCapabilityObject = ol.xml.pushParseAndPop({
  87363. 'version': this.version
  87364. }, ol.format.WMSCapabilities.PARSERS_, node, []);
  87365. return wmsCapabilityObject ? wmsCapabilityObject : null;
  87366. };
  87367. /**
  87368. * @private
  87369. * @param {Node} node Node.
  87370. * @param {Array.<*>} objectStack Object stack.
  87371. * @return {Object|undefined} Attribution object.
  87372. */
  87373. ol.format.WMSCapabilities.readAttribution_ = function(node, objectStack) {
  87374. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87375. 'node.nodeType should be ELEMENT');
  87376. goog.asserts.assert(node.localName == 'Attribution',
  87377. 'localName should be Attribution');
  87378. return ol.xml.pushParseAndPop(
  87379. {}, ol.format.WMSCapabilities.ATTRIBUTION_PARSERS_, node, objectStack);
  87380. };
  87381. /**
  87382. * @private
  87383. * @param {Node} node Node.
  87384. * @param {Array.<*>} objectStack Object stack.
  87385. * @return {Object} Bounding box object.
  87386. */
  87387. ol.format.WMSCapabilities.readBoundingBox_ = function(node, objectStack) {
  87388. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87389. 'node.nodeType should be ELEMENT');
  87390. goog.asserts.assert(node.localName == 'BoundingBox',
  87391. 'localName should be BoundingBox');
  87392. var extent = [
  87393. ol.format.XSD.readDecimalString(node.getAttribute('minx')),
  87394. ol.format.XSD.readDecimalString(node.getAttribute('miny')),
  87395. ol.format.XSD.readDecimalString(node.getAttribute('maxx')),
  87396. ol.format.XSD.readDecimalString(node.getAttribute('maxy'))
  87397. ];
  87398. var resolutions = [
  87399. ol.format.XSD.readDecimalString(node.getAttribute('resx')),
  87400. ol.format.XSD.readDecimalString(node.getAttribute('resy'))
  87401. ];
  87402. return {
  87403. 'crs': node.getAttribute('CRS'),
  87404. 'extent': extent,
  87405. 'res': resolutions
  87406. };
  87407. };
  87408. /**
  87409. * @private
  87410. * @param {Node} node Node.
  87411. * @param {Array.<*>} objectStack Object stack.
  87412. * @return {ol.Extent|undefined} Bounding box object.
  87413. */
  87414. ol.format.WMSCapabilities.readEXGeographicBoundingBox_ =
  87415. function(node, objectStack) {
  87416. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87417. 'node.nodeType should be ELEMENT');
  87418. goog.asserts.assert(node.localName == 'EX_GeographicBoundingBox',
  87419. 'localName should be EX_GeographicBoundingBox');
  87420. var geographicBoundingBox = ol.xml.pushParseAndPop(
  87421. {},
  87422. ol.format.WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_,
  87423. node, objectStack);
  87424. if (!geographicBoundingBox) {
  87425. return undefined;
  87426. }
  87427. var westBoundLongitude = /** @type {number|undefined} */
  87428. (geographicBoundingBox['westBoundLongitude']);
  87429. var southBoundLatitude = /** @type {number|undefined} */
  87430. (geographicBoundingBox['southBoundLatitude']);
  87431. var eastBoundLongitude = /** @type {number|undefined} */
  87432. (geographicBoundingBox['eastBoundLongitude']);
  87433. var northBoundLatitude = /** @type {number|undefined} */
  87434. (geographicBoundingBox['northBoundLatitude']);
  87435. if (westBoundLongitude === undefined || southBoundLatitude === undefined ||
  87436. eastBoundLongitude === undefined || northBoundLatitude === undefined) {
  87437. return undefined;
  87438. }
  87439. return /** @type {ol.Extent} */ ([
  87440. westBoundLongitude, southBoundLatitude,
  87441. eastBoundLongitude, northBoundLatitude
  87442. ]);
  87443. };
  87444. /**
  87445. * @param {Node} node Node.
  87446. * @param {Array.<*>} objectStack Object stack.
  87447. * @private
  87448. * @return {Object|undefined} Capability object.
  87449. */
  87450. ol.format.WMSCapabilities.readCapability_ = function(node, objectStack) {
  87451. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87452. 'node.nodeType should be ELEMENT');
  87453. goog.asserts.assert(node.localName == 'Capability',
  87454. 'localName should be Capability');
  87455. return ol.xml.pushParseAndPop(
  87456. {}, ol.format.WMSCapabilities.CAPABILITY_PARSERS_, node, objectStack);
  87457. };
  87458. /**
  87459. * @param {Node} node Node.
  87460. * @param {Array.<*>} objectStack Object stack.
  87461. * @private
  87462. * @return {Object|undefined} Service object.
  87463. */
  87464. ol.format.WMSCapabilities.readService_ = function(node, objectStack) {
  87465. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87466. 'node.nodeType should be ELEMENT');
  87467. goog.asserts.assert(node.localName == 'Service',
  87468. 'localName should be Service');
  87469. return ol.xml.pushParseAndPop(
  87470. {}, ol.format.WMSCapabilities.SERVICE_PARSERS_, node, objectStack);
  87471. };
  87472. /**
  87473. * @param {Node} node Node.
  87474. * @param {Array.<*>} objectStack Object stack.
  87475. * @private
  87476. * @return {Object|undefined} Contact information object.
  87477. */
  87478. ol.format.WMSCapabilities.readContactInformation_ =
  87479. function(node, objectStack) {
  87480. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87481. 'node.nodeType shpuld be ELEMENT');
  87482. goog.asserts.assert(node.localName == 'ContactInformation',
  87483. 'localName should be ContactInformation');
  87484. return ol.xml.pushParseAndPop(
  87485. {}, ol.format.WMSCapabilities.CONTACT_INFORMATION_PARSERS_,
  87486. node, objectStack);
  87487. };
  87488. /**
  87489. * @param {Node} node Node.
  87490. * @param {Array.<*>} objectStack Object stack.
  87491. * @private
  87492. * @return {Object|undefined} Contact person object.
  87493. */
  87494. ol.format.WMSCapabilities.readContactPersonPrimary_ =
  87495. function(node, objectStack) {
  87496. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87497. 'node.nodeType should be ELEMENT');
  87498. goog.asserts.assert(node.localName == 'ContactPersonPrimary',
  87499. 'localName should be ContactPersonPrimary');
  87500. return ol.xml.pushParseAndPop(
  87501. {}, ol.format.WMSCapabilities.CONTACT_PERSON_PARSERS_,
  87502. node, objectStack);
  87503. };
  87504. /**
  87505. * @param {Node} node Node.
  87506. * @param {Array.<*>} objectStack Object stack.
  87507. * @private
  87508. * @return {Object|undefined} Contact address object.
  87509. */
  87510. ol.format.WMSCapabilities.readContactAddress_ =
  87511. function(node, objectStack) {
  87512. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87513. 'node.nodeType should be ELEMENT');
  87514. goog.asserts.assert(node.localName == 'ContactAddress',
  87515. 'localName should be ContactAddress');
  87516. return ol.xml.pushParseAndPop(
  87517. {}, ol.format.WMSCapabilities.CONTACT_ADDRESS_PARSERS_,
  87518. node, objectStack);
  87519. };
  87520. /**
  87521. * @param {Node} node Node.
  87522. * @param {Array.<*>} objectStack Object stack.
  87523. * @private
  87524. * @return {Array.<string>|undefined} Format array.
  87525. */
  87526. ol.format.WMSCapabilities.readException_ = function(node, objectStack) {
  87527. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87528. 'node.nodeType should be ELEMENT');
  87529. goog.asserts.assert(node.localName == 'Exception',
  87530. 'localName should be Exception');
  87531. return ol.xml.pushParseAndPop(
  87532. [], ol.format.WMSCapabilities.EXCEPTION_PARSERS_, node, objectStack);
  87533. };
  87534. /**
  87535. * @param {Node} node Node.
  87536. * @param {Array.<*>} objectStack Object stack.
  87537. * @private
  87538. * @return {Object|undefined} Layer object.
  87539. */
  87540. ol.format.WMSCapabilities.readCapabilityLayer_ = function(node, objectStack) {
  87541. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87542. 'node.nodeType should be ELEMENT');
  87543. goog.asserts.assert(node.localName == 'Layer', 'localName should be Layer');
  87544. return ol.xml.pushParseAndPop(
  87545. {}, ol.format.WMSCapabilities.LAYER_PARSERS_, node, objectStack);
  87546. };
  87547. /**
  87548. * @private
  87549. * @param {Node} node Node.
  87550. * @param {Array.<*>} objectStack Object stack.
  87551. * @return {Object|undefined} Layer object.
  87552. */
  87553. ol.format.WMSCapabilities.readLayer_ = function(node, objectStack) {
  87554. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87555. 'node.nodeType should be ELEMENT');
  87556. goog.asserts.assert(node.localName == 'Layer', 'localName should be Layer');
  87557. var parentLayerObject = /** @type {Object.<string,*>} */
  87558. (objectStack[objectStack.length - 1]);
  87559. var layerObject = /** @type {Object.<string,*>} */ (ol.xml.pushParseAndPop(
  87560. {}, ol.format.WMSCapabilities.LAYER_PARSERS_, node, objectStack));
  87561. if (!layerObject) {
  87562. return undefined;
  87563. }
  87564. var queryable =
  87565. ol.format.XSD.readBooleanString(node.getAttribute('queryable'));
  87566. if (queryable === undefined) {
  87567. queryable = parentLayerObject['queryable'];
  87568. }
  87569. layerObject['queryable'] = queryable !== undefined ? queryable : false;
  87570. var cascaded = ol.format.XSD.readNonNegativeIntegerString(
  87571. node.getAttribute('cascaded'));
  87572. if (cascaded === undefined) {
  87573. cascaded = parentLayerObject['cascaded'];
  87574. }
  87575. layerObject['cascaded'] = cascaded;
  87576. var opaque = ol.format.XSD.readBooleanString(node.getAttribute('opaque'));
  87577. if (opaque === undefined) {
  87578. opaque = parentLayerObject['opaque'];
  87579. }
  87580. layerObject['opaque'] = opaque !== undefined ? opaque : false;
  87581. var noSubsets =
  87582. ol.format.XSD.readBooleanString(node.getAttribute('noSubsets'));
  87583. if (noSubsets === undefined) {
  87584. noSubsets = parentLayerObject['noSubsets'];
  87585. }
  87586. layerObject['noSubsets'] = noSubsets !== undefined ? noSubsets : false;
  87587. var fixedWidth =
  87588. ol.format.XSD.readDecimalString(node.getAttribute('fixedWidth'));
  87589. if (!fixedWidth) {
  87590. fixedWidth = parentLayerObject['fixedWidth'];
  87591. }
  87592. layerObject['fixedWidth'] = fixedWidth;
  87593. var fixedHeight =
  87594. ol.format.XSD.readDecimalString(node.getAttribute('fixedHeight'));
  87595. if (!fixedHeight) {
  87596. fixedHeight = parentLayerObject['fixedHeight'];
  87597. }
  87598. layerObject['fixedHeight'] = fixedHeight;
  87599. // See 7.2.4.8
  87600. var addKeys = ['Style', 'CRS', 'AuthorityURL'];
  87601. addKeys.forEach(function(key) {
  87602. if (key in parentLayerObject) {
  87603. var childValue = goog.object.setIfUndefined(layerObject, key, []);
  87604. childValue = childValue.concat(parentLayerObject[key]);
  87605. layerObject[key] = childValue;
  87606. }
  87607. });
  87608. var replaceKeys = ['EX_GeographicBoundingBox', 'BoundingBox', 'Dimension',
  87609. 'Attribution', 'MinScaleDenominator', 'MaxScaleDenominator'];
  87610. replaceKeys.forEach(function(key) {
  87611. if (!(key in layerObject)) {
  87612. var parentValue = parentLayerObject[key];
  87613. layerObject[key] = parentValue;
  87614. }
  87615. });
  87616. return layerObject;
  87617. };
  87618. /**
  87619. * @private
  87620. * @param {Node} node Node.
  87621. * @param {Array.<*>} objectStack Object stack.
  87622. * @return {Object} Dimension object.
  87623. */
  87624. ol.format.WMSCapabilities.readDimension_ = function(node, objectStack) {
  87625. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87626. 'node.nodeType should be ELEMENT');
  87627. goog.asserts.assert(node.localName == 'Dimension',
  87628. 'localName should be Dimension');
  87629. var dimensionObject = {
  87630. 'name': node.getAttribute('name'),
  87631. 'units': node.getAttribute('units'),
  87632. 'unitSymbol': node.getAttribute('unitSymbol'),
  87633. 'default': node.getAttribute('default'),
  87634. 'multipleValues': ol.format.XSD.readBooleanString(
  87635. node.getAttribute('multipleValues')),
  87636. 'nearestValue': ol.format.XSD.readBooleanString(
  87637. node.getAttribute('nearestValue')),
  87638. 'current': ol.format.XSD.readBooleanString(node.getAttribute('current')),
  87639. 'values': ol.format.XSD.readString(node)
  87640. };
  87641. return dimensionObject;
  87642. };
  87643. /**
  87644. * @private
  87645. * @param {Node} node Node.
  87646. * @param {Array.<*>} objectStack Object stack.
  87647. * @return {Object|undefined} Online resource object.
  87648. */
  87649. ol.format.WMSCapabilities.readFormatOnlineresource_ =
  87650. function(node, objectStack) {
  87651. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87652. 'node.nodeType should be ELEMENT');
  87653. return ol.xml.pushParseAndPop(
  87654. {}, ol.format.WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_,
  87655. node, objectStack);
  87656. };
  87657. /**
  87658. * @private
  87659. * @param {Node} node Node.
  87660. * @param {Array.<*>} objectStack Object stack.
  87661. * @return {Object|undefined} Request object.
  87662. */
  87663. ol.format.WMSCapabilities.readRequest_ = function(node, objectStack) {
  87664. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87665. 'node.nodeType should be ELEMENT');
  87666. goog.asserts.assert(node.localName == 'Request',
  87667. 'localName should be Request');
  87668. return ol.xml.pushParseAndPop(
  87669. {}, ol.format.WMSCapabilities.REQUEST_PARSERS_, node, objectStack);
  87670. };
  87671. /**
  87672. * @private
  87673. * @param {Node} node Node.
  87674. * @param {Array.<*>} objectStack Object stack.
  87675. * @return {Object|undefined} DCP type object.
  87676. */
  87677. ol.format.WMSCapabilities.readDCPType_ = function(node, objectStack) {
  87678. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87679. 'node.nodeType should be ELEMENT');
  87680. goog.asserts.assert(node.localName == 'DCPType',
  87681. 'localName should be DCPType');
  87682. return ol.xml.pushParseAndPop(
  87683. {}, ol.format.WMSCapabilities.DCPTYPE_PARSERS_, node, objectStack);
  87684. };
  87685. /**
  87686. * @private
  87687. * @param {Node} node Node.
  87688. * @param {Array.<*>} objectStack Object stack.
  87689. * @return {Object|undefined} HTTP object.
  87690. */
  87691. ol.format.WMSCapabilities.readHTTP_ = function(node, objectStack) {
  87692. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87693. 'node.nodeType should be ELEMENT');
  87694. goog.asserts.assert(node.localName == 'HTTP', 'localName should be HTTP');
  87695. return ol.xml.pushParseAndPop(
  87696. {}, ol.format.WMSCapabilities.HTTP_PARSERS_, node, objectStack);
  87697. };
  87698. /**
  87699. * @private
  87700. * @param {Node} node Node.
  87701. * @param {Array.<*>} objectStack Object stack.
  87702. * @return {Object|undefined} Operation type object.
  87703. */
  87704. ol.format.WMSCapabilities.readOperationType_ = function(node, objectStack) {
  87705. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87706. 'node.nodeType should be ELEMENT');
  87707. return ol.xml.pushParseAndPop(
  87708. {}, ol.format.WMSCapabilities.OPERATIONTYPE_PARSERS_, node, objectStack);
  87709. };
  87710. /**
  87711. * @private
  87712. * @param {Node} node Node.
  87713. * @param {Array.<*>} objectStack Object stack.
  87714. * @return {Object|undefined} Online resource object.
  87715. */
  87716. ol.format.WMSCapabilities.readSizedFormatOnlineresource_ =
  87717. function(node, objectStack) {
  87718. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87719. 'node.nodeType should be ELEMENT');
  87720. var formatOnlineresource =
  87721. ol.format.WMSCapabilities.readFormatOnlineresource_(node, objectStack);
  87722. if (formatOnlineresource) {
  87723. var size = [
  87724. ol.format.XSD.readNonNegativeIntegerString(node.getAttribute('width')),
  87725. ol.format.XSD.readNonNegativeIntegerString(node.getAttribute('height'))
  87726. ];
  87727. formatOnlineresource['size'] = size;
  87728. return formatOnlineresource;
  87729. }
  87730. return undefined;
  87731. };
  87732. /**
  87733. * @private
  87734. * @param {Node} node Node.
  87735. * @param {Array.<*>} objectStack Object stack.
  87736. * @return {Object|undefined} Authority URL object.
  87737. */
  87738. ol.format.WMSCapabilities.readAuthorityURL_ = function(node, objectStack) {
  87739. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87740. 'node.nodeType should be ELEMENT');
  87741. goog.asserts.assert(node.localName == 'AuthorityURL',
  87742. 'localName should be AuthorityURL');
  87743. var authorityObject =
  87744. ol.format.WMSCapabilities.readFormatOnlineresource_(node, objectStack);
  87745. if (authorityObject) {
  87746. authorityObject['name'] = node.getAttribute('name');
  87747. return authorityObject;
  87748. }
  87749. return undefined;
  87750. };
  87751. /**
  87752. * @private
  87753. * @param {Node} node Node.
  87754. * @param {Array.<*>} objectStack Object stack.
  87755. * @return {Object|undefined} Metadata URL object.
  87756. */
  87757. ol.format.WMSCapabilities.readMetadataURL_ = function(node, objectStack) {
  87758. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87759. 'node.nodeType should be ELEMENT');
  87760. goog.asserts.assert(node.localName == 'MetadataURL',
  87761. 'localName should be MetadataURL');
  87762. var metadataObject =
  87763. ol.format.WMSCapabilities.readFormatOnlineresource_(node, objectStack);
  87764. if (metadataObject) {
  87765. metadataObject['type'] = node.getAttribute('type');
  87766. return metadataObject;
  87767. }
  87768. return undefined;
  87769. };
  87770. /**
  87771. * @private
  87772. * @param {Node} node Node.
  87773. * @param {Array.<*>} objectStack Object stack.
  87774. * @return {Object|undefined} Style object.
  87775. */
  87776. ol.format.WMSCapabilities.readStyle_ = function(node, objectStack) {
  87777. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87778. 'node.nodeType should be ELEMENT');
  87779. goog.asserts.assert(node.localName == 'Style', 'localName should be Style');
  87780. return ol.xml.pushParseAndPop(
  87781. {}, ol.format.WMSCapabilities.STYLE_PARSERS_, node, objectStack);
  87782. };
  87783. /**
  87784. * @private
  87785. * @param {Node} node Node.
  87786. * @param {Array.<*>} objectStack Object stack.
  87787. * @return {Array.<string>|undefined} Keyword list.
  87788. */
  87789. ol.format.WMSCapabilities.readKeywordList_ = function(node, objectStack) {
  87790. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  87791. 'node.nodeType should be ELEMENT');
  87792. goog.asserts.assert(node.localName == 'KeywordList',
  87793. 'localName should be KeywordList');
  87794. return ol.xml.pushParseAndPop(
  87795. [], ol.format.WMSCapabilities.KEYWORDLIST_PARSERS_, node, objectStack);
  87796. };
  87797. /**
  87798. * @const
  87799. * @private
  87800. * @type {Array.<string>}
  87801. */
  87802. ol.format.WMSCapabilities.NAMESPACE_URIS_ = [
  87803. null,
  87804. 'http://www.opengis.net/wms'
  87805. ];
  87806. /**
  87807. * @const
  87808. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87809. * @private
  87810. */
  87811. ol.format.WMSCapabilities.PARSERS_ = ol.xml.makeStructureNS(
  87812. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87813. 'Service': ol.xml.makeObjectPropertySetter(
  87814. ol.format.WMSCapabilities.readService_),
  87815. 'Capability': ol.xml.makeObjectPropertySetter(
  87816. ol.format.WMSCapabilities.readCapability_)
  87817. });
  87818. /**
  87819. * @const
  87820. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87821. * @private
  87822. */
  87823. ol.format.WMSCapabilities.CAPABILITY_PARSERS_ = ol.xml.makeStructureNS(
  87824. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87825. 'Request': ol.xml.makeObjectPropertySetter(
  87826. ol.format.WMSCapabilities.readRequest_),
  87827. 'Exception': ol.xml.makeObjectPropertySetter(
  87828. ol.format.WMSCapabilities.readException_),
  87829. 'Layer': ol.xml.makeObjectPropertySetter(
  87830. ol.format.WMSCapabilities.readCapabilityLayer_)
  87831. });
  87832. /**
  87833. * @const
  87834. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87835. * @private
  87836. */
  87837. ol.format.WMSCapabilities.SERVICE_PARSERS_ = ol.xml.makeStructureNS(
  87838. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87839. 'Name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87840. 'Title': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87841. 'Abstract': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87842. 'KeywordList': ol.xml.makeObjectPropertySetter(
  87843. ol.format.WMSCapabilities.readKeywordList_),
  87844. 'OnlineResource': ol.xml.makeObjectPropertySetter(
  87845. ol.format.XLink.readHref),
  87846. 'ContactInformation': ol.xml.makeObjectPropertySetter(
  87847. ol.format.WMSCapabilities.readContactInformation_),
  87848. 'Fees': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87849. 'AccessConstraints': ol.xml.makeObjectPropertySetter(
  87850. ol.format.XSD.readString),
  87851. 'LayerLimit': ol.xml.makeObjectPropertySetter(
  87852. ol.format.XSD.readNonNegativeInteger),
  87853. 'MaxWidth': ol.xml.makeObjectPropertySetter(
  87854. ol.format.XSD.readNonNegativeInteger),
  87855. 'MaxHeight': ol.xml.makeObjectPropertySetter(
  87856. ol.format.XSD.readNonNegativeInteger)
  87857. });
  87858. /**
  87859. * @const
  87860. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87861. * @private
  87862. */
  87863. ol.format.WMSCapabilities.CONTACT_INFORMATION_PARSERS_ = ol.xml.makeStructureNS(
  87864. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87865. 'ContactPersonPrimary': ol.xml.makeObjectPropertySetter(
  87866. ol.format.WMSCapabilities.readContactPersonPrimary_),
  87867. 'ContactPosition': ol.xml.makeObjectPropertySetter(
  87868. ol.format.XSD.readString),
  87869. 'ContactAddress': ol.xml.makeObjectPropertySetter(
  87870. ol.format.WMSCapabilities.readContactAddress_),
  87871. 'ContactVoiceTelephone': ol.xml.makeObjectPropertySetter(
  87872. ol.format.XSD.readString),
  87873. 'ContactFacsimileTelephone': ol.xml.makeObjectPropertySetter(
  87874. ol.format.XSD.readString),
  87875. 'ContactElectronicMailAddress': ol.xml.makeObjectPropertySetter(
  87876. ol.format.XSD.readString)
  87877. });
  87878. /**
  87879. * @const
  87880. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87881. * @private
  87882. */
  87883. ol.format.WMSCapabilities.CONTACT_PERSON_PARSERS_ = ol.xml.makeStructureNS(
  87884. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87885. 'ContactPerson': ol.xml.makeObjectPropertySetter(
  87886. ol.format.XSD.readString),
  87887. 'ContactOrganization': ol.xml.makeObjectPropertySetter(
  87888. ol.format.XSD.readString)
  87889. });
  87890. /**
  87891. * @const
  87892. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87893. * @private
  87894. */
  87895. ol.format.WMSCapabilities.CONTACT_ADDRESS_PARSERS_ = ol.xml.makeStructureNS(
  87896. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87897. 'AddressType': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87898. 'Address': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87899. 'City': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87900. 'StateOrProvince': ol.xml.makeObjectPropertySetter(
  87901. ol.format.XSD.readString),
  87902. 'PostCode': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87903. 'Country': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString)
  87904. });
  87905. /**
  87906. * @const
  87907. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87908. * @private
  87909. */
  87910. ol.format.WMSCapabilities.EXCEPTION_PARSERS_ = ol.xml.makeStructureNS(
  87911. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87912. 'Format': ol.xml.makeArrayPusher(ol.format.XSD.readString)
  87913. });
  87914. /**
  87915. * @const
  87916. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87917. * @private
  87918. */
  87919. ol.format.WMSCapabilities.LAYER_PARSERS_ = ol.xml.makeStructureNS(
  87920. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87921. 'Name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87922. 'Title': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87923. 'Abstract': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87924. 'KeywordList': ol.xml.makeObjectPropertySetter(
  87925. ol.format.WMSCapabilities.readKeywordList_),
  87926. 'CRS': ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),
  87927. 'EX_GeographicBoundingBox': ol.xml.makeObjectPropertySetter(
  87928. ol.format.WMSCapabilities.readEXGeographicBoundingBox_),
  87929. 'BoundingBox': ol.xml.makeObjectPropertyPusher(
  87930. ol.format.WMSCapabilities.readBoundingBox_),
  87931. 'Dimension': ol.xml.makeObjectPropertyPusher(
  87932. ol.format.WMSCapabilities.readDimension_),
  87933. 'Attribution': ol.xml.makeObjectPropertySetter(
  87934. ol.format.WMSCapabilities.readAttribution_),
  87935. 'AuthorityURL': ol.xml.makeObjectPropertyPusher(
  87936. ol.format.WMSCapabilities.readAuthorityURL_),
  87937. 'Identifier': ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),
  87938. 'MetadataURL': ol.xml.makeObjectPropertyPusher(
  87939. ol.format.WMSCapabilities.readMetadataURL_),
  87940. 'DataURL': ol.xml.makeObjectPropertyPusher(
  87941. ol.format.WMSCapabilities.readFormatOnlineresource_),
  87942. 'FeatureListURL': ol.xml.makeObjectPropertyPusher(
  87943. ol.format.WMSCapabilities.readFormatOnlineresource_),
  87944. 'Style': ol.xml.makeObjectPropertyPusher(
  87945. ol.format.WMSCapabilities.readStyle_),
  87946. 'MinScaleDenominator': ol.xml.makeObjectPropertySetter(
  87947. ol.format.XSD.readDecimal),
  87948. 'MaxScaleDenominator': ol.xml.makeObjectPropertySetter(
  87949. ol.format.XSD.readDecimal),
  87950. 'Layer': ol.xml.makeObjectPropertyPusher(
  87951. ol.format.WMSCapabilities.readLayer_)
  87952. });
  87953. /**
  87954. * @const
  87955. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87956. * @private
  87957. */
  87958. ol.format.WMSCapabilities.ATTRIBUTION_PARSERS_ = ol.xml.makeStructureNS(
  87959. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87960. 'Title': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  87961. 'OnlineResource': ol.xml.makeObjectPropertySetter(
  87962. ol.format.XLink.readHref),
  87963. 'LogoURL': ol.xml.makeObjectPropertySetter(
  87964. ol.format.WMSCapabilities.readSizedFormatOnlineresource_)
  87965. });
  87966. /**
  87967. * @const
  87968. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87969. * @private
  87970. */
  87971. ol.format.WMSCapabilities.EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS_ =
  87972. ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87973. 'westBoundLongitude': ol.xml.makeObjectPropertySetter(
  87974. ol.format.XSD.readDecimal),
  87975. 'eastBoundLongitude': ol.xml.makeObjectPropertySetter(
  87976. ol.format.XSD.readDecimal),
  87977. 'southBoundLatitude': ol.xml.makeObjectPropertySetter(
  87978. ol.format.XSD.readDecimal),
  87979. 'northBoundLatitude': ol.xml.makeObjectPropertySetter(
  87980. ol.format.XSD.readDecimal)
  87981. });
  87982. /**
  87983. * @const
  87984. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87985. * @private
  87986. */
  87987. ol.format.WMSCapabilities.REQUEST_PARSERS_ = ol.xml.makeStructureNS(
  87988. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  87989. 'GetCapabilities': ol.xml.makeObjectPropertySetter(
  87990. ol.format.WMSCapabilities.readOperationType_),
  87991. 'GetMap': ol.xml.makeObjectPropertySetter(
  87992. ol.format.WMSCapabilities.readOperationType_),
  87993. 'GetFeatureInfo': ol.xml.makeObjectPropertySetter(
  87994. ol.format.WMSCapabilities.readOperationType_)
  87995. });
  87996. /**
  87997. * @const
  87998. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  87999. * @private
  88000. */
  88001. ol.format.WMSCapabilities.OPERATIONTYPE_PARSERS_ = ol.xml.makeStructureNS(
  88002. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88003. 'Format': ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString),
  88004. 'DCPType': ol.xml.makeObjectPropertyPusher(
  88005. ol.format.WMSCapabilities.readDCPType_)
  88006. });
  88007. /**
  88008. * @const
  88009. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88010. * @private
  88011. */
  88012. ol.format.WMSCapabilities.DCPTYPE_PARSERS_ = ol.xml.makeStructureNS(
  88013. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88014. 'HTTP': ol.xml.makeObjectPropertySetter(
  88015. ol.format.WMSCapabilities.readHTTP_)
  88016. });
  88017. /**
  88018. * @const
  88019. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88020. * @private
  88021. */
  88022. ol.format.WMSCapabilities.HTTP_PARSERS_ = ol.xml.makeStructureNS(
  88023. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88024. 'Get': ol.xml.makeObjectPropertySetter(
  88025. ol.format.WMSCapabilities.readFormatOnlineresource_),
  88026. 'Post': ol.xml.makeObjectPropertySetter(
  88027. ol.format.WMSCapabilities.readFormatOnlineresource_)
  88028. });
  88029. /**
  88030. * @const
  88031. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88032. * @private
  88033. */
  88034. ol.format.WMSCapabilities.STYLE_PARSERS_ = ol.xml.makeStructureNS(
  88035. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88036. 'Name': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  88037. 'Title': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  88038. 'Abstract': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  88039. 'LegendURL': ol.xml.makeObjectPropertyPusher(
  88040. ol.format.WMSCapabilities.readSizedFormatOnlineresource_),
  88041. 'StyleSheetURL': ol.xml.makeObjectPropertySetter(
  88042. ol.format.WMSCapabilities.readFormatOnlineresource_),
  88043. 'StyleURL': ol.xml.makeObjectPropertySetter(
  88044. ol.format.WMSCapabilities.readFormatOnlineresource_)
  88045. });
  88046. /**
  88047. * @const
  88048. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88049. * @private
  88050. */
  88051. ol.format.WMSCapabilities.FORMAT_ONLINERESOURCE_PARSERS_ =
  88052. ol.xml.makeStructureNS(ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88053. 'Format': ol.xml.makeObjectPropertySetter(ol.format.XSD.readString),
  88054. 'OnlineResource': ol.xml.makeObjectPropertySetter(
  88055. ol.format.XLink.readHref)
  88056. });
  88057. /**
  88058. * @const
  88059. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88060. * @private
  88061. */
  88062. ol.format.WMSCapabilities.KEYWORDLIST_PARSERS_ = ol.xml.makeStructureNS(
  88063. ol.format.WMSCapabilities.NAMESPACE_URIS_, {
  88064. 'Keyword': ol.xml.makeArrayPusher(ol.format.XSD.readString)
  88065. });
  88066. goog.provide('ol.format.WMSGetFeatureInfo');
  88067. goog.require('goog.array');
  88068. goog.require('goog.asserts');
  88069. goog.require('goog.dom.NodeType');
  88070. goog.require('goog.object');
  88071. goog.require('ol.format.GML2');
  88072. goog.require('ol.format.XMLFeature');
  88073. goog.require('ol.xml');
  88074. /**
  88075. * @classdesc
  88076. * Format for reading WMSGetFeatureInfo format. It uses
  88077. * {@link ol.format.GML2} to read features.
  88078. *
  88079. * @constructor
  88080. * @extends {ol.format.XMLFeature}
  88081. * @api
  88082. */
  88083. ol.format.WMSGetFeatureInfo = function() {
  88084. /**
  88085. * @private
  88086. * @type {string}
  88087. */
  88088. this.featureNS_ = 'http://mapserver.gis.umn.edu/mapserver';
  88089. /**
  88090. * @private
  88091. * @type {ol.format.GML2}
  88092. */
  88093. this.gmlFormat_ = new ol.format.GML2();
  88094. goog.base(this);
  88095. };
  88096. goog.inherits(ol.format.WMSGetFeatureInfo, ol.format.XMLFeature);
  88097. /**
  88098. * @const
  88099. * @type {string}
  88100. * @private
  88101. */
  88102. ol.format.WMSGetFeatureInfo.featureIdentifier_ = '_feature';
  88103. /**
  88104. * @const
  88105. * @type {string}
  88106. * @private
  88107. */
  88108. ol.format.WMSGetFeatureInfo.layerIdentifier_ = '_layer';
  88109. /**
  88110. * @param {Node} node Node.
  88111. * @param {Array.<*>} objectStack Object stack.
  88112. * @return {Array.<ol.Feature>} Features.
  88113. * @private
  88114. */
  88115. ol.format.WMSGetFeatureInfo.prototype.readFeatures_ =
  88116. function(node, objectStack) {
  88117. node.namespaceURI = this.featureNS_;
  88118. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  88119. 'node.nodeType should be ELEMENT');
  88120. var localName = ol.xml.getLocalName(node);
  88121. /** @type {Array.<ol.Feature>} */
  88122. var features = [];
  88123. if (node.childNodes.length === 0) {
  88124. return features;
  88125. }
  88126. if (localName == 'msGMLOutput') {
  88127. for (var i = 0, ii = node.childNodes.length; i < ii; i++) {
  88128. var layer = node.childNodes[i];
  88129. if (layer.nodeType !== goog.dom.NodeType.ELEMENT) {
  88130. continue;
  88131. }
  88132. var context = objectStack[0];
  88133. goog.asserts.assert(goog.isObject(context),
  88134. 'context should be an Object');
  88135. goog.asserts.assert(layer.localName.indexOf(
  88136. ol.format.WMSGetFeatureInfo.layerIdentifier_) >= 0,
  88137. 'localName of layer node should match layerIdentifier');
  88138. var toRemove = ol.format.WMSGetFeatureInfo.layerIdentifier_;
  88139. var featureType = layer.localName.replace(toRemove, '') +
  88140. ol.format.WMSGetFeatureInfo.featureIdentifier_;
  88141. context['featureType'] = featureType;
  88142. context['featureNS'] = this.featureNS_;
  88143. var parsers = {};
  88144. parsers[featureType] = ol.xml.makeArrayPusher(
  88145. this.gmlFormat_.readFeatureElement, this.gmlFormat_);
  88146. var parsersNS = ol.xml.makeStructureNS(
  88147. [context['featureNS'], null], parsers);
  88148. layer.namespaceURI = this.featureNS_;
  88149. var layerFeatures = ol.xml.pushParseAndPop(
  88150. [], parsersNS, layer, objectStack, this.gmlFormat_);
  88151. if (layerFeatures) {
  88152. goog.array.extend(features, layerFeatures);
  88153. }
  88154. }
  88155. }
  88156. if (localName == 'FeatureCollection') {
  88157. var gmlFeatures = ol.xml.pushParseAndPop([],
  88158. this.gmlFormat_.FEATURE_COLLECTION_PARSERS, node,
  88159. [{}], this.gmlFormat_);
  88160. if (gmlFeatures) {
  88161. features = gmlFeatures;
  88162. }
  88163. }
  88164. return features;
  88165. };
  88166. /**
  88167. * Read all features from a WMSGetFeatureInfo response.
  88168. *
  88169. * @function
  88170. * @param {Document|Node|Object|string} source Source.
  88171. * @param {olx.format.ReadOptions=} opt_options Options.
  88172. * @return {Array.<ol.Feature>} Features.
  88173. * @api stable
  88174. */
  88175. ol.format.WMSGetFeatureInfo.prototype.readFeatures;
  88176. /**
  88177. * @inheritDoc
  88178. */
  88179. ol.format.WMSGetFeatureInfo.prototype.readFeaturesFromNode =
  88180. function(node, opt_options) {
  88181. var options = {
  88182. 'featureType': this.featureType,
  88183. 'featureNS': this.featureNS
  88184. };
  88185. if (opt_options) {
  88186. goog.object.extend(options, this.getReadOptions(node, opt_options));
  88187. }
  88188. return this.readFeatures_(node, [options]);
  88189. };
  88190. goog.provide('ol.format.WMTSCapabilities');
  88191. goog.require('goog.asserts');
  88192. goog.require('goog.dom.NodeType');
  88193. goog.require('ol.extent');
  88194. goog.require('ol.format.OWS');
  88195. goog.require('ol.format.XLink');
  88196. goog.require('ol.format.XML');
  88197. goog.require('ol.format.XSD');
  88198. goog.require('ol.xml');
  88199. /**
  88200. * @classdesc
  88201. * Format for reading WMTS capabilities data.
  88202. *
  88203. * @constructor
  88204. * @extends {ol.format.XML}
  88205. * @api
  88206. */
  88207. ol.format.WMTSCapabilities = function() {
  88208. goog.base(this);
  88209. /**
  88210. * @type {ol.format.OWS}
  88211. * @private
  88212. */
  88213. this.owsParser_ = new ol.format.OWS();
  88214. };
  88215. goog.inherits(ol.format.WMTSCapabilities, ol.format.XML);
  88216. /**
  88217. * Read a WMTS capabilities document.
  88218. *
  88219. * @function
  88220. * @param {Document|Node|string} source The XML source.
  88221. * @return {Object} An object representing the WMTS capabilities.
  88222. * @api
  88223. */
  88224. ol.format.WMTSCapabilities.prototype.read;
  88225. /**
  88226. * @param {Document} doc Document.
  88227. * @return {Object} WMTS Capability object.
  88228. */
  88229. ol.format.WMTSCapabilities.prototype.readFromDocument = function(doc) {
  88230. goog.asserts.assert(doc.nodeType == goog.dom.NodeType.DOCUMENT,
  88231. 'doc.nodeType should be DOCUMENT');
  88232. for (var n = doc.firstChild; n; n = n.nextSibling) {
  88233. if (n.nodeType == goog.dom.NodeType.ELEMENT) {
  88234. return this.readFromNode(n);
  88235. }
  88236. }
  88237. return null;
  88238. };
  88239. /**
  88240. * @param {Node} node Node.
  88241. * @return {Object} WMTS Capability object.
  88242. */
  88243. ol.format.WMTSCapabilities.prototype.readFromNode = function(node) {
  88244. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  88245. 'node.nodeType should be ELEMENT');
  88246. goog.asserts.assert(node.localName == 'Capabilities',
  88247. 'localName should be Capabilities');
  88248. this.version = node.getAttribute('version').trim();
  88249. goog.asserts.assertString(this.version, 'this.version should be a string');
  88250. var WMTSCapabilityObject = this.owsParser_.readFromNode(node);
  88251. if (!WMTSCapabilityObject) {
  88252. return null;
  88253. }
  88254. WMTSCapabilityObject['version'] = this.version;
  88255. WMTSCapabilityObject = ol.xml.pushParseAndPop(WMTSCapabilityObject,
  88256. ol.format.WMTSCapabilities.PARSERS_, node, []);
  88257. return WMTSCapabilityObject ? WMTSCapabilityObject : null;
  88258. };
  88259. /**
  88260. * @private
  88261. * @param {Node} node Node.
  88262. * @param {Array.<*>} objectStack Object stack.
  88263. * @return {Object|undefined} Attribution object.
  88264. */
  88265. ol.format.WMTSCapabilities.readContents_ = function(node, objectStack) {
  88266. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  88267. 'node.nodeType should be ELEMENT');
  88268. goog.asserts.assert(node.localName == 'Contents',
  88269. 'localName should be Contents');
  88270. return ol.xml.pushParseAndPop({},
  88271. ol.format.WMTSCapabilities.CONTENTS_PARSERS_, node, objectStack);
  88272. };
  88273. /**
  88274. * @private
  88275. * @param {Node} node Node.
  88276. * @param {Array.<*>} objectStack Object stack.
  88277. * @return {Object|undefined} Layers object.
  88278. */
  88279. ol.format.WMTSCapabilities.readLayer_ = function(node, objectStack) {
  88280. goog.asserts.assert(node.nodeType == goog.dom.NodeType.ELEMENT,
  88281. 'node.nodeType should be ELEMENT');
  88282. goog.asserts.assert(node.localName == 'Layer', 'localName should be Layer');
  88283. return ol.xml.pushParseAndPop({},
  88284. ol.format.WMTSCapabilities.LAYER_PARSERS_, node, objectStack);
  88285. };
  88286. /**
  88287. * @private
  88288. * @param {Node} node Node.
  88289. * @param {Array.<*>} objectStack Object stack.
  88290. * @return {Object|undefined} Tile Matrix Set object.
  88291. */
  88292. ol.format.WMTSCapabilities.readTileMatrixSet_ = function(node, objectStack) {
  88293. return ol.xml.pushParseAndPop({},
  88294. ol.format.WMTSCapabilities.TMS_PARSERS_, node, objectStack);
  88295. };
  88296. /**
  88297. * @private
  88298. * @param {Node} node Node.
  88299. * @param {Array.<*>} objectStack Object stack.
  88300. * @return {Object|undefined} Style object.
  88301. */
  88302. ol.format.WMTSCapabilities.readStyle_ = function(node, objectStack) {
  88303. var style = ol.xml.pushParseAndPop({},
  88304. ol.format.WMTSCapabilities.STYLE_PARSERS_, node, objectStack);
  88305. if (!style) {
  88306. return undefined;
  88307. }
  88308. var isDefault = node.getAttribute('isDefault') === 'true';
  88309. style['isDefault'] = isDefault;
  88310. return style;
  88311. };
  88312. /**
  88313. * @private
  88314. * @param {Node} node Node.
  88315. * @param {Array.<*>} objectStack Object stack.
  88316. * @return {Object|undefined} Tile Matrix Set Link object.
  88317. */
  88318. ol.format.WMTSCapabilities.readTileMatrixSetLink_ = function(node,
  88319. objectStack) {
  88320. return ol.xml.pushParseAndPop({},
  88321. ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_, node, objectStack);
  88322. };
  88323. /**
  88324. * @private
  88325. * @param {Node} node Node.
  88326. * @param {Array.<*>} objectStack Object stack.
  88327. * @return {Object|undefined} Resource URL object.
  88328. */
  88329. ol.format.WMTSCapabilities.readResourceUrl_ = function(node, objectStack) {
  88330. var format = node.getAttribute('format');
  88331. var template = node.getAttribute('template');
  88332. var resourceType = node.getAttribute('resourceType');
  88333. var resource = {};
  88334. if (format) {
  88335. resource['format'] = format;
  88336. }
  88337. if (template) {
  88338. resource['template'] = template;
  88339. }
  88340. if (resourceType) {
  88341. resource['resourceType'] = resourceType;
  88342. }
  88343. return resource;
  88344. };
  88345. /**
  88346. * @private
  88347. * @param {Node} node Node.
  88348. * @param {Array.<*>} objectStack Object stack.
  88349. * @return {Object|undefined} WGS84 BBox object.
  88350. */
  88351. ol.format.WMTSCapabilities.readWgs84BoundingBox_ = function(node, objectStack) {
  88352. var coordinates = ol.xml.pushParseAndPop([],
  88353. ol.format.WMTSCapabilities.WGS84_BBOX_READERS_, node, objectStack);
  88354. if (coordinates.length != 2) {
  88355. return undefined;
  88356. }
  88357. return ol.extent.boundingExtent(coordinates);
  88358. };
  88359. /**
  88360. * @private
  88361. * @param {Node} node Node.
  88362. * @param {Array.<*>} objectStack Object stack.
  88363. * @return {Object|undefined} Legend object.
  88364. */
  88365. ol.format.WMTSCapabilities.readLegendUrl_ = function(node, objectStack) {
  88366. var legend = {};
  88367. legend['format'] = node.getAttribute('format');
  88368. legend['href'] = ol.format.XLink.readHref(node);
  88369. return legend;
  88370. };
  88371. /**
  88372. * @private
  88373. * @param {Node} node Node.
  88374. * @param {Array.<*>} objectStack Object stack.
  88375. * @return {Object|undefined} Coordinates object.
  88376. */
  88377. ol.format.WMTSCapabilities.readCoordinates_ = function(node, objectStack) {
  88378. var coordinates = ol.format.XSD.readString(node).split(' ');
  88379. if (!coordinates || coordinates.length != 2) {
  88380. return undefined;
  88381. }
  88382. var x = +coordinates[0];
  88383. var y = +coordinates[1];
  88384. if (isNaN(x) || isNaN(y)) {
  88385. return undefined;
  88386. }
  88387. return [x, y];
  88388. };
  88389. /**
  88390. * @private
  88391. * @param {Node} node Node.
  88392. * @param {Array.<*>} objectStack Object stack.
  88393. * @return {Object|undefined} TileMatrix object.
  88394. */
  88395. ol.format.WMTSCapabilities.readTileMatrix_ = function(node, objectStack) {
  88396. return ol.xml.pushParseAndPop({},
  88397. ol.format.WMTSCapabilities.TM_PARSERS_, node, objectStack);
  88398. };
  88399. /**
  88400. * @const
  88401. * @private
  88402. * @type {Array.<string>}
  88403. */
  88404. ol.format.WMTSCapabilities.NAMESPACE_URIS_ = [
  88405. null,
  88406. 'http://www.opengis.net/wmts/1.0'
  88407. ];
  88408. /**
  88409. * @const
  88410. * @private
  88411. * @type {Array.<string>}
  88412. */
  88413. ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_ = [
  88414. null,
  88415. 'http://www.opengis.net/ows/1.1'
  88416. ];
  88417. /**
  88418. * @const
  88419. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88420. * @private
  88421. */
  88422. ol.format.WMTSCapabilities.PARSERS_ = ol.xml.makeStructureNS(
  88423. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88424. 'Contents': ol.xml.makeObjectPropertySetter(
  88425. ol.format.WMTSCapabilities.readContents_)
  88426. });
  88427. /**
  88428. * @const
  88429. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88430. * @private
  88431. */
  88432. ol.format.WMTSCapabilities.CONTENTS_PARSERS_ = ol.xml.makeStructureNS(
  88433. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88434. 'Layer': ol.xml.makeObjectPropertyPusher(
  88435. ol.format.WMTSCapabilities.readLayer_),
  88436. 'TileMatrixSet': ol.xml.makeObjectPropertyPusher(
  88437. ol.format.WMTSCapabilities.readTileMatrixSet_)
  88438. });
  88439. /**
  88440. * @const
  88441. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88442. * @private
  88443. */
  88444. ol.format.WMTSCapabilities.LAYER_PARSERS_ = ol.xml.makeStructureNS(
  88445. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88446. 'Style': ol.xml.makeObjectPropertyPusher(
  88447. ol.format.WMTSCapabilities.readStyle_),
  88448. 'Format': ol.xml.makeObjectPropertyPusher(
  88449. ol.format.XSD.readString),
  88450. 'TileMatrixSetLink': ol.xml.makeObjectPropertyPusher(
  88451. ol.format.WMTSCapabilities.readTileMatrixSetLink_),
  88452. 'ResourceURL': ol.xml.makeObjectPropertyPusher(
  88453. ol.format.WMTSCapabilities.readResourceUrl_)
  88454. }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
  88455. 'Title': ol.xml.makeObjectPropertySetter(
  88456. ol.format.XSD.readString),
  88457. 'Abstract': ol.xml.makeObjectPropertySetter(
  88458. ol.format.XSD.readString),
  88459. 'WGS84BoundingBox': ol.xml.makeObjectPropertySetter(
  88460. ol.format.WMTSCapabilities.readWgs84BoundingBox_),
  88461. 'Identifier': ol.xml.makeObjectPropertySetter(
  88462. ol.format.XSD.readString)
  88463. }));
  88464. /**
  88465. * @const
  88466. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88467. * @private
  88468. */
  88469. ol.format.WMTSCapabilities.STYLE_PARSERS_ = ol.xml.makeStructureNS(
  88470. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88471. 'LegendURL': ol.xml.makeObjectPropertyPusher(
  88472. ol.format.WMTSCapabilities.readLegendUrl_)
  88473. }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
  88474. 'Title': ol.xml.makeObjectPropertySetter(
  88475. ol.format.XSD.readString),
  88476. 'Identifier': ol.xml.makeObjectPropertySetter(
  88477. ol.format.XSD.readString)
  88478. }));
  88479. /**
  88480. * @const
  88481. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88482. * @private
  88483. */
  88484. ol.format.WMTSCapabilities.TMS_LINKS_PARSERS_ = ol.xml.makeStructureNS(
  88485. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88486. 'TileMatrixSet': ol.xml.makeObjectPropertySetter(
  88487. ol.format.XSD.readString)
  88488. });
  88489. /**
  88490. * @const
  88491. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88492. * @private
  88493. */
  88494. ol.format.WMTSCapabilities.WGS84_BBOX_READERS_ = ol.xml.makeStructureNS(
  88495. ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
  88496. 'LowerCorner': ol.xml.makeArrayPusher(
  88497. ol.format.WMTSCapabilities.readCoordinates_),
  88498. 'UpperCorner': ol.xml.makeArrayPusher(
  88499. ol.format.WMTSCapabilities.readCoordinates_)
  88500. });
  88501. /**
  88502. * @const
  88503. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88504. * @private
  88505. */
  88506. ol.format.WMTSCapabilities.TMS_PARSERS_ = ol.xml.makeStructureNS(
  88507. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88508. 'WellKnownScaleSet': ol.xml.makeObjectPropertySetter(
  88509. ol.format.XSD.readString),
  88510. 'TileMatrix': ol.xml.makeObjectPropertyPusher(
  88511. ol.format.WMTSCapabilities.readTileMatrix_)
  88512. }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
  88513. 'SupportedCRS': ol.xml.makeObjectPropertySetter(
  88514. ol.format.XSD.readString),
  88515. 'Identifier': ol.xml.makeObjectPropertySetter(
  88516. ol.format.XSD.readString)
  88517. }));
  88518. /**
  88519. * @const
  88520. * @type {Object.<string, Object.<string, ol.xml.Parser>>}
  88521. * @private
  88522. */
  88523. ol.format.WMTSCapabilities.TM_PARSERS_ = ol.xml.makeStructureNS(
  88524. ol.format.WMTSCapabilities.NAMESPACE_URIS_, {
  88525. 'TopLeftCorner': ol.xml.makeObjectPropertySetter(
  88526. ol.format.WMTSCapabilities.readCoordinates_),
  88527. 'ScaleDenominator': ol.xml.makeObjectPropertySetter(
  88528. ol.format.XSD.readDecimal),
  88529. 'TileWidth': ol.xml.makeObjectPropertySetter(
  88530. ol.format.XSD.readNonNegativeInteger),
  88531. 'TileHeight': ol.xml.makeObjectPropertySetter(
  88532. ol.format.XSD.readNonNegativeInteger),
  88533. 'MatrixWidth': ol.xml.makeObjectPropertySetter(
  88534. ol.format.XSD.readNonNegativeInteger),
  88535. 'MatrixHeight': ol.xml.makeObjectPropertySetter(
  88536. ol.format.XSD.readNonNegativeInteger)
  88537. }, ol.xml.makeStructureNS(ol.format.WMTSCapabilities.OWS_NAMESPACE_URIS_, {
  88538. 'Identifier': ol.xml.makeObjectPropertySetter(
  88539. ol.format.XSD.readString)
  88540. }));
  88541. goog.provide('ol.sphere.WGS84');
  88542. goog.require('ol.Sphere');
  88543. /**
  88544. * A sphere with radius equal to the semi-major axis of the WGS84 ellipsoid.
  88545. * @const
  88546. * @type {ol.Sphere}
  88547. */
  88548. ol.sphere.WGS84 = new ol.Sphere(6378137);
  88549. // FIXME handle geolocation not supported
  88550. goog.provide('ol.Geolocation');
  88551. goog.provide('ol.GeolocationProperty');
  88552. goog.require('goog.events');
  88553. goog.require('goog.events.EventType');
  88554. goog.require('goog.math');
  88555. goog.require('ol.Coordinate');
  88556. goog.require('ol.Object');
  88557. goog.require('ol.geom.Geometry');
  88558. goog.require('ol.geom.Polygon');
  88559. goog.require('ol.has');
  88560. goog.require('ol.proj');
  88561. goog.require('ol.sphere.WGS84');
  88562. /**
  88563. * @enum {string}
  88564. */
  88565. ol.GeolocationProperty = {
  88566. ACCURACY: 'accuracy',
  88567. ACCURACY_GEOMETRY: 'accuracyGeometry',
  88568. ALTITUDE: 'altitude',
  88569. ALTITUDE_ACCURACY: 'altitudeAccuracy',
  88570. HEADING: 'heading',
  88571. POSITION: 'position',
  88572. PROJECTION: 'projection',
  88573. SPEED: 'speed',
  88574. TRACKING: 'tracking',
  88575. TRACKING_OPTIONS: 'trackingOptions'
  88576. };
  88577. /**
  88578. * @classdesc
  88579. * Helper class for providing HTML5 Geolocation capabilities.
  88580. * The [Geolocation API](http://www.w3.org/TR/geolocation-API/)
  88581. * is used to locate a user's position.
  88582. *
  88583. * To get notified of position changes, register a listener for the generic
  88584. * `change` event on your instance of `ol.Geolocation`.
  88585. *
  88586. * Example:
  88587. *
  88588. * var geolocation = new ol.Geolocation({
  88589. * // take the projection to use from the map's view
  88590. * projection: view.getProjection()
  88591. * });
  88592. * // listen to changes in position
  88593. * geolocation.on('change', function(evt) {
  88594. * window.console.log(geolocation.getPosition());
  88595. * });
  88596. *
  88597. * @constructor
  88598. * @extends {ol.Object}
  88599. * @param {olx.GeolocationOptions=} opt_options Options.
  88600. * @api stable
  88601. */
  88602. ol.Geolocation = function(opt_options) {
  88603. goog.base(this);
  88604. var options = opt_options || {};
  88605. /**
  88606. * The unprojected (EPSG:4326) device position.
  88607. * @private
  88608. * @type {ol.Coordinate}
  88609. */
  88610. this.position_ = null;
  88611. /**
  88612. * @private
  88613. * @type {ol.TransformFunction}
  88614. */
  88615. this.transform_ = ol.proj.identityTransform;
  88616. /**
  88617. * @private
  88618. * @type {number|undefined}
  88619. */
  88620. this.watchId_ = undefined;
  88621. goog.events.listen(
  88622. this, ol.Object.getChangeEventType(ol.GeolocationProperty.PROJECTION),
  88623. this.handleProjectionChanged_, false, this);
  88624. goog.events.listen(
  88625. this, ol.Object.getChangeEventType(ol.GeolocationProperty.TRACKING),
  88626. this.handleTrackingChanged_, false, this);
  88627. if (options.projection !== undefined) {
  88628. this.setProjection(ol.proj.get(options.projection));
  88629. }
  88630. if (options.trackingOptions !== undefined) {
  88631. this.setTrackingOptions(options.trackingOptions);
  88632. }
  88633. this.setTracking(options.tracking !== undefined ? options.tracking : false);
  88634. };
  88635. goog.inherits(ol.Geolocation, ol.Object);
  88636. /**
  88637. * @inheritDoc
  88638. */
  88639. ol.Geolocation.prototype.disposeInternal = function() {
  88640. this.setTracking(false);
  88641. goog.base(this, 'disposeInternal');
  88642. };
  88643. /**
  88644. * @private
  88645. */
  88646. ol.Geolocation.prototype.handleProjectionChanged_ = function() {
  88647. var projection = this.getProjection();
  88648. if (projection) {
  88649. this.transform_ = ol.proj.getTransformFromProjections(
  88650. ol.proj.get('EPSG:4326'), projection);
  88651. if (this.position_) {
  88652. this.set(
  88653. ol.GeolocationProperty.POSITION, this.transform_(this.position_));
  88654. }
  88655. }
  88656. };
  88657. /**
  88658. * @private
  88659. */
  88660. ol.Geolocation.prototype.handleTrackingChanged_ = function() {
  88661. if (ol.has.GEOLOCATION) {
  88662. var tracking = this.getTracking();
  88663. if (tracking && this.watchId_ === undefined) {
  88664. this.watchId_ = goog.global.navigator.geolocation.watchPosition(
  88665. goog.bind(this.positionChange_, this),
  88666. goog.bind(this.positionError_, this),
  88667. this.getTrackingOptions());
  88668. } else if (!tracking && this.watchId_ !== undefined) {
  88669. goog.global.navigator.geolocation.clearWatch(this.watchId_);
  88670. this.watchId_ = undefined;
  88671. }
  88672. }
  88673. };
  88674. /**
  88675. * @private
  88676. * @param {GeolocationPosition} position position event.
  88677. */
  88678. ol.Geolocation.prototype.positionChange_ = function(position) {
  88679. var coords = position.coords;
  88680. this.set(ol.GeolocationProperty.ACCURACY, coords.accuracy);
  88681. this.set(ol.GeolocationProperty.ALTITUDE,
  88682. coords.altitude === null ? undefined : coords.altitude);
  88683. this.set(ol.GeolocationProperty.ALTITUDE_ACCURACY,
  88684. coords.altitudeAccuracy === null ?
  88685. undefined : coords.altitudeAccuracy);
  88686. this.set(ol.GeolocationProperty.HEADING, coords.heading === null ?
  88687. undefined : goog.math.toRadians(coords.heading));
  88688. if (!this.position_) {
  88689. this.position_ = [coords.longitude, coords.latitude];
  88690. } else {
  88691. this.position_[0] = coords.longitude;
  88692. this.position_[1] = coords.latitude;
  88693. }
  88694. var projectedPosition = this.transform_(this.position_);
  88695. this.set(ol.GeolocationProperty.POSITION, projectedPosition);
  88696. this.set(ol.GeolocationProperty.SPEED,
  88697. coords.speed === null ? undefined : coords.speed);
  88698. var geometry = ol.geom.Polygon.circular(
  88699. ol.sphere.WGS84, this.position_, coords.accuracy);
  88700. geometry.applyTransform(this.transform_);
  88701. this.set(ol.GeolocationProperty.ACCURACY_GEOMETRY, geometry);
  88702. this.changed();
  88703. };
  88704. /**
  88705. * @private
  88706. * @param {GeolocationPositionError} error error object.
  88707. */
  88708. ol.Geolocation.prototype.positionError_ = function(error) {
  88709. error.type = goog.events.EventType.ERROR;
  88710. this.setTracking(false);
  88711. this.dispatchEvent(error);
  88712. };
  88713. /**
  88714. * Get the accuracy of the position in meters.
  88715. * @return {number|undefined} The accuracy of the position measurement in
  88716. * meters.
  88717. * @observable
  88718. * @api stable
  88719. */
  88720. ol.Geolocation.prototype.getAccuracy = function() {
  88721. return /** @type {number|undefined} */ (
  88722. this.get(ol.GeolocationProperty.ACCURACY));
  88723. };
  88724. /**
  88725. * Get a geometry of the position accuracy.
  88726. * @return {?ol.geom.Geometry} A geometry of the position accuracy.
  88727. * @observable
  88728. * @api stable
  88729. */
  88730. ol.Geolocation.prototype.getAccuracyGeometry = function() {
  88731. return /** @type {?ol.geom.Geometry} */ (
  88732. this.get(ol.GeolocationProperty.ACCURACY_GEOMETRY) || null);
  88733. };
  88734. /**
  88735. * Get the altitude associated with the position.
  88736. * @return {number|undefined} The altitude of the position in meters above mean
  88737. * sea level.
  88738. * @observable
  88739. * @api stable
  88740. */
  88741. ol.Geolocation.prototype.getAltitude = function() {
  88742. return /** @type {number|undefined} */ (
  88743. this.get(ol.GeolocationProperty.ALTITUDE));
  88744. };
  88745. /**
  88746. * Get the altitude accuracy of the position.
  88747. * @return {number|undefined} The accuracy of the altitude measurement in
  88748. * meters.
  88749. * @observable
  88750. * @api stable
  88751. */
  88752. ol.Geolocation.prototype.getAltitudeAccuracy = function() {
  88753. return /** @type {number|undefined} */ (
  88754. this.get(ol.GeolocationProperty.ALTITUDE_ACCURACY));
  88755. };
  88756. /**
  88757. * Get the heading as radians clockwise from North.
  88758. * @return {number|undefined} The heading of the device in radians from north.
  88759. * @observable
  88760. * @api stable
  88761. */
  88762. ol.Geolocation.prototype.getHeading = function() {
  88763. return /** @type {number|undefined} */ (
  88764. this.get(ol.GeolocationProperty.HEADING));
  88765. };
  88766. /**
  88767. * Get the position of the device.
  88768. * @return {ol.Coordinate|undefined} The current position of the device reported
  88769. * in the current projection.
  88770. * @observable
  88771. * @api stable
  88772. */
  88773. ol.Geolocation.prototype.getPosition = function() {
  88774. return /** @type {ol.Coordinate|undefined} */ (
  88775. this.get(ol.GeolocationProperty.POSITION));
  88776. };
  88777. /**
  88778. * Get the projection associated with the position.
  88779. * @return {ol.proj.Projection|undefined} The projection the position is
  88780. * reported in.
  88781. * @observable
  88782. * @api stable
  88783. */
  88784. ol.Geolocation.prototype.getProjection = function() {
  88785. return /** @type {ol.proj.Projection|undefined} */ (
  88786. this.get(ol.GeolocationProperty.PROJECTION));
  88787. };
  88788. /**
  88789. * Get the speed in meters per second.
  88790. * @return {number|undefined} The instantaneous speed of the device in meters
  88791. * per second.
  88792. * @observable
  88793. * @api stable
  88794. */
  88795. ol.Geolocation.prototype.getSpeed = function() {
  88796. return /** @type {number|undefined} */ (
  88797. this.get(ol.GeolocationProperty.SPEED));
  88798. };
  88799. /**
  88800. * Determine if the device location is being tracked.
  88801. * @return {boolean} The device location is being tracked.
  88802. * @observable
  88803. * @api stable
  88804. */
  88805. ol.Geolocation.prototype.getTracking = function() {
  88806. return /** @type {boolean} */ (
  88807. this.get(ol.GeolocationProperty.TRACKING));
  88808. };
  88809. /**
  88810. * Get the tracking options.
  88811. * @see http://www.w3.org/TR/geolocation-API/#position-options
  88812. * @return {GeolocationPositionOptions|undefined} PositionOptions as defined by
  88813. * the [HTML5 Geolocation spec
  88814. * ](http://www.w3.org/TR/geolocation-API/#position_options_interface).
  88815. * @observable
  88816. * @api stable
  88817. */
  88818. ol.Geolocation.prototype.getTrackingOptions = function() {
  88819. return /** @type {GeolocationPositionOptions|undefined} */ (
  88820. this.get(ol.GeolocationProperty.TRACKING_OPTIONS));
  88821. };
  88822. /**
  88823. * Set the projection to use for transforming the coordinates.
  88824. * @param {ol.proj.Projection} projection The projection the position is
  88825. * reported in.
  88826. * @observable
  88827. * @api stable
  88828. */
  88829. ol.Geolocation.prototype.setProjection = function(projection) {
  88830. this.set(ol.GeolocationProperty.PROJECTION, projection);
  88831. };
  88832. /**
  88833. * Enable or disable tracking.
  88834. * @param {boolean} tracking Enable tracking.
  88835. * @observable
  88836. * @api stable
  88837. */
  88838. ol.Geolocation.prototype.setTracking = function(tracking) {
  88839. this.set(ol.GeolocationProperty.TRACKING, tracking);
  88840. };
  88841. /**
  88842. * Set the tracking options.
  88843. * @see http://www.w3.org/TR/geolocation-API/#position-options
  88844. * @param {GeolocationPositionOptions} options PositionOptions as defined by the
  88845. * [HTML5 Geolocation spec
  88846. * ](http://www.w3.org/TR/geolocation-API/#position_options_interface).
  88847. * @observable
  88848. * @api stable
  88849. */
  88850. ol.Geolocation.prototype.setTrackingOptions = function(options) {
  88851. this.set(ol.GeolocationProperty.TRACKING_OPTIONS, options);
  88852. };
  88853. goog.provide('ol.geom.flat.geodesic');
  88854. goog.require('goog.asserts');
  88855. goog.require('goog.math');
  88856. goog.require('goog.object');
  88857. goog.require('ol.TransformFunction');
  88858. goog.require('ol.math');
  88859. goog.require('ol.proj');
  88860. /**
  88861. * @private
  88862. * @param {function(number): ol.Coordinate} interpolate Interpolate function.
  88863. * @param {ol.TransformFunction} transform Transform from longitude/latitude to
  88864. * projected coordinates.
  88865. * @param {number} squaredTolerance Squared tolerance.
  88866. * @return {Array.<number>} Flat coordinates.
  88867. */
  88868. ol.geom.flat.geodesic.line_ =
  88869. function(interpolate, transform, squaredTolerance) {
  88870. // FIXME reduce garbage generation
  88871. // FIXME optimize stack operations
  88872. /** @type {Array.<number>} */
  88873. var flatCoordinates = [];
  88874. var geoA = interpolate(0);
  88875. var geoB = interpolate(1);
  88876. var a = transform(geoA);
  88877. var b = transform(geoB);
  88878. /** @type {Array.<ol.Coordinate>} */
  88879. var geoStack = [geoB, geoA];
  88880. /** @type {Array.<ol.Coordinate>} */
  88881. var stack = [b, a];
  88882. /** @type {Array.<number>} */
  88883. var fractionStack = [1, 0];
  88884. /** @type {Object.<string, boolean>} */
  88885. var fractions = {};
  88886. var maxIterations = 1e5;
  88887. var geoM, m, fracA, fracB, fracM, key;
  88888. while (--maxIterations > 0 && fractionStack.length > 0) {
  88889. // Pop the a coordinate off the stack
  88890. fracA = fractionStack.pop();
  88891. geoA = geoStack.pop();
  88892. a = stack.pop();
  88893. // Add the a coordinate if it has not been added yet
  88894. key = fracA.toString();
  88895. if (!goog.object.containsKey(fractions, key)) {
  88896. flatCoordinates.push(a[0], a[1]);
  88897. fractions[key] = true;
  88898. }
  88899. // Pop the b coordinate off the stack
  88900. fracB = fractionStack.pop();
  88901. geoB = geoStack.pop();
  88902. b = stack.pop();
  88903. // Find the m point between the a and b coordinates
  88904. fracM = (fracA + fracB) / 2;
  88905. geoM = interpolate(fracM);
  88906. m = transform(geoM);
  88907. if (ol.math.squaredSegmentDistance(m[0], m[1], a[0], a[1],
  88908. b[0], b[1]) < squaredTolerance) {
  88909. // If the m point is sufficiently close to the straight line, then we
  88910. // discard it. Just use the b coordinate and move on to the next line
  88911. // segment.
  88912. flatCoordinates.push(b[0], b[1]);
  88913. key = fracB.toString();
  88914. goog.asserts.assert(!goog.object.containsKey(fractions, key),
  88915. 'fractions object should contain key : ' + key);
  88916. fractions[key] = true;
  88917. } else {
  88918. // Otherwise, we need to subdivide the current line segment. Split it
  88919. // into two and push the two line segments onto the stack.
  88920. fractionStack.push(fracB, fracM, fracM, fracA);
  88921. stack.push(b, m, m, a);
  88922. geoStack.push(geoB, geoM, geoM, geoA);
  88923. }
  88924. }
  88925. goog.asserts.assert(maxIterations > 0,
  88926. 'maxIterations should be more than 0');
  88927. return flatCoordinates;
  88928. };
  88929. /**
  88930. * Generate a great-circle arcs between two lat/lon points.
  88931. * @param {number} lon1 Longitude 1 in degrees.
  88932. * @param {number} lat1 Latitude 1 in degrees.
  88933. * @param {number} lon2 Longitude 2 in degrees.
  88934. * @param {number} lat2 Latitude 2 in degrees.
  88935. * @param {ol.proj.Projection} projection Projection.
  88936. * @param {number} squaredTolerance Squared tolerance.
  88937. * @return {Array.<number>} Flat coordinates.
  88938. */
  88939. ol.geom.flat.geodesic.greatCircleArc = function(
  88940. lon1, lat1, lon2, lat2, projection, squaredTolerance) {
  88941. var geoProjection = ol.proj.get('EPSG:4326');
  88942. var cosLat1 = Math.cos(goog.math.toRadians(lat1));
  88943. var sinLat1 = Math.sin(goog.math.toRadians(lat1));
  88944. var cosLat2 = Math.cos(goog.math.toRadians(lat2));
  88945. var sinLat2 = Math.sin(goog.math.toRadians(lat2));
  88946. var cosDeltaLon = Math.cos(goog.math.toRadians(lon2 - lon1));
  88947. var sinDeltaLon = Math.sin(goog.math.toRadians(lon2 - lon1));
  88948. var d = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDeltaLon;
  88949. return ol.geom.flat.geodesic.line_(
  88950. /**
  88951. * @param {number} frac Fraction.
  88952. * @return {ol.Coordinate} Coordinate.
  88953. */
  88954. function(frac) {
  88955. if (1 <= d) {
  88956. return [lon2, lat2];
  88957. }
  88958. var D = frac * Math.acos(d);
  88959. var cosD = Math.cos(D);
  88960. var sinD = Math.sin(D);
  88961. var y = sinDeltaLon * cosLat2;
  88962. var x = cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDeltaLon;
  88963. var theta = Math.atan2(y, x);
  88964. var lat = Math.asin(sinLat1 * cosD + cosLat1 * sinD * Math.cos(theta));
  88965. var lon = goog.math.toRadians(lon1) +
  88966. Math.atan2(Math.sin(theta) * sinD * cosLat1,
  88967. cosD - sinLat1 * Math.sin(lat));
  88968. return [goog.math.toDegrees(lon), goog.math.toDegrees(lat)];
  88969. }, ol.proj.getTransform(geoProjection, projection), squaredTolerance);
  88970. };
  88971. /**
  88972. * Generate a meridian (line at constant longitude).
  88973. * @param {number} lon Longitude.
  88974. * @param {number} lat1 Latitude 1.
  88975. * @param {number} lat2 Latitude 2.
  88976. * @param {ol.proj.Projection} projection Projection.
  88977. * @param {number} squaredTolerance Squared tolerance.
  88978. * @return {Array.<number>} Flat coordinates.
  88979. */
  88980. ol.geom.flat.geodesic.meridian =
  88981. function(lon, lat1, lat2, projection, squaredTolerance) {
  88982. var epsg4326Projection = ol.proj.get('EPSG:4326');
  88983. return ol.geom.flat.geodesic.line_(
  88984. /**
  88985. * @param {number} frac Fraction.
  88986. * @return {ol.Coordinate} Coordinate.
  88987. */
  88988. function(frac) {
  88989. return [lon, lat1 + ((lat2 - lat1) * frac)];
  88990. },
  88991. ol.proj.getTransform(epsg4326Projection, projection), squaredTolerance);
  88992. };
  88993. /**
  88994. * Generate a parallel (line at constant latitude).
  88995. * @param {number} lat Latitude.
  88996. * @param {number} lon1 Longitude 1.
  88997. * @param {number} lon2 Longitude 2.
  88998. * @param {ol.proj.Projection} projection Projection.
  88999. * @param {number} squaredTolerance Squared tolerance.
  89000. * @return {Array.<number>} Flat coordinates.
  89001. */
  89002. ol.geom.flat.geodesic.parallel =
  89003. function(lat, lon1, lon2, projection, squaredTolerance) {
  89004. var epsg4326Projection = ol.proj.get('EPSG:4326');
  89005. return ol.geom.flat.geodesic.line_(
  89006. /**
  89007. * @param {number} frac Fraction.
  89008. * @return {ol.Coordinate} Coordinate.
  89009. */
  89010. function(frac) {
  89011. return [lon1 + ((lon2 - lon1) * frac), lat];
  89012. },
  89013. ol.proj.getTransform(epsg4326Projection, projection), squaredTolerance);
  89014. };
  89015. goog.provide('ol.Graticule');
  89016. goog.require('goog.asserts');
  89017. goog.require('ol.extent');
  89018. goog.require('ol.geom.GeometryLayout');
  89019. goog.require('ol.geom.LineString');
  89020. goog.require('ol.geom.flat.geodesic');
  89021. goog.require('ol.math');
  89022. goog.require('ol.proj');
  89023. goog.require('ol.render.EventType');
  89024. goog.require('ol.style.Stroke');
  89025. /**
  89026. * Render a grid for a coordinate system on a map.
  89027. * @constructor
  89028. * @param {olx.GraticuleOptions=} opt_options Options.
  89029. * @api
  89030. */
  89031. ol.Graticule = function(opt_options) {
  89032. var options = opt_options || {};
  89033. /**
  89034. * @type {ol.Map}
  89035. * @private
  89036. */
  89037. this.map_ = null;
  89038. /**
  89039. * @type {ol.proj.Projection}
  89040. * @private
  89041. */
  89042. this.projection_ = null;
  89043. /**
  89044. * @type {number}
  89045. * @private
  89046. */
  89047. this.maxLat_ = Infinity;
  89048. /**
  89049. * @type {number}
  89050. * @private
  89051. */
  89052. this.maxLon_ = Infinity;
  89053. /**
  89054. * @type {number}
  89055. * @private
  89056. */
  89057. this.minLat_ = -Infinity;
  89058. /**
  89059. * @type {number}
  89060. * @private
  89061. */
  89062. this.minLon_ = -Infinity;
  89063. /**
  89064. * @type {number}
  89065. * @private
  89066. */
  89067. this.maxLatP_ = Infinity;
  89068. /**
  89069. * @type {number}
  89070. * @private
  89071. */
  89072. this.maxLonP_ = Infinity;
  89073. /**
  89074. * @type {number}
  89075. * @private
  89076. */
  89077. this.minLatP_ = -Infinity;
  89078. /**
  89079. * @type {number}
  89080. * @private
  89081. */
  89082. this.minLonP_ = -Infinity;
  89083. /**
  89084. * @type {number}
  89085. * @private
  89086. */
  89087. this.targetSize_ = options.targetSize !== undefined ?
  89088. options.targetSize : 100;
  89089. /**
  89090. * @type {number}
  89091. * @private
  89092. */
  89093. this.maxLines_ = options.maxLines !== undefined ? options.maxLines : 100;
  89094. goog.asserts.assert(this.maxLines_ > 0,
  89095. 'this.maxLines_ should be more than 0');
  89096. /**
  89097. * @type {Array.<ol.geom.LineString>}
  89098. * @private
  89099. */
  89100. this.meridians_ = [];
  89101. /**
  89102. * @type {Array.<ol.geom.LineString>}
  89103. * @private
  89104. */
  89105. this.parallels_ = [];
  89106. /**
  89107. * @type {ol.style.Stroke}
  89108. * @private
  89109. */
  89110. this.strokeStyle_ = options.strokeStyle !== undefined ?
  89111. options.strokeStyle : ol.Graticule.DEFAULT_STROKE_STYLE_;
  89112. /**
  89113. * @type {ol.TransformFunction|undefined}
  89114. * @private
  89115. */
  89116. this.fromLonLatTransform_ = undefined;
  89117. /**
  89118. * @type {ol.TransformFunction|undefined}
  89119. * @private
  89120. */
  89121. this.toLonLatTransform_ = undefined;
  89122. /**
  89123. * @type {ol.Coordinate}
  89124. * @private
  89125. */
  89126. this.projectionCenterLonLat_ = null;
  89127. this.setMap(options.map !== undefined ? options.map : null);
  89128. };
  89129. /**
  89130. * @type {ol.style.Stroke}
  89131. * @private
  89132. * @const
  89133. */
  89134. ol.Graticule.DEFAULT_STROKE_STYLE_ = new ol.style.Stroke({
  89135. color: 'rgba(0,0,0,0.2)'
  89136. });
  89137. /**
  89138. * TODO can be configurable
  89139. * @type {Array.<number>}
  89140. * @private
  89141. */
  89142. ol.Graticule.intervals_ = [90, 45, 30, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05,
  89143. 0.01, 0.005, 0.002, 0.001];
  89144. /**
  89145. * @param {number} lon Longitude.
  89146. * @param {number} minLat Minimal latitude.
  89147. * @param {number} maxLat Maximal latitude.
  89148. * @param {number} squaredTolerance Squared tolerance.
  89149. * @param {ol.Extent} extent Extent.
  89150. * @param {number} index Index.
  89151. * @return {number} Index.
  89152. * @private
  89153. */
  89154. ol.Graticule.prototype.addMeridian_ =
  89155. function(lon, minLat, maxLat, squaredTolerance, extent, index) {
  89156. var lineString = this.getMeridian_(lon, minLat, maxLat,
  89157. squaredTolerance, index);
  89158. if (ol.extent.intersects(lineString.getExtent(), extent)) {
  89159. this.meridians_[index++] = lineString;
  89160. }
  89161. return index;
  89162. };
  89163. /**
  89164. * @param {number} lat Latitude.
  89165. * @param {number} minLon Minimal longitude.
  89166. * @param {number} maxLon Maximal longitude.
  89167. * @param {number} squaredTolerance Squared tolerance.
  89168. * @param {ol.Extent} extent Extent.
  89169. * @param {number} index Index.
  89170. * @return {number} Index.
  89171. * @private
  89172. */
  89173. ol.Graticule.prototype.addParallel_ =
  89174. function(lat, minLon, maxLon, squaredTolerance, extent, index) {
  89175. var lineString = this.getParallel_(lat, minLon, maxLon, squaredTolerance,
  89176. index);
  89177. if (ol.extent.intersects(lineString.getExtent(), extent)) {
  89178. this.parallels_[index++] = lineString;
  89179. }
  89180. return index;
  89181. };
  89182. /**
  89183. * @param {ol.Extent} extent Extent.
  89184. * @param {ol.Coordinate} center Center.
  89185. * @param {number} resolution Resolution.
  89186. * @param {number} squaredTolerance Squared tolerance.
  89187. * @private
  89188. */
  89189. ol.Graticule.prototype.createGraticule_ =
  89190. function(extent, center, resolution, squaredTolerance) {
  89191. var interval = this.getInterval_(resolution);
  89192. if (interval == -1) {
  89193. this.meridians_.length = this.parallels_.length = 0;
  89194. return;
  89195. }
  89196. var centerLonLat = this.toLonLatTransform_(center);
  89197. var centerLon = centerLonLat[0];
  89198. var centerLat = centerLonLat[1];
  89199. var maxLines = this.maxLines_;
  89200. var cnt, idx, lat, lon;
  89201. var validExtent = [
  89202. Math.max(extent[0], this.minLonP_),
  89203. Math.max(extent[1], this.minLatP_),
  89204. Math.min(extent[2], this.maxLonP_),
  89205. Math.min(extent[3], this.maxLatP_)
  89206. ];
  89207. validExtent = ol.proj.transformExtent(validExtent, this.projection_,
  89208. 'EPSG:4326');
  89209. var maxLat = validExtent[3];
  89210. var maxLon = validExtent[2];
  89211. var minLat = validExtent[1];
  89212. var minLon = validExtent[0];
  89213. // Create meridians
  89214. centerLon = Math.floor(centerLon / interval) * interval;
  89215. lon = ol.math.clamp(centerLon, this.minLon_, this.maxLon_);
  89216. idx = this.addMeridian_(lon, minLat, maxLat, squaredTolerance, extent, 0);
  89217. cnt = 0;
  89218. while (lon != this.minLon_ && cnt++ < maxLines) {
  89219. lon = Math.max(lon - interval, this.minLon_);
  89220. idx = this.addMeridian_(lon, minLat, maxLat, squaredTolerance, extent, idx);
  89221. }
  89222. lon = ol.math.clamp(centerLon, this.minLon_, this.maxLon_);
  89223. cnt = 0;
  89224. while (lon != this.maxLon_ && cnt++ < maxLines) {
  89225. lon = Math.min(lon + interval, this.maxLon_);
  89226. idx = this.addMeridian_(lon, minLat, maxLat, squaredTolerance, extent, idx);
  89227. }
  89228. this.meridians_.length = idx;
  89229. // Create parallels
  89230. centerLat = Math.floor(centerLat / interval) * interval;
  89231. lat = ol.math.clamp(centerLat, this.minLat_, this.maxLat_);
  89232. idx = this.addParallel_(lat, minLon, maxLon, squaredTolerance, extent, 0);
  89233. cnt = 0;
  89234. while (lat != this.minLat_ && cnt++ < maxLines) {
  89235. lat = Math.max(lat - interval, this.minLat_);
  89236. idx = this.addParallel_(lat, minLon, maxLon, squaredTolerance, extent, idx);
  89237. }
  89238. lat = ol.math.clamp(centerLat, this.minLat_, this.maxLat_);
  89239. cnt = 0;
  89240. while (lat != this.maxLat_ && cnt++ < maxLines) {
  89241. lat = Math.min(lat + interval, this.maxLat_);
  89242. idx = this.addParallel_(lat, minLon, maxLon, squaredTolerance, extent, idx);
  89243. }
  89244. this.parallels_.length = idx;
  89245. };
  89246. /**
  89247. * @param {number} resolution Resolution.
  89248. * @return {number} The interval in degrees.
  89249. * @private
  89250. */
  89251. ol.Graticule.prototype.getInterval_ = function(resolution) {
  89252. var centerLon = this.projectionCenterLonLat_[0];
  89253. var centerLat = this.projectionCenterLonLat_[1];
  89254. var interval = -1;
  89255. var i, ii, delta, dist;
  89256. var target = Math.pow(this.targetSize_ * resolution, 2);
  89257. /** @type {Array.<number>} **/
  89258. var p1 = [];
  89259. /** @type {Array.<number>} **/
  89260. var p2 = [];
  89261. for (i = 0, ii = ol.Graticule.intervals_.length; i < ii; ++i) {
  89262. delta = ol.Graticule.intervals_[i] / 2;
  89263. p1[0] = centerLon - delta;
  89264. p1[1] = centerLat - delta;
  89265. p2[0] = centerLon + delta;
  89266. p2[1] = centerLat + delta;
  89267. this.fromLonLatTransform_(p1, p1);
  89268. this.fromLonLatTransform_(p2, p2);
  89269. dist = Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2);
  89270. if (dist <= target) {
  89271. break;
  89272. }
  89273. interval = ol.Graticule.intervals_[i];
  89274. }
  89275. return interval;
  89276. };
  89277. /**
  89278. * Get the map associated with this graticule.
  89279. * @return {ol.Map} The map.
  89280. * @api
  89281. */
  89282. ol.Graticule.prototype.getMap = function() {
  89283. return this.map_;
  89284. };
  89285. /**
  89286. * @param {number} lon Longitude.
  89287. * @param {number} minLat Minimal latitude.
  89288. * @param {number} maxLat Maximal latitude.
  89289. * @param {number} squaredTolerance Squared tolerance.
  89290. * @return {ol.geom.LineString} The meridian line string.
  89291. * @param {number} index Index.
  89292. * @private
  89293. */
  89294. ol.Graticule.prototype.getMeridian_ = function(lon, minLat, maxLat,
  89295. squaredTolerance, index) {
  89296. goog.asserts.assert(lon >= this.minLon_,
  89297. 'lon should be larger than or equal to this.minLon_');
  89298. goog.asserts.assert(lon <= this.maxLon_,
  89299. 'lon should be smaller than or equal to this.maxLon_');
  89300. var flatCoordinates = ol.geom.flat.geodesic.meridian(lon,
  89301. minLat, maxLat, this.projection_, squaredTolerance);
  89302. goog.asserts.assert(flatCoordinates.length > 0,
  89303. 'flatCoordinates cannot be empty');
  89304. var lineString = this.meridians_[index] !== undefined ?
  89305. this.meridians_[index] : new ol.geom.LineString(null);
  89306. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  89307. return lineString;
  89308. };
  89309. /**
  89310. * Get the list of meridians. Meridians are lines of equal longitude.
  89311. * @return {Array.<ol.geom.LineString>} The meridians.
  89312. * @api
  89313. */
  89314. ol.Graticule.prototype.getMeridians = function() {
  89315. return this.meridians_;
  89316. };
  89317. /**
  89318. * @param {number} lat Latitude.
  89319. * @param {number} minLon Minimal longitude.
  89320. * @param {number} maxLon Maximal longitude.
  89321. * @param {number} squaredTolerance Squared tolerance.
  89322. * @return {ol.geom.LineString} The parallel line string.
  89323. * @param {number} index Index.
  89324. * @private
  89325. */
  89326. ol.Graticule.prototype.getParallel_ = function(lat, minLon, maxLon,
  89327. squaredTolerance, index) {
  89328. goog.asserts.assert(lat >= this.minLat_,
  89329. 'lat should be larger than or equal to this.minLat_');
  89330. goog.asserts.assert(lat <= this.maxLat_,
  89331. 'lat should be smaller than or equal to this.maxLat_');
  89332. var flatCoordinates = ol.geom.flat.geodesic.parallel(lat,
  89333. this.minLon_, this.maxLon_, this.projection_, squaredTolerance);
  89334. goog.asserts.assert(flatCoordinates.length > 0,
  89335. 'flatCoordinates cannot be empty');
  89336. var lineString = this.parallels_[index] !== undefined ?
  89337. this.parallels_[index] : new ol.geom.LineString(null);
  89338. lineString.setFlatCoordinates(ol.geom.GeometryLayout.XY, flatCoordinates);
  89339. return lineString;
  89340. };
  89341. /**
  89342. * Get the list of parallels. Pallels are lines of equal latitude.
  89343. * @return {Array.<ol.geom.LineString>} The parallels.
  89344. * @api
  89345. */
  89346. ol.Graticule.prototype.getParallels = function() {
  89347. return this.parallels_;
  89348. };
  89349. /**
  89350. * @param {ol.render.Event} e Event.
  89351. * @private
  89352. */
  89353. ol.Graticule.prototype.handlePostCompose_ = function(e) {
  89354. var vectorContext = e.vectorContext;
  89355. var frameState = e.frameState;
  89356. var extent = frameState.extent;
  89357. var viewState = frameState.viewState;
  89358. var center = viewState.center;
  89359. var projection = viewState.projection;
  89360. var resolution = viewState.resolution;
  89361. var pixelRatio = frameState.pixelRatio;
  89362. var squaredTolerance =
  89363. resolution * resolution / (4 * pixelRatio * pixelRatio);
  89364. var updateProjectionInfo = !this.projection_ ||
  89365. !ol.proj.equivalent(this.projection_, projection);
  89366. if (updateProjectionInfo) {
  89367. this.updateProjectionInfo_(projection);
  89368. }
  89369. //Fix the extent if wrapped.
  89370. //(note: this is the same extent as vectorContext.extent_)
  89371. var offsetX = 0;
  89372. if (projection.canWrapX()) {
  89373. var projectionExtent = projection.getExtent();
  89374. var worldWidth = ol.extent.getWidth(projectionExtent);
  89375. var x = frameState.focus[0];
  89376. if (x < projectionExtent[0] || x > projectionExtent[2]) {
  89377. var worldsAway = Math.ceil((projectionExtent[0] - x) / worldWidth);
  89378. offsetX = worldWidth * worldsAway;
  89379. extent = [
  89380. extent[0] + offsetX, extent[1],
  89381. extent[2] + offsetX, extent[3]
  89382. ];
  89383. }
  89384. }
  89385. this.createGraticule_(extent, center, resolution, squaredTolerance);
  89386. // Draw the lines
  89387. vectorContext.setFillStrokeStyle(null, this.strokeStyle_);
  89388. var i, l, line;
  89389. for (i = 0, l = this.meridians_.length; i < l; ++i) {
  89390. line = this.meridians_[i];
  89391. vectorContext.drawLineStringGeometry(line, null);
  89392. }
  89393. for (i = 0, l = this.parallels_.length; i < l; ++i) {
  89394. line = this.parallels_[i];
  89395. vectorContext.drawLineStringGeometry(line, null);
  89396. }
  89397. };
  89398. /**
  89399. * @param {ol.proj.Projection} projection Projection.
  89400. * @private
  89401. */
  89402. ol.Graticule.prototype.updateProjectionInfo_ = function(projection) {
  89403. goog.asserts.assert(projection, 'projection cannot be null');
  89404. var epsg4326Projection = ol.proj.get('EPSG:4326');
  89405. var extent = projection.getExtent();
  89406. var worldExtent = projection.getWorldExtent();
  89407. var worldExtentP = ol.proj.transformExtent(worldExtent,
  89408. epsg4326Projection, projection);
  89409. var maxLat = worldExtent[3];
  89410. var maxLon = worldExtent[2];
  89411. var minLat = worldExtent[1];
  89412. var minLon = worldExtent[0];
  89413. var maxLatP = worldExtentP[3];
  89414. var maxLonP = worldExtentP[2];
  89415. var minLatP = worldExtentP[1];
  89416. var minLonP = worldExtentP[0];
  89417. goog.asserts.assert(extent, 'extent cannot be null');
  89418. goog.asserts.assert(maxLat !== undefined, 'maxLat should be defined');
  89419. goog.asserts.assert(maxLon !== undefined, 'maxLon should be defined');
  89420. goog.asserts.assert(minLat !== undefined, 'minLat should be defined');
  89421. goog.asserts.assert(minLon !== undefined, 'minLon should be defined');
  89422. goog.asserts.assert(maxLatP !== undefined,
  89423. 'projected maxLat should be defined');
  89424. goog.asserts.assert(maxLonP !== undefined,
  89425. 'projected maxLon should be defined');
  89426. goog.asserts.assert(minLatP !== undefined,
  89427. 'projected minLat should be defined');
  89428. goog.asserts.assert(minLonP !== undefined,
  89429. 'projected minLon should be defined');
  89430. this.maxLat_ = maxLat;
  89431. this.maxLon_ = maxLon;
  89432. this.minLat_ = minLat;
  89433. this.minLon_ = minLon;
  89434. this.maxLatP_ = maxLatP;
  89435. this.maxLonP_ = maxLonP;
  89436. this.minLatP_ = minLatP;
  89437. this.minLonP_ = minLonP;
  89438. this.fromLonLatTransform_ = ol.proj.getTransform(
  89439. epsg4326Projection, projection);
  89440. this.toLonLatTransform_ = ol.proj.getTransform(
  89441. projection, epsg4326Projection);
  89442. this.projectionCenterLonLat_ = this.toLonLatTransform_(
  89443. ol.extent.getCenter(extent));
  89444. this.projection_ = projection;
  89445. };
  89446. /**
  89447. * Set the map for this graticule. The graticule will be rendered on the
  89448. * provided map.
  89449. * @param {ol.Map} map Map.
  89450. * @api
  89451. */
  89452. ol.Graticule.prototype.setMap = function(map) {
  89453. if (this.map_) {
  89454. this.map_.un(ol.render.EventType.POSTCOMPOSE,
  89455. this.handlePostCompose_, this);
  89456. this.map_.render();
  89457. }
  89458. if (map) {
  89459. map.on(ol.render.EventType.POSTCOMPOSE,
  89460. this.handlePostCompose_, this);
  89461. map.render();
  89462. }
  89463. this.map_ = map;
  89464. };
  89465. goog.provide('ol.Image');
  89466. goog.require('goog.asserts');
  89467. goog.require('goog.events');
  89468. goog.require('goog.events.EventType');
  89469. goog.require('goog.object');
  89470. goog.require('ol.ImageBase');
  89471. goog.require('ol.ImageState');
  89472. goog.require('ol.extent');
  89473. /**
  89474. * @constructor
  89475. * @extends {ol.ImageBase}
  89476. * @param {ol.Extent} extent Extent.
  89477. * @param {number|undefined} resolution Resolution.
  89478. * @param {number} pixelRatio Pixel ratio.
  89479. * @param {Array.<ol.Attribution>} attributions Attributions.
  89480. * @param {string} src Image source URI.
  89481. * @param {?string} crossOrigin Cross origin.
  89482. * @param {ol.ImageLoadFunctionType} imageLoadFunction Image load function.
  89483. */
  89484. ol.Image = function(extent, resolution, pixelRatio, attributions, src,
  89485. crossOrigin, imageLoadFunction) {
  89486. goog.base(this, extent, resolution, pixelRatio, ol.ImageState.IDLE,
  89487. attributions);
  89488. /**
  89489. * @private
  89490. * @type {string}
  89491. */
  89492. this.src_ = src;
  89493. /**
  89494. * @private
  89495. * @type {Image}
  89496. */
  89497. this.image_ = new Image();
  89498. if (crossOrigin) {
  89499. this.image_.crossOrigin = crossOrigin;
  89500. }
  89501. /**
  89502. * @private
  89503. * @type {Object.<number, Image>}
  89504. */
  89505. this.imageByContext_ = {};
  89506. /**
  89507. * @private
  89508. * @type {Array.<goog.events.Key>}
  89509. */
  89510. this.imageListenerKeys_ = null;
  89511. /**
  89512. * @protected
  89513. * @type {ol.ImageState}
  89514. */
  89515. this.state = ol.ImageState.IDLE;
  89516. /**
  89517. * @private
  89518. * @type {ol.ImageLoadFunctionType}
  89519. */
  89520. this.imageLoadFunction_ = imageLoadFunction;
  89521. };
  89522. goog.inherits(ol.Image, ol.ImageBase);
  89523. /**
  89524. * Get the HTML image element (may be a Canvas, Image, or Video).
  89525. * @param {Object=} opt_context Object.
  89526. * @return {HTMLCanvasElement|Image|HTMLVideoElement} Image.
  89527. * @api
  89528. */
  89529. ol.Image.prototype.getImage = function(opt_context) {
  89530. if (opt_context !== undefined) {
  89531. var image;
  89532. var key = goog.getUid(opt_context);
  89533. if (key in this.imageByContext_) {
  89534. return this.imageByContext_[key];
  89535. } else if (goog.object.isEmpty(this.imageByContext_)) {
  89536. image = this.image_;
  89537. } else {
  89538. image = /** @type {Image} */ (this.image_.cloneNode(false));
  89539. }
  89540. this.imageByContext_[key] = image;
  89541. return image;
  89542. } else {
  89543. return this.image_;
  89544. }
  89545. };
  89546. /**
  89547. * Tracks loading or read errors.
  89548. *
  89549. * @private
  89550. */
  89551. ol.Image.prototype.handleImageError_ = function() {
  89552. this.state = ol.ImageState.ERROR;
  89553. this.unlistenImage_();
  89554. this.changed();
  89555. };
  89556. /**
  89557. * Tracks successful image load.
  89558. *
  89559. * @private
  89560. */
  89561. ol.Image.prototype.handleImageLoad_ = function() {
  89562. if (this.resolution === undefined) {
  89563. this.resolution = ol.extent.getHeight(this.extent) / this.image_.height;
  89564. }
  89565. this.state = ol.ImageState.LOADED;
  89566. this.unlistenImage_();
  89567. this.changed();
  89568. };
  89569. /**
  89570. * Load not yet loaded URI.
  89571. */
  89572. ol.Image.prototype.load = function() {
  89573. if (this.state == ol.ImageState.IDLE) {
  89574. this.state = ol.ImageState.LOADING;
  89575. this.changed();
  89576. goog.asserts.assert(!this.imageListenerKeys_,
  89577. 'this.imageListenerKeys_ should be null');
  89578. this.imageListenerKeys_ = [
  89579. goog.events.listenOnce(this.image_, goog.events.EventType.ERROR,
  89580. this.handleImageError_, false, this),
  89581. goog.events.listenOnce(this.image_, goog.events.EventType.LOAD,
  89582. this.handleImageLoad_, false, this)
  89583. ];
  89584. this.imageLoadFunction_(this, this.src_);
  89585. }
  89586. };
  89587. /**
  89588. * Discards event handlers which listen for load completion or errors.
  89589. *
  89590. * @private
  89591. */
  89592. ol.Image.prototype.unlistenImage_ = function() {
  89593. goog.asserts.assert(this.imageListenerKeys_,
  89594. 'this.imageListenerKeys_ should not be null');
  89595. this.imageListenerKeys_.forEach(goog.events.unlistenByKey);
  89596. this.imageListenerKeys_ = null;
  89597. };
  89598. goog.provide('ol.ImageLoadFunctionType');
  89599. /**
  89600. * A function that takes an {@link ol.Image} for the image and a `{string}` for
  89601. * the src as arguments. It is supposed to make it so the underlying image
  89602. * {@link ol.Image#getImage} is assigned the content specified by the src. If
  89603. * not specified, the default is
  89604. *
  89605. * function(image, src) {
  89606. * image.getImage().src = src;
  89607. * }
  89608. *
  89609. * Providing a custom `imageLoadFunction` can be useful to load images with
  89610. * post requests or - in general - through XHR requests, where the src of the
  89611. * image element would be set to a data URI when the content is loaded.
  89612. *
  89613. * @typedef {function(ol.Image, string)}
  89614. * @api
  89615. */
  89616. ol.ImageLoadFunctionType;
  89617. goog.provide('ol.TileLoadFunctionType');
  89618. goog.provide('ol.TileVectorLoadFunctionType');
  89619. /**
  89620. * A function that takes an {@link ol.ImageTile} for the image tile and a
  89621. * `{string}` for the src as arguments.
  89622. *
  89623. * @typedef {function(ol.ImageTile, string)}
  89624. * @api
  89625. */
  89626. ol.TileLoadFunctionType;
  89627. /**
  89628. * A function that is called with a tile url for the features to load and
  89629. * a callback that takes the loaded features as argument.
  89630. *
  89631. * @typedef {function(string, function(Array.<ol.Feature>))}
  89632. * @api
  89633. */
  89634. ol.TileVectorLoadFunctionType;
  89635. goog.provide('ol.ImageTile');
  89636. goog.require('goog.asserts');
  89637. goog.require('goog.events');
  89638. goog.require('goog.events.EventType');
  89639. goog.require('goog.object');
  89640. goog.require('ol.Tile');
  89641. goog.require('ol.TileCoord');
  89642. goog.require('ol.TileLoadFunctionType');
  89643. goog.require('ol.TileState');
  89644. /**
  89645. * @constructor
  89646. * @extends {ol.Tile}
  89647. * @param {ol.TileCoord} tileCoord Tile coordinate.
  89648. * @param {ol.TileState} state State.
  89649. * @param {string} src Image source URI.
  89650. * @param {?string} crossOrigin Cross origin.
  89651. * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
  89652. */
  89653. ol.ImageTile = function(tileCoord, state, src, crossOrigin, tileLoadFunction) {
  89654. goog.base(this, tileCoord, state);
  89655. /**
  89656. * Image URI
  89657. *
  89658. * @private
  89659. * @type {string}
  89660. */
  89661. this.src_ = src;
  89662. /**
  89663. * @private
  89664. * @type {Image}
  89665. */
  89666. this.image_ = new Image();
  89667. if (crossOrigin) {
  89668. this.image_.crossOrigin = crossOrigin;
  89669. }
  89670. /**
  89671. * @private
  89672. * @type {Object.<number, Image>}
  89673. */
  89674. this.imageByContext_ = {};
  89675. /**
  89676. * @private
  89677. * @type {Array.<goog.events.Key>}
  89678. */
  89679. this.imageListenerKeys_ = null;
  89680. /**
  89681. * @private
  89682. * @type {ol.TileLoadFunctionType}
  89683. */
  89684. this.tileLoadFunction_ = tileLoadFunction;
  89685. };
  89686. goog.inherits(ol.ImageTile, ol.Tile);
  89687. /**
  89688. * @inheritDoc
  89689. */
  89690. ol.ImageTile.prototype.disposeInternal = function() {
  89691. if (this.state == ol.TileState.LOADING) {
  89692. this.unlistenImage_();
  89693. }
  89694. goog.base(this, 'disposeInternal');
  89695. };
  89696. /**
  89697. * Get the image element for this tile.
  89698. * @inheritDoc
  89699. * @api
  89700. */
  89701. ol.ImageTile.prototype.getImage = function(opt_context) {
  89702. if (opt_context !== undefined) {
  89703. var image;
  89704. var key = goog.getUid(opt_context);
  89705. if (key in this.imageByContext_) {
  89706. return this.imageByContext_[key];
  89707. } else if (goog.object.isEmpty(this.imageByContext_)) {
  89708. image = this.image_;
  89709. } else {
  89710. image = /** @type {Image} */ (this.image_.cloneNode(false));
  89711. }
  89712. this.imageByContext_[key] = image;
  89713. return image;
  89714. } else {
  89715. return this.image_;
  89716. }
  89717. };
  89718. /**
  89719. * @inheritDoc
  89720. */
  89721. ol.ImageTile.prototype.getKey = function() {
  89722. return this.src_;
  89723. };
  89724. /**
  89725. * Tracks loading or read errors.
  89726. *
  89727. * @private
  89728. */
  89729. ol.ImageTile.prototype.handleImageError_ = function() {
  89730. this.state = ol.TileState.ERROR;
  89731. this.unlistenImage_();
  89732. this.changed();
  89733. };
  89734. /**
  89735. * Tracks successful image load.
  89736. *
  89737. * @private
  89738. */
  89739. ol.ImageTile.prototype.handleImageLoad_ = function() {
  89740. if (this.image_.naturalWidth && this.image_.naturalHeight) {
  89741. this.state = ol.TileState.LOADED;
  89742. } else {
  89743. this.state = ol.TileState.EMPTY;
  89744. }
  89745. this.unlistenImage_();
  89746. this.changed();
  89747. };
  89748. /**
  89749. * Load not yet loaded URI.
  89750. */
  89751. ol.ImageTile.prototype.load = function() {
  89752. if (this.state == ol.TileState.IDLE) {
  89753. this.state = ol.TileState.LOADING;
  89754. this.changed();
  89755. goog.asserts.assert(!this.imageListenerKeys_,
  89756. 'this.imageListenerKeys_ should be null');
  89757. this.imageListenerKeys_ = [
  89758. goog.events.listenOnce(this.image_, goog.events.EventType.ERROR,
  89759. this.handleImageError_, false, this),
  89760. goog.events.listenOnce(this.image_, goog.events.EventType.LOAD,
  89761. this.handleImageLoad_, false, this)
  89762. ];
  89763. this.tileLoadFunction_(this, this.src_);
  89764. }
  89765. };
  89766. /**
  89767. * Discards event handlers which listen for load completion or errors.
  89768. *
  89769. * @private
  89770. */
  89771. ol.ImageTile.prototype.unlistenImage_ = function() {
  89772. goog.asserts.assert(this.imageListenerKeys_,
  89773. 'this.imageListenerKeys_ should not be null');
  89774. this.imageListenerKeys_.forEach(goog.events.unlistenByKey);
  89775. this.imageListenerKeys_ = null;
  89776. };
  89777. goog.provide('ol.ImageUrlFunction');
  89778. goog.provide('ol.ImageUrlFunctionType');
  89779. goog.require('ol.Size');
  89780. /**
  89781. * @typedef {function(this:ol.source.Image, ol.Extent, ol.Size,
  89782. * ol.proj.Projection): (string|undefined)}
  89783. */
  89784. ol.ImageUrlFunctionType;
  89785. /**
  89786. * @param {string} baseUrl Base URL (may have query data).
  89787. * @param {Object.<string,*>} params to encode in the URL.
  89788. * @param {function(string, Object.<string,*>, ol.Extent, ol.Size,
  89789. * ol.proj.Projection): (string|undefined)} paramsFunction params function.
  89790. * @return {ol.ImageUrlFunctionType} Image URL function.
  89791. */
  89792. ol.ImageUrlFunction.createFromParamsFunction =
  89793. function(baseUrl, params, paramsFunction) {
  89794. return (
  89795. /**
  89796. * @this {ol.source.Image}
  89797. * @param {ol.Extent} extent Extent.
  89798. * @param {ol.Size} size Size.
  89799. * @param {ol.proj.Projection} projection Projection.
  89800. * @return {string|undefined} URL.
  89801. */
  89802. function(extent, size, projection) {
  89803. return paramsFunction(baseUrl, params, extent, size, projection);
  89804. });
  89805. };
  89806. /**
  89807. * @this {ol.source.Image}
  89808. * @param {ol.Extent} extent Extent.
  89809. * @param {ol.Size} size Size.
  89810. * @return {string|undefined} Image URL.
  89811. */
  89812. ol.ImageUrlFunction.nullImageUrlFunction =
  89813. function(extent, size) {
  89814. return undefined;
  89815. };
  89816. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  89817. //
  89818. // Licensed under the Apache License, Version 2.0 (the "License");
  89819. // you may not use this file except in compliance with the License.
  89820. // You may obtain a copy of the License at
  89821. //
  89822. // http://www.apache.org/licenses/LICENSE-2.0
  89823. //
  89824. // Unless required by applicable law or agreed to in writing, software
  89825. // distributed under the License is distributed on an "AS-IS" BASIS,
  89826. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  89827. // See the License for the specific language governing permissions and
  89828. // limitations under the License.
  89829. /**
  89830. * @fileoverview Provides a files drag and drop event detector. It works on
  89831. * HTML5 browsers.
  89832. *
  89833. * @see ../demos/filedrophandler.html
  89834. */
  89835. goog.provide('goog.events.FileDropHandler');
  89836. goog.provide('goog.events.FileDropHandler.EventType');
  89837. goog.require('goog.array');
  89838. goog.require('goog.dom');
  89839. goog.require('goog.events.BrowserEvent');
  89840. goog.require('goog.events.EventHandler');
  89841. goog.require('goog.events.EventTarget');
  89842. goog.require('goog.events.EventType');
  89843. goog.require('goog.log');
  89844. goog.require('goog.log.Level');
  89845. /**
  89846. * A files drag and drop event detector. Gets an {@code element} as parameter
  89847. * and fires {@code goog.events.FileDropHandler.EventType.DROP} event when files
  89848. * are dropped in the {@code element}.
  89849. *
  89850. * @param {Element|Document} element The element or document to listen on.
  89851. * @param {boolean=} opt_preventDropOutside Whether to prevent a drop on the
  89852. * area outside the {@code element}. Default false.
  89853. * @constructor
  89854. * @extends {goog.events.EventTarget}
  89855. * @final
  89856. */
  89857. goog.events.FileDropHandler = function(element, opt_preventDropOutside) {
  89858. goog.events.EventTarget.call(this);
  89859. /**
  89860. * Handler for drag/drop events.
  89861. * @type {!goog.events.EventHandler<!goog.events.FileDropHandler>}
  89862. * @private
  89863. */
  89864. this.eventHandler_ = new goog.events.EventHandler(this);
  89865. var doc = element;
  89866. if (opt_preventDropOutside) {
  89867. doc = goog.dom.getOwnerDocument(element);
  89868. }
  89869. // Add dragenter listener to the owner document of the element.
  89870. this.eventHandler_.listen(doc,
  89871. goog.events.EventType.DRAGENTER,
  89872. this.onDocDragEnter_);
  89873. // Add dragover listener to the owner document of the element only if the
  89874. // document is not the element itself.
  89875. if (doc != element) {
  89876. this.eventHandler_.listen(doc,
  89877. goog.events.EventType.DRAGOVER,
  89878. this.onDocDragOver_);
  89879. }
  89880. // Add dragover and drop listeners to the element.
  89881. this.eventHandler_.listen(element,
  89882. goog.events.EventType.DRAGOVER,
  89883. this.onElemDragOver_);
  89884. this.eventHandler_.listen(element,
  89885. goog.events.EventType.DROP,
  89886. this.onElemDrop_);
  89887. };
  89888. goog.inherits(goog.events.FileDropHandler, goog.events.EventTarget);
  89889. /**
  89890. * Whether the drag event contains files. It is initialized only in the
  89891. * dragenter event. It is used in all the drag events to prevent default actions
  89892. * only if the drag contains files. Preventing default actions is necessary to
  89893. * go from dragenter to dragover and from dragover to drop. However we do not
  89894. * always want to prevent default actions, e.g. when the user drags text or
  89895. * links on a text area we should not prevent the browser default action that
  89896. * inserts the text in the text area. It is also necessary to stop propagation
  89897. * when handling drag events on the element to prevent them from propagating
  89898. * to the document.
  89899. * @private
  89900. * @type {boolean}
  89901. */
  89902. goog.events.FileDropHandler.prototype.dndContainsFiles_ = false;
  89903. /**
  89904. * A logger, used to help us debug the algorithm.
  89905. * @type {goog.log.Logger}
  89906. * @private
  89907. */
  89908. goog.events.FileDropHandler.prototype.logger_ =
  89909. goog.log.getLogger('goog.events.FileDropHandler');
  89910. /**
  89911. * The types of events fired by this class.
  89912. * @enum {string}
  89913. */
  89914. goog.events.FileDropHandler.EventType = {
  89915. DROP: goog.events.EventType.DROP
  89916. };
  89917. /** @override */
  89918. goog.events.FileDropHandler.prototype.disposeInternal = function() {
  89919. goog.events.FileDropHandler.superClass_.disposeInternal.call(this);
  89920. this.eventHandler_.dispose();
  89921. };
  89922. /**
  89923. * Dispatches the DROP event.
  89924. * @param {goog.events.BrowserEvent} e The underlying browser event.
  89925. * @private
  89926. */
  89927. goog.events.FileDropHandler.prototype.dispatch_ = function(e) {
  89928. goog.log.fine(this.logger_, 'Firing DROP event...');
  89929. var event = new goog.events.BrowserEvent(e.getBrowserEvent());
  89930. event.type = goog.events.FileDropHandler.EventType.DROP;
  89931. this.dispatchEvent(event);
  89932. };
  89933. /**
  89934. * Handles dragenter on the document.
  89935. * @param {goog.events.BrowserEvent} e The dragenter event.
  89936. * @private
  89937. */
  89938. goog.events.FileDropHandler.prototype.onDocDragEnter_ = function(e) {
  89939. goog.log.log(this.logger_, goog.log.Level.FINER,
  89940. '"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type);
  89941. var dt = e.getBrowserEvent().dataTransfer;
  89942. // Check whether the drag event contains files.
  89943. this.dndContainsFiles_ = !!(dt &&
  89944. ((dt.types &&
  89945. (goog.array.contains(dt.types, 'Files') ||
  89946. goog.array.contains(dt.types, 'public.file-url'))) ||
  89947. (dt.files && dt.files.length > 0)));
  89948. // If it does
  89949. if (this.dndContainsFiles_) {
  89950. // Prevent default actions.
  89951. e.preventDefault();
  89952. }
  89953. goog.log.log(this.logger_, goog.log.Level.FINER,
  89954. 'dndContainsFiles_: ' + this.dndContainsFiles_);
  89955. };
  89956. /**
  89957. * Handles dragging something over the document.
  89958. * @param {goog.events.BrowserEvent} e The dragover event.
  89959. * @private
  89960. */
  89961. goog.events.FileDropHandler.prototype.onDocDragOver_ = function(e) {
  89962. goog.log.log(this.logger_, goog.log.Level.FINEST,
  89963. '"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type);
  89964. if (this.dndContainsFiles_) {
  89965. // Prevent default actions.
  89966. e.preventDefault();
  89967. // Disable the drop on the document outside the drop zone.
  89968. var dt = e.getBrowserEvent().dataTransfer;
  89969. dt.dropEffect = 'none';
  89970. }
  89971. };
  89972. /**
  89973. * Handles dragging something over the element (drop zone).
  89974. * @param {goog.events.BrowserEvent} e The dragover event.
  89975. * @private
  89976. */
  89977. goog.events.FileDropHandler.prototype.onElemDragOver_ = function(e) {
  89978. goog.log.log(this.logger_, goog.log.Level.FINEST,
  89979. '"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type);
  89980. if (this.dndContainsFiles_) {
  89981. // Prevent default actions and stop the event from propagating further to
  89982. // the document. Both lines are needed! (See comment above).
  89983. e.preventDefault();
  89984. e.stopPropagation();
  89985. // Allow the drop on the drop zone.
  89986. var dt = e.getBrowserEvent().dataTransfer;
  89987. // IE bug #811625 (https://goo.gl/UWuxX0) will throw error SCRIPT65535
  89988. // when attempting to set property effectAllowed on IE10+.
  89989. // See more: https://github.com/google/closure-library/issues/485.
  89990. try {
  89991. dt.effectAllowed = 'all';
  89992. } catch (err) {
  89993. }
  89994. dt.dropEffect = 'copy';
  89995. }
  89996. };
  89997. /**
  89998. * Handles dropping something onto the element (drop zone).
  89999. * @param {goog.events.BrowserEvent} e The drop event.
  90000. * @private
  90001. */
  90002. goog.events.FileDropHandler.prototype.onElemDrop_ = function(e) {
  90003. goog.log.log(this.logger_, goog.log.Level.FINER,
  90004. '"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type);
  90005. // If the drag and drop event contains files.
  90006. if (this.dndContainsFiles_) {
  90007. // Prevent default actions and stop the event from propagating further to
  90008. // the document. Both lines are needed! (See comment above).
  90009. e.preventDefault();
  90010. e.stopPropagation();
  90011. // Dispatch DROP event.
  90012. this.dispatch_(e);
  90013. }
  90014. };
  90015. // Copyright 2007 Bob Ippolito. All Rights Reserved.
  90016. // Modifications Copyright 2009 The Closure Library Authors. All Rights
  90017. // Reserved.
  90018. /**
  90019. * @license Portions of this code are from MochiKit, received by
  90020. * The Closure Authors under the MIT license. All other code is Copyright
  90021. * 2005-2009 The Closure Authors. All Rights Reserved.
  90022. */
  90023. /**
  90024. * @fileoverview Classes for tracking asynchronous operations and handling the
  90025. * results. The Deferred object here is patterned after the Deferred object in
  90026. * the Twisted python networking framework.
  90027. *
  90028. * See: http://twistedmatrix.com/projects/core/documentation/howto/defer.html
  90029. *
  90030. * Based on the Dojo code which in turn is based on the MochiKit code.
  90031. *
  90032. * @author arv@google.com (Erik Arvidsson)
  90033. * @author brenneman@google.com (Shawn Brenneman)
  90034. */
  90035. goog.provide('goog.async.Deferred');
  90036. goog.provide('goog.async.Deferred.AlreadyCalledError');
  90037. goog.provide('goog.async.Deferred.CanceledError');
  90038. goog.require('goog.Promise');
  90039. goog.require('goog.Thenable');
  90040. goog.require('goog.array');
  90041. goog.require('goog.asserts');
  90042. goog.require('goog.debug.Error');
  90043. /**
  90044. * A Deferred represents the result of an asynchronous operation. A Deferred
  90045. * instance has no result when it is created, and is "fired" (given an initial
  90046. * result) by calling {@code callback} or {@code errback}.
  90047. *
  90048. * Once fired, the result is passed through a sequence of callback functions
  90049. * registered with {@code addCallback} or {@code addErrback}. The functions may
  90050. * mutate the result before it is passed to the next function in the sequence.
  90051. *
  90052. * Callbacks and errbacks may be added at any time, including after the Deferred
  90053. * has been "fired". If there are no pending actions in the execution sequence
  90054. * of a fired Deferred, any new callback functions will be called with the last
  90055. * computed result. Adding a callback function is the only way to access the
  90056. * result of the Deferred.
  90057. *
  90058. * If a Deferred operation is canceled, an optional user-provided cancellation
  90059. * function is invoked which may perform any special cleanup, followed by firing
  90060. * the Deferred's errback sequence with a {@code CanceledError}. If the
  90061. * Deferred has already fired, cancellation is ignored.
  90062. *
  90063. * Deferreds may be templated to a specific type they produce using generics
  90064. * with syntax such as:
  90065. * <code>
  90066. * /** @type {goog.async.Deferred<string>} *&#47;
  90067. * var d = new goog.async.Deferred();
  90068. * // Compiler can infer that foo is a string.
  90069. * d.addCallback(function(foo) {...});
  90070. * d.callback('string'); // Checked to be passed a string
  90071. * </code>
  90072. * Since deferreds are often used to produce different values across a chain,
  90073. * the type information is not propagated across chains, but rather only
  90074. * associated with specifically cast objects.
  90075. *
  90076. * @param {Function=} opt_onCancelFunction A function that will be called if the
  90077. * Deferred is canceled. If provided, this function runs before the
  90078. * Deferred is fired with a {@code CanceledError}.
  90079. * @param {Object=} opt_defaultScope The default object context to call
  90080. * callbacks and errbacks in.
  90081. * @constructor
  90082. * @implements {goog.Thenable<VALUE>}
  90083. * @template VALUE
  90084. */
  90085. goog.async.Deferred = function(opt_onCancelFunction, opt_defaultScope) {
  90086. /**
  90087. * Entries in the sequence are arrays containing a callback, an errback, and
  90088. * an optional scope. The callback or errback in an entry may be null.
  90089. * @type {!Array<!Array>}
  90090. * @private
  90091. */
  90092. this.sequence_ = [];
  90093. /**
  90094. * Optional function that will be called if the Deferred is canceled.
  90095. * @type {Function|undefined}
  90096. * @private
  90097. */
  90098. this.onCancelFunction_ = opt_onCancelFunction;
  90099. /**
  90100. * The default scope to execute callbacks and errbacks in.
  90101. * @type {Object}
  90102. * @private
  90103. */
  90104. this.defaultScope_ = opt_defaultScope || null;
  90105. /**
  90106. * Whether the Deferred has been fired.
  90107. * @type {boolean}
  90108. * @private
  90109. */
  90110. this.fired_ = false;
  90111. /**
  90112. * Whether the last result in the execution sequence was an error.
  90113. * @type {boolean}
  90114. * @private
  90115. */
  90116. this.hadError_ = false;
  90117. /**
  90118. * The current Deferred result, updated as callbacks and errbacks are
  90119. * executed.
  90120. * @type {*}
  90121. * @private
  90122. */
  90123. this.result_ = undefined;
  90124. /**
  90125. * Whether the Deferred is blocked waiting on another Deferred to fire. If a
  90126. * callback or errback returns a Deferred as a result, the execution sequence
  90127. * is blocked until that Deferred result becomes available.
  90128. * @type {boolean}
  90129. * @private
  90130. */
  90131. this.blocked_ = false;
  90132. /**
  90133. * Whether this Deferred is blocking execution of another Deferred. If this
  90134. * instance was returned as a result in another Deferred's execution
  90135. * sequence,that other Deferred becomes blocked until this instance's
  90136. * execution sequence completes. No additional callbacks may be added to a
  90137. * Deferred once it is blocking another instance.
  90138. * @type {boolean}
  90139. * @private
  90140. */
  90141. this.blocking_ = false;
  90142. /**
  90143. * Whether the Deferred has been canceled without having a custom cancel
  90144. * function.
  90145. * @type {boolean}
  90146. * @private
  90147. */
  90148. this.silentlyCanceled_ = false;
  90149. /**
  90150. * If an error is thrown during Deferred execution with no errback to catch
  90151. * it, the error is rethrown after a timeout. Reporting the error after a
  90152. * timeout allows execution to continue in the calling context (empty when
  90153. * no error is scheduled).
  90154. * @type {number}
  90155. * @private
  90156. */
  90157. this.unhandledErrorId_ = 0;
  90158. /**
  90159. * If this Deferred was created by branch(), this will be the "parent"
  90160. * Deferred.
  90161. * @type {goog.async.Deferred}
  90162. * @private
  90163. */
  90164. this.parent_ = null;
  90165. /**
  90166. * The number of Deferred objects that have been branched off this one. This
  90167. * will be decremented whenever a branch is fired or canceled.
  90168. * @type {number}
  90169. * @private
  90170. */
  90171. this.branches_ = 0;
  90172. if (goog.async.Deferred.LONG_STACK_TRACES) {
  90173. /**
  90174. * Holds the stack trace at time of deferred creation if the JS engine
  90175. * provides the Error.captureStackTrace API.
  90176. * @private {?string}
  90177. */
  90178. this.constructorStack_ = null;
  90179. if (Error.captureStackTrace) {
  90180. var target = { stack: '' };
  90181. Error.captureStackTrace(target, goog.async.Deferred);
  90182. // Check if Error.captureStackTrace worked. It fails in gjstest.
  90183. if (typeof target.stack == 'string') {
  90184. // Remove first line and force stringify to prevent memory leak due to
  90185. // holding on to actual stack frames.
  90186. this.constructorStack_ = target.stack.replace(/^[^\n]*\n/, '');
  90187. }
  90188. }
  90189. }
  90190. };
  90191. /**
  90192. * @define {boolean} Whether unhandled errors should always get rethrown to the
  90193. * global scope. Defaults to the value of goog.DEBUG.
  90194. */
  90195. goog.define('goog.async.Deferred.STRICT_ERRORS', false);
  90196. /**
  90197. * @define {boolean} Whether to attempt to make stack traces long. Defaults to
  90198. * the value of goog.DEBUG.
  90199. */
  90200. goog.define('goog.async.Deferred.LONG_STACK_TRACES', false);
  90201. /**
  90202. * Cancels a Deferred that has not yet been fired, or is blocked on another
  90203. * deferred operation. If this Deferred is waiting for a blocking Deferred to
  90204. * fire, the blocking Deferred will also be canceled.
  90205. *
  90206. * If this Deferred was created by calling branch() on a parent Deferred with
  90207. * opt_propagateCancel set to true, the parent may also be canceled. If
  90208. * opt_deepCancel is set, cancel() will be called on the parent (as well as any
  90209. * other ancestors if the parent is also a branch). If one or more branches were
  90210. * created with opt_propagateCancel set to true, the parent will be canceled if
  90211. * cancel() is called on all of those branches.
  90212. *
  90213. * @param {boolean=} opt_deepCancel If true, cancels this Deferred's parent even
  90214. * if cancel() hasn't been called on some of the parent's branches. Has no
  90215. * effect on a branch without opt_propagateCancel set to true.
  90216. */
  90217. goog.async.Deferred.prototype.cancel = function(opt_deepCancel) {
  90218. if (!this.hasFired()) {
  90219. if (this.parent_) {
  90220. // Get rid of the parent reference before potentially running the parent's
  90221. // canceler function to ensure that this cancellation isn't
  90222. // double-counted.
  90223. var parent = this.parent_;
  90224. delete this.parent_;
  90225. if (opt_deepCancel) {
  90226. parent.cancel(opt_deepCancel);
  90227. } else {
  90228. parent.branchCancel_();
  90229. }
  90230. }
  90231. if (this.onCancelFunction_) {
  90232. // Call in user-specified scope.
  90233. this.onCancelFunction_.call(this.defaultScope_, this);
  90234. } else {
  90235. this.silentlyCanceled_ = true;
  90236. }
  90237. if (!this.hasFired()) {
  90238. this.errback(new goog.async.Deferred.CanceledError(this));
  90239. }
  90240. } else if (this.result_ instanceof goog.async.Deferred) {
  90241. this.result_.cancel();
  90242. }
  90243. };
  90244. /**
  90245. * Handle a single branch being canceled. Once all branches are canceled, this
  90246. * Deferred will be canceled as well.
  90247. *
  90248. * @private
  90249. */
  90250. goog.async.Deferred.prototype.branchCancel_ = function() {
  90251. this.branches_--;
  90252. if (this.branches_ <= 0) {
  90253. this.cancel();
  90254. }
  90255. };
  90256. /**
  90257. * Called after a blocking Deferred fires. Unblocks this Deferred and resumes
  90258. * its execution sequence.
  90259. *
  90260. * @param {boolean} isSuccess Whether the result is a success or an error.
  90261. * @param {*} res The result of the blocking Deferred.
  90262. * @private
  90263. */
  90264. goog.async.Deferred.prototype.continue_ = function(isSuccess, res) {
  90265. this.blocked_ = false;
  90266. this.updateResult_(isSuccess, res);
  90267. };
  90268. /**
  90269. * Updates the current result based on the success or failure of the last action
  90270. * in the execution sequence.
  90271. *
  90272. * @param {boolean} isSuccess Whether the new result is a success or an error.
  90273. * @param {*} res The result.
  90274. * @private
  90275. */
  90276. goog.async.Deferred.prototype.updateResult_ = function(isSuccess, res) {
  90277. this.fired_ = true;
  90278. this.result_ = res;
  90279. this.hadError_ = !isSuccess;
  90280. this.fire_();
  90281. };
  90282. /**
  90283. * Verifies that the Deferred has not yet been fired.
  90284. *
  90285. * @private
  90286. * @throws {Error} If this has already been fired.
  90287. */
  90288. goog.async.Deferred.prototype.check_ = function() {
  90289. if (this.hasFired()) {
  90290. if (!this.silentlyCanceled_) {
  90291. throw new goog.async.Deferred.AlreadyCalledError(this);
  90292. }
  90293. this.silentlyCanceled_ = false;
  90294. }
  90295. };
  90296. /**
  90297. * Fire the execution sequence for this Deferred by passing the starting result
  90298. * to the first registered callback.
  90299. * @param {VALUE=} opt_result The starting result.
  90300. */
  90301. goog.async.Deferred.prototype.callback = function(opt_result) {
  90302. this.check_();
  90303. this.assertNotDeferred_(opt_result);
  90304. this.updateResult_(true /* isSuccess */, opt_result);
  90305. };
  90306. /**
  90307. * Fire the execution sequence for this Deferred by passing the starting error
  90308. * result to the first registered errback.
  90309. * @param {*=} opt_result The starting error.
  90310. */
  90311. goog.async.Deferred.prototype.errback = function(opt_result) {
  90312. this.check_();
  90313. this.assertNotDeferred_(opt_result);
  90314. this.makeStackTraceLong_(opt_result);
  90315. this.updateResult_(false /* isSuccess */, opt_result);
  90316. };
  90317. /**
  90318. * Attempt to make the error's stack trace be long in that it contains the
  90319. * stack trace from the point where the deferred was created on top of the
  90320. * current stack trace to give additional context.
  90321. * @param {*} error
  90322. * @private
  90323. */
  90324. goog.async.Deferred.prototype.makeStackTraceLong_ = function(error) {
  90325. if (!goog.async.Deferred.LONG_STACK_TRACES) {
  90326. return;
  90327. }
  90328. if (this.constructorStack_ && goog.isObject(error) && error.stack &&
  90329. // Stack looks like it was system generated. See
  90330. // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  90331. (/^[^\n]+(\n [^\n]+)+/).test(error.stack)) {
  90332. error.stack = error.stack + '\nDEFERRED OPERATION:\n' +
  90333. this.constructorStack_;
  90334. }
  90335. };
  90336. /**
  90337. * Asserts that an object is not a Deferred.
  90338. * @param {*} obj The object to test.
  90339. * @throws {Error} Throws an exception if the object is a Deferred.
  90340. * @private
  90341. */
  90342. goog.async.Deferred.prototype.assertNotDeferred_ = function(obj) {
  90343. goog.asserts.assert(
  90344. !(obj instanceof goog.async.Deferred),
  90345. 'An execution sequence may not be initiated with a blocking Deferred.');
  90346. };
  90347. /**
  90348. * Register a callback function to be called with a successful result. If no
  90349. * value is returned by the callback function, the result value is unchanged. If
  90350. * a new value is returned, it becomes the Deferred result and will be passed to
  90351. * the next callback in the execution sequence.
  90352. *
  90353. * If the function throws an error, the error becomes the new result and will be
  90354. * passed to the next errback in the execution chain.
  90355. *
  90356. * If the function returns a Deferred, the execution sequence will be blocked
  90357. * until that Deferred fires. Its result will be passed to the next callback (or
  90358. * errback if it is an error result) in this Deferred's execution sequence.
  90359. *
  90360. * @param {!function(this:T,VALUE):?} cb The function to be called with a
  90361. * successful result.
  90362. * @param {T=} opt_scope An optional scope to call the callback in.
  90363. * @return {!goog.async.Deferred} This Deferred.
  90364. * @template T
  90365. */
  90366. goog.async.Deferred.prototype.addCallback = function(cb, opt_scope) {
  90367. return this.addCallbacks(cb, null, opt_scope);
  90368. };
  90369. /**
  90370. * Register a callback function to be called with an error result. If no value
  90371. * is returned by the function, the error result is unchanged. If a new error
  90372. * value is returned or thrown, that error becomes the Deferred result and will
  90373. * be passed to the next errback in the execution sequence.
  90374. *
  90375. * If the errback function handles the error by returning a non-error value,
  90376. * that result will be passed to the next normal callback in the sequence.
  90377. *
  90378. * If the function returns a Deferred, the execution sequence will be blocked
  90379. * until that Deferred fires. Its result will be passed to the next callback (or
  90380. * errback if it is an error result) in this Deferred's execution sequence.
  90381. *
  90382. * @param {!function(this:T,?):?} eb The function to be called on an
  90383. * unsuccessful result.
  90384. * @param {T=} opt_scope An optional scope to call the errback in.
  90385. * @return {!goog.async.Deferred<VALUE>} This Deferred.
  90386. * @template T
  90387. */
  90388. goog.async.Deferred.prototype.addErrback = function(eb, opt_scope) {
  90389. return this.addCallbacks(null, eb, opt_scope);
  90390. };
  90391. /**
  90392. * Registers one function as both a callback and errback.
  90393. *
  90394. * @param {!function(this:T,?):?} f The function to be called on any result.
  90395. * @param {T=} opt_scope An optional scope to call the function in.
  90396. * @return {!goog.async.Deferred} This Deferred.
  90397. * @template T
  90398. */
  90399. goog.async.Deferred.prototype.addBoth = function(f, opt_scope) {
  90400. return this.addCallbacks(f, f, opt_scope);
  90401. };
  90402. /**
  90403. * Like addBoth, but propagates uncaught exceptions in the errback.
  90404. *
  90405. * @param {function(this:T,?):?} f The function to be called on any result.
  90406. * @param {T=} opt_scope An optional scope to call the function in.
  90407. * @return {!goog.async.Deferred<VALUE>} This Deferred.
  90408. * @template T
  90409. */
  90410. goog.async.Deferred.prototype.addFinally = function(f, opt_scope) {
  90411. var self = this;
  90412. return this.addCallbacks(f, function(err) {
  90413. var result = f.call(self, err);
  90414. if (!goog.isDef(result)) {
  90415. throw err;
  90416. }
  90417. return result;
  90418. }, opt_scope);
  90419. };
  90420. /**
  90421. * Registers a callback function and an errback function at the same position
  90422. * in the execution sequence. Only one of these functions will execute,
  90423. * depending on the error state during the execution sequence.
  90424. *
  90425. * NOTE: This is not equivalent to {@code def.addCallback().addErrback()}! If
  90426. * the callback is invoked, the errback will be skipped, and vice versa.
  90427. *
  90428. * @param {?(function(this:T,VALUE):?)} cb The function to be called on a
  90429. * successful result.
  90430. * @param {?(function(this:T,?):?)} eb The function to be called on an
  90431. * unsuccessful result.
  90432. * @param {T=} opt_scope An optional scope to call the functions in.
  90433. * @return {!goog.async.Deferred} This Deferred.
  90434. * @template T
  90435. */
  90436. goog.async.Deferred.prototype.addCallbacks = function(cb, eb, opt_scope) {
  90437. goog.asserts.assert(!this.blocking_, 'Blocking Deferreds can not be re-used');
  90438. this.sequence_.push([cb, eb, opt_scope]);
  90439. if (this.hasFired()) {
  90440. this.fire_();
  90441. }
  90442. return this;
  90443. };
  90444. /**
  90445. * Implements {@see goog.Thenable} for seamless integration with
  90446. * {@see goog.Promise}.
  90447. * Deferred results are mutable and may represent multiple values over
  90448. * their lifetime. Calling {@code then} on a Deferred returns a Promise
  90449. * with the result of the Deferred at that point in its callback chain.
  90450. * Note that if the Deferred result is never mutated, and only
  90451. * {@code then} calls are made, the Deferred will behave like a Promise.
  90452. *
  90453. * @override
  90454. */
  90455. goog.async.Deferred.prototype.then = function(opt_onFulfilled, opt_onRejected,
  90456. opt_context) {
  90457. var resolve, reject;
  90458. var promise = new goog.Promise(function(res, rej) {
  90459. // Copying resolvers to outer scope, so that they are available when the
  90460. // deferred callback fires (which may be synchronous).
  90461. resolve = res;
  90462. reject = rej;
  90463. });
  90464. this.addCallbacks(resolve, function(reason) {
  90465. if (reason instanceof goog.async.Deferred.CanceledError) {
  90466. promise.cancel();
  90467. } else {
  90468. reject(reason);
  90469. }
  90470. });
  90471. return promise.then(opt_onFulfilled, opt_onRejected, opt_context);
  90472. };
  90473. goog.Thenable.addImplementation(goog.async.Deferred);
  90474. /**
  90475. * Links another Deferred to the end of this Deferred's execution sequence. The
  90476. * result of this execution sequence will be passed as the starting result for
  90477. * the chained Deferred, invoking either its first callback or errback.
  90478. *
  90479. * @param {!goog.async.Deferred} otherDeferred The Deferred to chain.
  90480. * @return {!goog.async.Deferred} This Deferred.
  90481. */
  90482. goog.async.Deferred.prototype.chainDeferred = function(otherDeferred) {
  90483. this.addCallbacks(
  90484. otherDeferred.callback, otherDeferred.errback, otherDeferred);
  90485. return this;
  90486. };
  90487. /**
  90488. * Makes this Deferred wait for another Deferred's execution sequence to
  90489. * complete before continuing.
  90490. *
  90491. * This is equivalent to adding a callback that returns {@code otherDeferred},
  90492. * but doesn't prevent additional callbacks from being added to
  90493. * {@code otherDeferred}.
  90494. *
  90495. * @param {!goog.async.Deferred|!goog.Thenable} otherDeferred The Deferred
  90496. * to wait for.
  90497. * @return {!goog.async.Deferred} This Deferred.
  90498. */
  90499. goog.async.Deferred.prototype.awaitDeferred = function(otherDeferred) {
  90500. if (!(otherDeferred instanceof goog.async.Deferred)) {
  90501. // The Thenable case.
  90502. return this.addCallback(function() {
  90503. return otherDeferred;
  90504. });
  90505. }
  90506. return this.addCallback(goog.bind(otherDeferred.branch, otherDeferred));
  90507. };
  90508. /**
  90509. * Creates a branch off this Deferred's execution sequence, and returns it as a
  90510. * new Deferred. The branched Deferred's starting result will be shared with the
  90511. * parent at the point of the branch, even if further callbacks are added to the
  90512. * parent.
  90513. *
  90514. * All branches at the same stage in the execution sequence will receive the
  90515. * same starting value.
  90516. *
  90517. * @param {boolean=} opt_propagateCancel If cancel() is called on every child
  90518. * branch created with opt_propagateCancel, the parent will be canceled as
  90519. * well.
  90520. * @return {!goog.async.Deferred<VALUE>} A Deferred that will be started with
  90521. * the computed result from this stage in the execution sequence.
  90522. */
  90523. goog.async.Deferred.prototype.branch = function(opt_propagateCancel) {
  90524. var d = new goog.async.Deferred();
  90525. this.chainDeferred(d);
  90526. if (opt_propagateCancel) {
  90527. d.parent_ = this;
  90528. this.branches_++;
  90529. }
  90530. return d;
  90531. };
  90532. /**
  90533. * @return {boolean} Whether the execution sequence has been started on this
  90534. * Deferred by invoking {@code callback} or {@code errback}.
  90535. */
  90536. goog.async.Deferred.prototype.hasFired = function() {
  90537. return this.fired_;
  90538. };
  90539. /**
  90540. * @param {*} res The latest result in the execution sequence.
  90541. * @return {boolean} Whether the current result is an error that should cause
  90542. * the next errback to fire. May be overridden by subclasses to handle
  90543. * special error types.
  90544. * @protected
  90545. */
  90546. goog.async.Deferred.prototype.isError = function(res) {
  90547. return res instanceof Error;
  90548. };
  90549. /**
  90550. * @return {boolean} Whether an errback exists in the remaining sequence.
  90551. * @private
  90552. */
  90553. goog.async.Deferred.prototype.hasErrback_ = function() {
  90554. return goog.array.some(this.sequence_, function(sequenceRow) {
  90555. // The errback is the second element in the array.
  90556. return goog.isFunction(sequenceRow[1]);
  90557. });
  90558. };
  90559. /**
  90560. * Exhausts the execution sequence while a result is available. The result may
  90561. * be modified by callbacks or errbacks, and execution will block if the
  90562. * returned result is an incomplete Deferred.
  90563. *
  90564. * @private
  90565. */
  90566. goog.async.Deferred.prototype.fire_ = function() {
  90567. if (this.unhandledErrorId_ && this.hasFired() && this.hasErrback_()) {
  90568. // It is possible to add errbacks after the Deferred has fired. If a new
  90569. // errback is added immediately after the Deferred encountered an unhandled
  90570. // error, but before that error is rethrown, the error is unscheduled.
  90571. goog.async.Deferred.unscheduleError_(this.unhandledErrorId_);
  90572. this.unhandledErrorId_ = 0;
  90573. }
  90574. if (this.parent_) {
  90575. this.parent_.branches_--;
  90576. delete this.parent_;
  90577. }
  90578. var res = this.result_;
  90579. var unhandledException = false;
  90580. var isNewlyBlocked = false;
  90581. while (this.sequence_.length && !this.blocked_) {
  90582. var sequenceEntry = this.sequence_.shift();
  90583. var callback = sequenceEntry[0];
  90584. var errback = sequenceEntry[1];
  90585. var scope = sequenceEntry[2];
  90586. var f = this.hadError_ ? errback : callback;
  90587. if (f) {
  90588. /** @preserveTry */
  90589. try {
  90590. var ret = f.call(scope || this.defaultScope_, res);
  90591. // If no result, then use previous result.
  90592. if (goog.isDef(ret)) {
  90593. // Bubble up the error as long as the return value hasn't changed.
  90594. this.hadError_ = this.hadError_ && (ret == res || this.isError(ret));
  90595. this.result_ = res = ret;
  90596. }
  90597. if (goog.Thenable.isImplementedBy(res) ||
  90598. (typeof goog.global['Promise'] === 'function' &&
  90599. res instanceof goog.global['Promise'])) {
  90600. isNewlyBlocked = true;
  90601. this.blocked_ = true;
  90602. }
  90603. } catch (ex) {
  90604. res = ex;
  90605. this.hadError_ = true;
  90606. this.makeStackTraceLong_(res);
  90607. if (!this.hasErrback_()) {
  90608. // If an error is thrown with no additional errbacks in the queue,
  90609. // prepare to rethrow the error.
  90610. unhandledException = true;
  90611. }
  90612. }
  90613. }
  90614. }
  90615. this.result_ = res;
  90616. if (isNewlyBlocked) {
  90617. var onCallback = goog.bind(this.continue_, this, true /* isSuccess */);
  90618. var onErrback = goog.bind(this.continue_, this, false /* isSuccess */);
  90619. if (res instanceof goog.async.Deferred) {
  90620. res.addCallbacks(onCallback, onErrback);
  90621. res.blocking_ = true;
  90622. } else {
  90623. res.then(onCallback, onErrback);
  90624. }
  90625. } else if (goog.async.Deferred.STRICT_ERRORS && this.isError(res) &&
  90626. !(res instanceof goog.async.Deferred.CanceledError)) {
  90627. this.hadError_ = true;
  90628. unhandledException = true;
  90629. }
  90630. if (unhandledException) {
  90631. // Rethrow the unhandled error after a timeout. Execution will continue, but
  90632. // the error will be seen by global handlers and the user. The throw will
  90633. // be canceled if another errback is appended before the timeout executes.
  90634. // The error's original stack trace is preserved where available.
  90635. this.unhandledErrorId_ = goog.async.Deferred.scheduleError_(res);
  90636. }
  90637. };
  90638. /**
  90639. * Creates a Deferred that has an initial result.
  90640. *
  90641. * @param {*=} opt_result The result.
  90642. * @return {!goog.async.Deferred} The new Deferred.
  90643. */
  90644. goog.async.Deferred.succeed = function(opt_result) {
  90645. var d = new goog.async.Deferred();
  90646. d.callback(opt_result);
  90647. return d;
  90648. };
  90649. /**
  90650. * Creates a Deferred that fires when the given promise resolves.
  90651. * Use only during migration to Promises.
  90652. *
  90653. * @param {!goog.Promise<T>} promise
  90654. * @return {!goog.async.Deferred<T>} The new Deferred.
  90655. * @template T
  90656. */
  90657. goog.async.Deferred.fromPromise = function(promise) {
  90658. var d = new goog.async.Deferred();
  90659. d.callback();
  90660. d.addCallback(function() {
  90661. return promise;
  90662. });
  90663. return d;
  90664. };
  90665. /**
  90666. * Creates a Deferred that has an initial error result.
  90667. *
  90668. * @param {*} res The error result.
  90669. * @return {!goog.async.Deferred} The new Deferred.
  90670. */
  90671. goog.async.Deferred.fail = function(res) {
  90672. var d = new goog.async.Deferred();
  90673. d.errback(res);
  90674. return d;
  90675. };
  90676. /**
  90677. * Creates a Deferred that has already been canceled.
  90678. *
  90679. * @return {!goog.async.Deferred} The new Deferred.
  90680. */
  90681. goog.async.Deferred.canceled = function() {
  90682. var d = new goog.async.Deferred();
  90683. d.cancel();
  90684. return d;
  90685. };
  90686. /**
  90687. * Normalizes values that may or may not be Deferreds.
  90688. *
  90689. * If the input value is a Deferred, the Deferred is branched (so the original
  90690. * execution sequence is not modified) and the input callback added to the new
  90691. * branch. The branch is returned to the caller.
  90692. *
  90693. * If the input value is not a Deferred, the callback will be executed
  90694. * immediately and an already firing Deferred will be returned to the caller.
  90695. *
  90696. * In the following (contrived) example, if <code>isImmediate</code> is true
  90697. * then 3 is alerted immediately, otherwise 6 is alerted after a 2-second delay.
  90698. *
  90699. * <pre>
  90700. * var value;
  90701. * if (isImmediate) {
  90702. * value = 3;
  90703. * } else {
  90704. * value = new goog.async.Deferred();
  90705. * setTimeout(function() { value.callback(6); }, 2000);
  90706. * }
  90707. *
  90708. * var d = goog.async.Deferred.when(value, alert);
  90709. * </pre>
  90710. *
  90711. * @param {*} value Deferred or normal value to pass to the callback.
  90712. * @param {!function(this:T, ?):?} callback The callback to execute.
  90713. * @param {T=} opt_scope An optional scope to call the callback in.
  90714. * @return {!goog.async.Deferred} A new Deferred that will call the input
  90715. * callback with the input value.
  90716. * @template T
  90717. */
  90718. goog.async.Deferred.when = function(value, callback, opt_scope) {
  90719. if (value instanceof goog.async.Deferred) {
  90720. return value.branch(true).addCallback(callback, opt_scope);
  90721. } else {
  90722. return goog.async.Deferred.succeed(value).addCallback(callback, opt_scope);
  90723. }
  90724. };
  90725. /**
  90726. * An error sub class that is used when a Deferred has already been called.
  90727. * @param {!goog.async.Deferred} deferred The Deferred.
  90728. *
  90729. * @constructor
  90730. * @extends {goog.debug.Error}
  90731. */
  90732. goog.async.Deferred.AlreadyCalledError = function(deferred) {
  90733. goog.debug.Error.call(this);
  90734. /**
  90735. * The Deferred that raised this error.
  90736. * @type {goog.async.Deferred}
  90737. */
  90738. this.deferred = deferred;
  90739. };
  90740. goog.inherits(goog.async.Deferred.AlreadyCalledError, goog.debug.Error);
  90741. /** @override */
  90742. goog.async.Deferred.AlreadyCalledError.prototype.message =
  90743. 'Deferred has already fired';
  90744. /** @override */
  90745. goog.async.Deferred.AlreadyCalledError.prototype.name = 'AlreadyCalledError';
  90746. /**
  90747. * An error sub class that is used when a Deferred is canceled.
  90748. *
  90749. * @param {!goog.async.Deferred} deferred The Deferred object.
  90750. * @constructor
  90751. * @extends {goog.debug.Error}
  90752. */
  90753. goog.async.Deferred.CanceledError = function(deferred) {
  90754. goog.debug.Error.call(this);
  90755. /**
  90756. * The Deferred that raised this error.
  90757. * @type {goog.async.Deferred}
  90758. */
  90759. this.deferred = deferred;
  90760. };
  90761. goog.inherits(goog.async.Deferred.CanceledError, goog.debug.Error);
  90762. /** @override */
  90763. goog.async.Deferred.CanceledError.prototype.message = 'Deferred was canceled';
  90764. /** @override */
  90765. goog.async.Deferred.CanceledError.prototype.name = 'CanceledError';
  90766. /**
  90767. * Wrapper around errors that are scheduled to be thrown by failing deferreds
  90768. * after a timeout.
  90769. *
  90770. * @param {*} error Error from a failing deferred.
  90771. * @constructor
  90772. * @final
  90773. * @private
  90774. * @struct
  90775. */
  90776. goog.async.Deferred.Error_ = function(error) {
  90777. /** @const @private {number} */
  90778. this.id_ = goog.global.setTimeout(goog.bind(this.throwError, this), 0);
  90779. /** @const @private {*} */
  90780. this.error_ = error;
  90781. };
  90782. /**
  90783. * Actually throws the error and removes it from the list of pending
  90784. * deferred errors.
  90785. */
  90786. goog.async.Deferred.Error_.prototype.throwError = function() {
  90787. goog.asserts.assert(goog.async.Deferred.errorMap_[this.id_],
  90788. 'Cannot throw an error that is not scheduled.');
  90789. delete goog.async.Deferred.errorMap_[this.id_];
  90790. throw this.error_;
  90791. };
  90792. /**
  90793. * Resets the error throw timer.
  90794. */
  90795. goog.async.Deferred.Error_.prototype.resetTimer = function() {
  90796. goog.global.clearTimeout(this.id_);
  90797. };
  90798. /**
  90799. * Map of unhandled errors scheduled to be rethrown in a future timestep.
  90800. * @private {!Object<number|string, goog.async.Deferred.Error_>}
  90801. */
  90802. goog.async.Deferred.errorMap_ = {};
  90803. /**
  90804. * Schedules an error to be thrown after a delay.
  90805. * @param {*} error Error from a failing deferred.
  90806. * @return {number} Id of the error.
  90807. * @private
  90808. */
  90809. goog.async.Deferred.scheduleError_ = function(error) {
  90810. var deferredError = new goog.async.Deferred.Error_(error);
  90811. goog.async.Deferred.errorMap_[deferredError.id_] = deferredError;
  90812. return deferredError.id_;
  90813. };
  90814. /**
  90815. * Unschedules an error from being thrown.
  90816. * @param {number} id Id of the deferred error to unschedule.
  90817. * @private
  90818. */
  90819. goog.async.Deferred.unscheduleError_ = function(id) {
  90820. var error = goog.async.Deferred.errorMap_[id];
  90821. if (error) {
  90822. error.resetTimer();
  90823. delete goog.async.Deferred.errorMap_[id];
  90824. }
  90825. };
  90826. /**
  90827. * Asserts that there are no pending deferred errors. If there are any
  90828. * scheduled errors, one will be thrown immediately to make this function fail.
  90829. */
  90830. goog.async.Deferred.assertNoErrors = function() {
  90831. var map = goog.async.Deferred.errorMap_;
  90832. for (var key in map) {
  90833. var error = map[key];
  90834. error.resetTimer();
  90835. error.throwError();
  90836. }
  90837. };
  90838. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  90839. //
  90840. // Licensed under the Apache License, Version 2.0 (the "License");
  90841. // you may not use this file except in compliance with the License.
  90842. // You may obtain a copy of the License at
  90843. //
  90844. // http://www.apache.org/licenses/LICENSE-2.0
  90845. //
  90846. // Unless required by applicable law or agreed to in writing, software
  90847. // distributed under the License is distributed on an "AS-IS" BASIS,
  90848. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  90849. // See the License for the specific language governing permissions and
  90850. // limitations under the License.
  90851. /**
  90852. * @fileoverview A wrapper for the HTML5 FileError object.
  90853. *
  90854. */
  90855. goog.provide('goog.fs.Error');
  90856. goog.provide('goog.fs.Error.ErrorCode');
  90857. goog.require('goog.debug.Error');
  90858. goog.require('goog.object');
  90859. goog.require('goog.string');
  90860. /**
  90861. * A filesystem error. Since the filesystem API is asynchronous, stack traces
  90862. * are less useful for identifying where errors come from, so this includes a
  90863. * large amount of metadata in the message.
  90864. *
  90865. * @param {!DOMError} error
  90866. * @param {string} action The action being undertaken when the error was raised.
  90867. * @constructor
  90868. * @extends {goog.debug.Error}
  90869. * @final
  90870. */
  90871. goog.fs.Error = function(error, action) {
  90872. /** @type {string} */
  90873. this.name;
  90874. /**
  90875. * @type {goog.fs.Error.ErrorCode}
  90876. * @deprecated Use the 'name' or 'message' field instead.
  90877. */
  90878. this.code;
  90879. if (goog.isDef(error.name)) {
  90880. this.name = error.name;
  90881. // TODO(user): Remove warning suppression after JSCompiler stops
  90882. // firing a spurious warning here.
  90883. /** @suppress {deprecated} */
  90884. this.code = goog.fs.Error.getCodeFromName_(error.name);
  90885. } else {
  90886. this.code = error.code;
  90887. this.name = goog.fs.Error.getNameFromCode_(error.code);
  90888. }
  90889. goog.fs.Error.base(this, 'constructor',
  90890. goog.string.subs('%s %s', this.name, action));
  90891. };
  90892. goog.inherits(goog.fs.Error, goog.debug.Error);
  90893. /**
  90894. * Names of errors that may be thrown by the File API, the File System API, or
  90895. * the File Writer API.
  90896. *
  90897. * @see http://dev.w3.org/2006/webapi/FileAPI/#ErrorAndException
  90898. * @see http://www.w3.org/TR/file-system-api/#definitions
  90899. * @see http://dev.w3.org/2009/dap/file-system/file-writer.html#definitions
  90900. * @enum {string}
  90901. */
  90902. goog.fs.Error.ErrorName = {
  90903. ABORT: 'AbortError',
  90904. ENCODING: 'EncodingError',
  90905. INVALID_MODIFICATION: 'InvalidModificationError',
  90906. INVALID_STATE: 'InvalidStateError',
  90907. NOT_FOUND: 'NotFoundError',
  90908. NOT_READABLE: 'NotReadableError',
  90909. NO_MODIFICATION_ALLOWED: 'NoModificationAllowedError',
  90910. PATH_EXISTS: 'PathExistsError',
  90911. QUOTA_EXCEEDED: 'QuotaExceededError',
  90912. SECURITY: 'SecurityError',
  90913. SYNTAX: 'SyntaxError',
  90914. TYPE_MISMATCH: 'TypeMismatchError'
  90915. };
  90916. /**
  90917. * Error codes for file errors.
  90918. * @see http://www.w3.org/TR/file-system-api/#idl-def-FileException
  90919. *
  90920. * @enum {number}
  90921. * @deprecated Use the 'name' or 'message' attribute instead.
  90922. */
  90923. goog.fs.Error.ErrorCode = {
  90924. NOT_FOUND: 1,
  90925. SECURITY: 2,
  90926. ABORT: 3,
  90927. NOT_READABLE: 4,
  90928. ENCODING: 5,
  90929. NO_MODIFICATION_ALLOWED: 6,
  90930. INVALID_STATE: 7,
  90931. SYNTAX: 8,
  90932. INVALID_MODIFICATION: 9,
  90933. QUOTA_EXCEEDED: 10,
  90934. TYPE_MISMATCH: 11,
  90935. PATH_EXISTS: 12
  90936. };
  90937. /**
  90938. * @param {goog.fs.Error.ErrorCode} code
  90939. * @return {string} name
  90940. * @private
  90941. */
  90942. goog.fs.Error.getNameFromCode_ = function(code) {
  90943. var name = goog.object.findKey(goog.fs.Error.NameToCodeMap_, function(c) {
  90944. return code == c;
  90945. });
  90946. if (!goog.isDef(name)) {
  90947. throw new Error('Invalid code: ' + code);
  90948. }
  90949. return name;
  90950. };
  90951. /**
  90952. * Returns the code that corresponds to the given name.
  90953. * @param {string} name
  90954. * @return {goog.fs.Error.ErrorCode} code
  90955. * @private
  90956. */
  90957. goog.fs.Error.getCodeFromName_ = function(name) {
  90958. return goog.fs.Error.NameToCodeMap_[name];
  90959. };
  90960. /**
  90961. * Mapping from error names to values from the ErrorCode enum.
  90962. * @see http://www.w3.org/TR/file-system-api/#definitions.
  90963. * @private {!Object<string, goog.fs.Error.ErrorCode>}
  90964. */
  90965. goog.fs.Error.NameToCodeMap_ = goog.object.create(
  90966. goog.fs.Error.ErrorName.ABORT,
  90967. goog.fs.Error.ErrorCode.ABORT,
  90968. goog.fs.Error.ErrorName.ENCODING,
  90969. goog.fs.Error.ErrorCode.ENCODING,
  90970. goog.fs.Error.ErrorName.INVALID_MODIFICATION,
  90971. goog.fs.Error.ErrorCode.INVALID_MODIFICATION,
  90972. goog.fs.Error.ErrorName.INVALID_STATE,
  90973. goog.fs.Error.ErrorCode.INVALID_STATE,
  90974. goog.fs.Error.ErrorName.NOT_FOUND,
  90975. goog.fs.Error.ErrorCode.NOT_FOUND,
  90976. goog.fs.Error.ErrorName.NOT_READABLE,
  90977. goog.fs.Error.ErrorCode.NOT_READABLE,
  90978. goog.fs.Error.ErrorName.NO_MODIFICATION_ALLOWED,
  90979. goog.fs.Error.ErrorCode.NO_MODIFICATION_ALLOWED,
  90980. goog.fs.Error.ErrorName.PATH_EXISTS,
  90981. goog.fs.Error.ErrorCode.PATH_EXISTS,
  90982. goog.fs.Error.ErrorName.QUOTA_EXCEEDED,
  90983. goog.fs.Error.ErrorCode.QUOTA_EXCEEDED,
  90984. goog.fs.Error.ErrorName.SECURITY,
  90985. goog.fs.Error.ErrorCode.SECURITY,
  90986. goog.fs.Error.ErrorName.SYNTAX,
  90987. goog.fs.Error.ErrorCode.SYNTAX,
  90988. goog.fs.Error.ErrorName.TYPE_MISMATCH,
  90989. goog.fs.Error.ErrorCode.TYPE_MISMATCH);
  90990. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  90991. //
  90992. // Licensed under the Apache License, Version 2.0 (the "License");
  90993. // you may not use this file except in compliance with the License.
  90994. // You may obtain a copy of the License at
  90995. //
  90996. // http://www.apache.org/licenses/LICENSE-2.0
  90997. //
  90998. // Unless required by applicable law or agreed to in writing, software
  90999. // distributed under the License is distributed on an "AS-IS" BASIS,
  91000. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  91001. // See the License for the specific language governing permissions and
  91002. // limitations under the License.
  91003. /**
  91004. * @fileoverview A wrapper for the HTML5 File ProgressEvent objects.
  91005. *
  91006. */
  91007. goog.provide('goog.fs.ProgressEvent');
  91008. goog.require('goog.events.Event');
  91009. /**
  91010. * A wrapper for the progress events emitted by the File APIs.
  91011. *
  91012. * @param {!ProgressEvent} event The underlying event object.
  91013. * @param {!Object} target The file access object emitting the event.
  91014. * @extends {goog.events.Event}
  91015. * @constructor
  91016. * @final
  91017. */
  91018. goog.fs.ProgressEvent = function(event, target) {
  91019. goog.fs.ProgressEvent.base(this, 'constructor', event.type, target);
  91020. /**
  91021. * The underlying event object.
  91022. * @type {!ProgressEvent}
  91023. * @private
  91024. */
  91025. this.event_ = event;
  91026. };
  91027. goog.inherits(goog.fs.ProgressEvent, goog.events.Event);
  91028. /**
  91029. * @return {boolean} Whether or not the total size of the of the file being
  91030. * saved is known.
  91031. */
  91032. goog.fs.ProgressEvent.prototype.isLengthComputable = function() {
  91033. return this.event_.lengthComputable;
  91034. };
  91035. /**
  91036. * @return {number} The number of bytes saved so far.
  91037. */
  91038. goog.fs.ProgressEvent.prototype.getLoaded = function() {
  91039. return this.event_.loaded;
  91040. };
  91041. /**
  91042. * @return {number} The total number of bytes in the file being saved.
  91043. */
  91044. goog.fs.ProgressEvent.prototype.getTotal = function() {
  91045. return this.event_.total;
  91046. };
  91047. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  91048. //
  91049. // Licensed under the Apache License, Version 2.0 (the "License");
  91050. // you may not use this file except in compliance with the License.
  91051. // You may obtain a copy of the License at
  91052. //
  91053. // http://www.apache.org/licenses/LICENSE-2.0
  91054. //
  91055. // Unless required by applicable law or agreed to in writing, software
  91056. // distributed under the License is distributed on an "AS-IS" BASIS,
  91057. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  91058. // See the License for the specific language governing permissions and
  91059. // limitations under the License.
  91060. /**
  91061. * @fileoverview A wrapper for the HTML5 FileReader object.
  91062. *
  91063. */
  91064. goog.provide('goog.fs.FileReader');
  91065. goog.provide('goog.fs.FileReader.EventType');
  91066. goog.provide('goog.fs.FileReader.ReadyState');
  91067. goog.require('goog.async.Deferred');
  91068. goog.require('goog.events.EventTarget');
  91069. goog.require('goog.fs.Error');
  91070. goog.require('goog.fs.ProgressEvent');
  91071. /**
  91072. * An object for monitoring the reading of files. This emits ProgressEvents of
  91073. * the types listed in {@link goog.fs.FileReader.EventType}.
  91074. *
  91075. * @constructor
  91076. * @extends {goog.events.EventTarget}
  91077. * @final
  91078. */
  91079. goog.fs.FileReader = function() {
  91080. goog.fs.FileReader.base(this, 'constructor');
  91081. /**
  91082. * The underlying FileReader object.
  91083. *
  91084. * @type {!FileReader}
  91085. * @private
  91086. */
  91087. this.reader_ = new FileReader();
  91088. this.reader_.onloadstart = goog.bind(this.dispatchProgressEvent_, this);
  91089. this.reader_.onprogress = goog.bind(this.dispatchProgressEvent_, this);
  91090. this.reader_.onload = goog.bind(this.dispatchProgressEvent_, this);
  91091. this.reader_.onabort = goog.bind(this.dispatchProgressEvent_, this);
  91092. this.reader_.onerror = goog.bind(this.dispatchProgressEvent_, this);
  91093. this.reader_.onloadend = goog.bind(this.dispatchProgressEvent_, this);
  91094. };
  91095. goog.inherits(goog.fs.FileReader, goog.events.EventTarget);
  91096. /**
  91097. * Possible states for a FileReader.
  91098. *
  91099. * @enum {number}
  91100. */
  91101. goog.fs.FileReader.ReadyState = {
  91102. /**
  91103. * The object has been constructed, but there is no pending read.
  91104. */
  91105. INIT: 0,
  91106. /**
  91107. * Data is being read.
  91108. */
  91109. LOADING: 1,
  91110. /**
  91111. * The data has been read from the file, the read was aborted, or an error
  91112. * occurred.
  91113. */
  91114. DONE: 2
  91115. };
  91116. /**
  91117. * Events emitted by a FileReader.
  91118. *
  91119. * @enum {string}
  91120. */
  91121. goog.fs.FileReader.EventType = {
  91122. /**
  91123. * Emitted when the reading begins. readyState will be LOADING.
  91124. */
  91125. LOAD_START: 'loadstart',
  91126. /**
  91127. * Emitted when progress has been made in reading the file. readyState will be
  91128. * LOADING.
  91129. */
  91130. PROGRESS: 'progress',
  91131. /**
  91132. * Emitted when the data has been successfully read. readyState will be
  91133. * LOADING.
  91134. */
  91135. LOAD: 'load',
  91136. /**
  91137. * Emitted when the reading has been aborted. readyState will be LOADING.
  91138. */
  91139. ABORT: 'abort',
  91140. /**
  91141. * Emitted when an error is encountered or the reading has been aborted.
  91142. * readyState will be LOADING.
  91143. */
  91144. ERROR: 'error',
  91145. /**
  91146. * Emitted when the reading is finished, whether successfully or not.
  91147. * readyState will be DONE.
  91148. */
  91149. LOAD_END: 'loadend'
  91150. };
  91151. /**
  91152. * Abort the reading of the file.
  91153. */
  91154. goog.fs.FileReader.prototype.abort = function() {
  91155. try {
  91156. this.reader_.abort();
  91157. } catch (e) {
  91158. throw new goog.fs.Error(e, 'aborting read');
  91159. }
  91160. };
  91161. /**
  91162. * @return {goog.fs.FileReader.ReadyState} The current state of the FileReader.
  91163. */
  91164. goog.fs.FileReader.prototype.getReadyState = function() {
  91165. return /** @type {goog.fs.FileReader.ReadyState} */ (this.reader_.readyState);
  91166. };
  91167. /**
  91168. * @return {*} The result of the file read.
  91169. */
  91170. goog.fs.FileReader.prototype.getResult = function() {
  91171. return this.reader_.result;
  91172. };
  91173. /**
  91174. * @return {goog.fs.Error} The error encountered while reading, if any.
  91175. */
  91176. goog.fs.FileReader.prototype.getError = function() {
  91177. return this.reader_.error &&
  91178. new goog.fs.Error(this.reader_.error, 'reading file');
  91179. };
  91180. /**
  91181. * Wrap a progress event emitted by the underlying file reader and re-emit it.
  91182. *
  91183. * @param {!ProgressEvent} event The underlying event.
  91184. * @private
  91185. */
  91186. goog.fs.FileReader.prototype.dispatchProgressEvent_ = function(event) {
  91187. this.dispatchEvent(new goog.fs.ProgressEvent(event, this));
  91188. };
  91189. /** @override */
  91190. goog.fs.FileReader.prototype.disposeInternal = function() {
  91191. goog.fs.FileReader.base(this, 'disposeInternal');
  91192. delete this.reader_;
  91193. };
  91194. /**
  91195. * Starts reading a blob as a binary string.
  91196. * @param {!Blob} blob The blob to read.
  91197. */
  91198. goog.fs.FileReader.prototype.readAsBinaryString = function(blob) {
  91199. this.reader_.readAsBinaryString(blob);
  91200. };
  91201. /**
  91202. * Reads a blob as a binary string.
  91203. * @param {!Blob} blob The blob to read.
  91204. * @return {!goog.async.Deferred} The deferred Blob contents as a binary string.
  91205. * If an error occurs, the errback is called with a {@link goog.fs.Error}.
  91206. */
  91207. goog.fs.FileReader.readAsBinaryString = function(blob) {
  91208. var reader = new goog.fs.FileReader();
  91209. var d = goog.fs.FileReader.createDeferred_(reader);
  91210. reader.readAsBinaryString(blob);
  91211. return d;
  91212. };
  91213. /**
  91214. * Starts reading a blob as an array buffer.
  91215. * @param {!Blob} blob The blob to read.
  91216. */
  91217. goog.fs.FileReader.prototype.readAsArrayBuffer = function(blob) {
  91218. this.reader_.readAsArrayBuffer(blob);
  91219. };
  91220. /**
  91221. * Reads a blob as an array buffer.
  91222. * @param {!Blob} blob The blob to read.
  91223. * @return {!goog.async.Deferred} The deferred Blob contents as an array buffer.
  91224. * If an error occurs, the errback is called with a {@link goog.fs.Error}.
  91225. */
  91226. goog.fs.FileReader.readAsArrayBuffer = function(blob) {
  91227. var reader = new goog.fs.FileReader();
  91228. var d = goog.fs.FileReader.createDeferred_(reader);
  91229. reader.readAsArrayBuffer(blob);
  91230. return d;
  91231. };
  91232. /**
  91233. * Starts reading a blob as text.
  91234. * @param {!Blob} blob The blob to read.
  91235. * @param {string=} opt_encoding The name of the encoding to use.
  91236. */
  91237. goog.fs.FileReader.prototype.readAsText = function(blob, opt_encoding) {
  91238. this.reader_.readAsText(blob, opt_encoding);
  91239. };
  91240. /**
  91241. * Reads a blob as text.
  91242. * @param {!Blob} blob The blob to read.
  91243. * @param {string=} opt_encoding The name of the encoding to use.
  91244. * @return {!goog.async.Deferred} The deferred Blob contents as text.
  91245. * If an error occurs, the errback is called with a {@link goog.fs.Error}.
  91246. */
  91247. goog.fs.FileReader.readAsText = function(blob, opt_encoding) {
  91248. var reader = new goog.fs.FileReader();
  91249. var d = goog.fs.FileReader.createDeferred_(reader);
  91250. reader.readAsText(blob, opt_encoding);
  91251. return d;
  91252. };
  91253. /**
  91254. * Starts reading a blob as a data URL.
  91255. * @param {!Blob} blob The blob to read.
  91256. */
  91257. goog.fs.FileReader.prototype.readAsDataUrl = function(blob) {
  91258. this.reader_.readAsDataURL(blob);
  91259. };
  91260. /**
  91261. * Reads a blob as a data URL.
  91262. * @param {!Blob} blob The blob to read.
  91263. * @return {!goog.async.Deferred} The deferred Blob contents as a data URL.
  91264. * If an error occurs, the errback is called with a {@link goog.fs.Error}.
  91265. */
  91266. goog.fs.FileReader.readAsDataUrl = function(blob) {
  91267. var reader = new goog.fs.FileReader();
  91268. var d = goog.fs.FileReader.createDeferred_(reader);
  91269. reader.readAsDataUrl(blob);
  91270. return d;
  91271. };
  91272. /**
  91273. * Creates a new deferred object for the results of a read method.
  91274. * @param {goog.fs.FileReader} reader The reader to create a deferred for.
  91275. * @return {!goog.async.Deferred} The deferred results.
  91276. * @private
  91277. */
  91278. goog.fs.FileReader.createDeferred_ = function(reader) {
  91279. var deferred = new goog.async.Deferred();
  91280. reader.listen(goog.fs.FileReader.EventType.LOAD_END,
  91281. goog.partial(function(d, r, e) {
  91282. var result = r.getResult();
  91283. var error = r.getError();
  91284. if (result != null && !error) {
  91285. d.callback(result);
  91286. } else {
  91287. d.errback(error);
  91288. }
  91289. r.dispose();
  91290. }, deferred, reader));
  91291. return deferred;
  91292. };
  91293. // FIXME should handle all geo-referenced data, not just vector data
  91294. goog.provide('ol.interaction.DragAndDrop');
  91295. goog.provide('ol.interaction.DragAndDropEvent');
  91296. goog.require('goog.asserts');
  91297. goog.require('goog.events');
  91298. goog.require('goog.events.Event');
  91299. goog.require('goog.events.FileDropHandler');
  91300. goog.require('goog.events.FileDropHandler.EventType');
  91301. goog.require('goog.fs.FileReader');
  91302. goog.require('goog.functions');
  91303. goog.require('ol.interaction.Interaction');
  91304. goog.require('ol.proj');
  91305. /**
  91306. * @classdesc
  91307. * Handles input of vector data by drag and drop.
  91308. *
  91309. * @constructor
  91310. * @extends {ol.interaction.Interaction}
  91311. * @fires ol.interaction.DragAndDropEvent
  91312. * @param {olx.interaction.DragAndDropOptions=} opt_options Options.
  91313. * @api stable
  91314. */
  91315. ol.interaction.DragAndDrop = function(opt_options) {
  91316. var options = opt_options ? opt_options : {};
  91317. goog.base(this, {
  91318. handleEvent: ol.interaction.DragAndDrop.handleEvent
  91319. });
  91320. /**
  91321. * @private
  91322. * @type {Array.<function(new: ol.format.Feature)>}
  91323. */
  91324. this.formatConstructors_ = options.formatConstructors ?
  91325. options.formatConstructors : [];
  91326. /**
  91327. * @private
  91328. * @type {ol.proj.Projection}
  91329. */
  91330. this.projection_ = options.projection ?
  91331. ol.proj.get(options.projection) : null;
  91332. /**
  91333. * @private
  91334. * @type {goog.events.FileDropHandler}
  91335. */
  91336. this.fileDropHandler_ = null;
  91337. /**
  91338. * @private
  91339. * @type {goog.events.Key|undefined}
  91340. */
  91341. this.dropListenKey_ = undefined;
  91342. };
  91343. goog.inherits(ol.interaction.DragAndDrop, ol.interaction.Interaction);
  91344. /**
  91345. * @inheritDoc
  91346. */
  91347. ol.interaction.DragAndDrop.prototype.disposeInternal = function() {
  91348. if (this.dropListenKey_) {
  91349. goog.events.unlistenByKey(this.dropListenKey_);
  91350. }
  91351. goog.base(this, 'disposeInternal');
  91352. };
  91353. /**
  91354. * @param {goog.events.BrowserEvent} event Event.
  91355. * @private
  91356. */
  91357. ol.interaction.DragAndDrop.prototype.handleDrop_ = function(event) {
  91358. var files = event.getBrowserEvent().dataTransfer.files;
  91359. var i, ii, file;
  91360. for (i = 0, ii = files.length; i < ii; ++i) {
  91361. file = files[i];
  91362. // The empty string param is a workaround for
  91363. // https://code.google.com/p/closure-library/issues/detail?id=524
  91364. var reader = goog.fs.FileReader.readAsText(file, '');
  91365. reader.addCallback(goog.partial(this.handleResult_, file), this);
  91366. }
  91367. };
  91368. /**
  91369. * @param {File} file File.
  91370. * @param {string} result Result.
  91371. * @private
  91372. */
  91373. ol.interaction.DragAndDrop.prototype.handleResult_ = function(file, result) {
  91374. var map = this.getMap();
  91375. goog.asserts.assert(map, 'map must be set');
  91376. var projection = this.projection_;
  91377. if (!projection) {
  91378. var view = map.getView();
  91379. goog.asserts.assert(view, 'map must have view');
  91380. projection = view.getProjection();
  91381. goog.asserts.assert(projection !== undefined,
  91382. 'projection should be defined');
  91383. }
  91384. var formatConstructors = this.formatConstructors_;
  91385. var features = [];
  91386. var i, ii;
  91387. for (i = 0, ii = formatConstructors.length; i < ii; ++i) {
  91388. var formatConstructor = formatConstructors[i];
  91389. var format = new formatConstructor();
  91390. var readFeatures = this.tryReadFeatures_(format, result);
  91391. if (readFeatures) {
  91392. var featureProjection = format.readProjection(result);
  91393. var transform = ol.proj.getTransform(featureProjection, projection);
  91394. var j, jj;
  91395. for (j = 0, jj = readFeatures.length; j < jj; ++j) {
  91396. var feature = readFeatures[j];
  91397. var geometry = feature.getGeometry();
  91398. if (geometry) {
  91399. geometry.applyTransform(transform);
  91400. }
  91401. features.push(feature);
  91402. }
  91403. }
  91404. }
  91405. this.dispatchEvent(
  91406. new ol.interaction.DragAndDropEvent(
  91407. ol.interaction.DragAndDropEventType.ADD_FEATURES, this, file,
  91408. features, projection));
  91409. };
  91410. /**
  91411. * Handles the {@link ol.MapBrowserEvent map browser event} unconditionally and
  91412. * neither prevents the browser default nor stops event propagation.
  91413. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  91414. * @return {boolean} `false` to stop event propagation.
  91415. * @this {ol.interaction.DragAndDrop}
  91416. * @api
  91417. */
  91418. ol.interaction.DragAndDrop.handleEvent = goog.functions.TRUE;
  91419. /**
  91420. * @inheritDoc
  91421. */
  91422. ol.interaction.DragAndDrop.prototype.setMap = function(map) {
  91423. if (this.dropListenKey_) {
  91424. goog.events.unlistenByKey(this.dropListenKey_);
  91425. this.dropListenKey_ = undefined;
  91426. }
  91427. if (this.fileDropHandler_) {
  91428. goog.dispose(this.fileDropHandler_);
  91429. this.fileDropHandler_ = null;
  91430. }
  91431. goog.asserts.assert(this.dropListenKey_ === undefined,
  91432. 'this.dropListenKey_ should be undefined');
  91433. goog.base(this, 'setMap', map);
  91434. if (map) {
  91435. this.fileDropHandler_ = new goog.events.FileDropHandler(map.getViewport());
  91436. this.dropListenKey_ = goog.events.listen(
  91437. this.fileDropHandler_, goog.events.FileDropHandler.EventType.DROP,
  91438. this.handleDrop_, false, this);
  91439. }
  91440. };
  91441. /**
  91442. * @param {ol.format.Feature} format Format.
  91443. * @param {string} text Text.
  91444. * @private
  91445. * @return {Array.<ol.Feature>} Features.
  91446. */
  91447. ol.interaction.DragAndDrop.prototype.tryReadFeatures_ = function(format, text) {
  91448. try {
  91449. return format.readFeatures(text);
  91450. } catch (e) {
  91451. return null;
  91452. }
  91453. };
  91454. /**
  91455. * @enum {string}
  91456. */
  91457. ol.interaction.DragAndDropEventType = {
  91458. /**
  91459. * Triggered when features are added
  91460. * @event ol.interaction.DragAndDropEvent#addfeatures
  91461. * @api stable
  91462. */
  91463. ADD_FEATURES: 'addfeatures'
  91464. };
  91465. /**
  91466. * @classdesc
  91467. * Events emitted by {@link ol.interaction.DragAndDrop} instances are instances
  91468. * of this type.
  91469. *
  91470. * @constructor
  91471. * @extends {goog.events.Event}
  91472. * @implements {oli.interaction.DragAndDropEvent}
  91473. * @param {ol.interaction.DragAndDropEventType} type Type.
  91474. * @param {Object} target Target.
  91475. * @param {File} file File.
  91476. * @param {Array.<ol.Feature>=} opt_features Features.
  91477. * @param {ol.proj.Projection=} opt_projection Projection.
  91478. */
  91479. ol.interaction.DragAndDropEvent =
  91480. function(type, target, file, opt_features, opt_projection) {
  91481. goog.base(this, type, target);
  91482. /**
  91483. * The features parsed from dropped data.
  91484. * @type {Array.<ol.Feature>|undefined}
  91485. * @api stable
  91486. */
  91487. this.features = opt_features;
  91488. /**
  91489. * The dropped file.
  91490. * @type {File}
  91491. * @api stable
  91492. */
  91493. this.file = file;
  91494. /**
  91495. * The feature projection.
  91496. * @type {ol.proj.Projection|undefined}
  91497. * @api
  91498. */
  91499. this.projection = opt_projection;
  91500. };
  91501. goog.inherits(ol.interaction.DragAndDropEvent, goog.events.Event);
  91502. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  91503. //
  91504. // Licensed under the Apache License, Version 2.0 (the "License");
  91505. // you may not use this file except in compliance with the License.
  91506. // You may obtain a copy of the License at
  91507. //
  91508. // http://www.apache.org/licenses/LICENSE-2.0
  91509. //
  91510. // Unless required by applicable law or agreed to in writing, software
  91511. // distributed under the License is distributed on an "AS-IS" BASIS,
  91512. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  91513. // See the License for the specific language governing permissions and
  91514. // limitations under the License.
  91515. /**
  91516. * @fileoverview Defines a 2-element vector class that can be used for
  91517. * coordinate math, useful for animation systems and point manipulation.
  91518. *
  91519. * Vec2 objects inherit from goog.math.Coordinate and may be used wherever a
  91520. * Coordinate is required. Where appropriate, Vec2 functions accept both Vec2
  91521. * and Coordinate objects as input.
  91522. *
  91523. * @author brenneman@google.com (Shawn Brenneman)
  91524. */
  91525. goog.provide('goog.math.Vec2');
  91526. goog.require('goog.math');
  91527. goog.require('goog.math.Coordinate');
  91528. /**
  91529. * Class for a two-dimensional vector object and assorted functions useful for
  91530. * manipulating points.
  91531. *
  91532. * @param {number} x The x coordinate for the vector.
  91533. * @param {number} y The y coordinate for the vector.
  91534. * @struct
  91535. * @constructor
  91536. * @extends {goog.math.Coordinate}
  91537. */
  91538. goog.math.Vec2 = function(x, y) {
  91539. /**
  91540. * X-value
  91541. * @type {number}
  91542. */
  91543. this.x = x;
  91544. /**
  91545. * Y-value
  91546. * @type {number}
  91547. */
  91548. this.y = y;
  91549. };
  91550. goog.inherits(goog.math.Vec2, goog.math.Coordinate);
  91551. /**
  91552. * @return {!goog.math.Vec2} A random unit-length vector.
  91553. */
  91554. goog.math.Vec2.randomUnit = function() {
  91555. var angle = Math.random() * Math.PI * 2;
  91556. return new goog.math.Vec2(Math.cos(angle), Math.sin(angle));
  91557. };
  91558. /**
  91559. * @return {!goog.math.Vec2} A random vector inside the unit-disc.
  91560. */
  91561. goog.math.Vec2.random = function() {
  91562. var mag = Math.sqrt(Math.random());
  91563. var angle = Math.random() * Math.PI * 2;
  91564. return new goog.math.Vec2(Math.cos(angle) * mag, Math.sin(angle) * mag);
  91565. };
  91566. /**
  91567. * Returns a new Vec2 object from a given coordinate.
  91568. * @param {!goog.math.Coordinate} a The coordinate.
  91569. * @return {!goog.math.Vec2} A new vector object.
  91570. */
  91571. goog.math.Vec2.fromCoordinate = function(a) {
  91572. return new goog.math.Vec2(a.x, a.y);
  91573. };
  91574. /**
  91575. * @return {!goog.math.Vec2} A new vector with the same coordinates as this one.
  91576. * @override
  91577. */
  91578. goog.math.Vec2.prototype.clone = function() {
  91579. return new goog.math.Vec2(this.x, this.y);
  91580. };
  91581. /**
  91582. * Returns the magnitude of the vector measured from the origin.
  91583. * @return {number} The length of the vector.
  91584. */
  91585. goog.math.Vec2.prototype.magnitude = function() {
  91586. return Math.sqrt(this.x * this.x + this.y * this.y);
  91587. };
  91588. /**
  91589. * Returns the squared magnitude of the vector measured from the origin.
  91590. * NOTE(brenneman): Leaving out the square root is not a significant
  91591. * optimization in JavaScript.
  91592. * @return {number} The length of the vector, squared.
  91593. */
  91594. goog.math.Vec2.prototype.squaredMagnitude = function() {
  91595. return this.x * this.x + this.y * this.y;
  91596. };
  91597. /**
  91598. * @return {!goog.math.Vec2} This coordinate after scaling.
  91599. * @override
  91600. */
  91601. goog.math.Vec2.prototype.scale =
  91602. /** @type {function(number, number=):!goog.math.Vec2} */
  91603. (goog.math.Coordinate.prototype.scale);
  91604. /**
  91605. * Reverses the sign of the vector. Equivalent to scaling the vector by -1.
  91606. * @return {!goog.math.Vec2} The inverted vector.
  91607. */
  91608. goog.math.Vec2.prototype.invert = function() {
  91609. this.x = -this.x;
  91610. this.y = -this.y;
  91611. return this;
  91612. };
  91613. /**
  91614. * Normalizes the current vector to have a magnitude of 1.
  91615. * @return {!goog.math.Vec2} The normalized vector.
  91616. */
  91617. goog.math.Vec2.prototype.normalize = function() {
  91618. return this.scale(1 / this.magnitude());
  91619. };
  91620. /**
  91621. * Adds another vector to this vector in-place.
  91622. * @param {!goog.math.Coordinate} b The vector to add.
  91623. * @return {!goog.math.Vec2} This vector with {@code b} added.
  91624. */
  91625. goog.math.Vec2.prototype.add = function(b) {
  91626. this.x += b.x;
  91627. this.y += b.y;
  91628. return this;
  91629. };
  91630. /**
  91631. * Subtracts another vector from this vector in-place.
  91632. * @param {!goog.math.Coordinate} b The vector to subtract.
  91633. * @return {!goog.math.Vec2} This vector with {@code b} subtracted.
  91634. */
  91635. goog.math.Vec2.prototype.subtract = function(b) {
  91636. this.x -= b.x;
  91637. this.y -= b.y;
  91638. return this;
  91639. };
  91640. /**
  91641. * Rotates this vector in-place by a given angle, specified in radians.
  91642. * @param {number} angle The angle, in radians.
  91643. * @return {!goog.math.Vec2} This vector rotated {@code angle} radians.
  91644. */
  91645. goog.math.Vec2.prototype.rotate = function(angle) {
  91646. var cos = Math.cos(angle);
  91647. var sin = Math.sin(angle);
  91648. var newX = this.x * cos - this.y * sin;
  91649. var newY = this.y * cos + this.x * sin;
  91650. this.x = newX;
  91651. this.y = newY;
  91652. return this;
  91653. };
  91654. /**
  91655. * Rotates a vector by a given angle, specified in radians, relative to a given
  91656. * axis rotation point. The returned vector is a newly created instance - no
  91657. * in-place changes are done.
  91658. * @param {!goog.math.Vec2} v A vector.
  91659. * @param {!goog.math.Vec2} axisPoint The rotation axis point.
  91660. * @param {number} angle The angle, in radians.
  91661. * @return {!goog.math.Vec2} The rotated vector in a newly created instance.
  91662. */
  91663. goog.math.Vec2.rotateAroundPoint = function(v, axisPoint, angle) {
  91664. var res = v.clone();
  91665. return res.subtract(axisPoint).rotate(angle).add(axisPoint);
  91666. };
  91667. /**
  91668. * Compares this vector with another for equality.
  91669. * @param {!goog.math.Vec2} b The other vector.
  91670. * @return {boolean} Whether this vector has the same x and y as the given
  91671. * vector.
  91672. */
  91673. goog.math.Vec2.prototype.equals = function(b) {
  91674. return this == b || !!b && this.x == b.x && this.y == b.y;
  91675. };
  91676. /**
  91677. * Returns the distance between two vectors.
  91678. * @param {!goog.math.Coordinate} a The first vector.
  91679. * @param {!goog.math.Coordinate} b The second vector.
  91680. * @return {number} The distance.
  91681. */
  91682. goog.math.Vec2.distance = goog.math.Coordinate.distance;
  91683. /**
  91684. * Returns the squared distance between two vectors.
  91685. * @param {!goog.math.Coordinate} a The first vector.
  91686. * @param {!goog.math.Coordinate} b The second vector.
  91687. * @return {number} The squared distance.
  91688. */
  91689. goog.math.Vec2.squaredDistance = goog.math.Coordinate.squaredDistance;
  91690. /**
  91691. * Compares vectors for equality.
  91692. * @param {!goog.math.Coordinate} a The first vector.
  91693. * @param {!goog.math.Coordinate} b The second vector.
  91694. * @return {boolean} Whether the vectors have the same x and y coordinates.
  91695. */
  91696. goog.math.Vec2.equals = goog.math.Coordinate.equals;
  91697. /**
  91698. * Returns the sum of two vectors as a new Vec2.
  91699. * @param {!goog.math.Coordinate} a The first vector.
  91700. * @param {!goog.math.Coordinate} b The second vector.
  91701. * @return {!goog.math.Vec2} The sum vector.
  91702. */
  91703. goog.math.Vec2.sum = function(a, b) {
  91704. return new goog.math.Vec2(a.x + b.x, a.y + b.y);
  91705. };
  91706. /**
  91707. * Returns the difference between two vectors as a new Vec2.
  91708. * @param {!goog.math.Coordinate} a The first vector.
  91709. * @param {!goog.math.Coordinate} b The second vector.
  91710. * @return {!goog.math.Vec2} The difference vector.
  91711. */
  91712. goog.math.Vec2.difference = function(a, b) {
  91713. return new goog.math.Vec2(a.x - b.x, a.y - b.y);
  91714. };
  91715. /**
  91716. * Returns the dot-product of two vectors.
  91717. * @param {!goog.math.Coordinate} a The first vector.
  91718. * @param {!goog.math.Coordinate} b The second vector.
  91719. * @return {number} The dot-product of the two vectors.
  91720. */
  91721. goog.math.Vec2.dot = function(a, b) {
  91722. return a.x * b.x + a.y * b.y;
  91723. };
  91724. /**
  91725. * Returns the determinant of two vectors.
  91726. * @param {!goog.math.Vec2} a The first vector.
  91727. * @param {!goog.math.Vec2} b The second vector.
  91728. * @return {number} The determinant of the two vectors.
  91729. */
  91730. goog.math.Vec2.determinant = function(a, b) {
  91731. return a.x * b.y - a.y * b.x;
  91732. };
  91733. /**
  91734. * Returns a new Vec2 that is the linear interpolant between vectors a and b at
  91735. * scale-value x.
  91736. * @param {!goog.math.Coordinate} a Vector a.
  91737. * @param {!goog.math.Coordinate} b Vector b.
  91738. * @param {number} x The proportion between a and b.
  91739. * @return {!goog.math.Vec2} The interpolated vector.
  91740. */
  91741. goog.math.Vec2.lerp = function(a, b, x) {
  91742. return new goog.math.Vec2(goog.math.lerp(a.x, b.x, x),
  91743. goog.math.lerp(a.y, b.y, x));
  91744. };
  91745. goog.provide('ol.interaction.DragRotateAndZoom');
  91746. goog.require('goog.math.Vec2');
  91747. goog.require('ol');
  91748. goog.require('ol.ViewHint');
  91749. goog.require('ol.events.ConditionType');
  91750. goog.require('ol.events.condition');
  91751. goog.require('ol.interaction.Interaction');
  91752. goog.require('ol.interaction.Pointer');
  91753. /**
  91754. * @classdesc
  91755. * Allows the user to zoom and rotate the map by clicking and dragging
  91756. * on the map. By default, this interaction is limited to when the shift
  91757. * key is held down.
  91758. *
  91759. * This interaction is only supported for mouse devices.
  91760. *
  91761. * And this interaction is not included in the default interactions.
  91762. *
  91763. * @constructor
  91764. * @extends {ol.interaction.Pointer}
  91765. * @param {olx.interaction.DragRotateAndZoomOptions=} opt_options Options.
  91766. * @api stable
  91767. */
  91768. ol.interaction.DragRotateAndZoom = function(opt_options) {
  91769. var options = opt_options ? opt_options : {};
  91770. goog.base(this, {
  91771. handleDownEvent: ol.interaction.DragRotateAndZoom.handleDownEvent_,
  91772. handleDragEvent: ol.interaction.DragRotateAndZoom.handleDragEvent_,
  91773. handleUpEvent: ol.interaction.DragRotateAndZoom.handleUpEvent_
  91774. });
  91775. /**
  91776. * @private
  91777. * @type {ol.events.ConditionType}
  91778. */
  91779. this.condition_ = options.condition ?
  91780. options.condition : ol.events.condition.shiftKeyOnly;
  91781. /**
  91782. * @private
  91783. * @type {number|undefined}
  91784. */
  91785. this.lastAngle_ = undefined;
  91786. /**
  91787. * @private
  91788. * @type {number|undefined}
  91789. */
  91790. this.lastMagnitude_ = undefined;
  91791. /**
  91792. * @private
  91793. * @type {number}
  91794. */
  91795. this.lastScaleDelta_ = 0;
  91796. /**
  91797. * @private
  91798. * @type {number}
  91799. */
  91800. this.duration_ = options.duration ? options.duration : 400;
  91801. };
  91802. goog.inherits(ol.interaction.DragRotateAndZoom, ol.interaction.Pointer);
  91803. /**
  91804. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  91805. * @this {ol.interaction.DragRotateAndZoom}
  91806. * @private
  91807. */
  91808. ol.interaction.DragRotateAndZoom.handleDragEvent_ = function(mapBrowserEvent) {
  91809. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  91810. return;
  91811. }
  91812. var map = mapBrowserEvent.map;
  91813. var size = map.getSize();
  91814. var offset = mapBrowserEvent.pixel;
  91815. var delta = new goog.math.Vec2(
  91816. offset[0] - size[0] / 2,
  91817. size[1] / 2 - offset[1]);
  91818. var theta = Math.atan2(delta.y, delta.x);
  91819. var magnitude = delta.magnitude();
  91820. var view = map.getView();
  91821. map.render();
  91822. if (this.lastAngle_ !== undefined) {
  91823. var angleDelta = theta - this.lastAngle_;
  91824. ol.interaction.Interaction.rotateWithoutConstraints(
  91825. map, view, view.getRotation() - angleDelta);
  91826. }
  91827. this.lastAngle_ = theta;
  91828. if (this.lastMagnitude_ !== undefined) {
  91829. var resolution = this.lastMagnitude_ * (view.getResolution() / magnitude);
  91830. ol.interaction.Interaction.zoomWithoutConstraints(map, view, resolution);
  91831. }
  91832. if (this.lastMagnitude_ !== undefined) {
  91833. this.lastScaleDelta_ = this.lastMagnitude_ / magnitude;
  91834. }
  91835. this.lastMagnitude_ = magnitude;
  91836. };
  91837. /**
  91838. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  91839. * @return {boolean} Stop drag sequence?
  91840. * @this {ol.interaction.DragRotateAndZoom}
  91841. * @private
  91842. */
  91843. ol.interaction.DragRotateAndZoom.handleUpEvent_ = function(mapBrowserEvent) {
  91844. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  91845. return true;
  91846. }
  91847. var map = mapBrowserEvent.map;
  91848. var view = map.getView();
  91849. view.setHint(ol.ViewHint.INTERACTING, -1);
  91850. var direction = this.lastScaleDelta_ - 1;
  91851. ol.interaction.Interaction.rotate(map, view, view.getRotation());
  91852. ol.interaction.Interaction.zoom(map, view, view.getResolution(),
  91853. undefined, this.duration_, direction);
  91854. this.lastScaleDelta_ = 0;
  91855. return false;
  91856. };
  91857. /**
  91858. * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
  91859. * @return {boolean} Start drag sequence?
  91860. * @this {ol.interaction.DragRotateAndZoom}
  91861. * @private
  91862. */
  91863. ol.interaction.DragRotateAndZoom.handleDownEvent_ = function(mapBrowserEvent) {
  91864. if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {
  91865. return false;
  91866. }
  91867. if (this.condition_(mapBrowserEvent)) {
  91868. mapBrowserEvent.map.getView().setHint(ol.ViewHint.INTERACTING, 1);
  91869. this.lastAngle_ = undefined;
  91870. this.lastMagnitude_ = undefined;
  91871. return true;
  91872. } else {
  91873. return false;
  91874. }
  91875. };
  91876. goog.provide('ol.interaction.Draw');
  91877. goog.provide('ol.interaction.DrawEvent');
  91878. goog.provide('ol.interaction.DrawEventType');
  91879. goog.provide('ol.interaction.DrawGeometryFunctionType');
  91880. goog.provide('ol.interaction.DrawMode');
  91881. goog.require('goog.asserts');
  91882. goog.require('goog.events');
  91883. goog.require('goog.events.Event');
  91884. goog.require('ol.Collection');
  91885. goog.require('ol.Coordinate');
  91886. goog.require('ol.Feature');
  91887. goog.require('ol.MapBrowserEvent');
  91888. goog.require('ol.MapBrowserEvent.EventType');
  91889. goog.require('ol.Object');
  91890. goog.require('ol.coordinate');
  91891. goog.require('ol.events.condition');
  91892. goog.require('ol.geom.Circle');
  91893. goog.require('ol.geom.GeometryType');
  91894. goog.require('ol.geom.LineString');
  91895. goog.require('ol.geom.MultiLineString');
  91896. goog.require('ol.geom.MultiPoint');
  91897. goog.require('ol.geom.MultiPolygon');
  91898. goog.require('ol.geom.Point');
  91899. goog.require('ol.geom.Polygon');
  91900. goog.require('ol.geom.SimpleGeometry');
  91901. goog.require('ol.interaction.InteractionProperty');
  91902. goog.require('ol.interaction.Pointer');
  91903. goog.require('ol.layer.Vector');
  91904. goog.require('ol.source.Vector');
  91905. /**
  91906. * @enum {string}
  91907. */
  91908. ol.interaction.DrawEventType = {
  91909. /**
  91910. * Triggered upon feature draw start
  91911. * @event ol.interaction.DrawEvent#drawstart
  91912. * @api stable
  91913. */
  91914. DRAWSTART: 'drawstart',
  91915. /**
  91916. * Triggered upon feature draw end
  91917. * @event ol.interaction.DrawEvent#drawend
  91918. * @api stable
  91919. */
  91920. DRAWEND: 'drawend'
  91921. };
  91922. /**
  91923. * @classdesc
  91924. * Events emitted by {@link ol.interaction.Draw} instances are instances of
  91925. * this type.
  91926. *
  91927. * @constructor
  91928. * @extends {goog.events.Event}
  91929. * @implements {oli.DrawEvent}
  91930. * @param {ol.interaction.DrawEventType} type Type.
  91931. * @param {ol.Feature} feature The feature drawn.
  91932. */
  91933. ol.interaction.DrawEvent = function(type, feature) {
  91934. goog.base(this, type);
  91935. /**
  91936. * The feature being drawn.
  91937. * @type {ol.Feature}
  91938. * @api stable
  91939. */
  91940. this.feature = feature;
  91941. };
  91942. goog.inherits(ol.interaction.DrawEvent, goog.events.Event);
  91943. /**
  91944. * @classdesc
  91945. * Interaction for drawing feature geometries.
  91946. *
  91947. * @constructor
  91948. * @extends {ol.interaction.Pointer}
  91949. * @fires ol.interaction.DrawEvent
  91950. * @param {olx.interaction.DrawOptions} options Options.
  91951. * @api stable
  91952. */
  91953. ol.interaction.Draw = function(options) {
  91954. goog.base(this, {
  91955. handleDownEvent: ol.interaction.Draw.handleDownEvent_,
  91956. handleEvent: ol.interaction.Draw.handleEvent,
  91957. handleUpEvent: ol.interaction.Draw.handleUpEvent_
  91958. });
  91959. /**
  91960. * @type {ol.Pixel}
  91961. * @private
  91962. */
  91963. this.downPx_ = null;
  91964. /**
  91965. * @type {boolean}
  91966. * @private
  91967. */
  91968. this.freehand_ = false;
  91969. /**
  91970. * Target source for drawn features.
  91971. * @type {ol.source.Vector}
  91972. * @private
  91973. */
  91974. this.source_ = options.source ? options.source : null;
  91975. /**
  91976. * Target collection for drawn features.
  91977. * @type {ol.Collection.<ol.Feature>}
  91978. * @private
  91979. */
  91980. this.features_ = options.features ? options.features : null;
  91981. /**
  91982. * Pixel distance for snapping.
  91983. * @type {number}
  91984. * @private
  91985. */
  91986. this.snapTolerance_ = options.snapTolerance ? options.snapTolerance : 12;
  91987. /**
  91988. * Geometry type.
  91989. * @type {ol.geom.GeometryType}
  91990. * @private
  91991. */
  91992. this.type_ = options.type;
  91993. /**
  91994. * Drawing mode (derived from geometry type.
  91995. * @type {ol.interaction.DrawMode}
  91996. * @private
  91997. */
  91998. this.mode_ = ol.interaction.Draw.getMode_(this.type_);
  91999. /**
  92000. * The number of points that must be drawn before a polygon ring or line
  92001. * string can be finished. The default is 3 for polygon rings and 2 for
  92002. * line strings.
  92003. * @type {number}
  92004. * @private
  92005. */
  92006. this.minPoints_ = options.minPoints ?
  92007. options.minPoints :
  92008. (this.mode_ === ol.interaction.DrawMode.POLYGON ? 3 : 2);
  92009. /**
  92010. * The number of points that can be drawn before a polygon ring or line string
  92011. * is finished. The default is no restriction.
  92012. * @type {number}
  92013. * @private
  92014. */
  92015. this.maxPoints_ = options.maxPoints ? options.maxPoints : Infinity;
  92016. var geometryFunction = options.geometryFunction;
  92017. if (!geometryFunction) {
  92018. if (this.type_ === ol.geom.GeometryType.CIRCLE) {
  92019. /**
  92020. * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
  92021. * @param {ol.geom.SimpleGeometry=} opt_geometry
  92022. * @return {ol.geom.SimpleGeometry}
  92023. */
  92024. geometryFunction = function(coordinates, opt_geometry) {
  92025. var circle = opt_geometry ? opt_geometry :
  92026. new ol.geom.Circle([NaN, NaN]);
  92027. goog.asserts.assertInstanceof(circle, ol.geom.Circle,
  92028. 'geometry must be an ol.geom.Circle');
  92029. var squaredLength = ol.coordinate.squaredDistance(
  92030. coordinates[0], coordinates[1]);
  92031. circle.setCenterAndRadius(coordinates[0], Math.sqrt(squaredLength));
  92032. return circle;
  92033. };
  92034. } else {
  92035. var Constructor;
  92036. var mode = this.mode_;
  92037. if (mode === ol.interaction.DrawMode.POINT) {
  92038. Constructor = ol.geom.Point;
  92039. } else if (mode === ol.interaction.DrawMode.LINE_STRING) {
  92040. Constructor = ol.geom.LineString;
  92041. } else if (mode === ol.interaction.DrawMode.POLYGON) {
  92042. Constructor = ol.geom.Polygon;
  92043. }
  92044. /**
  92045. * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
  92046. * @param {ol.geom.SimpleGeometry=} opt_geometry
  92047. * @return {ol.geom.SimpleGeometry}
  92048. */
  92049. geometryFunction = function(coordinates, opt_geometry) {
  92050. var geometry = opt_geometry;
  92051. if (geometry) {
  92052. geometry.setCoordinates(coordinates);
  92053. } else {
  92054. geometry = new Constructor(coordinates);
  92055. }
  92056. return geometry;
  92057. };
  92058. }
  92059. }
  92060. /**
  92061. * @type {ol.interaction.DrawGeometryFunctionType}
  92062. * @private
  92063. */
  92064. this.geometryFunction_ = geometryFunction;
  92065. /**
  92066. * Finish coordinate for the feature (first point for polygons, last point for
  92067. * linestrings).
  92068. * @type {ol.Coordinate}
  92069. * @private
  92070. */
  92071. this.finishCoordinate_ = null;
  92072. /**
  92073. * Sketch feature.
  92074. * @type {ol.Feature}
  92075. * @private
  92076. */
  92077. this.sketchFeature_ = null;
  92078. /**
  92079. * Sketch point.
  92080. * @type {ol.Feature}
  92081. * @private
  92082. */
  92083. this.sketchPoint_ = null;
  92084. /**
  92085. * Sketch coordinates. Used when drawing a line or polygon.
  92086. * @type {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>}
  92087. * @private
  92088. */
  92089. this.sketchCoords_ = null;
  92090. /**
  92091. * Sketch line. Used when drawing polygon.
  92092. * @type {ol.Feature}
  92093. * @private
  92094. */
  92095. this.sketchLine_ = null;
  92096. /**
  92097. * Sketch line coordinates. Used when drawing a polygon or circle.
  92098. * @type {Array.<ol.Coordinate>}
  92099. * @private
  92100. */
  92101. this.sketchLineCoords_ = null;
  92102. /**
  92103. * Squared tolerance for handling up events. If the squared distance
  92104. * between a down and up event is greater than this tolerance, up events
  92105. * will not be handled.
  92106. * @type {number}
  92107. * @private
  92108. */
  92109. this.squaredClickTolerance_ = options.clickTolerance ?
  92110. options.clickTolerance * options.clickTolerance : 36;
  92111. /**
  92112. * Draw overlay where our sketch features are drawn.
  92113. * @type {ol.layer.Vector}
  92114. * @private
  92115. */
  92116. this.overlay_ = new ol.layer.Vector({
  92117. source: new ol.source.Vector({
  92118. useSpatialIndex: false,
  92119. wrapX: options.wrapX ? options.wrapX : false
  92120. }),
  92121. style: options.style ? options.style :
  92122. ol.interaction.Draw.getDefaultStyleFunction()
  92123. });
  92124. /**
  92125. * Name of the geometry attribute for newly created features.
  92126. * @type {string|undefined}
  92127. * @private
  92128. */
  92129. this.geometryName_ = options.geometryName;
  92130. /**
  92131. * @private
  92132. * @type {ol.events.ConditionType}
  92133. */
  92134. this.condition_ = options.condition ?
  92135. options.condition : ol.events.condition.noModifierKeys;
  92136. /**
  92137. * @private
  92138. * @type {ol.events.ConditionType}
  92139. */
  92140. this.freehandCondition_ = options.freehandCondition ?
  92141. options.freehandCondition : ol.events.condition.shiftKeyOnly;
  92142. goog.events.listen(this,
  92143. ol.Object.getChangeEventType(ol.interaction.InteractionProperty.ACTIVE),
  92144. this.updateState_, false, this);
  92145. };
  92146. goog.inherits(ol.interaction.Draw, ol.interaction.Pointer);
  92147. /**
  92148. * @return {ol.style.StyleFunction} Styles.
  92149. */
  92150. ol.interaction.Draw.getDefaultStyleFunction = function() {
  92151. var styles = ol.style.createDefaultEditingStyles();
  92152. return function(feature, resolution) {
  92153. return styles[feature.getGeometry().getType()];
  92154. };
  92155. };
  92156. /**
  92157. * @inheritDoc
  92158. */
  92159. ol.interaction.Draw.prototype.setMap = function(map) {
  92160. goog.base(this, 'setMap', map);
  92161. this.updateState_();
  92162. };
  92163. /**
  92164. * Handles the {@link ol.MapBrowserEvent map browser event} and may actually
  92165. * draw or finish the drawing.
  92166. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  92167. * @return {boolean} `false` to stop event propagation.
  92168. * @this {ol.interaction.Draw}
  92169. * @api
  92170. */
  92171. ol.interaction.Draw.handleEvent = function(mapBrowserEvent) {
  92172. var pass = !this.freehand_;
  92173. if (this.freehand_ &&
  92174. mapBrowserEvent.type === ol.MapBrowserEvent.EventType.POINTERDRAG) {
  92175. this.addToDrawing_(mapBrowserEvent);
  92176. pass = false;
  92177. } else if (mapBrowserEvent.type ===
  92178. ol.MapBrowserEvent.EventType.POINTERMOVE) {
  92179. pass = this.handlePointerMove_(mapBrowserEvent);
  92180. } else if (mapBrowserEvent.type === ol.MapBrowserEvent.EventType.DBLCLICK) {
  92181. pass = false;
  92182. }
  92183. return ol.interaction.Pointer.handleEvent.call(this, mapBrowserEvent) && pass;
  92184. };
  92185. /**
  92186. * @param {ol.MapBrowserPointerEvent} event Event.
  92187. * @return {boolean} Start drag sequence?
  92188. * @this {ol.interaction.Draw}
  92189. * @private
  92190. */
  92191. ol.interaction.Draw.handleDownEvent_ = function(event) {
  92192. if (this.condition_(event)) {
  92193. this.downPx_ = event.pixel;
  92194. return true;
  92195. } else if ((this.mode_ === ol.interaction.DrawMode.LINE_STRING ||
  92196. this.mode_ === ol.interaction.DrawMode.POLYGON) &&
  92197. this.freehandCondition_(event)) {
  92198. this.downPx_ = event.pixel;
  92199. this.freehand_ = true;
  92200. if (!this.finishCoordinate_) {
  92201. this.startDrawing_(event);
  92202. }
  92203. return true;
  92204. } else {
  92205. return false;
  92206. }
  92207. };
  92208. /**
  92209. * @param {ol.MapBrowserPointerEvent} event Event.
  92210. * @return {boolean} Stop drag sequence?
  92211. * @this {ol.interaction.Draw}
  92212. * @private
  92213. */
  92214. ol.interaction.Draw.handleUpEvent_ = function(event) {
  92215. this.freehand_ = false;
  92216. var downPx = this.downPx_;
  92217. var clickPx = event.pixel;
  92218. var dx = downPx[0] - clickPx[0];
  92219. var dy = downPx[1] - clickPx[1];
  92220. var squaredDistance = dx * dx + dy * dy;
  92221. var pass = true;
  92222. if (squaredDistance <= this.squaredClickTolerance_) {
  92223. this.handlePointerMove_(event);
  92224. if (!this.finishCoordinate_) {
  92225. this.startDrawing_(event);
  92226. if (this.mode_ === ol.interaction.DrawMode.POINT) {
  92227. this.finishDrawing();
  92228. }
  92229. } else if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
  92230. this.finishDrawing();
  92231. } else if (this.atFinish_(event)) {
  92232. this.finishDrawing();
  92233. } else {
  92234. this.addToDrawing_(event);
  92235. }
  92236. pass = false;
  92237. }
  92238. return pass;
  92239. };
  92240. /**
  92241. * Handle move events.
  92242. * @param {ol.MapBrowserEvent} event A move event.
  92243. * @return {boolean} Pass the event to other interactions.
  92244. * @private
  92245. */
  92246. ol.interaction.Draw.prototype.handlePointerMove_ = function(event) {
  92247. if (this.finishCoordinate_) {
  92248. this.modifyDrawing_(event);
  92249. } else {
  92250. this.createOrUpdateSketchPoint_(event);
  92251. }
  92252. return true;
  92253. };
  92254. /**
  92255. * Determine if an event is within the snapping tolerance of the start coord.
  92256. * @param {ol.MapBrowserEvent} event Event.
  92257. * @return {boolean} The event is within the snapping tolerance of the start.
  92258. * @private
  92259. */
  92260. ol.interaction.Draw.prototype.atFinish_ = function(event) {
  92261. var at = false;
  92262. if (this.sketchFeature_) {
  92263. var potentiallyDone = false;
  92264. var potentiallyFinishCoordinates = [this.finishCoordinate_];
  92265. if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
  92266. potentiallyDone = this.sketchCoords_.length > this.minPoints_;
  92267. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92268. potentiallyDone = this.sketchCoords_[0].length >
  92269. this.minPoints_;
  92270. potentiallyFinishCoordinates = [this.sketchCoords_[0][0],
  92271. this.sketchCoords_[0][this.sketchCoords_[0].length - 2]];
  92272. }
  92273. if (potentiallyDone) {
  92274. var map = event.map;
  92275. for (var i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) {
  92276. var finishCoordinate = potentiallyFinishCoordinates[i];
  92277. var finishPixel = map.getPixelFromCoordinate(finishCoordinate);
  92278. var pixel = event.pixel;
  92279. var dx = pixel[0] - finishPixel[0];
  92280. var dy = pixel[1] - finishPixel[1];
  92281. var freehand = this.freehand_ && this.freehandCondition_(event);
  92282. var snapTolerance = freehand ? 1 : this.snapTolerance_;
  92283. at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;
  92284. if (at) {
  92285. this.finishCoordinate_ = finishCoordinate;
  92286. break;
  92287. }
  92288. }
  92289. }
  92290. }
  92291. return at;
  92292. };
  92293. /**
  92294. * @param {ol.MapBrowserEvent} event Event.
  92295. * @private
  92296. */
  92297. ol.interaction.Draw.prototype.createOrUpdateSketchPoint_ = function(event) {
  92298. var coordinates = event.coordinate.slice();
  92299. if (!this.sketchPoint_) {
  92300. this.sketchPoint_ = new ol.Feature(new ol.geom.Point(coordinates));
  92301. this.updateSketchFeatures_();
  92302. } else {
  92303. var sketchPointGeom = this.sketchPoint_.getGeometry();
  92304. goog.asserts.assertInstanceof(sketchPointGeom, ol.geom.Point,
  92305. 'sketchPointGeom should be an ol.geom.Point');
  92306. sketchPointGeom.setCoordinates(coordinates);
  92307. }
  92308. };
  92309. /**
  92310. * Start the drawing.
  92311. * @param {ol.MapBrowserEvent} event Event.
  92312. * @private
  92313. */
  92314. ol.interaction.Draw.prototype.startDrawing_ = function(event) {
  92315. var start = event.coordinate;
  92316. this.finishCoordinate_ = start;
  92317. if (this.mode_ === ol.interaction.DrawMode.POINT) {
  92318. this.sketchCoords_ = start.slice();
  92319. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92320. this.sketchCoords_ = [[start.slice(), start.slice()]];
  92321. this.sketchLineCoords_ = this.sketchCoords_[0];
  92322. } else {
  92323. this.sketchCoords_ = [start.slice(), start.slice()];
  92324. if (this.mode_ === ol.interaction.DrawMode.CIRCLE) {
  92325. this.sketchLineCoords_ = this.sketchCoords_;
  92326. }
  92327. }
  92328. if (this.sketchLineCoords_) {
  92329. this.sketchLine_ = new ol.Feature(
  92330. new ol.geom.LineString(this.sketchLineCoords_));
  92331. }
  92332. var geometry = this.geometryFunction_(this.sketchCoords_);
  92333. goog.asserts.assert(geometry !== undefined, 'geometry should be defined');
  92334. this.sketchFeature_ = new ol.Feature();
  92335. if (this.geometryName_) {
  92336. this.sketchFeature_.setGeometryName(this.geometryName_);
  92337. }
  92338. this.sketchFeature_.setGeometry(geometry);
  92339. this.updateSketchFeatures_();
  92340. this.dispatchEvent(new ol.interaction.DrawEvent(
  92341. ol.interaction.DrawEventType.DRAWSTART, this.sketchFeature_));
  92342. };
  92343. /**
  92344. * Modify the drawing.
  92345. * @param {ol.MapBrowserEvent} event Event.
  92346. * @private
  92347. */
  92348. ol.interaction.Draw.prototype.modifyDrawing_ = function(event) {
  92349. var coordinate = event.coordinate;
  92350. var geometry = this.sketchFeature_.getGeometry();
  92351. goog.asserts.assertInstanceof(geometry, ol.geom.SimpleGeometry,
  92352. 'geometry should be ol.geom.SimpleGeometry or subclass');
  92353. var coordinates, last;
  92354. if (this.mode_ === ol.interaction.DrawMode.POINT) {
  92355. last = this.sketchCoords_;
  92356. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92357. coordinates = this.sketchCoords_[0];
  92358. last = coordinates[coordinates.length - 1];
  92359. if (this.atFinish_(event)) {
  92360. // snap to finish
  92361. coordinate = this.finishCoordinate_.slice();
  92362. }
  92363. } else {
  92364. coordinates = this.sketchCoords_;
  92365. last = coordinates[coordinates.length - 1];
  92366. }
  92367. last[0] = coordinate[0];
  92368. last[1] = coordinate[1];
  92369. goog.asserts.assert(this.sketchCoords_, 'sketchCoords_ expected');
  92370. this.geometryFunction_(this.sketchCoords_, geometry);
  92371. if (this.sketchPoint_) {
  92372. var sketchPointGeom = this.sketchPoint_.getGeometry();
  92373. goog.asserts.assertInstanceof(sketchPointGeom, ol.geom.Point,
  92374. 'sketchPointGeom should be an ol.geom.Point');
  92375. sketchPointGeom.setCoordinates(coordinate);
  92376. }
  92377. var sketchLineGeom;
  92378. if (geometry instanceof ol.geom.Polygon &&
  92379. this.mode_ !== ol.interaction.DrawMode.POLYGON) {
  92380. if (!this.sketchLine_) {
  92381. this.sketchLine_ = new ol.Feature(new ol.geom.LineString(null));
  92382. }
  92383. var ring = geometry.getLinearRing(0);
  92384. sketchLineGeom = this.sketchLine_.getGeometry();
  92385. goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
  92386. 'sketchLineGeom must be an ol.geom.LineString');
  92387. sketchLineGeom.setFlatCoordinates(
  92388. ring.getLayout(), ring.getFlatCoordinates());
  92389. } else if (this.sketchLineCoords_) {
  92390. sketchLineGeom = this.sketchLine_.getGeometry();
  92391. goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
  92392. 'sketchLineGeom must be an ol.geom.LineString');
  92393. sketchLineGeom.setCoordinates(this.sketchLineCoords_);
  92394. }
  92395. this.updateSketchFeatures_();
  92396. };
  92397. /**
  92398. * Add a new coordinate to the drawing.
  92399. * @param {ol.MapBrowserEvent} event Event.
  92400. * @private
  92401. */
  92402. ol.interaction.Draw.prototype.addToDrawing_ = function(event) {
  92403. var coordinate = event.coordinate;
  92404. var geometry = this.sketchFeature_.getGeometry();
  92405. goog.asserts.assertInstanceof(geometry, ol.geom.SimpleGeometry,
  92406. 'geometry must be an ol.geom.SimpleGeometry');
  92407. var done;
  92408. var coordinates;
  92409. if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
  92410. this.finishCoordinate_ = coordinate.slice();
  92411. coordinates = this.sketchCoords_;
  92412. coordinates.push(coordinate.slice());
  92413. done = coordinates.length > this.maxPoints_;
  92414. this.geometryFunction_(coordinates, geometry);
  92415. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92416. coordinates = this.sketchCoords_[0];
  92417. coordinates.push(coordinate.slice());
  92418. done = coordinates.length > this.maxPoints_;
  92419. if (done) {
  92420. this.finishCoordinate_ = coordinates[0];
  92421. }
  92422. this.geometryFunction_(this.sketchCoords_, geometry);
  92423. }
  92424. this.updateSketchFeatures_();
  92425. if (done) {
  92426. this.finishDrawing();
  92427. }
  92428. };
  92429. /**
  92430. * Remove last point of the feature currently being drawn.
  92431. * @api
  92432. */
  92433. ol.interaction.Draw.prototype.removeLastPoint = function() {
  92434. var geometry = this.sketchFeature_.getGeometry();
  92435. goog.asserts.assertInstanceof(geometry, ol.geom.SimpleGeometry,
  92436. 'geometry must be an ol.geom.SimpleGeometry');
  92437. var coordinates, sketchLineGeom;
  92438. if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
  92439. coordinates = this.sketchCoords_;
  92440. coordinates.splice(-2, 1);
  92441. this.geometryFunction_(coordinates, geometry);
  92442. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92443. coordinates = this.sketchCoords_[0];
  92444. coordinates.splice(-2, 1);
  92445. sketchLineGeom = this.sketchLine_.getGeometry();
  92446. goog.asserts.assertInstanceof(sketchLineGeom, ol.geom.LineString,
  92447. 'sketchLineGeom must be an ol.geom.LineString');
  92448. sketchLineGeom.setCoordinates(coordinates);
  92449. this.geometryFunction_(this.sketchCoords_, geometry);
  92450. }
  92451. if (coordinates.length === 0) {
  92452. this.finishCoordinate_ = null;
  92453. }
  92454. this.updateSketchFeatures_();
  92455. };
  92456. /**
  92457. * Stop drawing and add the sketch feature to the target layer.
  92458. * The {@link ol.interaction.DrawEventType.DRAWEND} event is dispatched before
  92459. * inserting the feature.
  92460. * @api
  92461. */
  92462. ol.interaction.Draw.prototype.finishDrawing = function() {
  92463. var sketchFeature = this.abortDrawing_();
  92464. goog.asserts.assert(sketchFeature, 'sketchFeature expected to be truthy');
  92465. var coordinates = this.sketchCoords_;
  92466. var geometry = sketchFeature.getGeometry();
  92467. goog.asserts.assertInstanceof(geometry, ol.geom.SimpleGeometry,
  92468. 'geometry must be an ol.geom.SimpleGeometry');
  92469. if (this.mode_ === ol.interaction.DrawMode.LINE_STRING) {
  92470. // remove the redundant last point
  92471. coordinates.pop();
  92472. this.geometryFunction_(coordinates, geometry);
  92473. } else if (this.mode_ === ol.interaction.DrawMode.POLYGON) {
  92474. // When we finish drawing a polygon on the last point,
  92475. // the last coordinate is duplicated as for LineString
  92476. // we force the replacement by the first point
  92477. coordinates[0].pop();
  92478. coordinates[0].push(coordinates[0][0]);
  92479. this.geometryFunction_(coordinates, geometry);
  92480. }
  92481. // cast multi-part geometries
  92482. if (this.type_ === ol.geom.GeometryType.MULTI_POINT) {
  92483. sketchFeature.setGeometry(new ol.geom.MultiPoint([coordinates]));
  92484. } else if (this.type_ === ol.geom.GeometryType.MULTI_LINE_STRING) {
  92485. sketchFeature.setGeometry(new ol.geom.MultiLineString([coordinates]));
  92486. } else if (this.type_ === ol.geom.GeometryType.MULTI_POLYGON) {
  92487. sketchFeature.setGeometry(new ol.geom.MultiPolygon([coordinates]));
  92488. }
  92489. // First dispatch event to allow full set up of feature
  92490. this.dispatchEvent(new ol.interaction.DrawEvent(
  92491. ol.interaction.DrawEventType.DRAWEND, sketchFeature));
  92492. // Then insert feature
  92493. if (this.features_) {
  92494. this.features_.push(sketchFeature);
  92495. }
  92496. if (this.source_) {
  92497. this.source_.addFeature(sketchFeature);
  92498. }
  92499. };
  92500. /**
  92501. * Stop drawing without adding the sketch feature to the target layer.
  92502. * @return {ol.Feature} The sketch feature (or null if none).
  92503. * @private
  92504. */
  92505. ol.interaction.Draw.prototype.abortDrawing_ = function() {
  92506. this.finishCoordinate_ = null;
  92507. var sketchFeature = this.sketchFeature_;
  92508. if (sketchFeature) {
  92509. this.sketchFeature_ = null;
  92510. this.sketchPoint_ = null;
  92511. this.sketchLine_ = null;
  92512. this.overlay_.getSource().clear(true);
  92513. }
  92514. return sketchFeature;
  92515. };
  92516. /**
  92517. * Extend an existing geometry by adding additional points. This only works
  92518. * on features with `LineString` geometries, where the interaction will
  92519. * extend lines by adding points to the end of the coordinates array.
  92520. * @param {!ol.Feature} feature Feature to be extended.
  92521. * @api
  92522. */
  92523. ol.interaction.Draw.prototype.extend = function(feature) {
  92524. var geometry = feature.getGeometry();
  92525. goog.asserts.assert(this.mode_ == ol.interaction.DrawMode.LINE_STRING,
  92526. 'interaction mode must be "line"');
  92527. goog.asserts.assert(geometry, 'feature must have a geometry');
  92528. goog.asserts.assert(geometry.getType() == ol.geom.GeometryType.LINE_STRING,
  92529. 'feature geometry must be a line string');
  92530. var lineString = /** @type {ol.geom.LineString} */ (geometry);
  92531. this.sketchFeature_ = feature;
  92532. this.sketchCoords_ = lineString.getCoordinates();
  92533. var last = this.sketchCoords_[this.sketchCoords_.length - 1];
  92534. this.finishCoordinate_ = last.slice();
  92535. this.sketchCoords_.push(last.slice());
  92536. this.updateSketchFeatures_();
  92537. this.dispatchEvent(new ol.interaction.DrawEvent(
  92538. ol.interaction.DrawEventType.DRAWSTART, this.sketchFeature_));
  92539. };
  92540. /**
  92541. * @inheritDoc
  92542. */
  92543. ol.interaction.Draw.prototype.shouldStopEvent = goog.functions.FALSE;
  92544. /**
  92545. * Redraw the sketch features.
  92546. * @private
  92547. */
  92548. ol.interaction.Draw.prototype.updateSketchFeatures_ = function() {
  92549. var sketchFeatures = [];
  92550. if (this.sketchFeature_) {
  92551. sketchFeatures.push(this.sketchFeature_);
  92552. }
  92553. if (this.sketchLine_) {
  92554. sketchFeatures.push(this.sketchLine_);
  92555. }
  92556. if (this.sketchPoint_) {
  92557. sketchFeatures.push(this.sketchPoint_);
  92558. }
  92559. var overlaySource = this.overlay_.getSource();
  92560. overlaySource.clear(true);
  92561. overlaySource.addFeatures(sketchFeatures);
  92562. };
  92563. /**
  92564. * @private
  92565. */
  92566. ol.interaction.Draw.prototype.updateState_ = function() {
  92567. var map = this.getMap();
  92568. var active = this.getActive();
  92569. if (!map || !active) {
  92570. this.abortDrawing_();
  92571. }
  92572. this.overlay_.setMap(active ? map : null);
  92573. };
  92574. /**
  92575. * Create a `geometryFunction` for `mode: 'Circle'` that will create a regular
  92576. * polygon with a user specified number of sides and start angle instead of an
  92577. * `ol.geom.Circle` geometry.
  92578. * @param {number=} opt_sides Number of sides of the regular polygon. Default is
  92579. * 32.
  92580. * @param {number=} opt_angle Angle of the first point in radians. 0 means East.
  92581. * Default is the angle defined by the heading from the center of the
  92582. * regular polygon to the current pointer position.
  92583. * @return {ol.interaction.DrawGeometryFunctionType} Function that draws a
  92584. * polygon.
  92585. * @api
  92586. */
  92587. ol.interaction.Draw.createRegularPolygon = function(opt_sides, opt_angle) {
  92588. return (
  92589. /**
  92590. * @param {ol.Coordinate|Array.<ol.Coordinate>|Array.<Array.<ol.Coordinate>>} coordinates
  92591. * @param {ol.geom.SimpleGeometry=} opt_geometry
  92592. * @return {ol.geom.SimpleGeometry}
  92593. */
  92594. function(coordinates, opt_geometry) {
  92595. var center = coordinates[0];
  92596. var end = coordinates[1];
  92597. var radius = Math.sqrt(
  92598. ol.coordinate.squaredDistance(center, end));
  92599. var geometry = opt_geometry ? opt_geometry :
  92600. ol.geom.Polygon.fromCircle(new ol.geom.Circle(center), opt_sides);
  92601. goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
  92602. 'geometry must be a polygon');
  92603. var angle = opt_angle ? opt_angle :
  92604. Math.atan((end[1] - center[1]) / (end[0] - center[0]));
  92605. ol.geom.Polygon.makeRegular(geometry, center, radius, angle);
  92606. return geometry;
  92607. }
  92608. );
  92609. };
  92610. /**
  92611. * Get the drawing mode. The mode for mult-part geometries is the same as for
  92612. * their single-part cousins.
  92613. * @param {ol.geom.GeometryType} type Geometry type.
  92614. * @return {ol.interaction.DrawMode} Drawing mode.
  92615. * @private
  92616. */
  92617. ol.interaction.Draw.getMode_ = function(type) {
  92618. var mode;
  92619. if (type === ol.geom.GeometryType.POINT ||
  92620. type === ol.geom.GeometryType.MULTI_POINT) {
  92621. mode = ol.interaction.DrawMode.POINT;
  92622. } else if (type === ol.geom.GeometryType.LINE_STRING ||
  92623. type === ol.geom.GeometryType.MULTI_LINE_STRING) {
  92624. mode = ol.interaction.DrawMode.LINE_STRING;
  92625. } else if (type === ol.geom.GeometryType.POLYGON ||
  92626. type === ol.geom.GeometryType.MULTI_POLYGON) {
  92627. mode = ol.interaction.DrawMode.POLYGON;
  92628. } else if (type === ol.geom.GeometryType.CIRCLE) {
  92629. mode = ol.interaction.DrawMode.CIRCLE;
  92630. }
  92631. goog.asserts.assert(mode !== undefined, 'mode should be defined');
  92632. return mode;
  92633. };
  92634. /**
  92635. * Function that takes coordinates and an optional existing geometry as
  92636. * arguments, and returns a geometry. The optional existing geometry is the
  92637. * geometry that is returned when the function is called without a second
  92638. * argument.
  92639. * @typedef {function(!(ol.Coordinate|Array.<ol.Coordinate>|
  92640. * Array.<Array.<ol.Coordinate>>), ol.geom.SimpleGeometry=):
  92641. * ol.geom.SimpleGeometry}
  92642. * @api
  92643. */
  92644. ol.interaction.DrawGeometryFunctionType;
  92645. /**
  92646. * Draw mode. This collapses multi-part geometry types with their single-part
  92647. * cousins.
  92648. * @enum {string}
  92649. */
  92650. ol.interaction.DrawMode = {
  92651. POINT: 'Point',
  92652. LINE_STRING: 'LineString',
  92653. POLYGON: 'Polygon',
  92654. CIRCLE: 'Circle'
  92655. };
  92656. goog.provide('ol.interaction.Modify');
  92657. goog.provide('ol.interaction.ModifyEvent');
  92658. goog.require('goog.array');
  92659. goog.require('goog.asserts');
  92660. goog.require('goog.events');
  92661. goog.require('goog.events.Event');
  92662. goog.require('goog.events.EventType');
  92663. goog.require('goog.functions');
  92664. goog.require('ol');
  92665. goog.require('ol.Collection');
  92666. goog.require('ol.CollectionEventType');
  92667. goog.require('ol.Feature');
  92668. goog.require('ol.MapBrowserEvent.EventType');
  92669. goog.require('ol.MapBrowserPointerEvent');
  92670. goog.require('ol.ViewHint');
  92671. goog.require('ol.coordinate');
  92672. goog.require('ol.events.condition');
  92673. goog.require('ol.extent');
  92674. goog.require('ol.geom.GeometryType');
  92675. goog.require('ol.geom.LineString');
  92676. goog.require('ol.geom.MultiLineString');
  92677. goog.require('ol.geom.MultiPoint');
  92678. goog.require('ol.geom.MultiPolygon');
  92679. goog.require('ol.geom.Point');
  92680. goog.require('ol.geom.Polygon');
  92681. goog.require('ol.interaction.Pointer');
  92682. goog.require('ol.layer.Vector');
  92683. goog.require('ol.source.Vector');
  92684. goog.require('ol.structs.RBush');
  92685. /**
  92686. * @enum {string}
  92687. */
  92688. ol.ModifyEventType = {
  92689. /**
  92690. * Triggered upon feature modification start
  92691. * @event ol.interaction.ModifyEvent#modifystart
  92692. * @api
  92693. */
  92694. MODIFYSTART: 'modifystart',
  92695. /**
  92696. * Triggered upon feature modification end
  92697. * @event ol.interaction.ModifyEvent#modifyend
  92698. * @api
  92699. */
  92700. MODIFYEND: 'modifyend'
  92701. };
  92702. /**
  92703. * @classdesc
  92704. * Events emitted by {@link ol.interaction.Modify} instances are instances of
  92705. * this type.
  92706. *
  92707. * @constructor
  92708. * @extends {goog.events.Event}
  92709. * @implements {oli.ModifyEvent}
  92710. * @param {ol.ModifyEventType} type Type.
  92711. * @param {ol.Collection.<ol.Feature>} features The features modified.
  92712. * @param {ol.MapBrowserPointerEvent} mapBrowserPointerEvent Associated
  92713. * {@link ol.MapBrowserPointerEvent}.
  92714. */
  92715. ol.interaction.ModifyEvent = function(type, features, mapBrowserPointerEvent) {
  92716. goog.base(this, type);
  92717. /**
  92718. * The features being modified.
  92719. * @type {ol.Collection.<ol.Feature>}
  92720. * @api
  92721. */
  92722. this.features = features;
  92723. /**
  92724. * Associated {@link ol.MapBrowserPointerEvent}.
  92725. * @type {ol.MapBrowserPointerEvent}
  92726. * @api
  92727. */
  92728. this.mapBrowserPointerEvent = mapBrowserPointerEvent;
  92729. };
  92730. goog.inherits(ol.interaction.ModifyEvent, goog.events.Event);
  92731. /**
  92732. * @typedef {{depth: (Array.<number>|undefined),
  92733. * feature: ol.Feature,
  92734. * geometry: ol.geom.SimpleGeometry,
  92735. * index: (number|undefined),
  92736. * segment: Array.<ol.Extent>}}
  92737. */
  92738. ol.interaction.SegmentDataType;
  92739. /**
  92740. * @classdesc
  92741. * Interaction for modifying feature geometries.
  92742. *
  92743. * @constructor
  92744. * @extends {ol.interaction.Pointer}
  92745. * @param {olx.interaction.ModifyOptions} options Options.
  92746. * @fires ol.interaction.ModifyEvent
  92747. * @api
  92748. */
  92749. ol.interaction.Modify = function(options) {
  92750. goog.base(this, {
  92751. handleDownEvent: ol.interaction.Modify.handleDownEvent_,
  92752. handleDragEvent: ol.interaction.Modify.handleDragEvent_,
  92753. handleEvent: ol.interaction.Modify.handleEvent,
  92754. handleUpEvent: ol.interaction.Modify.handleUpEvent_
  92755. });
  92756. /**
  92757. * @type {ol.events.ConditionType}
  92758. * @private
  92759. */
  92760. this.deleteCondition_ = options.deleteCondition ?
  92761. options.deleteCondition :
  92762. /** @type {ol.events.ConditionType} */ (goog.functions.and(
  92763. ol.events.condition.noModifierKeys,
  92764. ol.events.condition.singleClick));
  92765. /**
  92766. * Editing vertex.
  92767. * @type {ol.Feature}
  92768. * @private
  92769. */
  92770. this.vertexFeature_ = null;
  92771. /**
  92772. * Segments intersecting {@link this.vertexFeature_} by segment uid.
  92773. * @type {Object.<string, boolean>}
  92774. * @private
  92775. */
  92776. this.vertexSegments_ = null;
  92777. /**
  92778. * @type {ol.Pixel}
  92779. * @private
  92780. */
  92781. this.lastPixel_ = [0, 0];
  92782. /**
  92783. * Tracks if the next `singleclick` event should be ignored to prevent
  92784. * accidental deletion right after vertex creation.
  92785. * @type {boolean}
  92786. * @private
  92787. */
  92788. this.ignoreNextSingleClick_ = false;
  92789. /**
  92790. * @type {boolean}
  92791. * @private
  92792. */
  92793. this.modified_ = false;
  92794. /**
  92795. * Segment RTree for each layer
  92796. * @type {ol.structs.RBush.<ol.interaction.SegmentDataType>}
  92797. * @private
  92798. */
  92799. this.rBush_ = new ol.structs.RBush();
  92800. /**
  92801. * @type {number}
  92802. * @private
  92803. */
  92804. this.pixelTolerance_ = options.pixelTolerance !== undefined ?
  92805. options.pixelTolerance : 10;
  92806. /**
  92807. * @type {boolean}
  92808. * @private
  92809. */
  92810. this.snappedToVertex_ = false;
  92811. /**
  92812. * Indicate whether the interaction is currently changing a feature's
  92813. * coordinates.
  92814. * @type {boolean}
  92815. * @private
  92816. */
  92817. this.changingFeature_ = false;
  92818. /**
  92819. * @type {Array}
  92820. * @private
  92821. */
  92822. this.dragSegments_ = null;
  92823. /**
  92824. * Draw overlay where sketch features are drawn.
  92825. * @type {ol.layer.Vector}
  92826. * @private
  92827. */
  92828. this.overlay_ = new ol.layer.Vector({
  92829. source: new ol.source.Vector({
  92830. useSpatialIndex: false,
  92831. wrapX: !!options.wrapX
  92832. }),
  92833. style: options.style ? options.style :
  92834. ol.interaction.Modify.getDefaultStyleFunction(),
  92835. updateWhileAnimating: true,
  92836. updateWhileInteracting: true
  92837. });
  92838. /**
  92839. * @const
  92840. * @private
  92841. * @type {Object.<string, function(ol.Feature, ol.geom.Geometry)> }
  92842. */
  92843. this.SEGMENT_WRITERS_ = {
  92844. 'Point': this.writePointGeometry_,
  92845. 'LineString': this.writeLineStringGeometry_,
  92846. 'LinearRing': this.writeLineStringGeometry_,
  92847. 'Polygon': this.writePolygonGeometry_,
  92848. 'MultiPoint': this.writeMultiPointGeometry_,
  92849. 'MultiLineString': this.writeMultiLineStringGeometry_,
  92850. 'MultiPolygon': this.writeMultiPolygonGeometry_,
  92851. 'GeometryCollection': this.writeGeometryCollectionGeometry_
  92852. };
  92853. /**
  92854. * @type {ol.Collection.<ol.Feature>}
  92855. * @private
  92856. */
  92857. this.features_ = options.features;
  92858. this.features_.forEach(this.addFeature_, this);
  92859. goog.events.listen(this.features_, ol.CollectionEventType.ADD,
  92860. this.handleFeatureAdd_, false, this);
  92861. goog.events.listen(this.features_, ol.CollectionEventType.REMOVE,
  92862. this.handleFeatureRemove_, false, this);
  92863. };
  92864. goog.inherits(ol.interaction.Modify, ol.interaction.Pointer);
  92865. /**
  92866. * @param {ol.Feature} feature Feature.
  92867. * @private
  92868. */
  92869. ol.interaction.Modify.prototype.addFeature_ = function(feature) {
  92870. var geometry = feature.getGeometry();
  92871. if (geometry.getType() in this.SEGMENT_WRITERS_) {
  92872. this.SEGMENT_WRITERS_[geometry.getType()].call(this, feature, geometry);
  92873. }
  92874. var map = this.getMap();
  92875. if (map) {
  92876. this.handlePointerAtPixel_(this.lastPixel_, map);
  92877. }
  92878. goog.events.listen(feature, goog.events.EventType.CHANGE,
  92879. this.handleFeatureChange_, false, this);
  92880. };
  92881. /**
  92882. * @param {ol.MapBrowserPointerEvent} evt Map browser event
  92883. * @private
  92884. */
  92885. ol.interaction.Modify.prototype.willModifyFeatures_ = function(evt) {
  92886. if (!this.modified_) {
  92887. this.modified_ = true;
  92888. this.dispatchEvent(new ol.interaction.ModifyEvent(
  92889. ol.ModifyEventType.MODIFYSTART, this.features_, evt));
  92890. }
  92891. };
  92892. /**
  92893. * @param {ol.Feature} feature Feature.
  92894. * @private
  92895. */
  92896. ol.interaction.Modify.prototype.removeFeature_ = function(feature) {
  92897. this.removeFeatureSegmentData_(feature);
  92898. // Remove the vertex feature if the collection of canditate features
  92899. // is empty.
  92900. if (this.vertexFeature_ && this.features_.getLength() === 0) {
  92901. this.overlay_.getSource().removeFeature(this.vertexFeature_);
  92902. this.vertexFeature_ = null;
  92903. }
  92904. goog.events.unlisten(feature, goog.events.EventType.CHANGE,
  92905. this.handleFeatureChange_, false, this);
  92906. };
  92907. /**
  92908. * @param {ol.Feature} feature Feature.
  92909. * @private
  92910. */
  92911. ol.interaction.Modify.prototype.removeFeatureSegmentData_ = function(feature) {
  92912. var rBush = this.rBush_;
  92913. var /** @type {Array.<ol.interaction.SegmentDataType>} */ nodesToRemove = [];
  92914. rBush.forEach(
  92915. /**
  92916. * @param {ol.interaction.SegmentDataType} node RTree node.
  92917. */
  92918. function(node) {
  92919. if (feature === node.feature) {
  92920. nodesToRemove.push(node);
  92921. }
  92922. });
  92923. for (var i = nodesToRemove.length - 1; i >= 0; --i) {
  92924. rBush.remove(nodesToRemove[i]);
  92925. }
  92926. };
  92927. /**
  92928. * @inheritDoc
  92929. */
  92930. ol.interaction.Modify.prototype.setMap = function(map) {
  92931. this.overlay_.setMap(map);
  92932. goog.base(this, 'setMap', map);
  92933. };
  92934. /**
  92935. * @param {ol.CollectionEvent} evt Event.
  92936. * @private
  92937. */
  92938. ol.interaction.Modify.prototype.handleFeatureAdd_ = function(evt) {
  92939. var feature = evt.element;
  92940. goog.asserts.assertInstanceof(feature, ol.Feature,
  92941. 'feature should be an ol.Feature');
  92942. this.addFeature_(feature);
  92943. };
  92944. /**
  92945. * @param {goog.events.Event} evt Event.
  92946. * @private
  92947. */
  92948. ol.interaction.Modify.prototype.handleFeatureChange_ = function(evt) {
  92949. if (!this.changingFeature_) {
  92950. var feature = /** @type {ol.Feature} */ (evt.target);
  92951. this.removeFeature_(feature);
  92952. this.addFeature_(feature);
  92953. }
  92954. };
  92955. /**
  92956. * @param {ol.CollectionEvent} evt Event.
  92957. * @private
  92958. */
  92959. ol.interaction.Modify.prototype.handleFeatureRemove_ = function(evt) {
  92960. var feature = /** @type {ol.Feature} */ (evt.element);
  92961. this.removeFeature_(feature);
  92962. };
  92963. /**
  92964. * @param {ol.Feature} feature Feature
  92965. * @param {ol.geom.Point} geometry Geometry.
  92966. * @private
  92967. */
  92968. ol.interaction.Modify.prototype.writePointGeometry_ =
  92969. function(feature, geometry) {
  92970. var coordinates = geometry.getCoordinates();
  92971. var segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  92972. feature: feature,
  92973. geometry: geometry,
  92974. segment: [coordinates, coordinates]
  92975. });
  92976. this.rBush_.insert(geometry.getExtent(), segmentData);
  92977. };
  92978. /**
  92979. * @param {ol.Feature} feature Feature
  92980. * @param {ol.geom.MultiPoint} geometry Geometry.
  92981. * @private
  92982. */
  92983. ol.interaction.Modify.prototype.writeMultiPointGeometry_ =
  92984. function(feature, geometry) {
  92985. var points = geometry.getCoordinates();
  92986. var coordinates, i, ii, segmentData;
  92987. for (i = 0, ii = points.length; i < ii; ++i) {
  92988. coordinates = points[i];
  92989. segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  92990. feature: feature,
  92991. geometry: geometry,
  92992. depth: [i],
  92993. index: i,
  92994. segment: [coordinates, coordinates]
  92995. });
  92996. this.rBush_.insert(geometry.getExtent(), segmentData);
  92997. }
  92998. };
  92999. /**
  93000. * @param {ol.Feature} feature Feature
  93001. * @param {ol.geom.LineString} geometry Geometry.
  93002. * @private
  93003. */
  93004. ol.interaction.Modify.prototype.writeLineStringGeometry_ =
  93005. function(feature, geometry) {
  93006. var coordinates = geometry.getCoordinates();
  93007. var i, ii, segment, segmentData;
  93008. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  93009. segment = coordinates.slice(i, i + 2);
  93010. segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93011. feature: feature,
  93012. geometry: geometry,
  93013. index: i,
  93014. segment: segment
  93015. });
  93016. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  93017. }
  93018. };
  93019. /**
  93020. * @param {ol.Feature} feature Feature
  93021. * @param {ol.geom.MultiLineString} geometry Geometry.
  93022. * @private
  93023. */
  93024. ol.interaction.Modify.prototype.writeMultiLineStringGeometry_ =
  93025. function(feature, geometry) {
  93026. var lines = geometry.getCoordinates();
  93027. var coordinates, i, ii, j, jj, segment, segmentData;
  93028. for (j = 0, jj = lines.length; j < jj; ++j) {
  93029. coordinates = lines[j];
  93030. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  93031. segment = coordinates.slice(i, i + 2);
  93032. segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93033. feature: feature,
  93034. geometry: geometry,
  93035. depth: [j],
  93036. index: i,
  93037. segment: segment
  93038. });
  93039. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  93040. }
  93041. }
  93042. };
  93043. /**
  93044. * @param {ol.Feature} feature Feature
  93045. * @param {ol.geom.Polygon} geometry Geometry.
  93046. * @private
  93047. */
  93048. ol.interaction.Modify.prototype.writePolygonGeometry_ =
  93049. function(feature, geometry) {
  93050. var rings = geometry.getCoordinates();
  93051. var coordinates, i, ii, j, jj, segment, segmentData;
  93052. for (j = 0, jj = rings.length; j < jj; ++j) {
  93053. coordinates = rings[j];
  93054. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  93055. segment = coordinates.slice(i, i + 2);
  93056. segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93057. feature: feature,
  93058. geometry: geometry,
  93059. depth: [j],
  93060. index: i,
  93061. segment: segment
  93062. });
  93063. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  93064. }
  93065. }
  93066. };
  93067. /**
  93068. * @param {ol.Feature} feature Feature
  93069. * @param {ol.geom.MultiPolygon} geometry Geometry.
  93070. * @private
  93071. */
  93072. ol.interaction.Modify.prototype.writeMultiPolygonGeometry_ =
  93073. function(feature, geometry) {
  93074. var polygons = geometry.getCoordinates();
  93075. var coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData;
  93076. for (k = 0, kk = polygons.length; k < kk; ++k) {
  93077. rings = polygons[k];
  93078. for (j = 0, jj = rings.length; j < jj; ++j) {
  93079. coordinates = rings[j];
  93080. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  93081. segment = coordinates.slice(i, i + 2);
  93082. segmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93083. feature: feature,
  93084. geometry: geometry,
  93085. depth: [j, k],
  93086. index: i,
  93087. segment: segment
  93088. });
  93089. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  93090. }
  93091. }
  93092. }
  93093. };
  93094. /**
  93095. * @param {ol.Feature} feature Feature
  93096. * @param {ol.geom.GeometryCollection} geometry Geometry.
  93097. * @private
  93098. */
  93099. ol.interaction.Modify.prototype.writeGeometryCollectionGeometry_ =
  93100. function(feature, geometry) {
  93101. var i, geometries = geometry.getGeometriesArray();
  93102. for (i = 0; i < geometries.length; ++i) {
  93103. this.SEGMENT_WRITERS_[geometries[i].getType()].call(
  93104. this, feature, geometries[i]);
  93105. }
  93106. };
  93107. /**
  93108. * @param {ol.Coordinate} coordinates Coordinates.
  93109. * @return {ol.Feature} Vertex feature.
  93110. * @private
  93111. */
  93112. ol.interaction.Modify.prototype.createOrUpdateVertexFeature_ =
  93113. function(coordinates) {
  93114. var vertexFeature = this.vertexFeature_;
  93115. if (!vertexFeature) {
  93116. vertexFeature = new ol.Feature(new ol.geom.Point(coordinates));
  93117. this.vertexFeature_ = vertexFeature;
  93118. this.overlay_.getSource().addFeature(vertexFeature);
  93119. } else {
  93120. var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry());
  93121. geometry.setCoordinates(coordinates);
  93122. }
  93123. return vertexFeature;
  93124. };
  93125. /**
  93126. * @param {ol.interaction.SegmentDataType} a
  93127. * @param {ol.interaction.SegmentDataType} b
  93128. * @return {number}
  93129. * @private
  93130. */
  93131. ol.interaction.Modify.compareIndexes_ = function(a, b) {
  93132. return a.index - b.index;
  93133. };
  93134. /**
  93135. * @param {ol.MapBrowserPointerEvent} evt Event.
  93136. * @return {boolean} Start drag sequence?
  93137. * @this {ol.interaction.Modify}
  93138. * @private
  93139. */
  93140. ol.interaction.Modify.handleDownEvent_ = function(evt) {
  93141. this.handlePointerAtPixel_(evt.pixel, evt.map);
  93142. this.dragSegments_ = [];
  93143. this.modified_ = false;
  93144. var vertexFeature = this.vertexFeature_;
  93145. if (vertexFeature) {
  93146. var insertVertices = [];
  93147. var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry());
  93148. var vertex = geometry.getCoordinates();
  93149. var vertexExtent = ol.extent.boundingExtent([vertex]);
  93150. var segmentDataMatches = this.rBush_.getInExtent(vertexExtent);
  93151. var componentSegments = {};
  93152. segmentDataMatches.sort(ol.interaction.Modify.compareIndexes_);
  93153. for (var i = 0, ii = segmentDataMatches.length; i < ii; ++i) {
  93154. var segmentDataMatch = segmentDataMatches[i];
  93155. var segment = segmentDataMatch.segment;
  93156. var uid = goog.getUid(segmentDataMatch.feature);
  93157. var depth = segmentDataMatch.depth;
  93158. if (depth) {
  93159. uid += '-' + depth.join('-'); // separate feature components
  93160. }
  93161. if (!componentSegments[uid]) {
  93162. componentSegments[uid] = new Array(2);
  93163. }
  93164. if (ol.coordinate.equals(segment[0], vertex) &&
  93165. !componentSegments[uid][0]) {
  93166. this.dragSegments_.push([segmentDataMatch, 0]);
  93167. componentSegments[uid][0] = segmentDataMatch;
  93168. } else if (ol.coordinate.equals(segment[1], vertex) &&
  93169. !componentSegments[uid][1]) {
  93170. // prevent dragging closed linestrings by the connecting node
  93171. if ((segmentDataMatch.geometry.getType() ===
  93172. ol.geom.GeometryType.LINE_STRING ||
  93173. segmentDataMatch.geometry.getType() ===
  93174. ol.geom.GeometryType.MULTI_LINE_STRING) &&
  93175. componentSegments[uid][0] &&
  93176. componentSegments[uid][0].index === 0) {
  93177. continue;
  93178. }
  93179. this.dragSegments_.push([segmentDataMatch, 1]);
  93180. componentSegments[uid][1] = segmentDataMatch;
  93181. } else if (goog.getUid(segment) in this.vertexSegments_ &&
  93182. (!componentSegments[uid][0] && !componentSegments[uid][1])) {
  93183. insertVertices.push([segmentDataMatch, vertex]);
  93184. }
  93185. }
  93186. if (insertVertices.length) {
  93187. this.willModifyFeatures_(evt);
  93188. }
  93189. for (i = insertVertices.length - 1; i >= 0; --i) {
  93190. this.insertVertex_.apply(this, insertVertices[i]);
  93191. }
  93192. }
  93193. return !!this.vertexFeature_;
  93194. };
  93195. /**
  93196. * @param {ol.MapBrowserPointerEvent} evt Event.
  93197. * @this {ol.interaction.Modify}
  93198. * @private
  93199. */
  93200. ol.interaction.Modify.handleDragEvent_ = function(evt) {
  93201. this.ignoreNextSingleClick_ = false;
  93202. this.willModifyFeatures_(evt);
  93203. var vertex = evt.coordinate;
  93204. for (var i = 0, ii = this.dragSegments_.length; i < ii; ++i) {
  93205. var dragSegment = this.dragSegments_[i];
  93206. var segmentData = dragSegment[0];
  93207. var depth = segmentData.depth;
  93208. var geometry = segmentData.geometry;
  93209. var coordinates = geometry.getCoordinates();
  93210. var segment = segmentData.segment;
  93211. var index = dragSegment[1];
  93212. while (vertex.length < geometry.getStride()) {
  93213. vertex.push(0);
  93214. }
  93215. switch (geometry.getType()) {
  93216. case ol.geom.GeometryType.POINT:
  93217. coordinates = vertex;
  93218. segment[0] = segment[1] = vertex;
  93219. break;
  93220. case ol.geom.GeometryType.MULTI_POINT:
  93221. coordinates[segmentData.index] = vertex;
  93222. segment[0] = segment[1] = vertex;
  93223. break;
  93224. case ol.geom.GeometryType.LINE_STRING:
  93225. coordinates[segmentData.index + index] = vertex;
  93226. segment[index] = vertex;
  93227. break;
  93228. case ol.geom.GeometryType.MULTI_LINE_STRING:
  93229. coordinates[depth[0]][segmentData.index + index] = vertex;
  93230. segment[index] = vertex;
  93231. break;
  93232. case ol.geom.GeometryType.POLYGON:
  93233. coordinates[depth[0]][segmentData.index + index] = vertex;
  93234. segment[index] = vertex;
  93235. break;
  93236. case ol.geom.GeometryType.MULTI_POLYGON:
  93237. coordinates[depth[1]][depth[0]][segmentData.index + index] = vertex;
  93238. segment[index] = vertex;
  93239. break;
  93240. }
  93241. this.setGeometryCoordinates_(geometry, coordinates);
  93242. }
  93243. this.createOrUpdateVertexFeature_(vertex);
  93244. };
  93245. /**
  93246. * @param {ol.MapBrowserPointerEvent} evt Event.
  93247. * @return {boolean} Stop drag sequence?
  93248. * @this {ol.interaction.Modify}
  93249. * @private
  93250. */
  93251. ol.interaction.Modify.handleUpEvent_ = function(evt) {
  93252. var segmentData;
  93253. for (var i = this.dragSegments_.length - 1; i >= 0; --i) {
  93254. segmentData = this.dragSegments_[i][0];
  93255. this.rBush_.update(ol.extent.boundingExtent(segmentData.segment),
  93256. segmentData);
  93257. }
  93258. if (this.modified_) {
  93259. this.dispatchEvent(new ol.interaction.ModifyEvent(
  93260. ol.ModifyEventType.MODIFYEND, this.features_, evt));
  93261. this.modified_ = false;
  93262. }
  93263. return false;
  93264. };
  93265. /**
  93266. * Handles the {@link ol.MapBrowserEvent map browser event} and may modify the
  93267. * geometry.
  93268. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  93269. * @return {boolean} `false` to stop event propagation.
  93270. * @this {ol.interaction.Modify}
  93271. * @api
  93272. */
  93273. ol.interaction.Modify.handleEvent = function(mapBrowserEvent) {
  93274. if (!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent)) {
  93275. return true;
  93276. }
  93277. var handled;
  93278. if (!mapBrowserEvent.map.getView().getHints()[ol.ViewHint.INTERACTING] &&
  93279. mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERMOVE &&
  93280. !this.handlingDownUpSequence) {
  93281. this.handlePointerMove_(mapBrowserEvent);
  93282. }
  93283. if (this.vertexFeature_ && this.deleteCondition_(mapBrowserEvent)) {
  93284. if (mapBrowserEvent.type != ol.MapBrowserEvent.EventType.SINGLECLICK ||
  93285. !this.ignoreNextSingleClick_) {
  93286. var geometry = this.vertexFeature_.getGeometry();
  93287. goog.asserts.assertInstanceof(geometry, ol.geom.Point,
  93288. 'geometry should be an ol.geom.Point');
  93289. this.willModifyFeatures_(mapBrowserEvent);
  93290. handled = this.removeVertex_();
  93291. this.dispatchEvent(new ol.interaction.ModifyEvent(
  93292. ol.ModifyEventType.MODIFYEND, this.features_, mapBrowserEvent));
  93293. this.modified_ = false;
  93294. } else {
  93295. handled = true;
  93296. }
  93297. }
  93298. if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.SINGLECLICK) {
  93299. this.ignoreNextSingleClick_ = false;
  93300. }
  93301. return ol.interaction.Pointer.handleEvent.call(this, mapBrowserEvent) &&
  93302. !handled;
  93303. };
  93304. /**
  93305. * @param {ol.MapBrowserEvent} evt Event.
  93306. * @private
  93307. */
  93308. ol.interaction.Modify.prototype.handlePointerMove_ = function(evt) {
  93309. this.lastPixel_ = evt.pixel;
  93310. this.handlePointerAtPixel_(evt.pixel, evt.map);
  93311. };
  93312. /**
  93313. * @param {ol.Pixel} pixel Pixel
  93314. * @param {ol.Map} map Map.
  93315. * @private
  93316. */
  93317. ol.interaction.Modify.prototype.handlePointerAtPixel_ = function(pixel, map) {
  93318. var pixelCoordinate = map.getCoordinateFromPixel(pixel);
  93319. var sortByDistance = function(a, b) {
  93320. return ol.coordinate.squaredDistanceToSegment(pixelCoordinate, a.segment) -
  93321. ol.coordinate.squaredDistanceToSegment(pixelCoordinate, b.segment);
  93322. };
  93323. var lowerLeft = map.getCoordinateFromPixel(
  93324. [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]);
  93325. var upperRight = map.getCoordinateFromPixel(
  93326. [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]);
  93327. var box = ol.extent.boundingExtent([lowerLeft, upperRight]);
  93328. var rBush = this.rBush_;
  93329. var nodes = rBush.getInExtent(box);
  93330. if (nodes.length > 0) {
  93331. nodes.sort(sortByDistance);
  93332. var node = nodes[0];
  93333. var closestSegment = node.segment;
  93334. var vertex = (ol.coordinate.closestOnSegment(pixelCoordinate,
  93335. closestSegment));
  93336. var vertexPixel = map.getPixelFromCoordinate(vertex);
  93337. if (Math.sqrt(ol.coordinate.squaredDistance(pixel, vertexPixel)) <=
  93338. this.pixelTolerance_) {
  93339. var pixel1 = map.getPixelFromCoordinate(closestSegment[0]);
  93340. var pixel2 = map.getPixelFromCoordinate(closestSegment[1]);
  93341. var squaredDist1 = ol.coordinate.squaredDistance(vertexPixel, pixel1);
  93342. var squaredDist2 = ol.coordinate.squaredDistance(vertexPixel, pixel2);
  93343. var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));
  93344. this.snappedToVertex_ = dist <= this.pixelTolerance_;
  93345. if (this.snappedToVertex_) {
  93346. vertex = squaredDist1 > squaredDist2 ?
  93347. closestSegment[1] : closestSegment[0];
  93348. }
  93349. this.createOrUpdateVertexFeature_(vertex);
  93350. var vertexSegments = {};
  93351. vertexSegments[goog.getUid(closestSegment)] = true;
  93352. var segment;
  93353. for (var i = 1, ii = nodes.length; i < ii; ++i) {
  93354. segment = nodes[i].segment;
  93355. if ((ol.coordinate.equals(closestSegment[0], segment[0]) &&
  93356. ol.coordinate.equals(closestSegment[1], segment[1]) ||
  93357. (ol.coordinate.equals(closestSegment[0], segment[1]) &&
  93358. ol.coordinate.equals(closestSegment[1], segment[0])))) {
  93359. vertexSegments[goog.getUid(segment)] = true;
  93360. } else {
  93361. break;
  93362. }
  93363. }
  93364. this.vertexSegments_ = vertexSegments;
  93365. return;
  93366. }
  93367. }
  93368. if (this.vertexFeature_) {
  93369. this.overlay_.getSource().removeFeature(this.vertexFeature_);
  93370. this.vertexFeature_ = null;
  93371. }
  93372. };
  93373. /**
  93374. * @param {ol.interaction.SegmentDataType} segmentData Segment data.
  93375. * @param {ol.Coordinate} vertex Vertex.
  93376. * @private
  93377. */
  93378. ol.interaction.Modify.prototype.insertVertex_ = function(segmentData, vertex) {
  93379. var segment = segmentData.segment;
  93380. var feature = segmentData.feature;
  93381. var geometry = segmentData.geometry;
  93382. var depth = segmentData.depth;
  93383. var index = segmentData.index;
  93384. var coordinates;
  93385. while (vertex.length < geometry.getStride()) {
  93386. vertex.push(0);
  93387. }
  93388. switch (geometry.getType()) {
  93389. case ol.geom.GeometryType.MULTI_LINE_STRING:
  93390. goog.asserts.assertInstanceof(geometry, ol.geom.MultiLineString,
  93391. 'geometry should be an ol.geom.MultiLineString');
  93392. coordinates = geometry.getCoordinates();
  93393. coordinates[depth[0]].splice(index + 1, 0, vertex);
  93394. break;
  93395. case ol.geom.GeometryType.POLYGON:
  93396. goog.asserts.assertInstanceof(geometry, ol.geom.Polygon,
  93397. 'geometry should be an ol.geom.Polygon');
  93398. coordinates = geometry.getCoordinates();
  93399. coordinates[depth[0]].splice(index + 1, 0, vertex);
  93400. break;
  93401. case ol.geom.GeometryType.MULTI_POLYGON:
  93402. goog.asserts.assertInstanceof(geometry, ol.geom.MultiPolygon,
  93403. 'geometry should be an ol.geom.MultiPolygon');
  93404. coordinates = geometry.getCoordinates();
  93405. coordinates[depth[1]][depth[0]].splice(index + 1, 0, vertex);
  93406. break;
  93407. case ol.geom.GeometryType.LINE_STRING:
  93408. goog.asserts.assertInstanceof(geometry, ol.geom.LineString,
  93409. 'geometry should be an ol.geom.LineString');
  93410. coordinates = geometry.getCoordinates();
  93411. coordinates.splice(index + 1, 0, vertex);
  93412. break;
  93413. default:
  93414. return;
  93415. }
  93416. this.setGeometryCoordinates_(geometry, coordinates);
  93417. var rTree = this.rBush_;
  93418. goog.asserts.assert(segment !== undefined, 'segment should be defined');
  93419. rTree.remove(segmentData);
  93420. goog.asserts.assert(index !== undefined, 'index should be defined');
  93421. this.updateSegmentIndices_(geometry, index, depth, 1);
  93422. var newSegmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93423. segment: [segment[0], vertex],
  93424. feature: feature,
  93425. geometry: geometry,
  93426. depth: depth,
  93427. index: index
  93428. });
  93429. rTree.insert(ol.extent.boundingExtent(newSegmentData.segment),
  93430. newSegmentData);
  93431. this.dragSegments_.push([newSegmentData, 1]);
  93432. var newSegmentData2 = /** @type {ol.interaction.SegmentDataType} */ ({
  93433. segment: [vertex, segment[1]],
  93434. feature: feature,
  93435. geometry: geometry,
  93436. depth: depth,
  93437. index: index + 1
  93438. });
  93439. rTree.insert(ol.extent.boundingExtent(newSegmentData2.segment),
  93440. newSegmentData2);
  93441. this.dragSegments_.push([newSegmentData2, 0]);
  93442. this.ignoreNextSingleClick_ = true;
  93443. };
  93444. /**
  93445. * Removes a vertex from all matching features.
  93446. * @return {boolean} True when a vertex was removed.
  93447. * @private
  93448. */
  93449. ol.interaction.Modify.prototype.removeVertex_ = function() {
  93450. var dragSegments = this.dragSegments_;
  93451. var segmentsByFeature = {};
  93452. var component, coordinates, dragSegment, geometry, i, index, left;
  93453. var newIndex, newSegment, right, segmentData, uid, deleted;
  93454. for (i = dragSegments.length - 1; i >= 0; --i) {
  93455. dragSegment = dragSegments[i];
  93456. segmentData = dragSegment[0];
  93457. geometry = segmentData.geometry;
  93458. coordinates = geometry.getCoordinates();
  93459. uid = goog.getUid(segmentData.feature);
  93460. if (segmentData.depth) {
  93461. // separate feature components
  93462. uid += '-' + segmentData.depth.join('-');
  93463. }
  93464. left = right = index = undefined;
  93465. if (dragSegment[1] === 0) {
  93466. right = segmentData;
  93467. index = segmentData.index;
  93468. } else if (dragSegment[1] == 1) {
  93469. left = segmentData;
  93470. index = segmentData.index + 1;
  93471. }
  93472. if (!(uid in segmentsByFeature)) {
  93473. segmentsByFeature[uid] = [left, right, index];
  93474. }
  93475. newSegment = segmentsByFeature[uid];
  93476. if (left !== undefined) {
  93477. newSegment[0] = left;
  93478. }
  93479. if (right !== undefined) {
  93480. newSegment[1] = right;
  93481. }
  93482. if (newSegment[0] !== undefined && newSegment[1] !== undefined) {
  93483. component = coordinates;
  93484. deleted = false;
  93485. newIndex = index - 1;
  93486. switch (geometry.getType()) {
  93487. case ol.geom.GeometryType.MULTI_LINE_STRING:
  93488. coordinates[segmentData.depth[0]].splice(index, 1);
  93489. deleted = true;
  93490. break;
  93491. case ol.geom.GeometryType.LINE_STRING:
  93492. coordinates.splice(index, 1);
  93493. deleted = true;
  93494. break;
  93495. case ol.geom.GeometryType.MULTI_POLYGON:
  93496. component = component[segmentData.depth[1]];
  93497. /* falls through */
  93498. case ol.geom.GeometryType.POLYGON:
  93499. component = component[segmentData.depth[0]];
  93500. if (component.length > 4) {
  93501. if (index == component.length - 1) {
  93502. index = 0;
  93503. }
  93504. component.splice(index, 1);
  93505. deleted = true;
  93506. if (index === 0) {
  93507. // close the ring again
  93508. component.pop();
  93509. component.push(component[0]);
  93510. newIndex = component.length - 1;
  93511. }
  93512. }
  93513. break;
  93514. }
  93515. if (deleted) {
  93516. this.rBush_.remove(newSegment[0]);
  93517. this.rBush_.remove(newSegment[1]);
  93518. this.setGeometryCoordinates_(geometry, coordinates);
  93519. goog.asserts.assert(newIndex >= 0, 'newIndex should be larger than 0');
  93520. var newSegmentData = /** @type {ol.interaction.SegmentDataType} */ ({
  93521. depth: segmentData.depth,
  93522. feature: segmentData.feature,
  93523. geometry: segmentData.geometry,
  93524. index: newIndex,
  93525. segment: [newSegment[0].segment[0], newSegment[1].segment[1]]
  93526. });
  93527. this.rBush_.insert(ol.extent.boundingExtent(newSegmentData.segment),
  93528. newSegmentData);
  93529. this.updateSegmentIndices_(geometry, index, segmentData.depth, -1);
  93530. if (this.vertexFeature_) {
  93531. this.overlay_.getSource().removeFeature(this.vertexFeature_);
  93532. this.vertexFeature_ = null;
  93533. }
  93534. }
  93535. }
  93536. }
  93537. return true;
  93538. };
  93539. /**
  93540. * @param {ol.geom.SimpleGeometry} geometry Geometry.
  93541. * @param {Array} coordinates Coordinates.
  93542. * @private
  93543. */
  93544. ol.interaction.Modify.prototype.setGeometryCoordinates_ =
  93545. function(geometry, coordinates) {
  93546. this.changingFeature_ = true;
  93547. geometry.setCoordinates(coordinates);
  93548. this.changingFeature_ = false;
  93549. };
  93550. /**
  93551. * @param {ol.geom.SimpleGeometry} geometry Geometry.
  93552. * @param {number} index Index.
  93553. * @param {Array.<number>|undefined} depth Depth.
  93554. * @param {number} delta Delta (1 or -1).
  93555. * @private
  93556. */
  93557. ol.interaction.Modify.prototype.updateSegmentIndices_ = function(
  93558. geometry, index, depth, delta) {
  93559. this.rBush_.forEachInExtent(geometry.getExtent(), function(segmentDataMatch) {
  93560. if (segmentDataMatch.geometry === geometry &&
  93561. (depth === undefined || segmentDataMatch.depth === undefined ||
  93562. goog.array.equals(
  93563. /** @type {null|{length: number}} */ (segmentDataMatch.depth),
  93564. depth)) &&
  93565. segmentDataMatch.index > index) {
  93566. segmentDataMatch.index += delta;
  93567. }
  93568. });
  93569. };
  93570. /**
  93571. * @return {ol.style.StyleFunction} Styles.
  93572. */
  93573. ol.interaction.Modify.getDefaultStyleFunction = function() {
  93574. var style = ol.style.createDefaultEditingStyles();
  93575. return function(feature, resolution) {
  93576. return style[ol.geom.GeometryType.POINT];
  93577. };
  93578. };
  93579. goog.provide('ol.interaction.Select');
  93580. goog.provide('ol.interaction.SelectEvent');
  93581. goog.provide('ol.interaction.SelectEventType');
  93582. goog.provide('ol.interaction.SelectFilterFunction');
  93583. goog.require('goog.array');
  93584. goog.require('goog.asserts');
  93585. goog.require('goog.events');
  93586. goog.require('goog.events.Event');
  93587. goog.require('goog.functions');
  93588. goog.require('goog.object');
  93589. goog.require('ol.CollectionEventType');
  93590. goog.require('ol.Feature');
  93591. goog.require('ol.array');
  93592. goog.require('ol.events.condition');
  93593. goog.require('ol.geom.GeometryType');
  93594. goog.require('ol.interaction.Interaction');
  93595. goog.require('ol.layer.Vector');
  93596. goog.require('ol.source.Vector');
  93597. /**
  93598. * @enum {string}
  93599. */
  93600. ol.interaction.SelectEventType = {
  93601. /**
  93602. * Triggered when feature(s) has been (de)selected.
  93603. * @event ol.interaction.SelectEvent#select
  93604. * @api
  93605. */
  93606. SELECT: 'select'
  93607. };
  93608. /**
  93609. * A function that takes an {@link ol.Feature} and an {@link ol.layer.Layer}
  93610. * and returns `true` if the feature may be selected or `false` otherwise.
  93611. * @typedef {function(ol.Feature, ol.layer.Layer): boolean}
  93612. * @api
  93613. */
  93614. ol.interaction.SelectFilterFunction;
  93615. /**
  93616. * @classdesc
  93617. * Events emitted by {@link ol.interaction.Select} instances are instances of
  93618. * this type.
  93619. *
  93620. * @param {string} type The event type.
  93621. * @param {Array.<ol.Feature>} selected Selected features.
  93622. * @param {Array.<ol.Feature>} deselected Deselected features.
  93623. * @param {ol.MapBrowserEvent} mapBrowserEvent Associated
  93624. * {@link ol.MapBrowserEvent}.
  93625. * @implements {oli.SelectEvent}
  93626. * @extends {goog.events.Event}
  93627. * @constructor
  93628. */
  93629. ol.interaction.SelectEvent =
  93630. function(type, selected, deselected, mapBrowserEvent) {
  93631. goog.base(this, type);
  93632. /**
  93633. * Selected features array.
  93634. * @type {Array.<ol.Feature>}
  93635. * @api
  93636. */
  93637. this.selected = selected;
  93638. /**
  93639. * Deselected features array.
  93640. * @type {Array.<ol.Feature>}
  93641. * @api
  93642. */
  93643. this.deselected = deselected;
  93644. /**
  93645. * Associated {@link ol.MapBrowserEvent}.
  93646. * @type {ol.MapBrowserEvent}
  93647. * @api
  93648. */
  93649. this.mapBrowserEvent = mapBrowserEvent;
  93650. };
  93651. goog.inherits(ol.interaction.SelectEvent, goog.events.Event);
  93652. /**
  93653. * @classdesc
  93654. * Interaction for selecting vector features. By default, selected features are
  93655. * styled differently, so this interaction can be used for visual highlighting,
  93656. * as well as selecting features for other actions, such as modification or
  93657. * output. There are three ways of controlling which features are selected:
  93658. * using the browser event as defined by the `condition` and optionally the
  93659. * `toggle`, `add`/`remove`, and `multi` options; a `layers` filter; and a
  93660. * further feature filter using the `filter` option.
  93661. *
  93662. * @constructor
  93663. * @extends {ol.interaction.Interaction}
  93664. * @param {olx.interaction.SelectOptions=} opt_options Options.
  93665. * @fires ol.interaction.SelectEvent
  93666. * @api stable
  93667. */
  93668. ol.interaction.Select = function(opt_options) {
  93669. goog.base(this, {
  93670. handleEvent: ol.interaction.Select.handleEvent
  93671. });
  93672. var options = opt_options ? opt_options : {};
  93673. /**
  93674. * @private
  93675. * @type {ol.events.ConditionType}
  93676. */
  93677. this.condition_ = options.condition ?
  93678. options.condition : ol.events.condition.singleClick;
  93679. /**
  93680. * @private
  93681. * @type {ol.events.ConditionType}
  93682. */
  93683. this.addCondition_ = options.addCondition ?
  93684. options.addCondition : ol.events.condition.never;
  93685. /**
  93686. * @private
  93687. * @type {ol.events.ConditionType}
  93688. */
  93689. this.removeCondition_ = options.removeCondition ?
  93690. options.removeCondition : ol.events.condition.never;
  93691. /**
  93692. * @private
  93693. * @type {ol.events.ConditionType}
  93694. */
  93695. this.toggleCondition_ = options.toggleCondition ?
  93696. options.toggleCondition : ol.events.condition.shiftKeyOnly;
  93697. /**
  93698. * @private
  93699. * @type {boolean}
  93700. */
  93701. this.multi_ = options.multi ? options.multi : false;
  93702. /**
  93703. * @private
  93704. * @type {ol.interaction.SelectFilterFunction}
  93705. */
  93706. this.filter_ = options.filter ? options.filter :
  93707. goog.functions.TRUE;
  93708. var layerFilter;
  93709. if (options.layers) {
  93710. if (goog.isFunction(options.layers)) {
  93711. layerFilter = options.layers;
  93712. } else {
  93713. var layers = options.layers;
  93714. layerFilter =
  93715. /**
  93716. * @param {ol.layer.Layer} layer Layer.
  93717. * @return {boolean} Include.
  93718. */
  93719. function(layer) {
  93720. return ol.array.includes(layers, layer);
  93721. };
  93722. }
  93723. } else {
  93724. layerFilter = goog.functions.TRUE;
  93725. }
  93726. /**
  93727. * @private
  93728. * @type {function(ol.layer.Layer): boolean}
  93729. */
  93730. this.layerFilter_ = layerFilter;
  93731. /**
  93732. * An association between selected feature (key)
  93733. * and layer (value)
  93734. * @private
  93735. * @type {Object.<number, ol.layer.Layer>}
  93736. */
  93737. this.featureLayerAssociation_ = {};
  93738. /**
  93739. * @private
  93740. * @type {ol.layer.Vector}
  93741. */
  93742. this.featureOverlay_ = new ol.layer.Vector({
  93743. source: new ol.source.Vector({
  93744. useSpatialIndex: false,
  93745. features: options.features,
  93746. wrapX: options.wrapX
  93747. }),
  93748. style: options.style ? options.style :
  93749. ol.interaction.Select.getDefaultStyleFunction(),
  93750. updateWhileAnimating: true,
  93751. updateWhileInteracting: true
  93752. });
  93753. var features = this.featureOverlay_.getSource().getFeaturesCollection();
  93754. goog.events.listen(features, ol.CollectionEventType.ADD,
  93755. this.addFeature_, false, this);
  93756. goog.events.listen(features, ol.CollectionEventType.REMOVE,
  93757. this.removeFeature_, false, this);
  93758. };
  93759. goog.inherits(ol.interaction.Select, ol.interaction.Interaction);
  93760. /**
  93761. * @param {ol.Feature} feature Feature.
  93762. * @param {ol.layer.Layer} layer Layer.
  93763. * @private
  93764. */
  93765. ol.interaction.Select.prototype.addFeatureLayerAssociation_ =
  93766. function(feature, layer) {
  93767. var key = goog.getUid(feature);
  93768. this.featureLayerAssociation_[key] = layer;
  93769. };
  93770. /**
  93771. * Get the selected features.
  93772. * @return {ol.Collection.<ol.Feature>} Features collection.
  93773. * @api stable
  93774. */
  93775. ol.interaction.Select.prototype.getFeatures = function() {
  93776. return this.featureOverlay_.getSource().getFeaturesCollection();
  93777. };
  93778. /**
  93779. * Returns the associated {@link ol.layer.Vector vectorlayer} of
  93780. * the (last) selected feature.
  93781. * @param {ol.Feature} feature Feature
  93782. * @return {ol.layer.Vector} Layer.
  93783. * @api
  93784. */
  93785. ol.interaction.Select.prototype.getLayer = function(feature) {
  93786. goog.asserts.assertInstanceof(feature, ol.Feature,
  93787. 'feature should be an ol.Feature');
  93788. var key = goog.getUid(feature);
  93789. return /** @type {ol.layer.Vector} */ (this.featureLayerAssociation_[key]);
  93790. };
  93791. /**
  93792. * Handles the {@link ol.MapBrowserEvent map browser event} and may change the
  93793. * selected state of features.
  93794. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
  93795. * @return {boolean} `false` to stop event propagation.
  93796. * @this {ol.interaction.Select}
  93797. * @api
  93798. */
  93799. ol.interaction.Select.handleEvent = function(mapBrowserEvent) {
  93800. if (!this.condition_(mapBrowserEvent)) {
  93801. return true;
  93802. }
  93803. var add = this.addCondition_(mapBrowserEvent);
  93804. var remove = this.removeCondition_(mapBrowserEvent);
  93805. var toggle = this.toggleCondition_(mapBrowserEvent);
  93806. var set = !add && !remove && !toggle;
  93807. var map = mapBrowserEvent.map;
  93808. var features = this.featureOverlay_.getSource().getFeaturesCollection();
  93809. var /** @type {!Array.<ol.Feature>} */ deselected = [];
  93810. var /** @type {!Array.<ol.Feature>} */ selected = [];
  93811. var change = false;
  93812. if (set) {
  93813. // Replace the currently selected feature(s) with the feature(s) at the
  93814. // pixel, or clear the selected feature(s) if there is no feature at
  93815. // the pixel.
  93816. map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
  93817. /**
  93818. * @param {ol.Feature} feature Feature.
  93819. * @param {ol.layer.Layer} layer Layer.
  93820. */
  93821. function(feature, layer) {
  93822. if (this.filter_(feature, layer)) {
  93823. selected.push(feature);
  93824. this.addFeatureLayerAssociation_(feature, layer);
  93825. return !this.multi_;
  93826. }
  93827. }, this, this.layerFilter_);
  93828. if (selected.length > 0 && features.getLength() == 1 &&
  93829. features.item(0) == selected[0]) {
  93830. // No change
  93831. } else {
  93832. change = true;
  93833. if (features.getLength() !== 0) {
  93834. deselected = Array.prototype.concat(features.getArray());
  93835. features.clear();
  93836. }
  93837. features.extend(selected);
  93838. // Modify object this.featureLayerAssociation_
  93839. if (selected.length === 0) {
  93840. goog.object.clear(this.featureLayerAssociation_);
  93841. } else {
  93842. if (deselected.length > 0) {
  93843. deselected.forEach(function(feature) {
  93844. this.removeFeatureLayerAssociation_(feature);
  93845. }, this);
  93846. }
  93847. }
  93848. }
  93849. } else {
  93850. // Modify the currently selected feature(s).
  93851. map.forEachFeatureAtPixel(mapBrowserEvent.pixel,
  93852. /**
  93853. * @param {ol.Feature} feature Feature.
  93854. * @param {ol.layer.Layer} layer Layer.
  93855. */
  93856. function(feature, layer) {
  93857. if (!ol.array.includes(features.getArray(), feature)) {
  93858. if (add || toggle) {
  93859. if (this.filter_(feature, layer)) {
  93860. selected.push(feature);
  93861. this.addFeatureLayerAssociation_(feature, layer);
  93862. }
  93863. }
  93864. } else {
  93865. if (remove || toggle) {
  93866. deselected.push(feature);
  93867. this.removeFeatureLayerAssociation_(feature);
  93868. }
  93869. }
  93870. }, this, this.layerFilter_);
  93871. var i;
  93872. for (i = deselected.length - 1; i >= 0; --i) {
  93873. features.remove(deselected[i]);
  93874. }
  93875. features.extend(selected);
  93876. if (selected.length > 0 || deselected.length > 0) {
  93877. change = true;
  93878. }
  93879. }
  93880. if (change) {
  93881. this.dispatchEvent(
  93882. new ol.interaction.SelectEvent(ol.interaction.SelectEventType.SELECT,
  93883. selected, deselected, mapBrowserEvent));
  93884. }
  93885. return ol.events.condition.pointerMove(mapBrowserEvent);
  93886. };
  93887. /**
  93888. * Remove the interaction from its current map, if any, and attach it to a new
  93889. * map, if any. Pass `null` to just remove the interaction from the current map.
  93890. * @param {ol.Map} map Map.
  93891. * @api stable
  93892. */
  93893. ol.interaction.Select.prototype.setMap = function(map) {
  93894. var currentMap = this.getMap();
  93895. var selectedFeatures =
  93896. this.featureOverlay_.getSource().getFeaturesCollection();
  93897. if (!goog.isNull(currentMap)) {
  93898. selectedFeatures.forEach(currentMap.unskipFeature, currentMap);
  93899. }
  93900. goog.base(this, 'setMap', map);
  93901. this.featureOverlay_.setMap(map);
  93902. if (!goog.isNull(map)) {
  93903. selectedFeatures.forEach(map.skipFeature, map);
  93904. }
  93905. };
  93906. /**
  93907. * @return {ol.style.StyleFunction} Styles.
  93908. */
  93909. ol.interaction.Select.getDefaultStyleFunction = function() {
  93910. var styles = ol.style.createDefaultEditingStyles();
  93911. goog.array.extend(styles[ol.geom.GeometryType.POLYGON],
  93912. styles[ol.geom.GeometryType.LINE_STRING]);
  93913. goog.array.extend(styles[ol.geom.GeometryType.GEOMETRY_COLLECTION],
  93914. styles[ol.geom.GeometryType.LINE_STRING]);
  93915. return function(feature, resolution) {
  93916. return styles[feature.getGeometry().getType()];
  93917. };
  93918. };
  93919. /**
  93920. * @param {ol.CollectionEvent} evt Event.
  93921. * @private
  93922. */
  93923. ol.interaction.Select.prototype.addFeature_ = function(evt) {
  93924. var feature = evt.element;
  93925. var map = this.getMap();
  93926. goog.asserts.assertInstanceof(feature, ol.Feature,
  93927. 'feature should be an ol.Feature');
  93928. if (!goog.isNull(map)) {
  93929. map.skipFeature(feature);
  93930. }
  93931. };
  93932. /**
  93933. * @param {ol.CollectionEvent} evt Event.
  93934. * @private
  93935. */
  93936. ol.interaction.Select.prototype.removeFeature_ = function(evt) {
  93937. var feature = evt.element;
  93938. var map = this.getMap();
  93939. goog.asserts.assertInstanceof(feature, ol.Feature,
  93940. 'feature should be an ol.Feature');
  93941. if (!goog.isNull(map)) {
  93942. map.unskipFeature(feature);
  93943. }
  93944. };
  93945. /**
  93946. * @param {ol.Feature} feature Feature.
  93947. * @private
  93948. */
  93949. ol.interaction.Select.prototype.removeFeatureLayerAssociation_ =
  93950. function(feature) {
  93951. var key = goog.getUid(feature);
  93952. delete this.featureLayerAssociation_[key];
  93953. };
  93954. goog.provide('ol.interaction.Snap');
  93955. goog.provide('ol.interaction.SnapProperty');
  93956. goog.require('goog.asserts');
  93957. goog.require('goog.events');
  93958. goog.require('goog.events.EventType');
  93959. goog.require('goog.object');
  93960. goog.require('ol');
  93961. goog.require('ol.Collection');
  93962. goog.require('ol.CollectionEvent');
  93963. goog.require('ol.CollectionEventType');
  93964. goog.require('ol.Extent');
  93965. goog.require('ol.Feature');
  93966. goog.require('ol.Object');
  93967. goog.require('ol.Observable');
  93968. goog.require('ol.coordinate');
  93969. goog.require('ol.extent');
  93970. goog.require('ol.geom.Geometry');
  93971. goog.require('ol.interaction.Pointer');
  93972. goog.require('ol.source.Vector');
  93973. goog.require('ol.source.VectorEvent');
  93974. goog.require('ol.source.VectorEventType');
  93975. goog.require('ol.structs.RBush');
  93976. /**
  93977. * @classdesc
  93978. * Handles snapping of vector features while modifying or drawing them. The
  93979. * features can come from a {@link ol.source.Vector} or {@link ol.Collection}
  93980. * Any interaction object that allows the user to interact
  93981. * with the features using the mouse can benefit from the snapping, as long
  93982. * as it is added before.
  93983. *
  93984. * The snap interaction modifies map browser event `coordinate` and `pixel`
  93985. * properties to force the snap to occur to any interaction that them.
  93986. *
  93987. * Example:
  93988. *
  93989. * var snap = new ol.interaction.Snap({
  93990. * source: source
  93991. * });
  93992. *
  93993. * @constructor
  93994. * @extends {ol.interaction.Pointer}
  93995. * @param {olx.interaction.SnapOptions=} opt_options Options.
  93996. * @api
  93997. */
  93998. ol.interaction.Snap = function(opt_options) {
  93999. goog.base(this, {
  94000. handleEvent: ol.interaction.Snap.handleEvent_,
  94001. handleDownEvent: goog.functions.TRUE,
  94002. handleUpEvent: ol.interaction.Snap.handleUpEvent_
  94003. });
  94004. var options = opt_options ? opt_options : {};
  94005. /**
  94006. * @type {ol.source.Vector}
  94007. * @private
  94008. */
  94009. this.source_ = options.source ? options.source : null;
  94010. /**
  94011. * @type {ol.Collection.<ol.Feature>}
  94012. * @private
  94013. */
  94014. this.features_ = options.features ? options.features : null;
  94015. /**
  94016. * @type {Array.<goog.events.Key>}
  94017. * @private
  94018. */
  94019. this.featuresListenerKeys_ = [];
  94020. /**
  94021. * @type {Object.<number, goog.events.Key>}
  94022. * @private
  94023. */
  94024. this.geometryChangeListenerKeys_ = {};
  94025. /**
  94026. * @type {Object.<number, goog.events.Key>}
  94027. * @private
  94028. */
  94029. this.geometryModifyListenerKeys_ = {};
  94030. /**
  94031. * Extents are preserved so indexed segment can be quickly removed
  94032. * when its feature geometry changes
  94033. * @type {Object.<number, ol.Extent>}
  94034. * @private
  94035. */
  94036. this.indexedFeaturesExtents_ = {};
  94037. /**
  94038. * If a feature geometry changes while a pointer drag|move event occurs, the
  94039. * feature doesn't get updated right away. It will be at the next 'pointerup'
  94040. * event fired.
  94041. * @type {Object.<number, ol.Feature>}
  94042. * @private
  94043. */
  94044. this.pendingFeatures_ = {};
  94045. /**
  94046. * Used for distance sorting in sortByDistance_
  94047. * @type {ol.Coordinate}
  94048. * @private
  94049. */
  94050. this.pixelCoordinate_ = null;
  94051. /**
  94052. * @type {number}
  94053. * @private
  94054. */
  94055. this.pixelTolerance_ = options.pixelTolerance !== undefined ?
  94056. options.pixelTolerance : 10;
  94057. /**
  94058. * @type {function(ol.interaction.Snap.SegmentDataType, ol.interaction.Snap.SegmentDataType): number}
  94059. * @private
  94060. */
  94061. this.sortByDistance_ = goog.bind(ol.interaction.Snap.sortByDistance, this);
  94062. /**
  94063. * Segment RTree for each layer
  94064. * @type {ol.structs.RBush.<ol.interaction.Snap.SegmentDataType>}
  94065. * @private
  94066. */
  94067. this.rBush_ = new ol.structs.RBush();
  94068. /**
  94069. * @const
  94070. * @private
  94071. * @type {Object.<string, function(ol.Feature, ol.geom.Geometry)> }
  94072. */
  94073. this.SEGMENT_WRITERS_ = {
  94074. 'Point': this.writePointGeometry_,
  94075. 'LineString': this.writeLineStringGeometry_,
  94076. 'LinearRing': this.writeLineStringGeometry_,
  94077. 'Polygon': this.writePolygonGeometry_,
  94078. 'MultiPoint': this.writeMultiPointGeometry_,
  94079. 'MultiLineString': this.writeMultiLineStringGeometry_,
  94080. 'MultiPolygon': this.writeMultiPolygonGeometry_,
  94081. 'GeometryCollection': this.writeGeometryCollectionGeometry_
  94082. };
  94083. };
  94084. goog.inherits(ol.interaction.Snap, ol.interaction.Pointer);
  94085. /**
  94086. * Add a feature to the collection of features that we may snap to.
  94087. * @param {ol.Feature} feature Feature.
  94088. * @param {boolean=} opt_listen Whether to listen to the geometry change or not
  94089. * Defaults to `true`.
  94090. * @api
  94091. */
  94092. ol.interaction.Snap.prototype.addFeature = function(feature, opt_listen) {
  94093. var listen = opt_listen !== undefined ? opt_listen : true;
  94094. var geometry = feature.getGeometry();
  94095. var segmentWriter = this.SEGMENT_WRITERS_[geometry.getType()];
  94096. if (segmentWriter) {
  94097. var feature_uid = goog.getUid(feature);
  94098. this.indexedFeaturesExtents_[feature_uid] = geometry.getExtent(
  94099. ol.extent.createEmpty());
  94100. segmentWriter.call(this, feature, geometry);
  94101. if (listen) {
  94102. this.geometryModifyListenerKeys_[feature_uid] = geometry.on(
  94103. goog.events.EventType.CHANGE,
  94104. goog.bind(this.handleGeometryModify_, this, feature),
  94105. this);
  94106. this.geometryChangeListenerKeys_[feature_uid] = feature.on(
  94107. ol.Object.getChangeEventType(feature.getGeometryName()),
  94108. this.handleGeometryChange_, this);
  94109. }
  94110. }
  94111. };
  94112. /**
  94113. * @param {ol.Feature} feature Feature.
  94114. * @private
  94115. */
  94116. ol.interaction.Snap.prototype.forEachFeatureAdd_ = function(feature) {
  94117. this.addFeature(feature);
  94118. };
  94119. /**
  94120. * @param {ol.Feature} feature Feature.
  94121. * @private
  94122. */
  94123. ol.interaction.Snap.prototype.forEachFeatureRemove_ = function(feature) {
  94124. this.removeFeature(feature);
  94125. };
  94126. /**
  94127. * @return {ol.Collection.<ol.Feature>|Array.<ol.Feature>}
  94128. * @private
  94129. */
  94130. ol.interaction.Snap.prototype.getFeatures_ = function() {
  94131. var features;
  94132. if (this.features_) {
  94133. features = this.features_;
  94134. } else if (this.source_) {
  94135. features = this.source_.getFeatures();
  94136. }
  94137. goog.asserts.assert(features !== undefined, 'features should be defined');
  94138. return features;
  94139. };
  94140. /**
  94141. * @param {ol.source.VectorEvent|ol.CollectionEvent} evt Event.
  94142. * @private
  94143. */
  94144. ol.interaction.Snap.prototype.handleFeatureAdd_ = function(evt) {
  94145. var feature;
  94146. if (evt instanceof ol.source.VectorEvent) {
  94147. feature = evt.feature;
  94148. } else if (evt instanceof ol.CollectionEvent) {
  94149. feature = evt.element;
  94150. }
  94151. goog.asserts.assertInstanceof(feature, ol.Feature,
  94152. 'feature should be an ol.Feature');
  94153. this.addFeature(feature);
  94154. };
  94155. /**
  94156. * @param {ol.source.VectorEvent|ol.CollectionEvent} evt Event.
  94157. * @private
  94158. */
  94159. ol.interaction.Snap.prototype.handleFeatureRemove_ = function(evt) {
  94160. var feature;
  94161. if (evt instanceof ol.source.VectorEvent) {
  94162. feature = evt.feature;
  94163. } else if (evt instanceof ol.CollectionEvent) {
  94164. feature = evt.element;
  94165. }
  94166. goog.asserts.assertInstanceof(feature, ol.Feature,
  94167. 'feature should be an ol.Feature');
  94168. this.removeFeature(feature);
  94169. };
  94170. /**
  94171. * @param {goog.events.Event} evt Event.
  94172. * @private
  94173. */
  94174. ol.interaction.Snap.prototype.handleGeometryChange_ = function(evt) {
  94175. var feature = evt.currentTarget;
  94176. goog.asserts.assertInstanceof(feature, ol.Feature);
  94177. this.removeFeature(feature, true);
  94178. this.addFeature(feature, true);
  94179. };
  94180. /**
  94181. * @param {ol.Feature} feature Feature which geometry was modified.
  94182. * @param {goog.events.Event} evt Event.
  94183. * @private
  94184. */
  94185. ol.interaction.Snap.prototype.handleGeometryModify_ = function(feature, evt) {
  94186. if (this.handlingDownUpSequence) {
  94187. var uid = goog.getUid(feature);
  94188. if (!(uid in this.pendingFeatures_)) {
  94189. this.pendingFeatures_[uid] = feature;
  94190. }
  94191. } else {
  94192. this.updateFeature_(feature);
  94193. }
  94194. };
  94195. /**
  94196. * Remove a feature from the collection of features that we may snap to.
  94197. * @param {ol.Feature} feature Feature
  94198. * @param {boolean=} opt_unlisten Whether to unlisten to the geometry change
  94199. * or not. Defaults to `true`.
  94200. * @api
  94201. */
  94202. ol.interaction.Snap.prototype.removeFeature = function(feature, opt_unlisten) {
  94203. var unlisten = opt_unlisten !== undefined ? opt_unlisten : true;
  94204. var feature_uid = goog.getUid(feature);
  94205. var extent = this.indexedFeaturesExtents_[feature_uid];
  94206. if (extent) {
  94207. var rBush = this.rBush_;
  94208. var i, nodesToRemove = [];
  94209. rBush.forEachInExtent(extent, function(node) {
  94210. if (feature === node.feature) {
  94211. nodesToRemove.push(node);
  94212. }
  94213. });
  94214. for (i = nodesToRemove.length - 1; i >= 0; --i) {
  94215. rBush.remove(nodesToRemove[i]);
  94216. }
  94217. if (unlisten) {
  94218. ol.Observable.unByKey(this.geometryModifyListenerKeys_[feature_uid]);
  94219. delete this.geometryModifyListenerKeys_[feature_uid];
  94220. ol.Observable.unByKey(this.geometryChangeListenerKeys_[feature_uid]);
  94221. delete this.geometryChangeListenerKeys_[feature_uid];
  94222. }
  94223. }
  94224. };
  94225. /**
  94226. * @inheritDoc
  94227. */
  94228. ol.interaction.Snap.prototype.setMap = function(map) {
  94229. var currentMap = this.getMap();
  94230. var keys = this.featuresListenerKeys_;
  94231. var features = this.getFeatures_();
  94232. if (currentMap) {
  94233. keys.forEach(ol.Observable.unByKey);
  94234. keys.length = 0;
  94235. features.forEach(this.forEachFeatureRemove_, this);
  94236. }
  94237. goog.base(this, 'setMap', map);
  94238. if (map) {
  94239. if (this.features_) {
  94240. keys.push(this.features_.on(ol.CollectionEventType.ADD,
  94241. this.handleFeatureAdd_, this));
  94242. keys.push(this.features_.on(ol.CollectionEventType.REMOVE,
  94243. this.handleFeatureRemove_, this));
  94244. } else if (this.source_) {
  94245. keys.push(this.source_.on(ol.source.VectorEventType.ADDFEATURE,
  94246. this.handleFeatureAdd_, this));
  94247. keys.push(this.source_.on(ol.source.VectorEventType.REMOVEFEATURE,
  94248. this.handleFeatureRemove_, this));
  94249. }
  94250. features.forEach(this.forEachFeatureAdd_, this);
  94251. }
  94252. };
  94253. /**
  94254. * @inheritDoc
  94255. */
  94256. ol.interaction.Snap.prototype.shouldStopEvent = goog.functions.FALSE;
  94257. /**
  94258. * @param {ol.Pixel} pixel Pixel
  94259. * @param {ol.Coordinate} pixelCoordinate Coordinate
  94260. * @param {ol.Map} map Map.
  94261. * @return {ol.interaction.Snap.ResultType} Snap result
  94262. */
  94263. ol.interaction.Snap.prototype.snapTo = function(pixel, pixelCoordinate, map) {
  94264. var lowerLeft = map.getCoordinateFromPixel(
  94265. [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]);
  94266. var upperRight = map.getCoordinateFromPixel(
  94267. [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]);
  94268. var box = ol.extent.boundingExtent([lowerLeft, upperRight]);
  94269. var segments = this.rBush_.getInExtent(box);
  94270. var snappedToVertex = false;
  94271. var snapped = false;
  94272. var vertex = null;
  94273. var vertexPixel = null;
  94274. if (segments.length > 0) {
  94275. this.pixelCoordinate_ = pixelCoordinate;
  94276. segments.sort(this.sortByDistance_);
  94277. var closestSegment = segments[0].segment;
  94278. vertex = (ol.coordinate.closestOnSegment(pixelCoordinate,
  94279. closestSegment));
  94280. vertexPixel = map.getPixelFromCoordinate(vertex);
  94281. if (Math.sqrt(ol.coordinate.squaredDistance(pixel, vertexPixel)) <=
  94282. this.pixelTolerance_) {
  94283. snapped = true;
  94284. var pixel1 = map.getPixelFromCoordinate(closestSegment[0]);
  94285. var pixel2 = map.getPixelFromCoordinate(closestSegment[1]);
  94286. var squaredDist1 = ol.coordinate.squaredDistance(vertexPixel, pixel1);
  94287. var squaredDist2 = ol.coordinate.squaredDistance(vertexPixel, pixel2);
  94288. var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));
  94289. snappedToVertex = dist <= this.pixelTolerance_;
  94290. if (snappedToVertex) {
  94291. vertex = squaredDist1 > squaredDist2 ?
  94292. closestSegment[1] : closestSegment[0];
  94293. vertexPixel = map.getPixelFromCoordinate(vertex);
  94294. vertexPixel = [Math.round(vertexPixel[0]), Math.round(vertexPixel[1])];
  94295. }
  94296. }
  94297. }
  94298. return /** @type {ol.interaction.Snap.ResultType} */ ({
  94299. snapped: snapped,
  94300. vertex: vertex,
  94301. vertexPixel: vertexPixel
  94302. });
  94303. };
  94304. /**
  94305. * @param {ol.Feature} feature Feature
  94306. * @private
  94307. */
  94308. ol.interaction.Snap.prototype.updateFeature_ = function(feature) {
  94309. this.removeFeature(feature, false);
  94310. this.addFeature(feature, false);
  94311. };
  94312. /**
  94313. * @param {ol.Feature} feature Feature
  94314. * @param {ol.geom.GeometryCollection} geometry Geometry.
  94315. * @private
  94316. */
  94317. ol.interaction.Snap.prototype.writeGeometryCollectionGeometry_ =
  94318. function(feature, geometry) {
  94319. var i, geometries = geometry.getGeometriesArray();
  94320. for (i = 0; i < geometries.length; ++i) {
  94321. this.SEGMENT_WRITERS_[geometries[i].getType()].call(
  94322. this, feature, geometries[i]);
  94323. }
  94324. };
  94325. /**
  94326. * @param {ol.Feature} feature Feature
  94327. * @param {ol.geom.LineString} geometry Geometry.
  94328. * @private
  94329. */
  94330. ol.interaction.Snap.prototype.writeLineStringGeometry_ =
  94331. function(feature, geometry) {
  94332. var coordinates = geometry.getCoordinates();
  94333. var i, ii, segment, segmentData;
  94334. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  94335. segment = coordinates.slice(i, i + 2);
  94336. segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94337. feature: feature,
  94338. segment: segment
  94339. });
  94340. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  94341. }
  94342. };
  94343. /**
  94344. * @param {ol.Feature} feature Feature
  94345. * @param {ol.geom.MultiLineString} geometry Geometry.
  94346. * @private
  94347. */
  94348. ol.interaction.Snap.prototype.writeMultiLineStringGeometry_ =
  94349. function(feature, geometry) {
  94350. var lines = geometry.getCoordinates();
  94351. var coordinates, i, ii, j, jj, segment, segmentData;
  94352. for (j = 0, jj = lines.length; j < jj; ++j) {
  94353. coordinates = lines[j];
  94354. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  94355. segment = coordinates.slice(i, i + 2);
  94356. segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94357. feature: feature,
  94358. segment: segment
  94359. });
  94360. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  94361. }
  94362. }
  94363. };
  94364. /**
  94365. * @param {ol.Feature} feature Feature
  94366. * @param {ol.geom.MultiPoint} geometry Geometry.
  94367. * @private
  94368. */
  94369. ol.interaction.Snap.prototype.writeMultiPointGeometry_ =
  94370. function(feature, geometry) {
  94371. var points = geometry.getCoordinates();
  94372. var coordinates, i, ii, segmentData;
  94373. for (i = 0, ii = points.length; i < ii; ++i) {
  94374. coordinates = points[i];
  94375. segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94376. feature: feature,
  94377. segment: [coordinates, coordinates]
  94378. });
  94379. this.rBush_.insert(geometry.getExtent(), segmentData);
  94380. }
  94381. };
  94382. /**
  94383. * @param {ol.Feature} feature Feature
  94384. * @param {ol.geom.MultiPolygon} geometry Geometry.
  94385. * @private
  94386. */
  94387. ol.interaction.Snap.prototype.writeMultiPolygonGeometry_ =
  94388. function(feature, geometry) {
  94389. var polygons = geometry.getCoordinates();
  94390. var coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData;
  94391. for (k = 0, kk = polygons.length; k < kk; ++k) {
  94392. rings = polygons[k];
  94393. for (j = 0, jj = rings.length; j < jj; ++j) {
  94394. coordinates = rings[j];
  94395. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  94396. segment = coordinates.slice(i, i + 2);
  94397. segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94398. feature: feature,
  94399. segment: segment
  94400. });
  94401. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  94402. }
  94403. }
  94404. }
  94405. };
  94406. /**
  94407. * @param {ol.Feature} feature Feature
  94408. * @param {ol.geom.Point} geometry Geometry.
  94409. * @private
  94410. */
  94411. ol.interaction.Snap.prototype.writePointGeometry_ =
  94412. function(feature, geometry) {
  94413. var coordinates = geometry.getCoordinates();
  94414. var segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94415. feature: feature,
  94416. segment: [coordinates, coordinates]
  94417. });
  94418. this.rBush_.insert(geometry.getExtent(), segmentData);
  94419. };
  94420. /**
  94421. * @param {ol.Feature} feature Feature
  94422. * @param {ol.geom.Polygon} geometry Geometry.
  94423. * @private
  94424. */
  94425. ol.interaction.Snap.prototype.writePolygonGeometry_ =
  94426. function(feature, geometry) {
  94427. var rings = geometry.getCoordinates();
  94428. var coordinates, i, ii, j, jj, segment, segmentData;
  94429. for (j = 0, jj = rings.length; j < jj; ++j) {
  94430. coordinates = rings[j];
  94431. for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
  94432. segment = coordinates.slice(i, i + 2);
  94433. segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
  94434. feature: feature,
  94435. segment: segment
  94436. });
  94437. this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  94438. }
  94439. }
  94440. };
  94441. /**
  94442. * @typedef {{
  94443. * snapped: {boolean},
  94444. * vertex: (ol.Coordinate|null),
  94445. * vertexPixel: (ol.Pixel|null)
  94446. * }}
  94447. */
  94448. ol.interaction.Snap.ResultType;
  94449. /**
  94450. * @typedef {{
  94451. * feature: ol.Feature,
  94452. * segment: Array.<ol.Coordinate>
  94453. * }}
  94454. */
  94455. ol.interaction.Snap.SegmentDataType;
  94456. /**
  94457. * Handle all pointer events events.
  94458. * @param {ol.MapBrowserEvent} evt A move event.
  94459. * @return {boolean} Pass the event to other interactions.
  94460. * @this {ol.interaction.Snap}
  94461. * @private
  94462. */
  94463. ol.interaction.Snap.handleEvent_ = function(evt) {
  94464. var result = this.snapTo(evt.pixel, evt.coordinate, evt.map);
  94465. if (result.snapped) {
  94466. evt.coordinate = result.vertex.slice(0, 2);
  94467. evt.pixel = result.vertexPixel;
  94468. }
  94469. return ol.interaction.Pointer.handleEvent.call(this, evt);
  94470. };
  94471. /**
  94472. * @param {ol.MapBrowserPointerEvent} evt Event.
  94473. * @return {boolean} Stop drag sequence?
  94474. * @this {ol.interaction.Snap}
  94475. * @private
  94476. */
  94477. ol.interaction.Snap.handleUpEvent_ = function(evt) {
  94478. var featuresToUpdate = goog.object.getValues(this.pendingFeatures_);
  94479. if (featuresToUpdate.length) {
  94480. featuresToUpdate.forEach(this.updateFeature_, this);
  94481. this.pendingFeatures_ = {};
  94482. }
  94483. return false;
  94484. };
  94485. /**
  94486. * Sort segments by distance, helper function
  94487. * @param {ol.interaction.Snap.SegmentDataType} a
  94488. * @param {ol.interaction.Snap.SegmentDataType} b
  94489. * @return {number}
  94490. * @this {ol.interaction.Snap}
  94491. */
  94492. ol.interaction.Snap.sortByDistance = function(a, b) {
  94493. return ol.coordinate.squaredDistanceToSegment(
  94494. this.pixelCoordinate_, a.segment) -
  94495. ol.coordinate.squaredDistanceToSegment(
  94496. this.pixelCoordinate_, b.segment);
  94497. };
  94498. goog.provide('ol.interaction.Translate');
  94499. goog.require('ol.array');
  94500. goog.require('ol.interaction.Pointer');
  94501. /**
  94502. * @classdesc
  94503. * Interaction for translating (moving) features.
  94504. *
  94505. * @constructor
  94506. * @extends {ol.interaction.Pointer}
  94507. * @param {olx.interaction.TranslateOptions} options Options.
  94508. * @api
  94509. */
  94510. ol.interaction.Translate = function(options) {
  94511. goog.base(this, {
  94512. handleDownEvent: ol.interaction.Translate.handleDownEvent_,
  94513. handleDragEvent: ol.interaction.Translate.handleDragEvent_,
  94514. handleMoveEvent: ol.interaction.Translate.handleMoveEvent_,
  94515. handleUpEvent: ol.interaction.Translate.handleUpEvent_
  94516. });
  94517. /**
  94518. * @type {string|undefined}
  94519. * @private
  94520. */
  94521. this.previousCursor_ = undefined;
  94522. /**
  94523. * The last position we translated to.
  94524. * @type {ol.Coordinate}
  94525. * @private
  94526. */
  94527. this.lastCoordinate_ = null;
  94528. /**
  94529. * @type {ol.Collection.<ol.Feature>}
  94530. * @private
  94531. */
  94532. this.features_ = options.features !== undefined ? options.features : null;
  94533. /**
  94534. * @type {ol.Feature}
  94535. * @private
  94536. */
  94537. this.lastFeature_ = null;
  94538. };
  94539. goog.inherits(ol.interaction.Translate, ol.interaction.Pointer);
  94540. /**
  94541. * @param {ol.MapBrowserPointerEvent} event Event.
  94542. * @return {boolean} Start drag sequence?
  94543. * @this {ol.interaction.Translate}
  94544. * @private
  94545. */
  94546. ol.interaction.Translate.handleDownEvent_ = function(event) {
  94547. this.lastFeature_ = this.featuresAtPixel_(event.pixel, event.map);
  94548. if (!this.lastCoordinate_ && this.lastFeature_) {
  94549. this.lastCoordinate_ = event.coordinate;
  94550. ol.interaction.Translate.handleMoveEvent_.call(this, event);
  94551. return true;
  94552. }
  94553. return false;
  94554. };
  94555. /**
  94556. * @param {ol.MapBrowserPointerEvent} event Event.
  94557. * @return {boolean} Stop drag sequence?
  94558. * @this {ol.interaction.Translate}
  94559. * @private
  94560. */
  94561. ol.interaction.Translate.handleUpEvent_ = function(event) {
  94562. if (this.lastCoordinate_) {
  94563. this.lastCoordinate_ = null;
  94564. ol.interaction.Translate.handleMoveEvent_.call(this, event);
  94565. return true;
  94566. }
  94567. return false;
  94568. };
  94569. /**
  94570. * @param {ol.MapBrowserPointerEvent} event Event.
  94571. * @this {ol.interaction.Translate}
  94572. * @private
  94573. */
  94574. ol.interaction.Translate.handleDragEvent_ = function(event) {
  94575. if (this.lastCoordinate_) {
  94576. var newCoordinate = event.coordinate;
  94577. var deltaX = newCoordinate[0] - this.lastCoordinate_[0];
  94578. var deltaY = newCoordinate[1] - this.lastCoordinate_[1];
  94579. if (this.features_) {
  94580. this.features_.forEach(function(feature) {
  94581. var geom = feature.getGeometry();
  94582. geom.translate(deltaX, deltaY);
  94583. feature.setGeometry(geom);
  94584. });
  94585. } else if (this.lastFeature_) {
  94586. var geom = this.lastFeature_.getGeometry();
  94587. geom.translate(deltaX, deltaY);
  94588. this.lastFeature_.setGeometry(geom);
  94589. }
  94590. this.lastCoordinate_ = newCoordinate;
  94591. }
  94592. };
  94593. /**
  94594. * @param {ol.MapBrowserEvent} event Event.
  94595. * @this {ol.interaction.Translate}
  94596. * @private
  94597. */
  94598. ol.interaction.Translate.handleMoveEvent_ = function(event)
  94599. {
  94600. var elem = event.map.getTargetElement();
  94601. var intersectingFeature = event.map.forEachFeatureAtPixel(event.pixel,
  94602. function(feature) {
  94603. return feature;
  94604. });
  94605. if (intersectingFeature) {
  94606. var isSelected = false;
  94607. if (this.features_ &&
  94608. ol.array.includes(this.features_.getArray(), intersectingFeature)) {
  94609. isSelected = true;
  94610. }
  94611. this.previousCursor_ = elem.style.cursor;
  94612. // WebKit browsers don't support the grab icons without a prefix
  94613. elem.style.cursor = this.lastCoordinate_ ?
  94614. '-webkit-grabbing' : (isSelected ? '-webkit-grab' : 'pointer');
  94615. // Thankfully, attempting to set the standard ones will silently fail,
  94616. // keeping the prefixed icons
  94617. elem.style.cursor = !this.lastCoordinate_ ?
  94618. 'grabbing' : (isSelected ? 'grab' : 'pointer');
  94619. } else {
  94620. elem.style.cursor = this.previousCursor_ !== undefined ?
  94621. this.previousCursor_ : '';
  94622. this.previousCursor_ = undefined;
  94623. }
  94624. };
  94625. /**
  94626. * Tests to see if the given coordinates intersects any of our selected
  94627. * features.
  94628. * @param {ol.Pixel} pixel Pixel coordinate to test for intersection.
  94629. * @param {ol.Map} map Map to test the intersection on.
  94630. * @return {ol.Feature} Returns the feature found at the specified pixel
  94631. * coordinates.
  94632. * @private
  94633. */
  94634. ol.interaction.Translate.prototype.featuresAtPixel_ = function(pixel, map) {
  94635. var found = null;
  94636. var intersectingFeature = map.forEachFeatureAtPixel(pixel,
  94637. function(feature) {
  94638. return feature;
  94639. });
  94640. if (this.features_ &&
  94641. ol.array.includes(this.features_.getArray(), intersectingFeature)) {
  94642. found = intersectingFeature;
  94643. }
  94644. return found;
  94645. };
  94646. goog.provide('ol.layer.Heatmap');
  94647. goog.require('goog.asserts');
  94648. goog.require('goog.events');
  94649. goog.require('goog.object');
  94650. goog.require('ol');
  94651. goog.require('ol.Object');
  94652. goog.require('ol.dom');
  94653. goog.require('ol.layer.Vector');
  94654. goog.require('ol.math');
  94655. goog.require('ol.render.EventType');
  94656. goog.require('ol.style.Icon');
  94657. goog.require('ol.style.Style');
  94658. /**
  94659. * @enum {string}
  94660. */
  94661. ol.layer.HeatmapLayerProperty = {
  94662. BLUR: 'blur',
  94663. GRADIENT: 'gradient',
  94664. RADIUS: 'radius'
  94665. };
  94666. /**
  94667. * @classdesc
  94668. * Layer for rendering vector data as a heatmap.
  94669. * Note that any property set in the options is set as a {@link ol.Object}
  94670. * property on the layer object; for example, setting `title: 'My Title'` in the
  94671. * options means that `title` is observable, and has get/set accessors.
  94672. *
  94673. * @constructor
  94674. * @extends {ol.layer.Vector}
  94675. * @fires ol.render.Event
  94676. * @param {olx.layer.HeatmapOptions=} opt_options Options.
  94677. * @api
  94678. */
  94679. ol.layer.Heatmap = function(opt_options) {
  94680. var options = opt_options ? opt_options : {};
  94681. var baseOptions = goog.object.clone(options);
  94682. delete baseOptions.gradient;
  94683. delete baseOptions.radius;
  94684. delete baseOptions.blur;
  94685. delete baseOptions.shadow;
  94686. delete baseOptions.weight;
  94687. goog.base(this, /** @type {olx.layer.VectorOptions} */ (baseOptions));
  94688. /**
  94689. * @private
  94690. * @type {Uint8ClampedArray}
  94691. */
  94692. this.gradient_ = null;
  94693. /**
  94694. * @private
  94695. * @type {number}
  94696. */
  94697. this.shadow_ = options.shadow !== undefined ? options.shadow : 250;
  94698. /**
  94699. * @private
  94700. * @type {string|undefined}
  94701. */
  94702. this.circleImage_ = undefined;
  94703. /**
  94704. * @private
  94705. * @type {Array.<Array.<ol.style.Style>>}
  94706. */
  94707. this.styleCache_ = null;
  94708. goog.events.listen(this,
  94709. ol.Object.getChangeEventType(ol.layer.HeatmapLayerProperty.GRADIENT),
  94710. this.handleGradientChanged_, false, this);
  94711. this.setGradient(options.gradient ?
  94712. options.gradient : ol.layer.Heatmap.DEFAULT_GRADIENT);
  94713. this.setBlur(options.blur !== undefined ? options.blur : 15);
  94714. this.setRadius(options.radius !== undefined ? options.radius : 8);
  94715. goog.events.listen(this, [
  94716. ol.Object.getChangeEventType(ol.layer.HeatmapLayerProperty.BLUR),
  94717. ol.Object.getChangeEventType(ol.layer.HeatmapLayerProperty.RADIUS)
  94718. ], this.handleStyleChanged_, false, this);
  94719. this.handleStyleChanged_();
  94720. var weight = options.weight ? options.weight : 'weight';
  94721. var weightFunction;
  94722. if (goog.isString(weight)) {
  94723. weightFunction = function(feature) {
  94724. return feature.get(weight);
  94725. };
  94726. } else {
  94727. weightFunction = weight;
  94728. }
  94729. goog.asserts.assert(goog.isFunction(weightFunction),
  94730. 'weightFunction should be a function');
  94731. this.setStyle(goog.bind(function(feature, resolution) {
  94732. goog.asserts.assert(this.styleCache_, 'this.styleCache_ expected');
  94733. goog.asserts.assert(this.circleImage_ !== undefined,
  94734. 'this.circleImage_ should be defined');
  94735. var weight = weightFunction(feature);
  94736. var opacity = weight !== undefined ? ol.math.clamp(weight, 0, 1) : 1;
  94737. // cast to 8 bits
  94738. var index = (255 * opacity) | 0;
  94739. var style = this.styleCache_[index];
  94740. if (!style) {
  94741. style = [
  94742. new ol.style.Style({
  94743. image: new ol.style.Icon({
  94744. opacity: opacity,
  94745. src: this.circleImage_
  94746. })
  94747. })
  94748. ];
  94749. this.styleCache_[index] = style;
  94750. }
  94751. return style;
  94752. }, this));
  94753. // For performance reasons, don't sort the features before rendering.
  94754. // The render order is not relevant for a heatmap representation.
  94755. this.setRenderOrder(null);
  94756. goog.events.listen(this, ol.render.EventType.RENDER,
  94757. this.handleRender_, false, this);
  94758. };
  94759. goog.inherits(ol.layer.Heatmap, ol.layer.Vector);
  94760. /**
  94761. * @const
  94762. * @type {Array.<string>}
  94763. */
  94764. ol.layer.Heatmap.DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00'];
  94765. /**
  94766. * @param {Array.<string>} colors
  94767. * @return {Uint8ClampedArray}
  94768. * @private
  94769. */
  94770. ol.layer.Heatmap.createGradient_ = function(colors) {
  94771. var width = 1;
  94772. var height = 256;
  94773. var context = ol.dom.createCanvasContext2D(width, height);
  94774. var gradient = context.createLinearGradient(0, 0, width, height);
  94775. var step = 1 / (colors.length - 1);
  94776. for (var i = 0, ii = colors.length; i < ii; ++i) {
  94777. gradient.addColorStop(i * step, colors[i]);
  94778. }
  94779. context.fillStyle = gradient;
  94780. context.fillRect(0, 0, width, height);
  94781. return context.getImageData(0, 0, width, height).data;
  94782. };
  94783. /**
  94784. * @return {string}
  94785. * @private
  94786. */
  94787. ol.layer.Heatmap.prototype.createCircle_ = function() {
  94788. var radius = this.getRadius();
  94789. var blur = this.getBlur();
  94790. goog.asserts.assert(radius !== undefined && blur !== undefined,
  94791. 'radius and blur should be defined');
  94792. var halfSize = radius + blur + 1;
  94793. var size = 2 * halfSize;
  94794. var context = ol.dom.createCanvasContext2D(size, size);
  94795. context.shadowOffsetX = context.shadowOffsetY = this.shadow_;
  94796. context.shadowBlur = blur;
  94797. context.shadowColor = '#000';
  94798. context.beginPath();
  94799. var center = halfSize - this.shadow_;
  94800. context.arc(center, center, radius, 0, Math.PI * 2, true);
  94801. context.fill();
  94802. return context.canvas.toDataURL();
  94803. };
  94804. /**
  94805. * Return the blur size in pixels.
  94806. * @return {number} Blur size in pixels.
  94807. * @api
  94808. * @observable
  94809. */
  94810. ol.layer.Heatmap.prototype.getBlur = function() {
  94811. return /** @type {number} */ (this.get(ol.layer.HeatmapLayerProperty.BLUR));
  94812. };
  94813. /**
  94814. * Return the gradient colors as array of strings.
  94815. * @return {Array.<string>} Colors.
  94816. * @api
  94817. * @observable
  94818. */
  94819. ol.layer.Heatmap.prototype.getGradient = function() {
  94820. return /** @type {Array.<string>} */ (
  94821. this.get(ol.layer.HeatmapLayerProperty.GRADIENT));
  94822. };
  94823. /**
  94824. * Return the size of the radius in pixels.
  94825. * @return {number} Radius size in pixel.
  94826. * @api
  94827. * @observable
  94828. */
  94829. ol.layer.Heatmap.prototype.getRadius = function() {
  94830. return /** @type {number} */ (this.get(ol.layer.HeatmapLayerProperty.RADIUS));
  94831. };
  94832. /**
  94833. * @private
  94834. */
  94835. ol.layer.Heatmap.prototype.handleGradientChanged_ = function() {
  94836. this.gradient_ = ol.layer.Heatmap.createGradient_(this.getGradient());
  94837. };
  94838. /**
  94839. * @private
  94840. */
  94841. ol.layer.Heatmap.prototype.handleStyleChanged_ = function() {
  94842. this.circleImage_ = this.createCircle_();
  94843. this.styleCache_ = new Array(256);
  94844. this.changed();
  94845. };
  94846. /**
  94847. * @param {ol.render.Event} event Post compose event
  94848. * @private
  94849. */
  94850. ol.layer.Heatmap.prototype.handleRender_ = function(event) {
  94851. goog.asserts.assert(event.type == ol.render.EventType.RENDER,
  94852. 'event.type should be RENDER');
  94853. goog.asserts.assert(this.gradient_, 'this.gradient_ expected');
  94854. var context = event.context;
  94855. var canvas = context.canvas;
  94856. var image = context.getImageData(0, 0, canvas.width, canvas.height);
  94857. var view8 = image.data;
  94858. var i, ii, alpha;
  94859. for (i = 0, ii = view8.length; i < ii; i += 4) {
  94860. alpha = view8[i + 3] * 4;
  94861. if (alpha) {
  94862. view8[i] = this.gradient_[alpha];
  94863. view8[i + 1] = this.gradient_[alpha + 1];
  94864. view8[i + 2] = this.gradient_[alpha + 2];
  94865. }
  94866. }
  94867. context.putImageData(image, 0, 0);
  94868. };
  94869. /**
  94870. * Set the blur size in pixels.
  94871. * @param {number} blur Blur size in pixels.
  94872. * @api
  94873. * @observable
  94874. */
  94875. ol.layer.Heatmap.prototype.setBlur = function(blur) {
  94876. this.set(ol.layer.HeatmapLayerProperty.BLUR, blur);
  94877. };
  94878. /**
  94879. * Set the gradient colors as array of strings.
  94880. * @param {Array.<string>} colors Gradient.
  94881. * @api
  94882. * @observable
  94883. */
  94884. ol.layer.Heatmap.prototype.setGradient = function(colors) {
  94885. this.set(ol.layer.HeatmapLayerProperty.GRADIENT, colors);
  94886. };
  94887. /**
  94888. * Set the size of the radius in pixels.
  94889. * @param {number} radius Radius size in pixel.
  94890. * @api
  94891. * @observable
  94892. */
  94893. ol.layer.Heatmap.prototype.setRadius = function(radius) {
  94894. this.set(ol.layer.HeatmapLayerProperty.RADIUS, radius);
  94895. };
  94896. goog.provide('ol.raster.Operation');
  94897. goog.provide('ol.raster.OperationType');
  94898. /**
  94899. * Raster operation type. Supported values are `'pixel'` and `'image'`.
  94900. * @enum {string}
  94901. * @api
  94902. */
  94903. ol.raster.OperationType = {
  94904. PIXEL: 'pixel',
  94905. IMAGE: 'image'
  94906. };
  94907. /**
  94908. * A function that takes an array of input data, performs some operation, and
  94909. * returns an array of ouput data. For `'pixel'` type operations, functions
  94910. * will be called with an array of {@link ol.raster.Pixel} data and should
  94911. * return an array of the same. For `'image'` type operations, functions will
  94912. * be called with an array of {@link ImageData
  94913. * https://developer.mozilla.org/en-US/docs/Web/API/ImageData} and should return
  94914. * an array of the same. The operations are called with a second "data"
  94915. * argument, which can be used for storage. The data object is accessible
  94916. * from raster events, where it can be initialized in "beforeoperations" and
  94917. * accessed again in "afteroperations".
  94918. *
  94919. * @typedef {function((Array.<ol.raster.Pixel>|Array.<ImageData>), Object):
  94920. * (Array.<ol.raster.Pixel>|Array.<ImageData>)}
  94921. * @api
  94922. */
  94923. ol.raster.Operation;
  94924. goog.provide('ol.raster.Pixel');
  94925. /**
  94926. * An array of numbers representing pixel values.
  94927. * @typedef {Array.<number>} ol.raster.Pixel
  94928. * @api
  94929. */
  94930. ol.raster.Pixel;
  94931. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  94932. //
  94933. // Licensed under the Apache License, Version 2.0 (the "License");
  94934. // you may not use this file except in compliance with the License.
  94935. // You may obtain a copy of the License at
  94936. //
  94937. // http://www.apache.org/licenses/LICENSE-2.0
  94938. //
  94939. // Unless required by applicable law or agreed to in writing, software
  94940. // distributed under the License is distributed on an "AS-IS" BASIS,
  94941. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  94942. // See the License for the specific language governing permissions and
  94943. // limitations under the License.
  94944. /**
  94945. * @fileoverview A utility to load JavaScript files via DOM script tags.
  94946. * Refactored from goog.net.Jsonp. Works cross-domain.
  94947. *
  94948. */
  94949. goog.provide('goog.net.jsloader');
  94950. goog.provide('goog.net.jsloader.Error');
  94951. goog.provide('goog.net.jsloader.ErrorCode');
  94952. goog.provide('goog.net.jsloader.Options');
  94953. goog.require('goog.array');
  94954. goog.require('goog.async.Deferred');
  94955. goog.require('goog.debug.Error');
  94956. goog.require('goog.dom');
  94957. goog.require('goog.dom.TagName');
  94958. goog.require('goog.object');
  94959. /**
  94960. * The name of the property of goog.global under which the JavaScript
  94961. * verification object is stored by the loaded script.
  94962. * @private {string}
  94963. */
  94964. goog.net.jsloader.GLOBAL_VERIFY_OBJS_ = 'closure_verification';
  94965. /**
  94966. * The default length of time, in milliseconds, we are prepared to wait for a
  94967. * load request to complete.
  94968. * @type {number}
  94969. */
  94970. goog.net.jsloader.DEFAULT_TIMEOUT = 5000;
  94971. /**
  94972. * Optional parameters for goog.net.jsloader.send.
  94973. * timeout: The length of time, in milliseconds, we are prepared to wait
  94974. * for a load request to complete. Default it 5 seconds.
  94975. * document: The HTML document under which to load the JavaScript. Default is
  94976. * the current document.
  94977. * cleanupWhenDone: If true clean up the script tag after script completes to
  94978. * load. This is important if you just want to read data from the JavaScript
  94979. * and then throw it away. Default is false.
  94980. * attributes: Additional attributes to set on the script tag.
  94981. *
  94982. * @typedef {{
  94983. * timeout: (number|undefined),
  94984. * document: (HTMLDocument|undefined),
  94985. * cleanupWhenDone: (boolean|undefined),
  94986. * attributes: (!Object<string, string>|undefined)
  94987. * }}
  94988. */
  94989. goog.net.jsloader.Options;
  94990. /**
  94991. * Scripts (URIs) waiting to be loaded.
  94992. * @private {!Array<string>}
  94993. */
  94994. goog.net.jsloader.scriptsToLoad_ = [];
  94995. /**
  94996. * The deferred result of loading the URIs in scriptsToLoad_.
  94997. * We need to return this to a caller that wants to load URIs while
  94998. * a deferred is already working on them.
  94999. * @private {!goog.async.Deferred<null>}
  95000. */
  95001. goog.net.jsloader.scriptLoadingDeferred_;
  95002. /**
  95003. * Loads and evaluates the JavaScript files at the specified URIs, guaranteeing
  95004. * the order of script loads.
  95005. *
  95006. * Because we have to load the scripts in serial (load script 1, exec script 1,
  95007. * load script 2, exec script 2, and so on), this will be slower than doing
  95008. * the network fetches in parallel.
  95009. *
  95010. * If you need to load a large number of scripts but dependency order doesn't
  95011. * matter, you should just call goog.net.jsloader.load N times.
  95012. *
  95013. * If you need to load a large number of scripts on the same domain,
  95014. * you may want to use goog.module.ModuleLoader.
  95015. *
  95016. * @param {Array<string>} uris The URIs to load.
  95017. * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
  95018. * goog.net.jsloader.options documentation for details.
  95019. * @return {!goog.async.Deferred} The deferred result, that may be used to add
  95020. * callbacks
  95021. */
  95022. goog.net.jsloader.loadMany = function(uris, opt_options) {
  95023. // Loading the scripts in serial introduces asynchronosity into the flow.
  95024. // Therefore, there are race conditions where client A can kick off the load
  95025. // sequence for client B, even though client A's scripts haven't all been
  95026. // loaded yet.
  95027. //
  95028. // To work around this issue, all module loads share a queue.
  95029. if (!uris.length) {
  95030. return goog.async.Deferred.succeed(null);
  95031. }
  95032. var isAnotherModuleLoading = goog.net.jsloader.scriptsToLoad_.length;
  95033. goog.array.extend(goog.net.jsloader.scriptsToLoad_, uris);
  95034. if (isAnotherModuleLoading) {
  95035. // jsloader is still loading some other scripts.
  95036. // In order to prevent the race condition noted above, we just add
  95037. // these URIs to the end of the scripts' queue and return the deferred
  95038. // result of the ongoing script load, so the caller knows when they
  95039. // finish loading.
  95040. return goog.net.jsloader.scriptLoadingDeferred_;
  95041. }
  95042. uris = goog.net.jsloader.scriptsToLoad_;
  95043. var popAndLoadNextScript = function() {
  95044. var uri = uris.shift();
  95045. var deferred = goog.net.jsloader.load(uri, opt_options);
  95046. if (uris.length) {
  95047. deferred.addBoth(popAndLoadNextScript);
  95048. }
  95049. return deferred;
  95050. };
  95051. goog.net.jsloader.scriptLoadingDeferred_ = popAndLoadNextScript();
  95052. return goog.net.jsloader.scriptLoadingDeferred_;
  95053. };
  95054. /**
  95055. * Loads and evaluates a JavaScript file.
  95056. * When the script loads, a user callback is called.
  95057. * It is the client's responsibility to verify that the script ran successfully.
  95058. *
  95059. * @param {string} uri The URI of the JavaScript.
  95060. * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
  95061. * goog.net.jsloader.Options documentation for details.
  95062. * @return {!goog.async.Deferred} The deferred result, that may be used to add
  95063. * callbacks and/or cancel the transmission.
  95064. * The error callback will be called with a single goog.net.jsloader.Error
  95065. * parameter.
  95066. */
  95067. goog.net.jsloader.load = function(uri, opt_options) {
  95068. var options = opt_options || {};
  95069. var doc = options.document || document;
  95070. var script = goog.dom.createElement(goog.dom.TagName.SCRIPT);
  95071. var request = {script_: script, timeout_: undefined};
  95072. var deferred = new goog.async.Deferred(goog.net.jsloader.cancel_, request);
  95073. // Set a timeout.
  95074. var timeout = null;
  95075. var timeoutDuration = goog.isDefAndNotNull(options.timeout) ?
  95076. options.timeout : goog.net.jsloader.DEFAULT_TIMEOUT;
  95077. if (timeoutDuration > 0) {
  95078. timeout = window.setTimeout(function() {
  95079. goog.net.jsloader.cleanup_(script, true);
  95080. deferred.errback(new goog.net.jsloader.Error(
  95081. goog.net.jsloader.ErrorCode.TIMEOUT,
  95082. 'Timeout reached for loading script ' + uri));
  95083. }, timeoutDuration);
  95084. request.timeout_ = timeout;
  95085. }
  95086. // Hang the user callback to be called when the script completes to load.
  95087. // NOTE(user): This callback will be called in IE even upon error. In any
  95088. // case it is the client's responsibility to verify that the script ran
  95089. // successfully.
  95090. script.onload = script.onreadystatechange = function() {
  95091. if (!script.readyState || script.readyState == 'loaded' ||
  95092. script.readyState == 'complete') {
  95093. var removeScriptNode = options.cleanupWhenDone || false;
  95094. goog.net.jsloader.cleanup_(script, removeScriptNode, timeout);
  95095. deferred.callback(null);
  95096. }
  95097. };
  95098. // Add an error callback.
  95099. // NOTE(user): Not supported in IE.
  95100. script.onerror = function() {
  95101. goog.net.jsloader.cleanup_(script, true, timeout);
  95102. deferred.errback(new goog.net.jsloader.Error(
  95103. goog.net.jsloader.ErrorCode.LOAD_ERROR,
  95104. 'Error while loading script ' + uri));
  95105. };
  95106. var properties = options.attributes || {};
  95107. goog.object.extend(properties, {
  95108. 'type': 'text/javascript',
  95109. 'charset': 'UTF-8',
  95110. // NOTE(user): Safari never loads the script if we don't set
  95111. // the src attribute before appending.
  95112. 'src': uri
  95113. });
  95114. goog.dom.setProperties(script, properties);
  95115. var scriptParent = goog.net.jsloader.getScriptParentElement_(doc);
  95116. scriptParent.appendChild(script);
  95117. return deferred;
  95118. };
  95119. /**
  95120. * Loads a JavaScript file and verifies it was evaluated successfully, using a
  95121. * verification object.
  95122. * The verification object is set by the loaded JavaScript at the end of the
  95123. * script.
  95124. * We verify this object was set and return its value in the success callback.
  95125. * If the object is not defined we trigger an error callback.
  95126. *
  95127. * @param {string} uri The URI of the JavaScript.
  95128. * @param {string} verificationObjName The name of the verification object that
  95129. * the loaded script should set.
  95130. * @param {goog.net.jsloader.Options} options Optional parameters. See
  95131. * goog.net.jsloader.Options documentation for details.
  95132. * @return {!goog.async.Deferred} The deferred result, that may be used to add
  95133. * callbacks and/or cancel the transmission.
  95134. * The success callback will be called with a single parameter containing
  95135. * the value of the verification object.
  95136. * The error callback will be called with a single goog.net.jsloader.Error
  95137. * parameter.
  95138. */
  95139. goog.net.jsloader.loadAndVerify = function(uri, verificationObjName, options) {
  95140. // Define the global objects variable.
  95141. if (!goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]) {
  95142. goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_] = {};
  95143. }
  95144. var verifyObjs = goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_];
  95145. // Verify that the expected object does not exist yet.
  95146. if (goog.isDef(verifyObjs[verificationObjName])) {
  95147. // TODO(user): Error or reset variable?
  95148. return goog.async.Deferred.fail(new goog.net.jsloader.Error(
  95149. goog.net.jsloader.ErrorCode.VERIFY_OBJECT_ALREADY_EXISTS,
  95150. 'Verification object ' + verificationObjName + ' already defined.'));
  95151. }
  95152. // Send request to load the JavaScript.
  95153. var sendDeferred = goog.net.jsloader.load(uri, options);
  95154. // Create a deferred object wrapping the send result.
  95155. var deferred = new goog.async.Deferred(
  95156. goog.bind(sendDeferred.cancel, sendDeferred));
  95157. // Call user back with object that was set by the script.
  95158. sendDeferred.addCallback(function() {
  95159. var result = verifyObjs[verificationObjName];
  95160. if (goog.isDef(result)) {
  95161. deferred.callback(result);
  95162. delete verifyObjs[verificationObjName];
  95163. } else {
  95164. // Error: script was not loaded properly.
  95165. deferred.errback(new goog.net.jsloader.Error(
  95166. goog.net.jsloader.ErrorCode.VERIFY_ERROR,
  95167. 'Script ' + uri + ' loaded, but verification object ' +
  95168. verificationObjName + ' was not defined.'));
  95169. }
  95170. });
  95171. // Pass error to new deferred object.
  95172. sendDeferred.addErrback(function(error) {
  95173. if (goog.isDef(verifyObjs[verificationObjName])) {
  95174. delete verifyObjs[verificationObjName];
  95175. }
  95176. deferred.errback(error);
  95177. });
  95178. return deferred;
  95179. };
  95180. /**
  95181. * Gets the DOM element under which we should add new script elements.
  95182. * How? Take the first head element, and if not found take doc.documentElement,
  95183. * which always exists.
  95184. *
  95185. * @param {!HTMLDocument} doc The relevant document.
  95186. * @return {!Element} The script parent element.
  95187. * @private
  95188. */
  95189. goog.net.jsloader.getScriptParentElement_ = function(doc) {
  95190. var headElements = doc.getElementsByTagName(goog.dom.TagName.HEAD);
  95191. if (!headElements || goog.array.isEmpty(headElements)) {
  95192. return doc.documentElement;
  95193. } else {
  95194. return headElements[0];
  95195. }
  95196. };
  95197. /**
  95198. * Cancels a given request.
  95199. * @this {{script_: Element, timeout_: number}} The request context.
  95200. * @private
  95201. */
  95202. goog.net.jsloader.cancel_ = function() {
  95203. var request = this;
  95204. if (request && request.script_) {
  95205. var scriptNode = request.script_;
  95206. if (scriptNode && scriptNode.tagName == goog.dom.TagName.SCRIPT) {
  95207. goog.net.jsloader.cleanup_(scriptNode, true, request.timeout_);
  95208. }
  95209. }
  95210. };
  95211. /**
  95212. * Removes the script node and the timeout.
  95213. *
  95214. * @param {Node} scriptNode The node to be cleaned up.
  95215. * @param {boolean} removeScriptNode If true completely remove the script node.
  95216. * @param {?number=} opt_timeout The timeout handler to cleanup.
  95217. * @private
  95218. */
  95219. goog.net.jsloader.cleanup_ = function(scriptNode, removeScriptNode,
  95220. opt_timeout) {
  95221. if (goog.isDefAndNotNull(opt_timeout)) {
  95222. goog.global.clearTimeout(opt_timeout);
  95223. }
  95224. scriptNode.onload = goog.nullFunction;
  95225. scriptNode.onerror = goog.nullFunction;
  95226. scriptNode.onreadystatechange = goog.nullFunction;
  95227. // Do this after a delay (removing the script node of a running script can
  95228. // confuse older IEs).
  95229. if (removeScriptNode) {
  95230. window.setTimeout(function() {
  95231. goog.dom.removeNode(scriptNode);
  95232. }, 0);
  95233. }
  95234. };
  95235. /**
  95236. * Possible error codes for jsloader.
  95237. * @enum {number}
  95238. */
  95239. goog.net.jsloader.ErrorCode = {
  95240. LOAD_ERROR: 0,
  95241. TIMEOUT: 1,
  95242. VERIFY_ERROR: 2,
  95243. VERIFY_OBJECT_ALREADY_EXISTS: 3
  95244. };
  95245. /**
  95246. * A jsloader error.
  95247. *
  95248. * @param {goog.net.jsloader.ErrorCode} code The error code.
  95249. * @param {string=} opt_message Additional message.
  95250. * @constructor
  95251. * @extends {goog.debug.Error}
  95252. * @final
  95253. */
  95254. goog.net.jsloader.Error = function(code, opt_message) {
  95255. var msg = 'Jsloader error (code #' + code + ')';
  95256. if (opt_message) {
  95257. msg += ': ' + opt_message;
  95258. }
  95259. goog.net.jsloader.Error.base(this, 'constructor', msg);
  95260. /**
  95261. * The code for this error.
  95262. *
  95263. * @type {goog.net.jsloader.ErrorCode}
  95264. */
  95265. this.code = code;
  95266. };
  95267. goog.inherits(goog.net.jsloader.Error, goog.debug.Error);
  95268. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  95269. //
  95270. // Licensed under the Apache License, Version 2.0 (the "License");
  95271. // you may not use this file except in compliance with the License.
  95272. // You may obtain a copy of the License at
  95273. //
  95274. // http://www.apache.org/licenses/LICENSE-2.0
  95275. //
  95276. // Unless required by applicable law or agreed to in writing, software
  95277. // distributed under the License is distributed on an "AS-IS" BASIS,
  95278. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  95279. // See the License for the specific language governing permissions and
  95280. // limitations under the License.
  95281. // The original file lives here: http://go/cross_domain_channel.js
  95282. /**
  95283. * @fileoverview Implements a cross-domain communication channel. A
  95284. * typical web page is prevented by browser security from sending
  95285. * request, such as a XMLHttpRequest, to other servers than the ones
  95286. * from which it came. The Jsonp class provides a workaround by
  95287. * using dynamically generated script tags. Typical usage:.
  95288. *
  95289. * var jsonp = new goog.net.Jsonp(new goog.Uri('http://my.host.com/servlet'));
  95290. * var payload = { 'foo': 1, 'bar': true };
  95291. * jsonp.send(payload, function(reply) { alert(reply) });
  95292. *
  95293. * This script works in all browsers that are currently supported by
  95294. * the Google Maps API, which is IE 6.0+, Firefox 0.8+, Safari 1.2.4+,
  95295. * Netscape 7.1+, Mozilla 1.4+, Opera 8.02+.
  95296. *
  95297. */
  95298. goog.provide('goog.net.Jsonp');
  95299. goog.require('goog.Uri');
  95300. goog.require('goog.net.jsloader');
  95301. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  95302. //
  95303. // This class allows us (Google) to send data from non-Google and thus
  95304. // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
  95305. // anything sensitive, such as session or cookie specific data. Return
  95306. // only data that you want parties external to Google to have. Also
  95307. // NEVER use this method to send data from web pages to untrusted
  95308. // servers, or redirects to unknown servers (www.google.com/cache,
  95309. // /q=xx&btnl, /url, www.googlepages.com, etc.)
  95310. //
  95311. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  95312. /**
  95313. * Creates a new cross domain channel that sends data to the specified
  95314. * host URL. By default, if no reply arrives within 5s, the channel
  95315. * assumes the call failed to complete successfully.
  95316. *
  95317. * @param {goog.Uri|string} uri The Uri of the server side code that receives
  95318. * data posted through this channel (e.g.,
  95319. * "http://maps.google.com/maps/geo").
  95320. *
  95321. * @param {string=} opt_callbackParamName The parameter name that is used to
  95322. * specify the callback. Defaults to "callback".
  95323. *
  95324. * @constructor
  95325. * @final
  95326. */
  95327. goog.net.Jsonp = function(uri, opt_callbackParamName) {
  95328. /**
  95329. * The uri_ object will be used to encode the payload that is sent to the
  95330. * server.
  95331. * @type {goog.Uri}
  95332. * @private
  95333. */
  95334. this.uri_ = new goog.Uri(uri);
  95335. /**
  95336. * This is the callback parameter name that is added to the uri.
  95337. * @type {string}
  95338. * @private
  95339. */
  95340. this.callbackParamName_ = opt_callbackParamName ?
  95341. opt_callbackParamName : 'callback';
  95342. /**
  95343. * The length of time, in milliseconds, this channel is prepared
  95344. * to wait for for a request to complete. The default value is 5 seconds.
  95345. * @type {number}
  95346. * @private
  95347. */
  95348. this.timeout_ = 5000;
  95349. };
  95350. /**
  95351. * The name of the property of goog.global under which the callback is
  95352. * stored.
  95353. */
  95354. goog.net.Jsonp.CALLBACKS = '_callbacks_';
  95355. /**
  95356. * Used to generate unique callback IDs. The counter must be global because
  95357. * all channels share a common callback object.
  95358. * @private
  95359. */
  95360. goog.net.Jsonp.scriptCounter_ = 0;
  95361. /**
  95362. * Sets the length of time, in milliseconds, this channel is prepared
  95363. * to wait for for a request to complete. If the call is not competed
  95364. * within the set time span, it is assumed to have failed. To wait
  95365. * indefinitely for a request to complete set the timout to a negative
  95366. * number.
  95367. *
  95368. * @param {number} timeout The length of time before calls are
  95369. * interrupted.
  95370. */
  95371. goog.net.Jsonp.prototype.setRequestTimeout = function(timeout) {
  95372. this.timeout_ = timeout;
  95373. };
  95374. /**
  95375. * Returns the current timeout value, in milliseconds.
  95376. *
  95377. * @return {number} The timeout value.
  95378. */
  95379. goog.net.Jsonp.prototype.getRequestTimeout = function() {
  95380. return this.timeout_;
  95381. };
  95382. /**
  95383. * Sends the given payload to the URL specified at the construction
  95384. * time. The reply is delivered to the given replyCallback. If the
  95385. * errorCallback is specified and the reply does not arrive within the
  95386. * timeout period set on this channel, the errorCallback is invoked
  95387. * with the original payload.
  95388. *
  95389. * If no reply callback is specified, then the response is expected to
  95390. * consist of calls to globally registered functions. No &callback=
  95391. * URL parameter will be sent in the request, and the script element
  95392. * will be cleaned up after the timeout.
  95393. *
  95394. * @param {Object=} opt_payload Name-value pairs. If given, these will be
  95395. * added as parameters to the supplied URI as GET parameters to the
  95396. * given server URI.
  95397. *
  95398. * @param {Function=} opt_replyCallback A function expecting one
  95399. * argument, called when the reply arrives, with the response data.
  95400. *
  95401. * @param {Function=} opt_errorCallback A function expecting one
  95402. * argument, called on timeout, with the payload (if given), otherwise
  95403. * null.
  95404. *
  95405. * @param {string=} opt_callbackParamValue Value to be used as the
  95406. * parameter value for the callback parameter (callbackParamName).
  95407. * To be used when the value needs to be fixed by the client for a
  95408. * particular request, to make use of the cached responses for the request.
  95409. * NOTE: If multiple requests are made with the same
  95410. * opt_callbackParamValue, only the last call will work whenever the
  95411. * response comes back.
  95412. *
  95413. * @return {!Object} A request descriptor that may be used to cancel this
  95414. * transmission, or null, if the message may not be cancelled.
  95415. */
  95416. goog.net.Jsonp.prototype.send = function(opt_payload,
  95417. opt_replyCallback,
  95418. opt_errorCallback,
  95419. opt_callbackParamValue) {
  95420. var payload = opt_payload || null;
  95421. var id = opt_callbackParamValue ||
  95422. '_' + (goog.net.Jsonp.scriptCounter_++).toString(36) +
  95423. goog.now().toString(36);
  95424. if (!goog.global[goog.net.Jsonp.CALLBACKS]) {
  95425. goog.global[goog.net.Jsonp.CALLBACKS] = {};
  95426. }
  95427. // Create a new Uri object onto which this payload will be added
  95428. var uri = this.uri_.clone();
  95429. if (payload) {
  95430. goog.net.Jsonp.addPayloadToUri_(payload, uri);
  95431. }
  95432. if (opt_replyCallback) {
  95433. var reply = goog.net.Jsonp.newReplyHandler_(id, opt_replyCallback);
  95434. goog.global[goog.net.Jsonp.CALLBACKS][id] = reply;
  95435. uri.setParameterValues(this.callbackParamName_,
  95436. goog.net.Jsonp.CALLBACKS + '.' + id);
  95437. }
  95438. var deferred = goog.net.jsloader.load(uri.toString(),
  95439. {timeout: this.timeout_, cleanupWhenDone: true});
  95440. var error = goog.net.Jsonp.newErrorHandler_(id, payload, opt_errorCallback);
  95441. deferred.addErrback(error);
  95442. return {id_: id, deferred_: deferred};
  95443. };
  95444. /**
  95445. * Cancels a given request. The request must be exactly the object returned by
  95446. * the send method.
  95447. *
  95448. * @param {Object} request The request object returned by the send method.
  95449. */
  95450. goog.net.Jsonp.prototype.cancel = function(request) {
  95451. if (request) {
  95452. if (request.deferred_) {
  95453. request.deferred_.cancel();
  95454. }
  95455. if (request.id_) {
  95456. goog.net.Jsonp.cleanup_(request.id_, false);
  95457. }
  95458. }
  95459. };
  95460. /**
  95461. * Creates a timeout callback that calls the given timeoutCallback with the
  95462. * original payload.
  95463. *
  95464. * @param {string} id The id of the script node.
  95465. * @param {Object} payload The payload that was sent to the server.
  95466. * @param {Function=} opt_errorCallback The function called on timeout.
  95467. * @return {!Function} A zero argument function that handles callback duties.
  95468. * @private
  95469. */
  95470. goog.net.Jsonp.newErrorHandler_ = function(id,
  95471. payload,
  95472. opt_errorCallback) {
  95473. /**
  95474. * When we call across domains with a request, this function is the
  95475. * timeout handler. Once it's done executing the user-specified
  95476. * error-handler, it removes the script node and original function.
  95477. */
  95478. return function() {
  95479. goog.net.Jsonp.cleanup_(id, false);
  95480. if (opt_errorCallback) {
  95481. opt_errorCallback(payload);
  95482. }
  95483. };
  95484. };
  95485. /**
  95486. * Creates a reply callback that calls the given replyCallback with data
  95487. * returned by the server.
  95488. *
  95489. * @param {string} id The id of the script node.
  95490. * @param {Function} replyCallback The function called on reply.
  95491. * @return {!Function} A reply callback function.
  95492. * @private
  95493. */
  95494. goog.net.Jsonp.newReplyHandler_ = function(id, replyCallback) {
  95495. /**
  95496. * This function is the handler for the all-is-well response. It
  95497. * clears the error timeout handler, calls the user's handler, then
  95498. * removes the script node and itself.
  95499. *
  95500. * @param {...Object} var_args The response data sent from the server.
  95501. */
  95502. var handler = function(var_args) {
  95503. goog.net.Jsonp.cleanup_(id, true);
  95504. replyCallback.apply(undefined, arguments);
  95505. };
  95506. return handler;
  95507. };
  95508. /**
  95509. * Removes the script node and reply handler with the given id.
  95510. *
  95511. * @param {string} id The id of the script node to be removed.
  95512. * @param {boolean} deleteReplyHandler If true, delete the reply handler
  95513. * instead of setting it to nullFunction (if we know the callback could
  95514. * never be called again).
  95515. * @private
  95516. */
  95517. goog.net.Jsonp.cleanup_ = function(id, deleteReplyHandler) {
  95518. if (goog.global[goog.net.Jsonp.CALLBACKS][id]) {
  95519. if (deleteReplyHandler) {
  95520. delete goog.global[goog.net.Jsonp.CALLBACKS][id];
  95521. } else {
  95522. // Removing the script tag doesn't necessarily prevent the script
  95523. // from firing, so we make the callback a noop.
  95524. goog.global[goog.net.Jsonp.CALLBACKS][id] = goog.nullFunction;
  95525. }
  95526. }
  95527. };
  95528. /**
  95529. * Returns URL encoded payload. The payload should be a map of name-value
  95530. * pairs, in the form {"foo": 1, "bar": true, ...}. If the map is empty,
  95531. * the URI will be unchanged.
  95532. *
  95533. * <p>The method uses hasOwnProperty() to assure the properties are on the
  95534. * object, not on its prototype.
  95535. *
  95536. * @param {!Object} payload A map of value name pairs to be encoded.
  95537. * A value may be specified as an array, in which case a query parameter
  95538. * will be created for each value, e.g.:
  95539. * {"foo": [1,2]} will encode to "foo=1&foo=2".
  95540. *
  95541. * @param {!goog.Uri} uri A Uri object onto which the payload key value pairs
  95542. * will be encoded.
  95543. *
  95544. * @return {!goog.Uri} A reference to the Uri sent as a parameter.
  95545. * @private
  95546. */
  95547. goog.net.Jsonp.addPayloadToUri_ = function(payload, uri) {
  95548. for (var name in payload) {
  95549. // NOTE(user): Safari/1.3 doesn't have hasOwnProperty(). In that
  95550. // case, we iterate over all properties as a very lame workaround.
  95551. if (!payload.hasOwnProperty || payload.hasOwnProperty(name)) {
  95552. uri.setParameterValues(name, payload[name]);
  95553. }
  95554. }
  95555. return uri;
  95556. };
  95557. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  95558. //
  95559. // This class allows us (Google) to send data from non-Google and thus
  95560. // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return
  95561. // anything sensitive, such as session or cookie specific data. Return
  95562. // only data that you want parties external to Google to have. Also
  95563. // NEVER use this method to send data from web pages to untrusted
  95564. // servers, or redirects to unknown servers (www.google.com/cache,
  95565. // /q=xx&btnl, /url, www.googlepages.com, etc.)
  95566. //
  95567. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
  95568. goog.provide('ol.TileUrlFunction');
  95569. goog.provide('ol.TileUrlFunctionType');
  95570. goog.require('goog.asserts');
  95571. goog.require('goog.math');
  95572. goog.require('ol.TileCoord');
  95573. goog.require('ol.tilecoord');
  95574. /**
  95575. * {@link ol.source.Tile} sources use a function of this type to get the url
  95576. * that provides a tile for a given tile coordinate.
  95577. *
  95578. * This function takes an {@link ol.TileCoord} for the tile coordinate, a
  95579. * `{number}` representing the pixel ratio and an {@link ol.proj.Projection} for
  95580. * the projection as arguments and returns a `{string}` representing the tile
  95581. * URL, or undefined if no tile should be requested for the passed tile
  95582. * coordinate.
  95583. *
  95584. * @typedef {function(ol.TileCoord, number,
  95585. * ol.proj.Projection): (string|undefined)}
  95586. * @api
  95587. */
  95588. ol.TileUrlFunctionType;
  95589. /**
  95590. * @typedef {function(ol.TileCoord, ol.proj.Projection, ol.TileCoord=):
  95591. * ol.TileCoord}
  95592. */
  95593. ol.TileCoordTransformType;
  95594. /**
  95595. * @param {string} template Template.
  95596. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  95597. * @return {ol.TileUrlFunctionType} Tile URL function.
  95598. */
  95599. ol.TileUrlFunction.createFromTemplate = function(template, tileGrid) {
  95600. var zRegEx = /\{z\}/g;
  95601. var xRegEx = /\{x\}/g;
  95602. var yRegEx = /\{y\}/g;
  95603. var dashYRegEx = /\{-y\}/g;
  95604. return (
  95605. /**
  95606. * @param {ol.TileCoord} tileCoord Tile Coordinate.
  95607. * @param {number} pixelRatio Pixel ratio.
  95608. * @param {ol.proj.Projection} projection Projection.
  95609. * @return {string|undefined} Tile URL.
  95610. */
  95611. function(tileCoord, pixelRatio, projection) {
  95612. if (!tileCoord) {
  95613. return undefined;
  95614. } else {
  95615. return template.replace(zRegEx, tileCoord[0].toString())
  95616. .replace(xRegEx, tileCoord[1].toString())
  95617. .replace(yRegEx, function() {
  95618. var y = -tileCoord[2] - 1;
  95619. return y.toString();
  95620. })
  95621. .replace(dashYRegEx, function() {
  95622. var z = tileCoord[0];
  95623. var range = tileGrid.getFullTileRange(z);
  95624. goog.asserts.assert(range,
  95625. 'The {-y} template requires a tile grid with extent');
  95626. var y = range.getHeight() + tileCoord[2];
  95627. return y.toString();
  95628. });
  95629. }
  95630. });
  95631. };
  95632. /**
  95633. * @param {Array.<string>} templates Templates.
  95634. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid.
  95635. * @return {ol.TileUrlFunctionType} Tile URL function.
  95636. */
  95637. ol.TileUrlFunction.createFromTemplates = function(templates, tileGrid) {
  95638. var len = templates.length;
  95639. var tileUrlFunctions = new Array(len);
  95640. for (var i = 0; i < len; ++i) {
  95641. tileUrlFunctions[i] = ol.TileUrlFunction.createFromTemplate(
  95642. templates[i], tileGrid);
  95643. }
  95644. return ol.TileUrlFunction.createFromTileUrlFunctions(tileUrlFunctions);
  95645. };
  95646. /**
  95647. * @param {Array.<ol.TileUrlFunctionType>} tileUrlFunctions Tile URL Functions.
  95648. * @return {ol.TileUrlFunctionType} Tile URL function.
  95649. */
  95650. ol.TileUrlFunction.createFromTileUrlFunctions = function(tileUrlFunctions) {
  95651. goog.asserts.assert(tileUrlFunctions.length > 0,
  95652. 'Length of tile url functions should be greater than 0');
  95653. if (tileUrlFunctions.length === 1) {
  95654. return tileUrlFunctions[0];
  95655. }
  95656. return (
  95657. /**
  95658. * @param {ol.TileCoord} tileCoord Tile Coordinate.
  95659. * @param {number} pixelRatio Pixel ratio.
  95660. * @param {ol.proj.Projection} projection Projection.
  95661. * @return {string|undefined} Tile URL.
  95662. */
  95663. function(tileCoord, pixelRatio, projection) {
  95664. if (!tileCoord) {
  95665. return undefined;
  95666. } else {
  95667. var h = ol.tilecoord.hash(tileCoord);
  95668. var index = goog.math.modulo(h, tileUrlFunctions.length);
  95669. return tileUrlFunctions[index](tileCoord, pixelRatio, projection);
  95670. }
  95671. });
  95672. };
  95673. /**
  95674. * @param {ol.TileCoord} tileCoord Tile coordinate.
  95675. * @param {number} pixelRatio Pixel ratio.
  95676. * @param {ol.proj.Projection} projection Projection.
  95677. * @return {string|undefined} Tile URL.
  95678. */
  95679. ol.TileUrlFunction.nullTileUrlFunction =
  95680. function(tileCoord, pixelRatio, projection) {
  95681. return undefined;
  95682. };
  95683. /**
  95684. * @param {string} url URL.
  95685. * @return {Array.<string>} Array of urls.
  95686. */
  95687. ol.TileUrlFunction.expandUrl = function(url) {
  95688. var urls = [];
  95689. var match = /\{(\d)-(\d)\}/.exec(url) || /\{([a-z])-([a-z])\}/.exec(url);
  95690. if (match) {
  95691. var startCharCode = match[1].charCodeAt(0);
  95692. var stopCharCode = match[2].charCodeAt(0);
  95693. var charCode;
  95694. for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) {
  95695. urls.push(url.replace(match[0], String.fromCharCode(charCode)));
  95696. }
  95697. } else {
  95698. urls.push(url);
  95699. }
  95700. return urls;
  95701. };
  95702. goog.provide('ol.source.TileImage');
  95703. goog.require('goog.asserts');
  95704. goog.require('goog.events');
  95705. goog.require('goog.events.EventType');
  95706. goog.require('ol.ImageTile');
  95707. goog.require('ol.TileCoord');
  95708. goog.require('ol.TileLoadFunctionType');
  95709. goog.require('ol.TileState');
  95710. goog.require('ol.TileUrlFunction');
  95711. goog.require('ol.TileUrlFunctionType');
  95712. goog.require('ol.source.Tile');
  95713. goog.require('ol.source.TileEvent');
  95714. /**
  95715. * @classdesc
  95716. * Base class for sources providing images divided into a tile grid.
  95717. *
  95718. * @constructor
  95719. * @fires ol.source.TileEvent
  95720. * @extends {ol.source.Tile}
  95721. * @param {olx.source.TileImageOptions} options Image tile options.
  95722. * @api
  95723. */
  95724. ol.source.TileImage = function(options) {
  95725. goog.base(this, {
  95726. attributions: options.attributions,
  95727. extent: options.extent,
  95728. logo: options.logo,
  95729. opaque: options.opaque,
  95730. projection: options.projection,
  95731. state: options.state !== undefined ?
  95732. /** @type {ol.source.State} */ (options.state) : undefined,
  95733. tileGrid: options.tileGrid,
  95734. tilePixelRatio: options.tilePixelRatio,
  95735. wrapX: options.wrapX
  95736. });
  95737. /**
  95738. * @protected
  95739. * @type {ol.TileUrlFunctionType}
  95740. */
  95741. this.tileUrlFunction = options.tileUrlFunction !== undefined ?
  95742. options.tileUrlFunction :
  95743. ol.TileUrlFunction.nullTileUrlFunction;
  95744. /**
  95745. * @protected
  95746. * @type {?string}
  95747. */
  95748. this.crossOrigin =
  95749. options.crossOrigin !== undefined ? options.crossOrigin : null;
  95750. /**
  95751. * @protected
  95752. * @type {ol.TileLoadFunctionType}
  95753. */
  95754. this.tileLoadFunction = options.tileLoadFunction !== undefined ?
  95755. options.tileLoadFunction : ol.source.TileImage.defaultTileLoadFunction;
  95756. /**
  95757. * @protected
  95758. * @type {function(new: ol.ImageTile, ol.TileCoord, ol.TileState, string,
  95759. * ?string, ol.TileLoadFunctionType)}
  95760. */
  95761. this.tileClass = options.tileClass !== undefined ?
  95762. options.tileClass : ol.ImageTile;
  95763. };
  95764. goog.inherits(ol.source.TileImage, ol.source.Tile);
  95765. /**
  95766. * @param {ol.ImageTile} imageTile Image tile.
  95767. * @param {string} src Source.
  95768. */
  95769. ol.source.TileImage.defaultTileLoadFunction = function(imageTile, src) {
  95770. imageTile.getImage().src = src;
  95771. };
  95772. /**
  95773. * @inheritDoc
  95774. */
  95775. ol.source.TileImage.prototype.getTile =
  95776. function(z, x, y, pixelRatio, projection) {
  95777. var tileCoordKey = this.getKeyZXY(z, x, y);
  95778. if (this.tileCache.containsKey(tileCoordKey)) {
  95779. return /** @type {!ol.Tile} */ (this.tileCache.get(tileCoordKey));
  95780. } else {
  95781. goog.asserts.assert(projection, 'argument projection is truthy');
  95782. var tileCoord = [z, x, y];
  95783. var urlTileCoord = this.getTileCoordForTileUrlFunction(
  95784. tileCoord, projection);
  95785. var tileUrl = !urlTileCoord ? undefined :
  95786. this.tileUrlFunction(urlTileCoord, pixelRatio, projection);
  95787. var tile = new this.tileClass(
  95788. tileCoord,
  95789. tileUrl !== undefined ? ol.TileState.IDLE : ol.TileState.EMPTY,
  95790. tileUrl !== undefined ? tileUrl : '',
  95791. this.crossOrigin,
  95792. this.tileLoadFunction);
  95793. goog.events.listen(tile, goog.events.EventType.CHANGE,
  95794. this.handleTileChange_, false, this);
  95795. this.tileCache.set(tileCoordKey, tile);
  95796. return tile;
  95797. }
  95798. };
  95799. /**
  95800. * Return the tile load function of the source.
  95801. * @return {ol.TileLoadFunctionType} TileLoadFunction
  95802. * @api
  95803. */
  95804. ol.source.TileImage.prototype.getTileLoadFunction = function() {
  95805. return this.tileLoadFunction;
  95806. };
  95807. /**
  95808. * Return the tile URL function of the source.
  95809. * @return {ol.TileUrlFunctionType} TileUrlFunction
  95810. * @api
  95811. */
  95812. ol.source.TileImage.prototype.getTileUrlFunction = function() {
  95813. return this.tileUrlFunction;
  95814. };
  95815. /**
  95816. * Handle tile change events.
  95817. * @param {goog.events.Event} event Event.
  95818. * @private
  95819. */
  95820. ol.source.TileImage.prototype.handleTileChange_ = function(event) {
  95821. var tile = /** @type {ol.Tile} */ (event.target);
  95822. switch (tile.getState()) {
  95823. case ol.TileState.LOADING:
  95824. this.dispatchEvent(
  95825. new ol.source.TileEvent(ol.source.TileEventType.TILELOADSTART, tile));
  95826. break;
  95827. case ol.TileState.LOADED:
  95828. this.dispatchEvent(
  95829. new ol.source.TileEvent(ol.source.TileEventType.TILELOADEND, tile));
  95830. break;
  95831. case ol.TileState.ERROR:
  95832. this.dispatchEvent(
  95833. new ol.source.TileEvent(ol.source.TileEventType.TILELOADERROR, tile));
  95834. break;
  95835. }
  95836. };
  95837. /**
  95838. * Set the tile load function of the source.
  95839. * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
  95840. * @api
  95841. */
  95842. ol.source.TileImage.prototype.setTileLoadFunction = function(tileLoadFunction) {
  95843. this.tileCache.clear();
  95844. this.tileLoadFunction = tileLoadFunction;
  95845. this.changed();
  95846. };
  95847. /**
  95848. * Set the tile URL function of the source.
  95849. * @param {ol.TileUrlFunctionType} tileUrlFunction Tile URL function.
  95850. * @api
  95851. */
  95852. ol.source.TileImage.prototype.setTileUrlFunction = function(tileUrlFunction) {
  95853. // FIXME It should be possible to be more intelligent and avoid clearing the
  95854. // FIXME cache. The tile URL function would need to be incorporated into the
  95855. // FIXME cache key somehow.
  95856. this.tileCache.clear();
  95857. this.tileUrlFunction = tileUrlFunction;
  95858. this.changed();
  95859. };
  95860. /**
  95861. * @inheritDoc
  95862. */
  95863. ol.source.TileImage.prototype.useTile = function(z, x, y) {
  95864. var tileCoordKey = this.getKeyZXY(z, x, y);
  95865. if (this.tileCache.containsKey(tileCoordKey)) {
  95866. this.tileCache.get(tileCoordKey);
  95867. }
  95868. };
  95869. goog.provide('ol.source.BingMaps');
  95870. goog.require('goog.Uri');
  95871. goog.require('goog.asserts');
  95872. goog.require('goog.net.Jsonp');
  95873. goog.require('ol.Attribution');
  95874. goog.require('ol.TileRange');
  95875. goog.require('ol.TileUrlFunction');
  95876. goog.require('ol.extent');
  95877. goog.require('ol.proj');
  95878. goog.require('ol.source.State');
  95879. goog.require('ol.source.TileImage');
  95880. goog.require('ol.tilecoord');
  95881. /**
  95882. * @classdesc
  95883. * Layer source for Bing Maps tile data.
  95884. *
  95885. * @constructor
  95886. * @extends {ol.source.TileImage}
  95887. * @param {olx.source.BingMapsOptions} options Bing Maps options.
  95888. * @api stable
  95889. */
  95890. ol.source.BingMaps = function(options) {
  95891. goog.base(this, {
  95892. crossOrigin: 'anonymous',
  95893. opaque: true,
  95894. projection: ol.proj.get('EPSG:3857'),
  95895. state: ol.source.State.LOADING,
  95896. tileLoadFunction: options.tileLoadFunction,
  95897. wrapX: options.wrapX !== undefined ? options.wrapX : true
  95898. });
  95899. /**
  95900. * @private
  95901. * @type {string}
  95902. */
  95903. this.culture_ = options.culture !== undefined ? options.culture : 'en-us';
  95904. /**
  95905. * @private
  95906. * @type {number}
  95907. */
  95908. this.maxZoom_ = options.maxZoom !== undefined ? options.maxZoom : -1;
  95909. var uri = new goog.Uri(
  95910. 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' +
  95911. options.imagerySet);
  95912. var jsonp = new goog.net.Jsonp(uri, 'jsonp');
  95913. jsonp.send({
  95914. 'include': 'ImageryProviders',
  95915. 'uriScheme': 'https',
  95916. 'key': options.key
  95917. }, goog.bind(this.handleImageryMetadataResponse, this));
  95918. };
  95919. goog.inherits(ol.source.BingMaps, ol.source.TileImage);
  95920. /**
  95921. * The attribution containing a link to the Microsoft® Bing™ Maps Platform APIs’
  95922. * Terms Of Use.
  95923. * @const
  95924. * @type {ol.Attribution}
  95925. * @api
  95926. */
  95927. ol.source.BingMaps.TOS_ATTRIBUTION = new ol.Attribution({
  95928. html: '<a class="ol-attribution-bing-tos" ' +
  95929. 'href="http://www.microsoft.com/maps/product/terms.html">' +
  95930. 'Terms of Use</a>'
  95931. });
  95932. /**
  95933. * @param {BingMapsImageryMetadataResponse} response Response.
  95934. */
  95935. ol.source.BingMaps.prototype.handleImageryMetadataResponse =
  95936. function(response) {
  95937. if (response.statusCode != 200 ||
  95938. response.statusDescription != 'OK' ||
  95939. response.authenticationResultCode != 'ValidCredentials' ||
  95940. response.resourceSets.length != 1 ||
  95941. response.resourceSets[0].resources.length != 1) {
  95942. this.setState(ol.source.State.ERROR);
  95943. return;
  95944. }
  95945. var brandLogoUri = response.brandLogoUri;
  95946. if (brandLogoUri.indexOf('https') == -1) {
  95947. brandLogoUri = brandLogoUri.replace('http', 'https');
  95948. }
  95949. //var copyright = response.copyright; // FIXME do we need to display this?
  95950. var resource = response.resourceSets[0].resources[0];
  95951. goog.asserts.assert(resource.imageWidth == resource.imageHeight,
  95952. 'resource has imageWidth equal to imageHeight, i.e. is square');
  95953. var maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_;
  95954. var sourceProjection = this.getProjection();
  95955. var extent = ol.tilegrid.extentFromProjection(sourceProjection);
  95956. var tileSize = resource.imageWidth == resource.imageHeight ?
  95957. resource.imageWidth : [resource.imageWidth, resource.imageHeight];
  95958. var tileGrid = ol.tilegrid.createXYZ({
  95959. extent: extent,
  95960. minZoom: resource.zoomMin,
  95961. maxZoom: maxZoom,
  95962. tileSize: tileSize
  95963. });
  95964. this.tileGrid = tileGrid;
  95965. var culture = this.culture_;
  95966. this.tileUrlFunction = ol.TileUrlFunction.createFromTileUrlFunctions(
  95967. resource.imageUrlSubdomains.map(function(subdomain) {
  95968. var quadKeyTileCoord = [0, 0, 0];
  95969. var imageUrl = resource.imageUrl
  95970. .replace('{subdomain}', subdomain)
  95971. .replace('{culture}', culture);
  95972. return (
  95973. /**
  95974. * @param {ol.TileCoord} tileCoord Tile coordinate.
  95975. * @param {number} pixelRatio Pixel ratio.
  95976. * @param {ol.proj.Projection} projection Projection.
  95977. * @return {string|undefined} Tile URL.
  95978. */
  95979. function(tileCoord, pixelRatio, projection) {
  95980. goog.asserts.assert(ol.proj.equivalent(
  95981. projection, sourceProjection),
  95982. 'projections are equivalent');
  95983. if (!tileCoord) {
  95984. return undefined;
  95985. } else {
  95986. ol.tilecoord.createOrUpdate(tileCoord[0], tileCoord[1],
  95987. -tileCoord[2] - 1, quadKeyTileCoord);
  95988. return imageUrl.replace('{quadkey}', ol.tilecoord.quadKey(
  95989. quadKeyTileCoord));
  95990. }
  95991. });
  95992. }));
  95993. if (resource.imageryProviders) {
  95994. var transform = ol.proj.getTransformFromProjections(
  95995. ol.proj.get('EPSG:4326'), this.getProjection());
  95996. var attributions = resource.imageryProviders.map(function(imageryProvider) {
  95997. var html = imageryProvider.attribution;
  95998. /** @type {Object.<string, Array.<ol.TileRange>>} */
  95999. var tileRanges = {};
  96000. imageryProvider.coverageAreas.forEach(function(coverageArea) {
  96001. var minZ = coverageArea.zoomMin;
  96002. var maxZ = Math.min(coverageArea.zoomMax, maxZoom);
  96003. var bbox = coverageArea.bbox;
  96004. var epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]];
  96005. var extent = ol.extent.applyTransform(epsg4326Extent, transform);
  96006. var tileRange, z, zKey;
  96007. for (z = minZ; z <= maxZ; ++z) {
  96008. zKey = z.toString();
  96009. tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  96010. if (zKey in tileRanges) {
  96011. tileRanges[zKey].push(tileRange);
  96012. } else {
  96013. tileRanges[zKey] = [tileRange];
  96014. }
  96015. }
  96016. });
  96017. return new ol.Attribution({html: html, tileRanges: tileRanges});
  96018. });
  96019. attributions.push(ol.source.BingMaps.TOS_ATTRIBUTION);
  96020. this.setAttributions(attributions);
  96021. }
  96022. this.setLogo(brandLogoUri);
  96023. this.setState(ol.source.State.READY);
  96024. };
  96025. // FIXME keep cluster cache by resolution ?
  96026. // FIXME distance not respected because of the centroid
  96027. goog.provide('ol.source.Cluster');
  96028. goog.require('goog.asserts');
  96029. goog.require('goog.events.EventType');
  96030. goog.require('goog.object');
  96031. goog.require('ol.Feature');
  96032. goog.require('ol.coordinate');
  96033. goog.require('ol.extent');
  96034. goog.require('ol.geom.Point');
  96035. goog.require('ol.source.Vector');
  96036. /**
  96037. * @classdesc
  96038. * Layer source to cluster vector data.
  96039. *
  96040. * @constructor
  96041. * @param {olx.source.ClusterOptions} options
  96042. * @extends {ol.source.Vector}
  96043. * @api
  96044. */
  96045. ol.source.Cluster = function(options) {
  96046. goog.base(this, {
  96047. attributions: options.attributions,
  96048. extent: options.extent,
  96049. logo: options.logo,
  96050. projection: options.projection
  96051. });
  96052. /**
  96053. * @type {number|undefined}
  96054. * @private
  96055. */
  96056. this.resolution_ = undefined;
  96057. /**
  96058. * @type {number}
  96059. * @private
  96060. */
  96061. this.distance_ = options.distance !== undefined ? options.distance : 20;
  96062. /**
  96063. * @type {Array.<ol.Feature>}
  96064. * @private
  96065. */
  96066. this.features_ = [];
  96067. /**
  96068. * @type {ol.source.Vector}
  96069. * @private
  96070. */
  96071. this.source_ = options.source;
  96072. this.source_.on(goog.events.EventType.CHANGE,
  96073. ol.source.Cluster.prototype.onSourceChange_, this);
  96074. };
  96075. goog.inherits(ol.source.Cluster, ol.source.Vector);
  96076. /**
  96077. * Get a reference to the wrapped source.
  96078. * @return {ol.source.Vector} Source.
  96079. * @api
  96080. */
  96081. ol.source.Cluster.prototype.getSource = function() {
  96082. return this.source_;
  96083. };
  96084. /**
  96085. * @inheritDoc
  96086. */
  96087. ol.source.Cluster.prototype.loadFeatures = function(extent, resolution,
  96088. projection) {
  96089. this.source_.loadFeatures(extent, resolution, projection);
  96090. if (resolution !== this.resolution_) {
  96091. this.clear();
  96092. this.resolution_ = resolution;
  96093. this.cluster_();
  96094. this.addFeatures(this.features_);
  96095. }
  96096. };
  96097. /**
  96098. * handle the source changing
  96099. * @private
  96100. */
  96101. ol.source.Cluster.prototype.onSourceChange_ = function() {
  96102. this.clear();
  96103. this.cluster_();
  96104. this.addFeatures(this.features_);
  96105. this.changed();
  96106. };
  96107. /**
  96108. * @private
  96109. */
  96110. ol.source.Cluster.prototype.cluster_ = function() {
  96111. if (this.resolution_ === undefined) {
  96112. return;
  96113. }
  96114. this.features_.length = 0;
  96115. var extent = ol.extent.createEmpty();
  96116. var mapDistance = this.distance_ * this.resolution_;
  96117. var features = this.source_.getFeatures();
  96118. /**
  96119. * @type {Object.<string, boolean>}
  96120. */
  96121. var clustered = {};
  96122. for (var i = 0, ii = features.length; i < ii; i++) {
  96123. var feature = features[i];
  96124. if (!goog.object.containsKey(clustered, goog.getUid(feature).toString())) {
  96125. var geometry = feature.getGeometry();
  96126. goog.asserts.assert(geometry instanceof ol.geom.Point,
  96127. 'feature geometry is a ol.geom.Point instance');
  96128. var coordinates = geometry.getCoordinates();
  96129. ol.extent.createOrUpdateFromCoordinate(coordinates, extent);
  96130. ol.extent.buffer(extent, mapDistance, extent);
  96131. var neighbors = this.source_.getFeaturesInExtent(extent);
  96132. goog.asserts.assert(neighbors.length >= 1, 'at least one neighbor found');
  96133. neighbors = neighbors.filter(function(neighbor) {
  96134. var uid = goog.getUid(neighbor).toString();
  96135. if (!goog.object.containsKey(clustered, uid)) {
  96136. clustered[uid] = true;
  96137. return true;
  96138. } else {
  96139. return false;
  96140. }
  96141. });
  96142. this.features_.push(this.createCluster_(neighbors));
  96143. }
  96144. }
  96145. goog.asserts.assert(
  96146. goog.object.getCount(clustered) == this.source_.getFeatures().length,
  96147. 'number of clustered equals number of features in the source');
  96148. };
  96149. /**
  96150. * @param {Array.<ol.Feature>} features Features
  96151. * @return {ol.Feature}
  96152. * @private
  96153. */
  96154. ol.source.Cluster.prototype.createCluster_ = function(features) {
  96155. var length = features.length;
  96156. var centroid = [0, 0];
  96157. for (var i = 0; i < length; i++) {
  96158. var geometry = features[i].getGeometry();
  96159. goog.asserts.assert(geometry instanceof ol.geom.Point,
  96160. 'feature geometry is a ol.geom.Point instance');
  96161. var coordinates = geometry.getCoordinates();
  96162. ol.coordinate.add(centroid, coordinates);
  96163. }
  96164. ol.coordinate.scale(centroid, 1 / length);
  96165. var cluster = new ol.Feature(new ol.geom.Point(centroid));
  96166. cluster.set('features', features);
  96167. return cluster;
  96168. };
  96169. goog.provide('ol.source.ImageMapGuide');
  96170. goog.require('goog.events');
  96171. goog.require('goog.events.EventType');
  96172. goog.require('goog.object');
  96173. goog.require('goog.uri.utils');
  96174. goog.require('ol.Image');
  96175. goog.require('ol.ImageLoadFunctionType');
  96176. goog.require('ol.ImageUrlFunction');
  96177. goog.require('ol.extent');
  96178. goog.require('ol.source.Image');
  96179. /**
  96180. * @classdesc
  96181. * Source for images from Mapguide servers
  96182. *
  96183. * @constructor
  96184. * @fires ol.source.ImageEvent
  96185. * @extends {ol.source.Image}
  96186. * @param {olx.source.ImageMapGuideOptions} options Options.
  96187. * @api stable
  96188. */
  96189. ol.source.ImageMapGuide = function(options) {
  96190. goog.base(this, {
  96191. projection: options.projection,
  96192. resolutions: options.resolutions
  96193. });
  96194. /**
  96195. * @private
  96196. * @type {?string}
  96197. */
  96198. this.crossOrigin_ =
  96199. options.crossOrigin !== undefined ? options.crossOrigin : null;
  96200. /**
  96201. * @private
  96202. * @type {number}
  96203. */
  96204. this.displayDpi_ = options.displayDpi !== undefined ?
  96205. options.displayDpi : 96;
  96206. /**
  96207. * @private
  96208. * @type {Object}
  96209. */
  96210. this.params_ = options.params !== undefined ? options.params : {};
  96211. var imageUrlFunction;
  96212. if (options.url !== undefined) {
  96213. imageUrlFunction = ol.ImageUrlFunction.createFromParamsFunction(
  96214. options.url, this.params_, goog.bind(this.getUrl, this));
  96215. } else {
  96216. imageUrlFunction = ol.ImageUrlFunction.nullImageUrlFunction;
  96217. }
  96218. /**
  96219. * @private
  96220. * @type {ol.ImageUrlFunctionType}
  96221. */
  96222. this.imageUrlFunction_ = imageUrlFunction;
  96223. /**
  96224. * @private
  96225. * @type {ol.ImageLoadFunctionType}
  96226. */
  96227. this.imageLoadFunction_ = options.imageLoadFunction !== undefined ?
  96228. options.imageLoadFunction : ol.source.Image.defaultImageLoadFunction;
  96229. /**
  96230. * @private
  96231. * @type {boolean}
  96232. */
  96233. this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;
  96234. /**
  96235. * @private
  96236. * @type {number}
  96237. */
  96238. this.metersPerUnit_ = options.metersPerUnit !== undefined ?
  96239. options.metersPerUnit : 1;
  96240. /**
  96241. * @private
  96242. * @type {number}
  96243. */
  96244. this.ratio_ = options.ratio !== undefined ? options.ratio : 1;
  96245. /**
  96246. * @private
  96247. * @type {boolean}
  96248. */
  96249. this.useOverlay_ = options.useOverlay !== undefined ?
  96250. options.useOverlay : false;
  96251. /**
  96252. * @private
  96253. * @type {ol.Image}
  96254. */
  96255. this.image_ = null;
  96256. /**
  96257. * @private
  96258. * @type {number}
  96259. */
  96260. this.renderedRevision_ = 0;
  96261. };
  96262. goog.inherits(ol.source.ImageMapGuide, ol.source.Image);
  96263. /**
  96264. * Get the user-provided params, i.e. those passed to the constructor through
  96265. * the "params" option, and possibly updated using the updateParams method.
  96266. * @return {Object} Params.
  96267. * @api stable
  96268. */
  96269. ol.source.ImageMapGuide.prototype.getParams = function() {
  96270. return this.params_;
  96271. };
  96272. /**
  96273. * @inheritDoc
  96274. */
  96275. ol.source.ImageMapGuide.prototype.getImage =
  96276. function(extent, resolution, pixelRatio, projection) {
  96277. resolution = this.findNearestResolution(resolution);
  96278. pixelRatio = this.hidpi_ ? pixelRatio : 1;
  96279. var image = this.image_;
  96280. if (image &&
  96281. this.renderedRevision_ == this.getRevision() &&
  96282. image.getResolution() == resolution &&
  96283. image.getPixelRatio() == pixelRatio &&
  96284. ol.extent.containsExtent(image.getExtent(), extent)) {
  96285. return image;
  96286. }
  96287. if (this.ratio_ != 1) {
  96288. extent = extent.slice();
  96289. ol.extent.scaleFromCenter(extent, this.ratio_);
  96290. }
  96291. var width = ol.extent.getWidth(extent) / resolution;
  96292. var height = ol.extent.getHeight(extent) / resolution;
  96293. var size = [width * pixelRatio, height * pixelRatio];
  96294. var imageUrl = this.imageUrlFunction_(extent, size, projection);
  96295. if (imageUrl !== undefined) {
  96296. image = new ol.Image(extent, resolution, pixelRatio,
  96297. this.getAttributions(), imageUrl, this.crossOrigin_,
  96298. this.imageLoadFunction_);
  96299. goog.events.listen(image, goog.events.EventType.CHANGE,
  96300. this.handleImageChange, false, this);
  96301. } else {
  96302. image = null;
  96303. }
  96304. this.image_ = image;
  96305. this.renderedRevision_ = this.getRevision();
  96306. return image;
  96307. };
  96308. /**
  96309. * Return the image load function of the source.
  96310. * @return {ol.ImageLoadFunctionType} The image load function.
  96311. * @api
  96312. */
  96313. ol.source.ImageMapGuide.prototype.getImageLoadFunction = function() {
  96314. return this.imageLoadFunction_;
  96315. };
  96316. /**
  96317. * @param {ol.Extent} extent The map extents.
  96318. * @param {ol.Size} size The viewport size.
  96319. * @param {number} metersPerUnit The meters-per-unit value.
  96320. * @param {number} dpi The display resolution.
  96321. * @return {number} The computed map scale.
  96322. */
  96323. ol.source.ImageMapGuide.getScale = function(extent, size, metersPerUnit, dpi) {
  96324. var mcsW = ol.extent.getWidth(extent);
  96325. var mcsH = ol.extent.getHeight(extent);
  96326. var devW = size[0];
  96327. var devH = size[1];
  96328. var mpp = 0.0254 / dpi;
  96329. if (devH * mcsW > devW * mcsH) {
  96330. return mcsW * metersPerUnit / (devW * mpp); // width limited
  96331. } else {
  96332. return mcsH * metersPerUnit / (devH * mpp); // height limited
  96333. }
  96334. };
  96335. /**
  96336. * Update the user-provided params.
  96337. * @param {Object} params Params.
  96338. * @api stable
  96339. */
  96340. ol.source.ImageMapGuide.prototype.updateParams = function(params) {
  96341. goog.object.extend(this.params_, params);
  96342. this.changed();
  96343. };
  96344. /**
  96345. * @param {string} baseUrl The mapagent url.
  96346. * @param {Object.<string, string|number>} params Request parameters.
  96347. * @param {ol.Extent} extent Extent.
  96348. * @param {ol.Size} size Size.
  96349. * @param {ol.proj.Projection} projection Projection.
  96350. * @return {string} The mapagent map image request URL.
  96351. */
  96352. ol.source.ImageMapGuide.prototype.getUrl =
  96353. function(baseUrl, params, extent, size, projection) {
  96354. var scale = ol.source.ImageMapGuide.getScale(extent, size,
  96355. this.metersPerUnit_, this.displayDpi_);
  96356. var center = ol.extent.getCenter(extent);
  96357. var baseParams = {
  96358. 'OPERATION': this.useOverlay_ ? 'GETDYNAMICMAPOVERLAYIMAGE' : 'GETMAPIMAGE',
  96359. 'VERSION': '2.0.0',
  96360. 'LOCALE': 'en',
  96361. 'CLIENTAGENT': 'ol.source.ImageMapGuide source',
  96362. 'CLIP': '1',
  96363. 'SETDISPLAYDPI': this.displayDpi_,
  96364. 'SETDISPLAYWIDTH': Math.round(size[0]),
  96365. 'SETDISPLAYHEIGHT': Math.round(size[1]),
  96366. 'SETVIEWSCALE': scale,
  96367. 'SETVIEWCENTERX': center[0],
  96368. 'SETVIEWCENTERY': center[1]
  96369. };
  96370. goog.object.extend(baseParams, params);
  96371. return goog.uri.utils.appendParamsFromMap(baseUrl, baseParams);
  96372. };
  96373. /**
  96374. * Set the image load function of the MapGuide source.
  96375. * @param {ol.ImageLoadFunctionType} imageLoadFunction Image load function.
  96376. * @api
  96377. */
  96378. ol.source.ImageMapGuide.prototype.setImageLoadFunction = function(
  96379. imageLoadFunction) {
  96380. this.image_ = null;
  96381. this.imageLoadFunction_ = imageLoadFunction;
  96382. this.changed();
  96383. };
  96384. goog.provide('ol.source.ImageStatic');
  96385. goog.require('goog.events');
  96386. goog.require('goog.events.EventType');
  96387. goog.require('ol.Image');
  96388. goog.require('ol.ImageLoadFunctionType');
  96389. goog.require('ol.extent');
  96390. goog.require('ol.proj');
  96391. goog.require('ol.source.Image');
  96392. /**
  96393. * @classdesc
  96394. * A layer source for displaying a single, static image.
  96395. *
  96396. * @constructor
  96397. * @extends {ol.source.Image}
  96398. * @param {olx.source.ImageStaticOptions} options Options.
  96399. * @api stable
  96400. */
  96401. ol.source.ImageStatic = function(options) {
  96402. var attributions = options.attributions !== undefined ?
  96403. options.attributions : null;
  96404. var imageExtent = options.imageExtent;
  96405. var resolution, resolutions;
  96406. if (options.imageSize !== undefined) {
  96407. resolution = ol.extent.getHeight(imageExtent) / options.imageSize[1];
  96408. resolutions = [resolution];
  96409. }
  96410. var crossOrigin = options.crossOrigin !== undefined ?
  96411. options.crossOrigin : null;
  96412. var /** @type {ol.ImageLoadFunctionType} */ imageLoadFunction =
  96413. options.imageLoadFunction !== undefined ?
  96414. options.imageLoadFunction : ol.source.Image.defaultImageLoadFunction;
  96415. goog.base(this, {
  96416. attributions: attributions,
  96417. logo: options.logo,
  96418. projection: ol.proj.get(options.projection),
  96419. resolutions: resolutions
  96420. });
  96421. /**
  96422. * @private
  96423. * @type {ol.Image}
  96424. */
  96425. this.image_ = new ol.Image(imageExtent, resolution, 1, attributions,
  96426. options.url, crossOrigin, imageLoadFunction);
  96427. goog.events.listen(this.image_, goog.events.EventType.CHANGE,
  96428. this.handleImageChange, false, this);
  96429. };
  96430. goog.inherits(ol.source.ImageStatic, ol.source.Image);
  96431. /**
  96432. * @inheritDoc
  96433. */
  96434. ol.source.ImageStatic.prototype.getImage =
  96435. function(extent, resolution, pixelRatio, projection) {
  96436. if (ol.extent.intersects(extent, this.image_.getExtent())) {
  96437. return this.image_;
  96438. }
  96439. return null;
  96440. };
  96441. goog.provide('ol.source.wms');
  96442. goog.provide('ol.source.wms.ServerType');
  96443. /**
  96444. * Available server types: `'carmentaserver'`, `'geoserver'`, `'mapserver'`,
  96445. * `'qgis'`. These are servers that have vendor parameters beyond the WMS
  96446. * specification that OpenLayers can make use of.
  96447. * @enum {string}
  96448. * @api
  96449. */
  96450. ol.source.wms.ServerType = {
  96451. CARMENTA_SERVER: 'carmentaserver',
  96452. GEOSERVER: 'geoserver',
  96453. MAPSERVER: 'mapserver',
  96454. QGIS: 'qgis'
  96455. };
  96456. // FIXME cannot be shared between maps with different projections
  96457. goog.provide('ol.source.ImageWMS');
  96458. goog.require('goog.asserts');
  96459. goog.require('goog.events');
  96460. goog.require('goog.events.EventType');
  96461. goog.require('goog.object');
  96462. goog.require('goog.string');
  96463. goog.require('goog.uri.utils');
  96464. goog.require('ol');
  96465. goog.require('ol.Image');
  96466. goog.require('ol.ImageLoadFunctionType');
  96467. goog.require('ol.extent');
  96468. goog.require('ol.proj');
  96469. goog.require('ol.source.Image');
  96470. goog.require('ol.source.wms');
  96471. goog.require('ol.source.wms.ServerType');
  96472. /**
  96473. * @classdesc
  96474. * Source for WMS servers providing single, untiled images.
  96475. *
  96476. * @constructor
  96477. * @fires ol.source.ImageEvent
  96478. * @extends {ol.source.Image}
  96479. * @param {olx.source.ImageWMSOptions=} opt_options Options.
  96480. * @api stable
  96481. */
  96482. ol.source.ImageWMS = function(opt_options) {
  96483. var options = opt_options || {};
  96484. goog.base(this, {
  96485. attributions: options.attributions,
  96486. logo: options.logo,
  96487. projection: options.projection,
  96488. resolutions: options.resolutions
  96489. });
  96490. /**
  96491. * @private
  96492. * @type {?string}
  96493. */
  96494. this.crossOrigin_ =
  96495. options.crossOrigin !== undefined ? options.crossOrigin : null;
  96496. /**
  96497. * @private
  96498. * @type {string|undefined}
  96499. */
  96500. this.url_ = options.url;
  96501. /**
  96502. * @private
  96503. * @type {ol.ImageLoadFunctionType}
  96504. */
  96505. this.imageLoadFunction_ = options.imageLoadFunction !== undefined ?
  96506. options.imageLoadFunction : ol.source.Image.defaultImageLoadFunction;
  96507. /**
  96508. * @private
  96509. * @type {Object}
  96510. */
  96511. this.params_ = options.params;
  96512. /**
  96513. * @private
  96514. * @type {boolean}
  96515. */
  96516. this.v13_ = true;
  96517. this.updateV13_();
  96518. /**
  96519. * @private
  96520. * @type {ol.source.wms.ServerType|undefined}
  96521. */
  96522. this.serverType_ =
  96523. /** @type {ol.source.wms.ServerType|undefined} */ (options.serverType);
  96524. /**
  96525. * @private
  96526. * @type {boolean}
  96527. */
  96528. this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;
  96529. /**
  96530. * @private
  96531. * @type {ol.Image}
  96532. */
  96533. this.image_ = null;
  96534. /**
  96535. * @private
  96536. * @type {ol.Size}
  96537. */
  96538. this.imageSize_ = [0, 0];
  96539. /**
  96540. * @private
  96541. * @type {number}
  96542. */
  96543. this.renderedRevision_ = 0;
  96544. /**
  96545. * @private
  96546. * @type {number}
  96547. */
  96548. this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;
  96549. };
  96550. goog.inherits(ol.source.ImageWMS, ol.source.Image);
  96551. /**
  96552. * @const
  96553. * @type {ol.Size}
  96554. * @private
  96555. */
  96556. ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_ = [101, 101];
  96557. /**
  96558. * Return the GetFeatureInfo URL for the passed coordinate, resolution, and
  96559. * projection. Return `undefined` if the GetFeatureInfo URL cannot be
  96560. * constructed.
  96561. * @param {ol.Coordinate} coordinate Coordinate.
  96562. * @param {number} resolution Resolution.
  96563. * @param {ol.proj.ProjectionLike} projection Projection.
  96564. * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should
  96565. * be provided. If `QUERY_LAYERS` is not provided then the layers specified
  96566. * in the `LAYERS` parameter will be used. `VERSION` should not be
  96567. * specified here.
  96568. * @return {string|undefined} GetFeatureInfo URL.
  96569. * @api stable
  96570. */
  96571. ol.source.ImageWMS.prototype.getGetFeatureInfoUrl =
  96572. function(coordinate, resolution, projection, params) {
  96573. goog.asserts.assert(!('VERSION' in params),
  96574. 'key VERSION is not allowed in params');
  96575. if (this.url_ === undefined) {
  96576. return undefined;
  96577. }
  96578. var extent = ol.extent.getForViewAndSize(
  96579. coordinate, resolution, 0,
  96580. ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_);
  96581. var baseParams = {
  96582. 'SERVICE': 'WMS',
  96583. 'VERSION': ol.DEFAULT_WMS_VERSION,
  96584. 'REQUEST': 'GetFeatureInfo',
  96585. 'FORMAT': 'image/png',
  96586. 'TRANSPARENT': true,
  96587. 'QUERY_LAYERS': this.params_['LAYERS']
  96588. };
  96589. goog.object.extend(baseParams, this.params_, params);
  96590. var x = Math.floor((coordinate[0] - extent[0]) / resolution);
  96591. var y = Math.floor((extent[3] - coordinate[1]) / resolution);
  96592. baseParams[this.v13_ ? 'I' : 'X'] = x;
  96593. baseParams[this.v13_ ? 'J' : 'Y'] = y;
  96594. return this.getRequestUrl_(
  96595. extent, ol.source.ImageWMS.GETFEATUREINFO_IMAGE_SIZE_,
  96596. 1, ol.proj.get(projection), baseParams);
  96597. };
  96598. /**
  96599. * Get the user-provided params, i.e. those passed to the constructor through
  96600. * the "params" option, and possibly updated using the updateParams method.
  96601. * @return {Object} Params.
  96602. * @api stable
  96603. */
  96604. ol.source.ImageWMS.prototype.getParams = function() {
  96605. return this.params_;
  96606. };
  96607. /**
  96608. * @inheritDoc
  96609. */
  96610. ol.source.ImageWMS.prototype.getImage =
  96611. function(extent, resolution, pixelRatio, projection) {
  96612. if (this.url_ === undefined) {
  96613. return null;
  96614. }
  96615. resolution = this.findNearestResolution(resolution);
  96616. if (pixelRatio != 1 && (!this.hidpi_ || this.serverType_ === undefined)) {
  96617. pixelRatio = 1;
  96618. }
  96619. extent = extent.slice();
  96620. var centerX = (extent[0] + extent[2]) / 2;
  96621. var centerY = (extent[1] + extent[3]) / 2;
  96622. if (this.ratio_ != 1) {
  96623. var halfWidth = this.ratio_ * ol.extent.getWidth(extent) / 2;
  96624. var halfHeight = this.ratio_ * ol.extent.getHeight(extent) / 2;
  96625. extent[0] = centerX - halfWidth;
  96626. extent[1] = centerY - halfHeight;
  96627. extent[2] = centerX + halfWidth;
  96628. extent[3] = centerY + halfHeight;
  96629. }
  96630. var imageResolution = resolution / pixelRatio;
  96631. // Compute an integer width and height.
  96632. var width = Math.ceil(ol.extent.getWidth(extent) / imageResolution);
  96633. var height = Math.ceil(ol.extent.getHeight(extent) / imageResolution);
  96634. // Modify the extent to match the integer width and height.
  96635. extent[0] = centerX - imageResolution * width / 2;
  96636. extent[2] = centerX + imageResolution * width / 2;
  96637. extent[1] = centerY - imageResolution * height / 2;
  96638. extent[3] = centerY + imageResolution * height / 2;
  96639. var image = this.image_;
  96640. if (image &&
  96641. this.renderedRevision_ == this.getRevision() &&
  96642. image.getResolution() == resolution &&
  96643. image.getPixelRatio() == pixelRatio &&
  96644. ol.extent.containsExtent(image.getExtent(), extent)) {
  96645. return image;
  96646. }
  96647. var params = {
  96648. 'SERVICE': 'WMS',
  96649. 'VERSION': ol.DEFAULT_WMS_VERSION,
  96650. 'REQUEST': 'GetMap',
  96651. 'FORMAT': 'image/png',
  96652. 'TRANSPARENT': true
  96653. };
  96654. goog.object.extend(params, this.params_);
  96655. this.imageSize_[0] = width;
  96656. this.imageSize_[1] = height;
  96657. var url = this.getRequestUrl_(extent, this.imageSize_, pixelRatio,
  96658. projection, params);
  96659. this.image_ = new ol.Image(extent, resolution, pixelRatio,
  96660. this.getAttributions(), url, this.crossOrigin_, this.imageLoadFunction_);
  96661. this.renderedRevision_ = this.getRevision();
  96662. goog.events.listen(this.image_, goog.events.EventType.CHANGE,
  96663. this.handleImageChange, false, this);
  96664. return this.image_;
  96665. };
  96666. /**
  96667. * Return the image load function of the source.
  96668. * @return {ol.ImageLoadFunctionType} The image load function.
  96669. * @api
  96670. */
  96671. ol.source.ImageWMS.prototype.getImageLoadFunction = function() {
  96672. return this.imageLoadFunction_;
  96673. };
  96674. /**
  96675. * @param {ol.Extent} extent Extent.
  96676. * @param {ol.Size} size Size.
  96677. * @param {number} pixelRatio Pixel ratio.
  96678. * @param {ol.proj.Projection} projection Projection.
  96679. * @param {Object} params Params.
  96680. * @return {string} Request URL.
  96681. * @private
  96682. */
  96683. ol.source.ImageWMS.prototype.getRequestUrl_ =
  96684. function(extent, size, pixelRatio, projection, params) {
  96685. goog.asserts.assert(this.url_ !== undefined, 'url is defined');
  96686. params[this.v13_ ? 'CRS' : 'SRS'] = projection.getCode();
  96687. if (!('STYLES' in this.params_)) {
  96688. /* jshint -W053 */
  96689. params['STYLES'] = new String('');
  96690. /* jshint +W053 */
  96691. }
  96692. if (pixelRatio != 1) {
  96693. switch (this.serverType_) {
  96694. case ol.source.wms.ServerType.GEOSERVER:
  96695. var dpi = (90 * pixelRatio + 0.5) | 0;
  96696. if ('FORMAT_OPTIONS' in params) {
  96697. params['FORMAT_OPTIONS'] += ';dpi:' + dpi;
  96698. } else {
  96699. params['FORMAT_OPTIONS'] = 'dpi:' + dpi;
  96700. }
  96701. break;
  96702. case ol.source.wms.ServerType.MAPSERVER:
  96703. params['MAP_RESOLUTION'] = 90 * pixelRatio;
  96704. break;
  96705. case ol.source.wms.ServerType.CARMENTA_SERVER:
  96706. case ol.source.wms.ServerType.QGIS:
  96707. params['DPI'] = 90 * pixelRatio;
  96708. break;
  96709. default:
  96710. goog.asserts.fail('unknown serverType configured');
  96711. break;
  96712. }
  96713. }
  96714. params['WIDTH'] = size[0];
  96715. params['HEIGHT'] = size[1];
  96716. var axisOrientation = projection.getAxisOrientation();
  96717. var bbox;
  96718. if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') {
  96719. bbox = [extent[1], extent[0], extent[3], extent[2]];
  96720. } else {
  96721. bbox = extent;
  96722. }
  96723. params['BBOX'] = bbox.join(',');
  96724. return goog.uri.utils.appendParamsFromMap(this.url_, params);
  96725. };
  96726. /**
  96727. * Return the URL used for this WMS source.
  96728. * @return {string|undefined} URL.
  96729. * @api stable
  96730. */
  96731. ol.source.ImageWMS.prototype.getUrl = function() {
  96732. return this.url_;
  96733. };
  96734. /**
  96735. * Set the image load function of the source.
  96736. * @param {ol.ImageLoadFunctionType} imageLoadFunction Image load function.
  96737. * @api
  96738. */
  96739. ol.source.ImageWMS.prototype.setImageLoadFunction = function(
  96740. imageLoadFunction) {
  96741. this.image_ = null;
  96742. this.imageLoadFunction_ = imageLoadFunction;
  96743. this.changed();
  96744. };
  96745. /**
  96746. * Set the URL to use for requests.
  96747. * @param {string|undefined} url URL.
  96748. * @api stable
  96749. */
  96750. ol.source.ImageWMS.prototype.setUrl = function(url) {
  96751. if (url != this.url_) {
  96752. this.url_ = url;
  96753. this.image_ = null;
  96754. this.changed();
  96755. }
  96756. };
  96757. /**
  96758. * Update the user-provided params.
  96759. * @param {Object} params Params.
  96760. * @api stable
  96761. */
  96762. ol.source.ImageWMS.prototype.updateParams = function(params) {
  96763. goog.object.extend(this.params_, params);
  96764. this.updateV13_();
  96765. this.image_ = null;
  96766. this.changed();
  96767. };
  96768. /**
  96769. * @private
  96770. */
  96771. ol.source.ImageWMS.prototype.updateV13_ = function() {
  96772. var version =
  96773. goog.object.get(this.params_, 'VERSION', ol.DEFAULT_WMS_VERSION);
  96774. this.v13_ = goog.string.compareVersions(version, '1.3') >= 0;
  96775. };
  96776. goog.provide('ol.source.XYZ');
  96777. goog.require('ol.TileUrlFunction');
  96778. goog.require('ol.source.TileImage');
  96779. /**
  96780. * @classdesc
  96781. * Layer source for tile data with URLs in a set XYZ format that are
  96782. * defined in a URL template. By default, this follows the widely-used
  96783. * Google grid where `x` 0 and `y` 0 are in the top left. Grids like
  96784. * TMS where `x` 0 and `y` 0 are in the bottom left can be used by
  96785. * using the `{-y}` placeholder in the URL template, so long as the
  96786. * source does not have a custom tile grid. In this case,
  96787. * {@link ol.source.TileImage} can be used with a `tileUrlFunction`
  96788. * such as:
  96789. *
  96790. * tileUrlFunction: function(coordinate) {
  96791. * return 'http://mapserver.com/' + coordinate[0] + '/' +
  96792. * coordinate[1] + '/' + coordinate[2] + '.png';
  96793. * }
  96794. *
  96795. *
  96796. * @constructor
  96797. * @extends {ol.source.TileImage}
  96798. * @param {olx.source.XYZOptions} options XYZ options.
  96799. * @api stable
  96800. */
  96801. ol.source.XYZ = function(options) {
  96802. var projection = options.projection !== undefined ?
  96803. options.projection : 'EPSG:3857';
  96804. var tileGrid = options.tileGrid !== undefined ? options.tileGrid :
  96805. ol.tilegrid.createXYZ({
  96806. extent: ol.tilegrid.extentFromProjection(projection),
  96807. maxZoom: options.maxZoom,
  96808. tileSize: options.tileSize
  96809. });
  96810. /**
  96811. * @private
  96812. * @type {!Array.<string>|null}
  96813. */
  96814. this.urls_ = null;
  96815. goog.base(this, {
  96816. attributions: options.attributions,
  96817. crossOrigin: options.crossOrigin,
  96818. logo: options.logo,
  96819. projection: projection,
  96820. tileGrid: tileGrid,
  96821. tileLoadFunction: options.tileLoadFunction,
  96822. tilePixelRatio: options.tilePixelRatio,
  96823. tileUrlFunction: ol.TileUrlFunction.nullTileUrlFunction,
  96824. wrapX: options.wrapX !== undefined ? options.wrapX : true
  96825. });
  96826. if (options.tileUrlFunction !== undefined) {
  96827. this.setTileUrlFunction(options.tileUrlFunction);
  96828. } else if (options.urls !== undefined) {
  96829. this.setUrls(options.urls);
  96830. } else if (options.url !== undefined) {
  96831. this.setUrl(options.url);
  96832. }
  96833. };
  96834. goog.inherits(ol.source.XYZ, ol.source.TileImage);
  96835. /**
  96836. * Return the URLs used for this XYZ source.
  96837. * When a tileUrlFunction is used instead of url or urls,
  96838. * null will be returned.
  96839. * @return {!Array.<string>|null} URLs.
  96840. * @api
  96841. */
  96842. ol.source.XYZ.prototype.getUrls = function() {
  96843. return this.urls_;
  96844. };
  96845. /**
  96846. * Set the URL to use for requests.
  96847. * @param {string} url URL.
  96848. * @api stable
  96849. */
  96850. ol.source.XYZ.prototype.setUrl = function(url) {
  96851. this.setTileUrlFunction(ol.TileUrlFunction.createFromTemplates(
  96852. ol.TileUrlFunction.expandUrl(url), this.tileGrid));
  96853. this.urls_ = [url];
  96854. };
  96855. /**
  96856. * Set the URLs to use for requests.
  96857. * @param {Array.<string>} urls URLs.
  96858. */
  96859. ol.source.XYZ.prototype.setUrls = function(urls) {
  96860. this.setTileUrlFunction(
  96861. ol.TileUrlFunction.createFromTemplates(urls, this.tileGrid));
  96862. this.urls_ = urls;
  96863. };
  96864. goog.provide('ol.source.OSM');
  96865. goog.require('ol.Attribution');
  96866. goog.require('ol.source.XYZ');
  96867. /**
  96868. * @classdesc
  96869. * Layer source for the OpenStreetMap tile server.
  96870. *
  96871. * @constructor
  96872. * @extends {ol.source.XYZ}
  96873. * @param {olx.source.OSMOptions=} opt_options Open Street Map options.
  96874. * @api stable
  96875. */
  96876. ol.source.OSM = function(opt_options) {
  96877. var options = opt_options || {};
  96878. var attributions;
  96879. if (options.attributions !== undefined) {
  96880. attributions = options.attributions;
  96881. } else {
  96882. attributions = [ol.source.OSM.ATTRIBUTION];
  96883. }
  96884. var crossOrigin = options.crossOrigin !== undefined ?
  96885. options.crossOrigin : 'anonymous';
  96886. var url = options.url !== undefined ?
  96887. options.url : 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png';
  96888. goog.base(this, {
  96889. attributions: attributions,
  96890. crossOrigin: crossOrigin,
  96891. opaque: true,
  96892. maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
  96893. tileLoadFunction: options.tileLoadFunction,
  96894. url: url,
  96895. wrapX: options.wrapX
  96896. });
  96897. };
  96898. goog.inherits(ol.source.OSM, ol.source.XYZ);
  96899. /**
  96900. * The attribution containing a link to the OpenStreetMap Copyright and License
  96901. * page.
  96902. * @const
  96903. * @type {ol.Attribution}
  96904. * @api
  96905. */
  96906. ol.source.OSM.ATTRIBUTION = new ol.Attribution({
  96907. html: '&copy; ' +
  96908. '<a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> ' +
  96909. 'contributors.'
  96910. });
  96911. goog.provide('ol.source.MapQuest');
  96912. goog.require('goog.asserts');
  96913. goog.require('ol.Attribution');
  96914. goog.require('ol.source.OSM');
  96915. goog.require('ol.source.XYZ');
  96916. /**
  96917. * @classdesc
  96918. * Layer source for the MapQuest tile server.
  96919. *
  96920. * @constructor
  96921. * @extends {ol.source.XYZ}
  96922. * @param {olx.source.MapQuestOptions=} opt_options MapQuest options.
  96923. * @api stable
  96924. */
  96925. ol.source.MapQuest = function(opt_options) {
  96926. var options = opt_options || {};
  96927. goog.asserts.assert(options.layer in ol.source.MapQuestConfig,
  96928. 'known layer configured');
  96929. var layerConfig = ol.source.MapQuestConfig[options.layer];
  96930. /**
  96931. * Layer. Possible values are `osm`, `sat`, and `hyb`.
  96932. * @type {string}
  96933. * @private
  96934. */
  96935. this.layer_ = options.layer;
  96936. var url = options.url !== undefined ? options.url :
  96937. 'https://otile{1-4}-s.mqcdn.com/tiles/1.0.0/' +
  96938. this.layer_ + '/{z}/{x}/{y}.jpg';
  96939. goog.base(this, {
  96940. attributions: layerConfig.attributions,
  96941. crossOrigin: 'anonymous',
  96942. logo: 'https://developer.mapquest.com/content/osm/mq_logo.png',
  96943. maxZoom: layerConfig.maxZoom,
  96944. opaque: true,
  96945. tileLoadFunction: options.tileLoadFunction,
  96946. url: url
  96947. });
  96948. };
  96949. goog.inherits(ol.source.MapQuest, ol.source.XYZ);
  96950. /**
  96951. * @const
  96952. * @type {ol.Attribution}
  96953. */
  96954. ol.source.MapQuest.TILE_ATTRIBUTION = new ol.Attribution({
  96955. html: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>'
  96956. });
  96957. /**
  96958. * @type {Object.<string, {maxZoom: number, attributions: (Array.<ol.Attribution>)}>}
  96959. */
  96960. ol.source.MapQuestConfig = {
  96961. 'osm': {
  96962. maxZoom: 19,
  96963. attributions: [
  96964. ol.source.MapQuest.TILE_ATTRIBUTION,
  96965. ol.source.OSM.ATTRIBUTION
  96966. ]
  96967. },
  96968. 'sat': {
  96969. maxZoom: 18,
  96970. attributions: [
  96971. ol.source.MapQuest.TILE_ATTRIBUTION,
  96972. new ol.Attribution({
  96973. html: 'Portions Courtesy NASA/JPL-Caltech and ' +
  96974. 'U.S. Depart. of Agriculture, Farm Service Agency'
  96975. })
  96976. ]
  96977. },
  96978. 'hyb': {
  96979. maxZoom: 18,
  96980. attributions: [
  96981. ol.source.MapQuest.TILE_ATTRIBUTION,
  96982. ol.source.OSM.ATTRIBUTION
  96983. ]
  96984. }
  96985. };
  96986. /**
  96987. * Get the layer of the source, either `osm`, `sat`, or `hyb`.
  96988. * @return {string} Layer.
  96989. * @api
  96990. */
  96991. ol.source.MapQuest.prototype.getLayer = function() {
  96992. return this.layer_;
  96993. };
  96994. goog.provide('ol.ext.pixelworks');
  96995. /** @typedef {function(*)} */
  96996. ol.ext.pixelworks;
  96997. (function() {
  96998. var exports = {};
  96999. var module = {exports: exports};
  97000. var define;
  97001. /**
  97002. * @fileoverview
  97003. * @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, uselessCode, visibility}
  97004. */
  97005. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pixelworks = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  97006. var Processor = require('./processor');
  97007. exports.Processor = Processor;
  97008. },{"./processor":2}],2:[function(require,module,exports){
  97009. /* eslint-disable dot-notation */
  97010. /**
  97011. * Create a function for running operations.
  97012. * @param {function(Array, Object):*} operation The operation.
  97013. * @return {function(Object):ArrayBuffer} A function that takes an object with
  97014. * buffers, meta, imageOps, width, and height properties and returns an array
  97015. * buffer.
  97016. */
  97017. function createMinion(operation) {
  97018. return function(data) {
  97019. // bracket notation for minification support
  97020. var buffers = data['buffers'];
  97021. var meta = data['meta'];
  97022. var imageOps = data['imageOps'];
  97023. var width = data['width'];
  97024. var height = data['height'];
  97025. var numBuffers = buffers.length;
  97026. var numBytes = buffers[0].byteLength;
  97027. var output, b;
  97028. if (imageOps) {
  97029. var images = new Array(numBuffers);
  97030. for (b = 0; b < numBuffers; ++b) {
  97031. images[b] = new ImageData(
  97032. new Uint8ClampedArray(buffers[b]), width, height);
  97033. }
  97034. output = operation(images, meta).data;
  97035. } else {
  97036. output = new Uint8ClampedArray(numBytes);
  97037. var arrays = new Array(numBuffers);
  97038. var pixels = new Array(numBuffers);
  97039. for (b = 0; b < numBuffers; ++b) {
  97040. arrays[b] = new Uint8ClampedArray(buffers[b]);
  97041. pixels[b] = [0, 0, 0, 0];
  97042. }
  97043. for (var i = 0; i < numBytes; i += 4) {
  97044. for (var j = 0; j < numBuffers; ++j) {
  97045. var array = arrays[j];
  97046. pixels[j][0] = array[i];
  97047. pixels[j][1] = array[i + 1];
  97048. pixels[j][2] = array[i + 2];
  97049. pixels[j][3] = array[i + 3];
  97050. }
  97051. var pixel = operation(pixels, meta);
  97052. output[i] = pixel[0];
  97053. output[i + 1] = pixel[1];
  97054. output[i + 2] = pixel[2];
  97055. output[i + 3] = pixel[3];
  97056. }
  97057. }
  97058. return output.buffer;
  97059. };
  97060. }
  97061. /**
  97062. * Create a worker for running operations.
  97063. * @param {Object} config Configuration.
  97064. * @param {function(Object)} onMessage Called with a message event.
  97065. * @return {Worker} The worker.
  97066. */
  97067. function createWorker(config, onMessage) {
  97068. var lib = Object.keys(config.lib || {}).map(function(name) {
  97069. return 'var ' + name + ' = ' + config.lib[name].toString() + ';';
  97070. });
  97071. var lines = lib.concat([
  97072. 'var __minion__ = (' + createMinion.toString() + ')(',
  97073. config.operation.toString(),
  97074. ');',
  97075. 'self.addEventListener("message", function(__event__) {',
  97076. 'var buffer = __minion__(__event__.data);',
  97077. 'self.postMessage({buffer: buffer, meta: __event__.data.meta}, [buffer]);',
  97078. '});'
  97079. ]);
  97080. var blob = new Blob(lines, {type: 'text/javascript'});
  97081. var source = URL.createObjectURL(blob);
  97082. var worker = new Worker(source);
  97083. worker.addEventListener('message', onMessage);
  97084. return worker;
  97085. }
  97086. /**
  97087. * Create a faux worker for running operations.
  97088. * @param {Object} config Configuration.
  97089. * @param {function(Object)} onMessage Called with a message event.
  97090. * @return {Object} The faux worker.
  97091. */
  97092. function createFauxWorker(config, onMessage) {
  97093. var minion = createMinion(config.operation);
  97094. return {
  97095. postMessage: function(data) {
  97096. setTimeout(function() {
  97097. onMessage({data: {buffer: minion(data), meta: data.meta}});
  97098. }, 0);
  97099. }
  97100. };
  97101. }
  97102. /**
  97103. * A processor runs pixel or image operations in workers.
  97104. * @param {Object} config Configuration.
  97105. */
  97106. function Processor(config) {
  97107. this._imageOps = !!config.imageOps;
  97108. var threads;
  97109. if (config.threads === 0) {
  97110. threads = 0;
  97111. } else if (this._imageOps) {
  97112. threads = 1;
  97113. } else {
  97114. threads = config.threads || 1;
  97115. }
  97116. var workers = [];
  97117. if (threads) {
  97118. for (var i = 0; i < threads; ++i) {
  97119. workers[i] = createWorker(config, this._onWorkerMessage.bind(this, i));
  97120. }
  97121. } else {
  97122. workers[0] = createFauxWorker(config, this._onWorkerMessage.bind(this, 0));
  97123. }
  97124. this._workers = workers;
  97125. this._queue = [];
  97126. this._maxQueueLength = config.queue || Infinity;
  97127. this._running = 0;
  97128. this._dataLookup = {};
  97129. this._job = null;
  97130. }
  97131. /**
  97132. * Run operation on input data.
  97133. * @param {Array.<Array|ImageData>} inputs Array of pixels or image data
  97134. * (depending on the operation type).
  97135. * @param {Object} meta A user data object. This is passed to all operations
  97136. * and must be serializable.
  97137. * @param {function(Error, ImageData, Object)} callback Called when work
  97138. * completes. The first argument is any error. The second is the ImageData
  97139. * generated by operations. The third is the user data object.
  97140. */
  97141. Processor.prototype.process = function(inputs, meta, callback) {
  97142. this._enqueue({
  97143. inputs: inputs,
  97144. meta: meta,
  97145. callback: callback
  97146. });
  97147. this._dispatch();
  97148. };
  97149. /**
  97150. * Stop responding to any completed work and destroy the processor.
  97151. */
  97152. Processor.prototype.destroy = function() {
  97153. for (var key in this) {
  97154. this[key] = null;
  97155. }
  97156. this._destroyed = true;
  97157. };
  97158. /**
  97159. * Add a job to the queue.
  97160. * @param {Object} job The job.
  97161. */
  97162. Processor.prototype._enqueue = function(job) {
  97163. this._queue.push(job);
  97164. while (this._queue.length > this._maxQueueLength) {
  97165. this._queue.shift().callback(null, null);
  97166. }
  97167. };
  97168. /**
  97169. * Dispatch a job.
  97170. */
  97171. Processor.prototype._dispatch = function() {
  97172. if (this._running === 0 && this._queue.length > 0) {
  97173. var job = this._job = this._queue.shift();
  97174. var width = job.inputs[0].width;
  97175. var height = job.inputs[0].height;
  97176. var buffers = job.inputs.map(function(input) {
  97177. return input.data.buffer;
  97178. });
  97179. var threads = this._workers.length;
  97180. this._running = threads;
  97181. if (threads === 1) {
  97182. this._workers[0].postMessage({
  97183. 'buffers': buffers,
  97184. 'meta': job.meta,
  97185. 'imageOps': this._imageOps,
  97186. 'width': width,
  97187. 'height': height
  97188. }, buffers);
  97189. } else {
  97190. var length = job.inputs[0].data.length;
  97191. var segmentLength = 4 * Math.ceil(length / 4 / threads);
  97192. for (var i = 0; i < threads; ++i) {
  97193. var offset = i * segmentLength;
  97194. var slices = [];
  97195. for (var j = 0, jj = buffers.length; j < jj; ++j) {
  97196. slices.push(buffers[i].slice(offset, offset + segmentLength));
  97197. }
  97198. this._workers[i].postMessage({
  97199. 'buffers': slices,
  97200. 'meta': job.meta,
  97201. 'imageOps': this._imageOps,
  97202. 'width': width,
  97203. 'height': height
  97204. }, slices);
  97205. }
  97206. }
  97207. }
  97208. };
  97209. /**
  97210. * Handle messages from the worker.
  97211. * @param {number} index The worker index.
  97212. * @param {Object} event The message event.
  97213. */
  97214. Processor.prototype._onWorkerMessage = function(index, event) {
  97215. if (this._destroyed) {
  97216. return;
  97217. }
  97218. this._dataLookup[index] = event.data;
  97219. --this._running;
  97220. if (this._running === 0) {
  97221. this._resolveJob();
  97222. }
  97223. };
  97224. /**
  97225. * Resolve a job. If there are no more worker threads, the processor callback
  97226. * will be called.
  97227. */
  97228. Processor.prototype._resolveJob = function() {
  97229. var job = this._job;
  97230. var threads = this._workers.length;
  97231. var data, meta;
  97232. if (threads === 1) {
  97233. data = new Uint8ClampedArray(this._dataLookup[0]['buffer']);
  97234. meta = this._dataLookup[0]['meta'];
  97235. } else {
  97236. var length = job.inputs[0].data.length;
  97237. data = new Uint8ClampedArray(length);
  97238. meta = new Array(length);
  97239. var segmentLength = 4 * Math.ceil(length / 4 / threads);
  97240. for (var i = 0; i < threads; ++i) {
  97241. var buffer = this._dataLookup[i]['buffer'];
  97242. var offset = i * segmentLength;
  97243. data.set(new Uint8ClampedArray(buffer), offset);
  97244. meta[i] = this._dataLookup[i]['meta'];
  97245. }
  97246. }
  97247. this._job = null;
  97248. this._dataLookup = {};
  97249. job.callback(null,
  97250. new ImageData(data, job.inputs[0].width, job.inputs[0].height), meta);
  97251. this._dispatch();
  97252. };
  97253. module.exports = Processor;
  97254. },{}]},{},[1])(1)
  97255. });
  97256. ol.ext.pixelworks = module.exports;
  97257. })();
  97258. goog.provide('ol.source.Raster');
  97259. goog.provide('ol.source.RasterEvent');
  97260. goog.provide('ol.source.RasterEventType');
  97261. goog.require('goog.asserts');
  97262. goog.require('goog.events');
  97263. goog.require('goog.events.Event');
  97264. goog.require('goog.events.EventType');
  97265. goog.require('goog.object');
  97266. goog.require('goog.vec.Mat4');
  97267. goog.require('ol.ImageCanvas');
  97268. goog.require('ol.TileQueue');
  97269. goog.require('ol.dom');
  97270. goog.require('ol.ext.pixelworks');
  97271. goog.require('ol.extent');
  97272. goog.require('ol.layer.Image');
  97273. goog.require('ol.layer.Tile');
  97274. goog.require('ol.raster.OperationType');
  97275. goog.require('ol.renderer.canvas.ImageLayer');
  97276. goog.require('ol.renderer.canvas.TileLayer');
  97277. goog.require('ol.source.Image');
  97278. goog.require('ol.source.State');
  97279. goog.require('ol.source.Tile');
  97280. /**
  97281. * @classdesc
  97282. * A source that transforms data from any number of input sources using an array
  97283. * of {@link ol.raster.Operation} functions to transform input pixel values into
  97284. * output pixel values.
  97285. *
  97286. * @constructor
  97287. * @extends {ol.source.Image}
  97288. * @param {olx.source.RasterOptions} options Options.
  97289. * @api
  97290. */
  97291. ol.source.Raster = function(options) {
  97292. /**
  97293. * @private
  97294. * @type {*}
  97295. */
  97296. this.worker_ = null;
  97297. /**
  97298. * @private
  97299. * @type {ol.raster.OperationType}
  97300. */
  97301. this.operationType_ = options.operationType !== undefined ?
  97302. options.operationType : ol.raster.OperationType.PIXEL;
  97303. /**
  97304. * @private
  97305. * @type {number}
  97306. */
  97307. this.threads_ = options.threads !== undefined ? options.threads : 1;
  97308. /**
  97309. * @private
  97310. * @type {Array.<ol.renderer.canvas.Layer>}
  97311. */
  97312. this.renderers_ = ol.source.Raster.createRenderers_(options.sources);
  97313. for (var r = 0, rr = this.renderers_.length; r < rr; ++r) {
  97314. goog.events.listen(this.renderers_[r], goog.events.EventType.CHANGE,
  97315. this.changed, false, this);
  97316. }
  97317. /**
  97318. * @private
  97319. * @type {CanvasRenderingContext2D}
  97320. */
  97321. this.canvasContext_ = ol.dom.createCanvasContext2D();
  97322. /**
  97323. * @private
  97324. * @type {ol.TileQueue}
  97325. */
  97326. this.tileQueue_ = new ol.TileQueue(
  97327. function() { return 1; },
  97328. goog.bind(this.changed, this));
  97329. var layerStatesArray = ol.source.Raster.getLayerStatesArray_(this.renderers_);
  97330. var layerStates = {};
  97331. for (var i = 0, ii = layerStatesArray.length; i < ii; ++i) {
  97332. layerStates[goog.getUid(layerStatesArray[i].layer)] = layerStatesArray[i];
  97333. }
  97334. /**
  97335. * The most recently rendered state.
  97336. * @type {?ol.source.Raster.RenderedState}
  97337. * @private
  97338. */
  97339. this.renderedState_ = null;
  97340. /**
  97341. * The most recently rendered image canvas.
  97342. * @type {ol.ImageCanvas}
  97343. * @private
  97344. */
  97345. this.renderedImageCanvas_ = null;
  97346. /**
  97347. * @private
  97348. * @type {olx.FrameState}
  97349. */
  97350. this.frameState_ = {
  97351. animate: false,
  97352. attributions: {},
  97353. coordinateToPixelMatrix: goog.vec.Mat4.createNumber(),
  97354. extent: null,
  97355. focus: null,
  97356. index: 0,
  97357. layerStates: layerStates,
  97358. layerStatesArray: layerStatesArray,
  97359. logos: {},
  97360. pixelRatio: 1,
  97361. pixelToCoordinateMatrix: goog.vec.Mat4.createNumber(),
  97362. postRenderFunctions: [],
  97363. size: [0, 0],
  97364. skippedFeatureUids: {},
  97365. tileQueue: this.tileQueue_,
  97366. time: Date.now(),
  97367. usedTiles: {},
  97368. viewState: /** @type {olx.ViewState} */ ({
  97369. rotation: 0
  97370. }),
  97371. viewHints: [],
  97372. wantedTiles: {}
  97373. };
  97374. goog.base(this, {});
  97375. if (options.operation !== undefined) {
  97376. this.setOperation(options.operation, options.lib);
  97377. }
  97378. };
  97379. goog.inherits(ol.source.Raster, ol.source.Image);
  97380. /**
  97381. * Set the operation.
  97382. * @param {ol.raster.Operation} operation New operation.
  97383. * @param {Object=} opt_lib Functions that will be available to operations run
  97384. * in a worker.
  97385. * @api
  97386. */
  97387. ol.source.Raster.prototype.setOperation = function(operation, opt_lib) {
  97388. this.worker_ = new ol.ext.pixelworks.Processor({
  97389. operation: operation,
  97390. imageOps: this.operationType_ === ol.raster.OperationType.IMAGE,
  97391. queue: 1,
  97392. lib: opt_lib,
  97393. threads: this.threads_
  97394. });
  97395. this.changed();
  97396. };
  97397. /**
  97398. * Update the stored frame state.
  97399. * @param {ol.Extent} extent The view extent (in map units).
  97400. * @param {number} resolution The view resolution.
  97401. * @param {ol.proj.Projection} projection The view projection.
  97402. * @return {olx.FrameState} The updated frame state.
  97403. * @private
  97404. */
  97405. ol.source.Raster.prototype.updateFrameState_ =
  97406. function(extent, resolution, projection) {
  97407. var frameState = /** @type {olx.FrameState} */ (
  97408. goog.object.clone(this.frameState_));
  97409. frameState.viewState = /** @type {olx.ViewState} */ (
  97410. goog.object.clone(frameState.viewState));
  97411. var center = ol.extent.getCenter(extent);
  97412. var width = Math.round(ol.extent.getWidth(extent) / resolution);
  97413. var height = Math.round(ol.extent.getHeight(extent) / resolution);
  97414. frameState.extent = extent;
  97415. frameState.focus = ol.extent.getCenter(extent);
  97416. frameState.size[0] = width;
  97417. frameState.size[1] = height;
  97418. var viewState = frameState.viewState;
  97419. viewState.center = center;
  97420. viewState.projection = projection;
  97421. viewState.resolution = resolution;
  97422. return frameState;
  97423. };
  97424. /**
  97425. * Determine if the most recently rendered image canvas is dirty.
  97426. * @param {ol.Extent} extent The requested extent.
  97427. * @param {number} resolution The requested resolution.
  97428. * @return {boolean} The image is dirty.
  97429. * @private
  97430. */
  97431. ol.source.Raster.prototype.isDirty_ = function(extent, resolution) {
  97432. var state = this.renderedState_;
  97433. return !state ||
  97434. this.getRevision() !== state.revision ||
  97435. resolution !== state.resolution ||
  97436. !ol.extent.equals(extent, state.extent);
  97437. };
  97438. /**
  97439. * @inheritDoc
  97440. */
  97441. ol.source.Raster.prototype.getImage =
  97442. function(extent, resolution, pixelRatio, projection) {
  97443. if (!this.allSourcesReady_()) {
  97444. return null;
  97445. }
  97446. if (!this.isDirty_(extent, resolution)) {
  97447. return this.renderedImageCanvas_;
  97448. }
  97449. var context = this.canvasContext_;
  97450. var canvas = context.canvas;
  97451. var width = Math.round(ol.extent.getWidth(extent) / resolution);
  97452. var height = Math.round(ol.extent.getHeight(extent) / resolution);
  97453. if (width !== canvas.width ||
  97454. height !== canvas.height) {
  97455. canvas.width = width;
  97456. canvas.height = height;
  97457. }
  97458. var frameState = this.updateFrameState_(extent, resolution, projection);
  97459. var imageCanvas = new ol.ImageCanvas(
  97460. extent, resolution, 1, this.getAttributions(), canvas,
  97461. this.composeFrame_.bind(this, frameState));
  97462. this.renderedImageCanvas_ = imageCanvas;
  97463. this.renderedState_ = {
  97464. extent: extent,
  97465. resolution: resolution,
  97466. revision: this.getRevision()
  97467. };
  97468. return imageCanvas;
  97469. };
  97470. /**
  97471. * Determine if all sources are ready.
  97472. * @return {boolean} All sources are ready.
  97473. * @private
  97474. */
  97475. ol.source.Raster.prototype.allSourcesReady_ = function() {
  97476. var ready = true;
  97477. var source;
  97478. for (var i = 0, ii = this.renderers_.length; i < ii; ++i) {
  97479. source = this.renderers_[i].getLayer().getSource();
  97480. if (source.getState() !== ol.source.State.READY) {
  97481. ready = false;
  97482. break;
  97483. }
  97484. }
  97485. return ready;
  97486. };
  97487. /**
  97488. * Compose the frame. This renders data from all sources, runs pixel-wise
  97489. * operations, and renders the result to the stored canvas context.
  97490. * @param {olx.FrameState} frameState The frame state.
  97491. * @param {function(Error)} callback Called when composition is complete.
  97492. * @private
  97493. */
  97494. ol.source.Raster.prototype.composeFrame_ = function(frameState, callback) {
  97495. var len = this.renderers_.length;
  97496. var imageDatas = new Array(len);
  97497. for (var i = 0; i < len; ++i) {
  97498. var imageData = ol.source.Raster.getImageData_(
  97499. this.renderers_[i], frameState, frameState.layerStatesArray[i]);
  97500. if (imageData) {
  97501. imageDatas[i] = imageData;
  97502. } else {
  97503. // image not yet ready
  97504. return;
  97505. }
  97506. }
  97507. var data = {};
  97508. this.dispatchEvent(new ol.source.RasterEvent(
  97509. ol.source.RasterEventType.BEFOREOPERATIONS, frameState, data));
  97510. this.worker_.process(imageDatas, data,
  97511. this.onWorkerComplete_.bind(this, frameState, callback));
  97512. frameState.tileQueue.loadMoreTiles(16, 16);
  97513. };
  97514. /**
  97515. * Called when pixel processing is complete.
  97516. * @param {olx.FrameState} frameState The frame state.
  97517. * @param {function(Error)} callback Called when rendering is complete.
  97518. * @param {Error} err Any error during processing.
  97519. * @param {ImageData} output The output image data.
  97520. * @param {Object} data The user data.
  97521. * @private
  97522. */
  97523. ol.source.Raster.prototype.onWorkerComplete_ =
  97524. function(frameState, callback, err, output, data) {
  97525. if (err) {
  97526. callback(err);
  97527. return;
  97528. }
  97529. if (!output) {
  97530. // job aborted
  97531. return;
  97532. }
  97533. this.dispatchEvent(new ol.source.RasterEvent(
  97534. ol.source.RasterEventType.AFTEROPERATIONS, frameState, data));
  97535. var resolution = frameState.viewState.resolution / frameState.pixelRatio;
  97536. if (!this.isDirty_(frameState.extent, resolution)) {
  97537. this.canvasContext_.putImageData(output, 0, 0);
  97538. }
  97539. callback(null);
  97540. };
  97541. /**
  97542. * Get image data from a renderer.
  97543. * @param {ol.renderer.canvas.Layer} renderer Layer renderer.
  97544. * @param {olx.FrameState} frameState The frame state.
  97545. * @param {ol.layer.LayerState} layerState The layer state.
  97546. * @return {ImageData} The image data.
  97547. * @private
  97548. */
  97549. ol.source.Raster.getImageData_ = function(renderer, frameState, layerState) {
  97550. renderer.prepareFrame(frameState, layerState);
  97551. // We should be able to call renderer.composeFrame(), but this is inefficient
  97552. // for tiled sources (we've already rendered to an intermediate canvas in the
  97553. // prepareFrame call and we don't need to render again to the output canvas).
  97554. // TODO: make all canvas renderers render to a single canvas
  97555. var image = renderer.getImage();
  97556. if (!image) {
  97557. return null;
  97558. }
  97559. var imageTransform = renderer.getImageTransform();
  97560. var dx = Math.round(goog.vec.Mat4.getElement(imageTransform, 0, 3));
  97561. var dy = Math.round(goog.vec.Mat4.getElement(imageTransform, 1, 3));
  97562. var width = frameState.size[0];
  97563. var height = frameState.size[1];
  97564. if (image instanceof Image) {
  97565. if (!ol.source.Raster.context_) {
  97566. ol.source.Raster.context_ = ol.dom.createCanvasContext2D(width, height);
  97567. } else {
  97568. var canvas = ol.source.Raster.context_.canvas;
  97569. if (canvas.width !== width || canvas.height !== height) {
  97570. ol.source.Raster.context_ = ol.dom.createCanvasContext2D(width, height);
  97571. } else {
  97572. ol.source.Raster.context_.clearRect(0, 0, width, height);
  97573. }
  97574. }
  97575. var dw = Math.round(
  97576. image.width * goog.vec.Mat4.getElement(imageTransform, 0, 0));
  97577. var dh = Math.round(
  97578. image.height * goog.vec.Mat4.getElement(imageTransform, 1, 1));
  97579. ol.source.Raster.context_.drawImage(image, dx, dy, dw, dh);
  97580. return ol.source.Raster.context_.getImageData(0, 0, width, height);
  97581. } else {
  97582. return image.getContext('2d').getImageData(-dx, -dy, width, height);
  97583. }
  97584. };
  97585. /**
  97586. * A reusable canvas context.
  97587. * @type {CanvasRenderingContext2D}
  97588. * @private
  97589. */
  97590. ol.source.Raster.context_ = null;
  97591. /**
  97592. * Get a list of layer states from a list of renderers.
  97593. * @param {Array.<ol.renderer.canvas.Layer>} renderers Layer renderers.
  97594. * @return {Array.<ol.layer.LayerState>} The layer states.
  97595. * @private
  97596. */
  97597. ol.source.Raster.getLayerStatesArray_ = function(renderers) {
  97598. return renderers.map(function(renderer) {
  97599. return renderer.getLayer().getLayerState();
  97600. });
  97601. };
  97602. /**
  97603. * Create renderers for all sources.
  97604. * @param {Array.<ol.source.Source>} sources The sources.
  97605. * @return {Array.<ol.renderer.canvas.Layer>} Array of layer renderers.
  97606. * @private
  97607. */
  97608. ol.source.Raster.createRenderers_ = function(sources) {
  97609. var len = sources.length;
  97610. var renderers = new Array(len);
  97611. for (var i = 0; i < len; ++i) {
  97612. renderers[i] = ol.source.Raster.createRenderer_(sources[i]);
  97613. }
  97614. return renderers;
  97615. };
  97616. /**
  97617. * Create a renderer for the provided source.
  97618. * @param {ol.source.Source} source The source.
  97619. * @return {ol.renderer.canvas.Layer} The renderer.
  97620. * @private
  97621. */
  97622. ol.source.Raster.createRenderer_ = function(source) {
  97623. var renderer = null;
  97624. if (source instanceof ol.source.Tile) {
  97625. renderer = ol.source.Raster.createTileRenderer_(source);
  97626. } else if (source instanceof ol.source.Image) {
  97627. renderer = ol.source.Raster.createImageRenderer_(source);
  97628. } else {
  97629. goog.asserts.fail('Unsupported source type: ' + source);
  97630. }
  97631. return renderer;
  97632. };
  97633. /**
  97634. * Create an image renderer for the provided source.
  97635. * @param {ol.source.Image} source The source.
  97636. * @return {ol.renderer.canvas.Layer} The renderer.
  97637. * @private
  97638. */
  97639. ol.source.Raster.createImageRenderer_ = function(source) {
  97640. var layer = new ol.layer.Image({source: source});
  97641. return new ol.renderer.canvas.ImageLayer(layer);
  97642. };
  97643. /**
  97644. * Create a tile renderer for the provided source.
  97645. * @param {ol.source.Tile} source The source.
  97646. * @return {ol.renderer.canvas.Layer} The renderer.
  97647. * @private
  97648. */
  97649. ol.source.Raster.createTileRenderer_ = function(source) {
  97650. var layer = new ol.layer.Tile({source: source});
  97651. return new ol.renderer.canvas.TileLayer(layer);
  97652. };
  97653. /**
  97654. * @typedef {{revision: number,
  97655. * resolution: number,
  97656. * extent: ol.Extent}}
  97657. */
  97658. ol.source.Raster.RenderedState;
  97659. /**
  97660. * @classdesc
  97661. * Events emitted by {@link ol.source.Raster} instances are instances of this
  97662. * type.
  97663. *
  97664. * @constructor
  97665. * @extends {goog.events.Event}
  97666. * @implements {oli.source.RasterEvent}
  97667. * @param {string} type Type.
  97668. * @param {olx.FrameState} frameState The frame state.
  97669. * @param {Object} data An object made available to operations.
  97670. */
  97671. ol.source.RasterEvent = function(type, frameState, data) {
  97672. goog.base(this, type);
  97673. /**
  97674. * The raster extent.
  97675. * @type {ol.Extent}
  97676. * @api
  97677. */
  97678. this.extent = frameState.extent;
  97679. /**
  97680. * The pixel resolution (map units per pixel).
  97681. * @type {number}
  97682. * @api
  97683. */
  97684. this.resolution = frameState.viewState.resolution / frameState.pixelRatio;
  97685. /**
  97686. * An object made available to all operations. This can be used by operations
  97687. * as a storage object (e.g. for calculating statistics).
  97688. * @type {Object}
  97689. * @api
  97690. */
  97691. this.data = data;
  97692. };
  97693. goog.inherits(ol.source.RasterEvent, goog.events.Event);
  97694. /**
  97695. * @enum {string}
  97696. */
  97697. ol.source.RasterEventType = {
  97698. /**
  97699. * Triggered before operations are run.
  97700. * @event ol.source.RasterEvent#beforeoperations
  97701. * @api
  97702. */
  97703. BEFOREOPERATIONS: 'beforeoperations',
  97704. /**
  97705. * Triggered after operations are run.
  97706. * @event ol.source.RasterEvent#afteroperations
  97707. * @api
  97708. */
  97709. AFTEROPERATIONS: 'afteroperations'
  97710. };
  97711. goog.provide('ol.source.Stamen');
  97712. goog.require('goog.asserts');
  97713. goog.require('ol.Attribution');
  97714. goog.require('ol.source.OSM');
  97715. goog.require('ol.source.XYZ');
  97716. /**
  97717. * @type {Object.<string, {extension: string, opaque: boolean}>}
  97718. */
  97719. ol.source.StamenLayerConfig = {
  97720. 'terrain': {
  97721. extension: 'jpg',
  97722. opaque: true
  97723. },
  97724. 'terrain-background': {
  97725. extension: 'jpg',
  97726. opaque: true
  97727. },
  97728. 'terrain-labels': {
  97729. extension: 'png',
  97730. opaque: false
  97731. },
  97732. 'terrain-lines': {
  97733. extension: 'png',
  97734. opaque: false
  97735. },
  97736. 'toner-background': {
  97737. extension: 'png',
  97738. opaque: true
  97739. },
  97740. 'toner': {
  97741. extension: 'png',
  97742. opaque: true
  97743. },
  97744. 'toner-hybrid': {
  97745. extension: 'png',
  97746. opaque: false
  97747. },
  97748. 'toner-labels': {
  97749. extension: 'png',
  97750. opaque: false
  97751. },
  97752. 'toner-lines': {
  97753. extension: 'png',
  97754. opaque: false
  97755. },
  97756. 'toner-lite': {
  97757. extension: 'png',
  97758. opaque: true
  97759. },
  97760. 'watercolor': {
  97761. extension: 'jpg',
  97762. opaque: true
  97763. }
  97764. };
  97765. /**
  97766. * @type {Object.<string, {minZoom: number, maxZoom: number}>}
  97767. */
  97768. ol.source.StamenProviderConfig = {
  97769. 'terrain': {
  97770. minZoom: 4,
  97771. maxZoom: 18
  97772. },
  97773. 'toner': {
  97774. minZoom: 0,
  97775. maxZoom: 20
  97776. },
  97777. 'watercolor': {
  97778. minZoom: 3,
  97779. maxZoom: 16
  97780. }
  97781. };
  97782. /**
  97783. * @classdesc
  97784. * Layer source for the Stamen tile server.
  97785. *
  97786. * @constructor
  97787. * @extends {ol.source.XYZ}
  97788. * @param {olx.source.StamenOptions} options Stamen options.
  97789. * @api stable
  97790. */
  97791. ol.source.Stamen = function(options) {
  97792. var i = options.layer.indexOf('-');
  97793. var provider = i == -1 ? options.layer : options.layer.slice(0, i);
  97794. goog.asserts.assert(provider in ol.source.StamenProviderConfig,
  97795. 'known provider configured');
  97796. var providerConfig = ol.source.StamenProviderConfig[provider];
  97797. goog.asserts.assert(options.layer in ol.source.StamenLayerConfig,
  97798. 'known layer configured');
  97799. var layerConfig = ol.source.StamenLayerConfig[options.layer];
  97800. var url = options.url !== undefined ? options.url :
  97801. 'https://stamen-tiles-{a-d}.a.ssl.fastly.net/' + options.layer +
  97802. '/{z}/{x}/{y}.' + layerConfig.extension;
  97803. goog.base(this, {
  97804. attributions: ol.source.Stamen.ATTRIBUTIONS,
  97805. crossOrigin: 'anonymous',
  97806. maxZoom: providerConfig.maxZoom,
  97807. // FIXME uncomment the following when tilegrid supports minZoom
  97808. //minZoom: providerConfig.minZoom,
  97809. opaque: layerConfig.opaque,
  97810. tileLoadFunction: options.tileLoadFunction,
  97811. url: url
  97812. });
  97813. };
  97814. goog.inherits(ol.source.Stamen, ol.source.XYZ);
  97815. /**
  97816. * @const
  97817. * @type {Array.<ol.Attribution>}
  97818. */
  97819. ol.source.Stamen.ATTRIBUTIONS = [
  97820. new ol.Attribution({
  97821. html: 'Map tiles by <a href="http://stamen.com/">Stamen Design</a>, ' +
  97822. 'under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY' +
  97823. ' 3.0</a>.'
  97824. }),
  97825. ol.source.OSM.ATTRIBUTION
  97826. ];
  97827. goog.provide('ol.source.TileArcGISRest');
  97828. goog.require('goog.asserts');
  97829. goog.require('goog.math');
  97830. goog.require('goog.object');
  97831. goog.require('goog.string');
  97832. goog.require('goog.uri.utils');
  97833. goog.require('ol');
  97834. goog.require('ol.TileCoord');
  97835. goog.require('ol.TileUrlFunction');
  97836. goog.require('ol.extent');
  97837. goog.require('ol.proj');
  97838. goog.require('ol.size');
  97839. goog.require('ol.source.TileImage');
  97840. goog.require('ol.tilecoord');
  97841. /**
  97842. * @classdesc
  97843. * Layer source for tile data from ArcGIS Rest services. Map and Image
  97844. * Services are supported.
  97845. *
  97846. * For cached ArcGIS services, better performance is available using the
  97847. * {@link ol.source.XYZ} data source.
  97848. *
  97849. * @constructor
  97850. * @extends {ol.source.TileImage}
  97851. * @param {olx.source.TileArcGISRestOptions=} opt_options Tile ArcGIS Rest
  97852. * options.
  97853. * @api
  97854. */
  97855. ol.source.TileArcGISRest = function(opt_options) {
  97856. var options = opt_options || {};
  97857. var params = options.params !== undefined ? options.params : {};
  97858. goog.base(this, {
  97859. attributions: options.attributions,
  97860. crossOrigin: options.crossOrigin,
  97861. logo: options.logo,
  97862. projection: options.projection,
  97863. tileGrid: options.tileGrid,
  97864. tileLoadFunction: options.tileLoadFunction,
  97865. tileUrlFunction: goog.bind(this.tileUrlFunction_, this),
  97866. wrapX: options.wrapX !== undefined ? options.wrapX : true
  97867. });
  97868. var urls = options.urls;
  97869. if (urls === undefined && options.url !== undefined) {
  97870. urls = ol.TileUrlFunction.expandUrl(options.url);
  97871. }
  97872. /**
  97873. * @private
  97874. * @type {!Array.<string>}
  97875. */
  97876. this.urls_ = urls || [];
  97877. /**
  97878. * @private
  97879. * @type {Object}
  97880. */
  97881. this.params_ = params;
  97882. /**
  97883. * @private
  97884. * @type {ol.Extent}
  97885. */
  97886. this.tmpExtent_ = ol.extent.createEmpty();
  97887. };
  97888. goog.inherits(ol.source.TileArcGISRest, ol.source.TileImage);
  97889. /**
  97890. * Get the user-provided params, i.e. those passed to the constructor through
  97891. * the "params" option, and possibly updated using the updateParams method.
  97892. * @return {Object} Params.
  97893. * @api
  97894. */
  97895. ol.source.TileArcGISRest.prototype.getParams = function() {
  97896. return this.params_;
  97897. };
  97898. /**
  97899. * @param {ol.TileCoord} tileCoord Tile coordinate.
  97900. * @param {ol.Size} tileSize Tile size.
  97901. * @param {ol.Extent} tileExtent Tile extent.
  97902. * @param {number} pixelRatio Pixel ratio.
  97903. * @param {ol.proj.Projection} projection Projection.
  97904. * @param {Object} params Params.
  97905. * @return {string|undefined} Request URL.
  97906. * @private
  97907. */
  97908. ol.source.TileArcGISRest.prototype.getRequestUrl_ =
  97909. function(tileCoord, tileSize, tileExtent,
  97910. pixelRatio, projection, params) {
  97911. var urls = this.urls_;
  97912. if (urls.length === 0) {
  97913. return undefined;
  97914. }
  97915. // ArcGIS Server only wants the numeric portion of the projection ID.
  97916. var srid = projection.getCode().split(':').pop();
  97917. params['SIZE'] = tileSize[0] + ',' + tileSize[1];
  97918. params['BBOX'] = tileExtent.join(',');
  97919. params['BBOXSR'] = srid;
  97920. params['IMAGESR'] = srid;
  97921. params['DPI'] = Math.round(90 * pixelRatio);
  97922. var url;
  97923. if (urls.length == 1) {
  97924. url = urls[0];
  97925. } else {
  97926. var index = goog.math.modulo(ol.tilecoord.hash(tileCoord), urls.length);
  97927. url = urls[index];
  97928. }
  97929. if (!goog.string.endsWith(url, '/')) {
  97930. url = url + '/';
  97931. }
  97932. // If a MapServer, use export. If an ImageServer, use exportImage.
  97933. if (goog.string.endsWith(url, 'MapServer/')) {
  97934. url = url + 'export';
  97935. }
  97936. else if (goog.string.endsWith(url, 'ImageServer/')) {
  97937. url = url + 'exportImage';
  97938. }
  97939. else {
  97940. goog.asserts.fail('Unknown Rest Service', url);
  97941. }
  97942. return goog.uri.utils.appendParamsFromMap(url, params);
  97943. };
  97944. /**
  97945. * @param {number} z Z.
  97946. * @param {number} pixelRatio Pixel ratio.
  97947. * @param {ol.proj.Projection} projection Projection.
  97948. * @return {ol.Size} Size.
  97949. */
  97950. ol.source.TileArcGISRest.prototype.getTilePixelSize =
  97951. function(z, pixelRatio, projection) {
  97952. var tileSize = goog.base(this, 'getTilePixelSize', z, pixelRatio, projection);
  97953. if (pixelRatio == 1) {
  97954. return tileSize;
  97955. } else {
  97956. return ol.size.scale(tileSize, pixelRatio, this.tmpSize);
  97957. }
  97958. };
  97959. /**
  97960. * Return the URLs used for this ArcGIS source.
  97961. * @return {!Array.<string>} URLs.
  97962. * @api stable
  97963. */
  97964. ol.source.TileArcGISRest.prototype.getUrls = function() {
  97965. return this.urls_;
  97966. };
  97967. /**
  97968. * Set the URL to use for requests.
  97969. * @param {string|undefined} url URL.
  97970. * @api stable
  97971. */
  97972. ol.source.TileArcGISRest.prototype.setUrl = function(url) {
  97973. var urls = url !== undefined ? ol.TileUrlFunction.expandUrl(url) : null;
  97974. this.setUrls(urls);
  97975. };
  97976. /**
  97977. * Set the URLs to use for requests.
  97978. * @param {Array.<string>|undefined} urls URLs.
  97979. * @api stable
  97980. */
  97981. ol.source.TileArcGISRest.prototype.setUrls = function(urls) {
  97982. this.urls_ = urls || [];
  97983. this.changed();
  97984. };
  97985. /**
  97986. * @param {ol.TileCoord} tileCoord Tile coordinate.
  97987. * @param {number} pixelRatio Pixel ratio.
  97988. * @param {ol.proj.Projection} projection Projection.
  97989. * @return {string|undefined} Tile URL.
  97990. * @private
  97991. */
  97992. ol.source.TileArcGISRest.prototype.tileUrlFunction_ =
  97993. function(tileCoord, pixelRatio, projection) {
  97994. var tileGrid = this.getTileGrid();
  97995. if (!tileGrid) {
  97996. tileGrid = this.getTileGridForProjection(projection);
  97997. }
  97998. if (tileGrid.getResolutions().length <= tileCoord[0]) {
  97999. return undefined;
  98000. }
  98001. var tileExtent = tileGrid.getTileCoordExtent(
  98002. tileCoord, this.tmpExtent_);
  98003. var tileSize = ol.size.toSize(
  98004. tileGrid.getTileSize(tileCoord[0]), this.tmpSize);
  98005. if (pixelRatio != 1) {
  98006. tileSize = ol.size.scale(tileSize, pixelRatio, this.tmpSize);
  98007. }
  98008. // Apply default params and override with user specified values.
  98009. var baseParams = {
  98010. 'F': 'image',
  98011. 'FORMAT': 'PNG32',
  98012. 'TRANSPARENT': true
  98013. };
  98014. goog.object.extend(baseParams, this.params_);
  98015. return this.getRequestUrl_(tileCoord, tileSize, tileExtent,
  98016. pixelRatio, projection, baseParams);
  98017. };
  98018. /**
  98019. * Update the user-provided params.
  98020. * @param {Object} params Params.
  98021. * @api stable
  98022. */
  98023. ol.source.TileArcGISRest.prototype.updateParams = function(params) {
  98024. goog.object.extend(this.params_, params);
  98025. this.changed();
  98026. };
  98027. goog.provide('ol.source.TileDebug');
  98028. goog.require('ol.Tile');
  98029. goog.require('ol.TileCoord');
  98030. goog.require('ol.TileState');
  98031. goog.require('ol.dom');
  98032. goog.require('ol.size');
  98033. goog.require('ol.source.Tile');
  98034. goog.require('ol.tilecoord');
  98035. /**
  98036. * @constructor
  98037. * @extends {ol.Tile}
  98038. * @param {ol.TileCoord} tileCoord Tile coordinate.
  98039. * @param {ol.Size} tileSize Tile size.
  98040. * @param {string} text Text.
  98041. * @private
  98042. */
  98043. ol.DebugTile_ = function(tileCoord, tileSize, text) {
  98044. goog.base(this, tileCoord, ol.TileState.LOADED);
  98045. /**
  98046. * @private
  98047. * @type {ol.Size}
  98048. */
  98049. this.tileSize_ = tileSize;
  98050. /**
  98051. * @private
  98052. * @type {string}
  98053. */
  98054. this.text_ = text;
  98055. /**
  98056. * @private
  98057. * @type {Object.<number, HTMLCanvasElement>}
  98058. */
  98059. this.canvasByContext_ = {};
  98060. };
  98061. goog.inherits(ol.DebugTile_, ol.Tile);
  98062. /**
  98063. * @inheritDoc
  98064. */
  98065. ol.DebugTile_.prototype.getImage = function(opt_context) {
  98066. var key = opt_context !== undefined ? goog.getUid(opt_context) : -1;
  98067. if (key in this.canvasByContext_) {
  98068. return this.canvasByContext_[key];
  98069. } else {
  98070. var tileSize = this.tileSize_;
  98071. var context = ol.dom.createCanvasContext2D(tileSize[0], tileSize[1]);
  98072. context.strokeStyle = 'black';
  98073. context.strokeRect(0.5, 0.5, tileSize[0] + 0.5, tileSize[1] + 0.5);
  98074. context.fillStyle = 'black';
  98075. context.textAlign = 'center';
  98076. context.textBaseline = 'middle';
  98077. context.font = '24px sans-serif';
  98078. context.fillText(this.text_, tileSize[0] / 2, tileSize[1] / 2);
  98079. this.canvasByContext_[key] = context.canvas;
  98080. return context.canvas;
  98081. }
  98082. };
  98083. /**
  98084. * @classdesc
  98085. * A pseudo tile source, which does not fetch tiles from a server, but renders
  98086. * a grid outline for the tile grid/projection along with the coordinates for
  98087. * each tile. See examples/canvas-tiles for an example.
  98088. *
  98089. * Uses Canvas context2d, so requires Canvas support.
  98090. *
  98091. * @constructor
  98092. * @extends {ol.source.Tile}
  98093. * @param {olx.source.TileDebugOptions} options Debug tile options.
  98094. * @api
  98095. */
  98096. ol.source.TileDebug = function(options) {
  98097. goog.base(this, {
  98098. opaque: false,
  98099. projection: options.projection,
  98100. tileGrid: options.tileGrid,
  98101. wrapX: options.wrapX !== undefined ? options.wrapX : true
  98102. });
  98103. };
  98104. goog.inherits(ol.source.TileDebug, ol.source.Tile);
  98105. /**
  98106. * @inheritDoc
  98107. */
  98108. ol.source.TileDebug.prototype.getTile = function(z, x, y) {
  98109. var tileCoordKey = this.getKeyZXY(z, x, y);
  98110. if (this.tileCache.containsKey(tileCoordKey)) {
  98111. return /** @type {!ol.DebugTile_} */ (this.tileCache.get(tileCoordKey));
  98112. } else {
  98113. var tileSize = ol.size.toSize(this.tileGrid.getTileSize(z));
  98114. var tileCoord = [z, x, y];
  98115. var textTileCoord = this.getTileCoordForTileUrlFunction(tileCoord);
  98116. var text = !textTileCoord ? '' : ol.tilecoord.toString(
  98117. this.getTileCoordForTileUrlFunction(textTileCoord));
  98118. var tile = new ol.DebugTile_(tileCoord, tileSize, text);
  98119. this.tileCache.set(tileCoordKey, tile);
  98120. return tile;
  98121. }
  98122. };
  98123. // FIXME check order of async callbacks
  98124. /**
  98125. * @see http://mapbox.com/developers/api/
  98126. */
  98127. goog.provide('ol.source.TileJSON');
  98128. goog.provide('ol.tilejson');
  98129. goog.require('goog.asserts');
  98130. goog.require('goog.net.Jsonp');
  98131. goog.require('ol.Attribution');
  98132. goog.require('ol.TileRange');
  98133. goog.require('ol.TileUrlFunction');
  98134. goog.require('ol.extent');
  98135. goog.require('ol.proj');
  98136. goog.require('ol.source.State');
  98137. goog.require('ol.source.TileImage');
  98138. /**
  98139. * @classdesc
  98140. * Layer source for tile data in TileJSON format.
  98141. *
  98142. * @constructor
  98143. * @extends {ol.source.TileImage}
  98144. * @param {olx.source.TileJSONOptions} options TileJSON options.
  98145. * @api stable
  98146. */
  98147. ol.source.TileJSON = function(options) {
  98148. goog.base(this, {
  98149. attributions: options.attributions,
  98150. crossOrigin: options.crossOrigin,
  98151. projection: ol.proj.get('EPSG:3857'),
  98152. state: ol.source.State.LOADING,
  98153. tileLoadFunction: options.tileLoadFunction,
  98154. wrapX: options.wrapX !== undefined ? options.wrapX : true
  98155. });
  98156. var request = new goog.net.Jsonp(options.url);
  98157. request.send(undefined, goog.bind(this.handleTileJSONResponse, this),
  98158. goog.bind(this.handleTileJSONError, this));
  98159. };
  98160. goog.inherits(ol.source.TileJSON, ol.source.TileImage);
  98161. /**
  98162. * @protected
  98163. * @param {TileJSON} tileJSON Tile JSON.
  98164. */
  98165. ol.source.TileJSON.prototype.handleTileJSONResponse = function(tileJSON) {
  98166. var epsg4326Projection = ol.proj.get('EPSG:4326');
  98167. var sourceProjection = this.getProjection();
  98168. var extent;
  98169. if (tileJSON.bounds !== undefined) {
  98170. var transform = ol.proj.getTransformFromProjections(
  98171. epsg4326Projection, sourceProjection);
  98172. extent = ol.extent.applyTransform(tileJSON.bounds, transform);
  98173. }
  98174. if (tileJSON.scheme !== undefined) {
  98175. goog.asserts.assert(tileJSON.scheme == 'xyz', 'tileJSON-scheme is "xyz"');
  98176. }
  98177. var minZoom = tileJSON.minzoom || 0;
  98178. var maxZoom = tileJSON.maxzoom || 22;
  98179. var tileGrid = ol.tilegrid.createXYZ({
  98180. extent: ol.tilegrid.extentFromProjection(sourceProjection),
  98181. maxZoom: maxZoom,
  98182. minZoom: minZoom
  98183. });
  98184. this.tileGrid = tileGrid;
  98185. this.tileUrlFunction =
  98186. ol.TileUrlFunction.createFromTemplates(tileJSON.tiles, tileGrid);
  98187. if (tileJSON.attribution !== undefined && !this.getAttributions()) {
  98188. var attributionExtent = extent !== undefined ?
  98189. extent : epsg4326Projection.getExtent();
  98190. /** @type {Object.<string, Array.<ol.TileRange>>} */
  98191. var tileRanges = {};
  98192. var z, zKey;
  98193. for (z = minZoom; z <= maxZoom; ++z) {
  98194. zKey = z.toString();
  98195. tileRanges[zKey] =
  98196. [tileGrid.getTileRangeForExtentAndZ(attributionExtent, z)];
  98197. }
  98198. this.setAttributions([
  98199. new ol.Attribution({
  98200. html: tileJSON.attribution,
  98201. tileRanges: tileRanges
  98202. })
  98203. ]);
  98204. }
  98205. this.setState(ol.source.State.READY);
  98206. };
  98207. /**
  98208. * @protected
  98209. */
  98210. ol.source.TileJSON.prototype.handleTileJSONError = function() {
  98211. this.setState(ol.source.State.ERROR);
  98212. };
  98213. goog.provide('ol.source.TileUTFGrid');
  98214. goog.require('goog.asserts');
  98215. goog.require('goog.async.nextTick');
  98216. goog.require('goog.events');
  98217. goog.require('goog.events.EventType');
  98218. goog.require('goog.net.Jsonp');
  98219. goog.require('ol.Attribution');
  98220. goog.require('ol.Tile');
  98221. goog.require('ol.TileState');
  98222. goog.require('ol.TileUrlFunction');
  98223. goog.require('ol.extent');
  98224. goog.require('ol.proj');
  98225. goog.require('ol.source.State');
  98226. goog.require('ol.source.Tile');
  98227. /**
  98228. * @classdesc
  98229. * Layer source for UTFGrid interaction data loaded from TileJSON format.
  98230. *
  98231. * @constructor
  98232. * @extends {ol.source.Tile}
  98233. * @param {olx.source.TileUTFGridOptions} options Source options.
  98234. * @api
  98235. */
  98236. ol.source.TileUTFGrid = function(options) {
  98237. goog.base(this, {
  98238. projection: ol.proj.get('EPSG:3857'),
  98239. state: ol.source.State.LOADING
  98240. });
  98241. /**
  98242. * @private
  98243. * @type {boolean}
  98244. */
  98245. this.preemptive_ = options.preemptive !== undefined ?
  98246. options.preemptive : true;
  98247. /**
  98248. * @private
  98249. * @type {!ol.TileUrlFunctionType}
  98250. */
  98251. this.tileUrlFunction_ = ol.TileUrlFunction.nullTileUrlFunction;
  98252. /**
  98253. * @private
  98254. * @type {string|undefined}
  98255. */
  98256. this.template_ = undefined;
  98257. var request = new goog.net.Jsonp(options.url);
  98258. request.send(undefined, goog.bind(this.handleTileJSONResponse, this));
  98259. };
  98260. goog.inherits(ol.source.TileUTFGrid, ol.source.Tile);
  98261. /**
  98262. * Return the template from TileJSON.
  98263. * @return {string|undefined} The template from TileJSON.
  98264. * @api
  98265. */
  98266. ol.source.TileUTFGrid.prototype.getTemplate = function() {
  98267. return this.template_;
  98268. };
  98269. /**
  98270. * Calls the callback (synchronously by default) with the available data
  98271. * for given coordinate and resolution (or `null` if not yet loaded or
  98272. * in case of an error).
  98273. * @param {ol.Coordinate} coordinate Coordinate.
  98274. * @param {number} resolution Resolution.
  98275. * @param {function(this: T, Object)} callback Callback.
  98276. * @param {T=} opt_this The object to use as `this` in the callback.
  98277. * @param {boolean=} opt_request If `true` the callback is always async.
  98278. * The tile data is requested if not yet loaded.
  98279. * @template T
  98280. * @api
  98281. */
  98282. ol.source.TileUTFGrid.prototype.forDataAtCoordinateAndResolution = function(
  98283. coordinate, resolution, callback, opt_this, opt_request) {
  98284. if (this.tileGrid) {
  98285. var tileCoord = this.tileGrid.getTileCoordForCoordAndResolution(
  98286. coordinate, resolution);
  98287. var tile = /** @type {!ol.source.TileUTFGridTile_} */(this.getTile(
  98288. tileCoord[0], tileCoord[1], tileCoord[2], 1, this.getProjection()));
  98289. tile.forDataAtCoordinate(coordinate, callback, opt_this, opt_request);
  98290. } else {
  98291. if (opt_request === true) {
  98292. goog.async.nextTick(function() {
  98293. callback.call(opt_this, null);
  98294. });
  98295. } else {
  98296. callback.call(opt_this, null);
  98297. }
  98298. }
  98299. };
  98300. /**
  98301. * TODO: very similar to ol.source.TileJSON#handleTileJSONResponse
  98302. * @protected
  98303. * @param {TileJSON} tileJSON Tile JSON.
  98304. */
  98305. ol.source.TileUTFGrid.prototype.handleTileJSONResponse = function(tileJSON) {
  98306. var epsg4326Projection = ol.proj.get('EPSG:4326');
  98307. var sourceProjection = this.getProjection();
  98308. var extent;
  98309. if (tileJSON.bounds !== undefined) {
  98310. var transform = ol.proj.getTransformFromProjections(
  98311. epsg4326Projection, sourceProjection);
  98312. extent = ol.extent.applyTransform(tileJSON.bounds, transform);
  98313. }
  98314. if (tileJSON.scheme !== undefined) {
  98315. goog.asserts.assert(tileJSON.scheme == 'xyz', 'tileJSON-scheme is "xyz"');
  98316. }
  98317. var minZoom = tileJSON.minzoom || 0;
  98318. var maxZoom = tileJSON.maxzoom || 22;
  98319. var tileGrid = ol.tilegrid.createXYZ({
  98320. extent: ol.tilegrid.extentFromProjection(sourceProjection),
  98321. maxZoom: maxZoom,
  98322. minZoom: minZoom
  98323. });
  98324. this.tileGrid = tileGrid;
  98325. this.template_ = tileJSON.template;
  98326. var grids = tileJSON.grids;
  98327. if (!grids) {
  98328. this.setState(ol.source.State.ERROR);
  98329. return;
  98330. }
  98331. this.tileUrlFunction_ =
  98332. ol.TileUrlFunction.createFromTemplates(grids, tileGrid);
  98333. if (tileJSON.attribution !== undefined) {
  98334. var attributionExtent = extent !== undefined ?
  98335. extent : epsg4326Projection.getExtent();
  98336. /** @type {Object.<string, Array.<ol.TileRange>>} */
  98337. var tileRanges = {};
  98338. var z, zKey;
  98339. for (z = minZoom; z <= maxZoom; ++z) {
  98340. zKey = z.toString();
  98341. tileRanges[zKey] =
  98342. [tileGrid.getTileRangeForExtentAndZ(attributionExtent, z)];
  98343. }
  98344. this.setAttributions([
  98345. new ol.Attribution({
  98346. html: tileJSON.attribution,
  98347. tileRanges: tileRanges
  98348. })
  98349. ]);
  98350. }
  98351. this.setState(ol.source.State.READY);
  98352. };
  98353. /**
  98354. * @inheritDoc
  98355. */
  98356. ol.source.TileUTFGrid.prototype.getTile =
  98357. function(z, x, y, pixelRatio, projection) {
  98358. var tileCoordKey = this.getKeyZXY(z, x, y);
  98359. if (this.tileCache.containsKey(tileCoordKey)) {
  98360. return /** @type {!ol.Tile} */ (this.tileCache.get(tileCoordKey));
  98361. } else {
  98362. goog.asserts.assert(projection, 'argument projection is truthy');
  98363. var tileCoord = [z, x, y];
  98364. var urlTileCoord =
  98365. this.getTileCoordForTileUrlFunction(tileCoord, projection);
  98366. var tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection);
  98367. var tile = new ol.source.TileUTFGridTile_(
  98368. tileCoord,
  98369. tileUrl !== undefined ? ol.TileState.IDLE : ol.TileState.EMPTY,
  98370. tileUrl !== undefined ? tileUrl : '',
  98371. this.tileGrid.getTileCoordExtent(tileCoord),
  98372. this.preemptive_);
  98373. this.tileCache.set(tileCoordKey, tile);
  98374. return tile;
  98375. }
  98376. };
  98377. /**
  98378. * @inheritDoc
  98379. */
  98380. ol.source.TileUTFGrid.prototype.useTile = function(z, x, y) {
  98381. var tileCoordKey = this.getKeyZXY(z, x, y);
  98382. if (this.tileCache.containsKey(tileCoordKey)) {
  98383. this.tileCache.get(tileCoordKey);
  98384. }
  98385. };
  98386. /**
  98387. * @constructor
  98388. * @extends {ol.Tile}
  98389. * @param {ol.TileCoord} tileCoord Tile coordinate.
  98390. * @param {ol.TileState} state State.
  98391. * @param {string} src Image source URI.
  98392. * @param {ol.Extent} extent Extent of the tile.
  98393. * @param {boolean} preemptive Load the tile when visible (before it's needed).
  98394. * @private
  98395. */
  98396. ol.source.TileUTFGridTile_ =
  98397. function(tileCoord, state, src, extent, preemptive) {
  98398. goog.base(this, tileCoord, state);
  98399. /**
  98400. * @private
  98401. * @type {string}
  98402. */
  98403. this.src_ = src;
  98404. /**
  98405. * @private
  98406. * @type {ol.Extent}
  98407. */
  98408. this.extent_ = extent;
  98409. /**
  98410. * @private
  98411. * @type {boolean}
  98412. */
  98413. this.preemptive_ = preemptive;
  98414. /**
  98415. * @private
  98416. * @type {Array.<string>}
  98417. */
  98418. this.grid_ = null;
  98419. /**
  98420. * @private
  98421. * @type {Array.<string>}
  98422. */
  98423. this.keys_ = null;
  98424. /**
  98425. * @private
  98426. * @type {Object.<string, Object>|undefined}
  98427. */
  98428. this.data_ = null;
  98429. };
  98430. goog.inherits(ol.source.TileUTFGridTile_, ol.Tile);
  98431. /**
  98432. * @inheritDoc
  98433. */
  98434. ol.source.TileUTFGridTile_.prototype.getImage = function(opt_context) {
  98435. return null;
  98436. };
  98437. /**
  98438. * Synchronously returns data at given coordinate (if available).
  98439. * @param {ol.Coordinate} coordinate Coordinate.
  98440. * @return {Object}
  98441. */
  98442. ol.source.TileUTFGridTile_.prototype.getData = function(coordinate) {
  98443. if (!this.grid_ || !this.keys_ || !this.data_) {
  98444. return null;
  98445. }
  98446. var xRelative = (coordinate[0] - this.extent_[0]) /
  98447. (this.extent_[2] - this.extent_[0]);
  98448. var yRelative = (coordinate[1] - this.extent_[1]) /
  98449. (this.extent_[3] - this.extent_[1]);
  98450. var row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)];
  98451. if (!goog.isString(row)) {
  98452. return null;
  98453. }
  98454. var code = row.charCodeAt(Math.floor(xRelative * row.length));
  98455. if (code >= 93) {
  98456. code--;
  98457. }
  98458. if (code >= 35) {
  98459. code--;
  98460. }
  98461. code -= 32;
  98462. return (code in this.keys_) ? this.data_[this.keys_[code]] : null;
  98463. };
  98464. /**
  98465. * Calls the callback (synchronously by default) with the available data
  98466. * for given coordinate (or `null` if not yet loaded).
  98467. * @param {ol.Coordinate} coordinate Coordinate.
  98468. * @param {function(this: T, Object)} callback Callback.
  98469. * @param {T=} opt_this The object to use as `this` in the callback.
  98470. * @param {boolean=} opt_request If `true` the callback is always async.
  98471. * The tile data is requested if not yet loaded.
  98472. * @template T
  98473. */
  98474. ol.source.TileUTFGridTile_.prototype.forDataAtCoordinate =
  98475. function(coordinate, callback, opt_this, opt_request) {
  98476. if (this.state == ol.TileState.IDLE && opt_request === true) {
  98477. goog.events.listenOnce(this, goog.events.EventType.CHANGE, function(e) {
  98478. callback.call(opt_this, this.getData(coordinate));
  98479. }, false, this);
  98480. this.loadInternal_();
  98481. } else {
  98482. if (opt_request === true) {
  98483. goog.async.nextTick(function() {
  98484. callback.call(opt_this, this.getData(coordinate));
  98485. }, this);
  98486. } else {
  98487. callback.call(opt_this, this.getData(coordinate));
  98488. }
  98489. }
  98490. };
  98491. /**
  98492. * @inheritDoc
  98493. */
  98494. ol.source.TileUTFGridTile_.prototype.getKey = function() {
  98495. return this.src_;
  98496. };
  98497. /**
  98498. * @private
  98499. */
  98500. ol.source.TileUTFGridTile_.prototype.handleError_ = function() {
  98501. this.state = ol.TileState.ERROR;
  98502. this.changed();
  98503. };
  98504. /**
  98505. * @param {!UTFGridJSON} json
  98506. * @private
  98507. */
  98508. ol.source.TileUTFGridTile_.prototype.handleLoad_ = function(json) {
  98509. this.grid_ = json.grid;
  98510. this.keys_ = json.keys;
  98511. this.data_ = json.data;
  98512. this.state = ol.TileState.EMPTY;
  98513. this.changed();
  98514. };
  98515. /**
  98516. * @private
  98517. */
  98518. ol.source.TileUTFGridTile_.prototype.loadInternal_ = function() {
  98519. if (this.state == ol.TileState.IDLE) {
  98520. this.state = ol.TileState.LOADING;
  98521. var request = new goog.net.Jsonp(this.src_);
  98522. request.send(undefined, goog.bind(this.handleLoad_, this),
  98523. goog.bind(this.handleError_, this));
  98524. }
  98525. };
  98526. /**
  98527. * Load not yet loaded URI.
  98528. */
  98529. ol.source.TileUTFGridTile_.prototype.load = function() {
  98530. if (this.preemptive_) {
  98531. this.loadInternal_();
  98532. }
  98533. };
  98534. goog.provide('ol.source.TileVector');
  98535. goog.require('goog.array');
  98536. goog.require('goog.asserts');
  98537. goog.require('goog.object');
  98538. goog.require('ol.TileUrlFunction');
  98539. goog.require('ol.featureloader');
  98540. goog.require('ol.source.State');
  98541. goog.require('ol.source.Vector');
  98542. goog.require('ol.tilecoord');
  98543. goog.require('ol.tilegrid.TileGrid');
  98544. /**
  98545. * @classdesc
  98546. * A vector source in one of the supported formats, where the data is divided
  98547. * into tiles in a fixed grid pattern.
  98548. *
  98549. * @constructor
  98550. * @extends {ol.source.Vector}
  98551. * @param {olx.source.TileVectorOptions} options Options.
  98552. * @api
  98553. */
  98554. ol.source.TileVector = function(options) {
  98555. goog.base(this, {
  98556. attributions: options.attributions,
  98557. logo: options.logo,
  98558. projection: undefined,
  98559. state: ol.source.State.READY,
  98560. wrapX: options.wrapX
  98561. });
  98562. /**
  98563. * @private
  98564. * @type {ol.format.Feature|undefined}
  98565. */
  98566. this.format_ = options.format !== undefined ? options.format : null;
  98567. /**
  98568. * @private
  98569. * @type {ol.tilegrid.TileGrid}
  98570. */
  98571. this.tileGrid_ = options.tileGrid;
  98572. /**
  98573. * @private
  98574. * @type {ol.TileUrlFunctionType}
  98575. */
  98576. this.tileUrlFunction_ = ol.TileUrlFunction.nullTileUrlFunction;
  98577. /**
  98578. * @private
  98579. * @type {?ol.TileVectorLoadFunctionType}
  98580. */
  98581. this.tileLoadFunction_ = options.tileLoadFunction !== undefined ?
  98582. options.tileLoadFunction : null;
  98583. goog.asserts.assert(this.format_ || this.tileLoadFunction_,
  98584. 'Either format or tileLoadFunction are required');
  98585. /**
  98586. * @private
  98587. * @type {Object.<string, Array.<ol.Feature>>}
  98588. */
  98589. this.tiles_ = {};
  98590. if (options.tileUrlFunction !== undefined) {
  98591. this.setTileUrlFunction(options.tileUrlFunction);
  98592. } else if (options.urls !== undefined) {
  98593. this.setUrls(options.urls);
  98594. } else if (options.url !== undefined) {
  98595. this.setUrl(options.url);
  98596. }
  98597. };
  98598. goog.inherits(ol.source.TileVector, ol.source.Vector);
  98599. /**
  98600. * @inheritDoc
  98601. */
  98602. ol.source.TileVector.prototype.addFeature = goog.abstractMethod;
  98603. /**
  98604. * @inheritDoc
  98605. */
  98606. ol.source.TileVector.prototype.addFeatures = goog.abstractMethod;
  98607. /**
  98608. * @inheritDoc
  98609. */
  98610. ol.source.TileVector.prototype.clear = function() {
  98611. goog.object.clear(this.tiles_);
  98612. };
  98613. /**
  98614. * @inheritDoc
  98615. */
  98616. ol.source.TileVector.prototype.forEachFeature = goog.abstractMethod;
  98617. /**
  98618. * Iterate through all features whose geometries contain the provided
  98619. * coordinate at the provided resolution, calling the callback with each
  98620. * feature. If the callback returns a "truthy" value, iteration will stop and
  98621. * the function will return the same value.
  98622. *
  98623. * @param {ol.Coordinate} coordinate Coordinate.
  98624. * @param {number} resolution Resolution.
  98625. * @param {function(this: T, ol.Feature): S} callback Called with each feature
  98626. * whose goemetry contains the provided coordinate.
  98627. * @param {T=} opt_this The object to use as `this` in the callback.
  98628. * @return {S|undefined} The return value from the last call to the callback.
  98629. * @template T,S
  98630. */
  98631. ol.source.TileVector.prototype.forEachFeatureAtCoordinateAndResolution =
  98632. function(coordinate, resolution, callback, opt_this) {
  98633. var tileGrid = this.tileGrid_;
  98634. var tiles = this.tiles_;
  98635. var tileCoord = tileGrid.getTileCoordForCoordAndResolution(coordinate,
  98636. resolution);
  98637. var tileKey = this.getTileKeyZXY_(tileCoord[0], tileCoord[1], tileCoord[2]);
  98638. var features = tiles[tileKey];
  98639. if (features !== undefined) {
  98640. var i, ii;
  98641. for (i = 0, ii = features.length; i < ii; ++i) {
  98642. var feature = features[i];
  98643. var geometry = feature.getGeometry();
  98644. goog.asserts.assert(geometry, 'feature geometry is defined and not null');
  98645. if (geometry.containsCoordinate(coordinate)) {
  98646. var result = callback.call(opt_this, feature);
  98647. if (result) {
  98648. return result;
  98649. }
  98650. }
  98651. }
  98652. }
  98653. return undefined;
  98654. };
  98655. /**
  98656. * @inheritDoc
  98657. */
  98658. ol.source.TileVector.prototype.forEachFeatureInExtent = goog.abstractMethod;
  98659. /**
  98660. * @inheritDoc
  98661. */
  98662. ol.source.TileVector.prototype.forEachFeatureInExtentAtResolution =
  98663. function(extent, resolution, f, opt_this) {
  98664. var tileGrid = this.tileGrid_;
  98665. var tiles = this.tiles_;
  98666. var z = tileGrid.getZForResolution(resolution);
  98667. var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  98668. var x, y;
  98669. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  98670. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  98671. var tileKey = this.getTileKeyZXY_(z, x, y);
  98672. var features = tiles[tileKey];
  98673. if (features !== undefined) {
  98674. var i, ii;
  98675. for (i = 0, ii = features.length; i < ii; ++i) {
  98676. var result = f.call(opt_this, features[i]);
  98677. if (result) {
  98678. return result;
  98679. }
  98680. }
  98681. }
  98682. }
  98683. }
  98684. return undefined;
  98685. };
  98686. /**
  98687. * @inheritDoc
  98688. */
  98689. ol.source.TileVector.prototype.getClosestFeatureToCoordinate =
  98690. goog.abstractMethod;
  98691. /**
  98692. * @inheritDoc
  98693. */
  98694. ol.source.TileVector.prototype.getExtent = goog.abstractMethod;
  98695. /**
  98696. * Return the features of the TileVector source.
  98697. * @inheritDoc
  98698. * @api
  98699. */
  98700. ol.source.TileVector.prototype.getFeatures = function() {
  98701. var tiles = this.tiles_;
  98702. var features = [];
  98703. var tileKey;
  98704. for (tileKey in tiles) {
  98705. goog.array.extend(features, tiles[tileKey]);
  98706. }
  98707. return features;
  98708. };
  98709. /**
  98710. * Get all features whose geometry intersects the provided coordinate for the
  98711. * provided resolution.
  98712. * @param {ol.Coordinate} coordinate Coordinate.
  98713. * @param {number} resolution Resolution.
  98714. * @return {Array.<ol.Feature>} Features.
  98715. * @api
  98716. */
  98717. ol.source.TileVector.prototype.getFeaturesAtCoordinateAndResolution =
  98718. function(coordinate, resolution) {
  98719. var features = [];
  98720. this.forEachFeatureAtCoordinateAndResolution(coordinate, resolution,
  98721. /**
  98722. * @param {ol.Feature} feature Feature.
  98723. */
  98724. function(feature) {
  98725. features.push(feature);
  98726. });
  98727. return features;
  98728. };
  98729. /**
  98730. * @inheritDoc
  98731. */
  98732. ol.source.TileVector.prototype.getFeaturesInExtent = goog.abstractMethod;
  98733. /**
  98734. * Handles x-axis wrapping and returns a tile coordinate transformed from the
  98735. * internal tile scheme to the tile grid's tile scheme. When the tile coordinate
  98736. * is outside the resolution and extent range of the tile grid, `null` will be
  98737. * returned.
  98738. * @param {ol.TileCoord} tileCoord Tile coordinate.
  98739. * @param {ol.proj.Projection} projection Projection.
  98740. * @return {ol.TileCoord} Tile coordinate to be passed to the tileUrlFunction or
  98741. * null if no tile URL should be created for the passed `tileCoord`.
  98742. */
  98743. ol.source.TileVector.prototype.getTileCoordForTileUrlFunction =
  98744. function(tileCoord, projection) {
  98745. var tileGrid = this.tileGrid_;
  98746. goog.asserts.assert(tileGrid, 'tile grid needed');
  98747. if (this.getWrapX() && projection.isGlobal()) {
  98748. tileCoord = ol.tilecoord.wrapX(tileCoord, tileGrid, projection);
  98749. }
  98750. return ol.tilecoord.withinExtentAndZ(tileCoord, tileGrid) ?
  98751. tileCoord : null;
  98752. };
  98753. /**
  98754. * @param {number} z Z.
  98755. * @param {number} x X.
  98756. * @param {number} y Y.
  98757. * @private
  98758. * @return {string} Tile key.
  98759. */
  98760. ol.source.TileVector.prototype.getTileKeyZXY_ = function(z, x, y) {
  98761. return z + '/' + x + '/' + y;
  98762. };
  98763. /**
  98764. * @inheritDoc
  98765. */
  98766. ol.source.TileVector.prototype.loadFeatures =
  98767. function(extent, resolution, projection) {
  98768. var tileGrid = this.tileGrid_;
  98769. var tileUrlFunction = this.tileUrlFunction_;
  98770. var tiles = this.tiles_;
  98771. var z = tileGrid.getZForResolution(resolution);
  98772. var tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  98773. var tileCoord = [z, 0, 0];
  98774. var x, y;
  98775. /**
  98776. * @param {string} tileKey Tile key.
  98777. * @param {Array.<ol.Feature>} features Features.
  98778. * @this {ol.source.TileVector}
  98779. */
  98780. function success(tileKey, features) {
  98781. tiles[tileKey] = features;
  98782. this.changed();
  98783. }
  98784. for (x = tileRange.minX; x <= tileRange.maxX; ++x) {
  98785. for (y = tileRange.minY; y <= tileRange.maxY; ++y) {
  98786. var tileKey = this.getTileKeyZXY_(z, x, y);
  98787. if (!(tileKey in tiles)) {
  98788. tileCoord[1] = x;
  98789. tileCoord[2] = y;
  98790. var urlTileCoord = this.getTileCoordForTileUrlFunction(
  98791. tileCoord, projection);
  98792. var url = !urlTileCoord ? undefined :
  98793. tileUrlFunction(urlTileCoord, 1, projection);
  98794. if (url !== undefined) {
  98795. tiles[tileKey] = [];
  98796. var tileSuccess = goog.partial(success, tileKey);
  98797. if (this.tileLoadFunction_) {
  98798. this.tileLoadFunction_(url, goog.bind(tileSuccess, this));
  98799. } else {
  98800. var loader = ol.featureloader.loadFeaturesXhr(url,
  98801. /** @type {ol.format.Feature} */ (this.format_), tileSuccess);
  98802. loader.call(this, extent, resolution, projection);
  98803. }
  98804. }
  98805. }
  98806. }
  98807. }
  98808. };
  98809. /**
  98810. * @inheritDoc
  98811. */
  98812. ol.source.TileVector.prototype.removeFeature = goog.abstractMethod;
  98813. /**
  98814. * @param {ol.TileUrlFunctionType} tileUrlFunction Tile URL function.
  98815. */
  98816. ol.source.TileVector.prototype.setTileUrlFunction = function(tileUrlFunction) {
  98817. this.tileUrlFunction_ = tileUrlFunction;
  98818. this.changed();
  98819. };
  98820. /**
  98821. * @param {string} url URL.
  98822. */
  98823. ol.source.TileVector.prototype.setUrl = function(url) {
  98824. this.setTileUrlFunction(ol.TileUrlFunction.createFromTemplates(
  98825. ol.TileUrlFunction.expandUrl(url), this.tileGrid_));
  98826. };
  98827. /**
  98828. * @param {Array.<string>} urls URLs.
  98829. */
  98830. ol.source.TileVector.prototype.setUrls = function(urls) {
  98831. this.setTileUrlFunction(
  98832. ol.TileUrlFunction.createFromTemplates(urls, this.tileGrid_));
  98833. };
  98834. // FIXME add minZoom support
  98835. // FIXME add date line wrap (tile coord transform)
  98836. // FIXME cannot be shared between maps with different projections
  98837. goog.provide('ol.source.TileWMS');
  98838. goog.require('goog.asserts');
  98839. goog.require('goog.math');
  98840. goog.require('goog.object');
  98841. goog.require('goog.string');
  98842. goog.require('goog.uri.utils');
  98843. goog.require('ol');
  98844. goog.require('ol.TileCoord');
  98845. goog.require('ol.TileUrlFunction');
  98846. goog.require('ol.extent');
  98847. goog.require('ol.proj');
  98848. goog.require('ol.size');
  98849. goog.require('ol.source.TileImage');
  98850. goog.require('ol.source.wms');
  98851. goog.require('ol.source.wms.ServerType');
  98852. goog.require('ol.tilecoord');
  98853. /**
  98854. * @classdesc
  98855. * Layer source for tile data from WMS servers.
  98856. *
  98857. * @constructor
  98858. * @extends {ol.source.TileImage}
  98859. * @param {olx.source.TileWMSOptions=} opt_options Tile WMS options.
  98860. * @api stable
  98861. */
  98862. ol.source.TileWMS = function(opt_options) {
  98863. var options = opt_options || {};
  98864. var params = options.params !== undefined ? options.params : {};
  98865. var transparent = goog.object.get(params, 'TRANSPARENT', true);
  98866. goog.base(this, {
  98867. attributions: options.attributions,
  98868. crossOrigin: options.crossOrigin,
  98869. logo: options.logo,
  98870. opaque: !transparent,
  98871. projection: options.projection,
  98872. tileGrid: options.tileGrid,
  98873. tileLoadFunction: options.tileLoadFunction,
  98874. tileUrlFunction: goog.bind(this.tileUrlFunction_, this),
  98875. wrapX: options.wrapX !== undefined ? options.wrapX : true
  98876. });
  98877. var urls = options.urls;
  98878. if (urls === undefined && options.url !== undefined) {
  98879. urls = ol.TileUrlFunction.expandUrl(options.url);
  98880. }
  98881. /**
  98882. * @private
  98883. * @type {!Array.<string>}
  98884. */
  98885. this.urls_ = urls || [];
  98886. /**
  98887. * @private
  98888. * @type {number}
  98889. */
  98890. this.gutter_ = options.gutter !== undefined ? options.gutter : 0;
  98891. /**
  98892. * @private
  98893. * @type {Object}
  98894. */
  98895. this.params_ = params;
  98896. /**
  98897. * @private
  98898. * @type {boolean}
  98899. */
  98900. this.v13_ = true;
  98901. /**
  98902. * @private
  98903. * @type {ol.source.wms.ServerType|undefined}
  98904. */
  98905. this.serverType_ =
  98906. /** @type {ol.source.wms.ServerType|undefined} */ (options.serverType);
  98907. /**
  98908. * @private
  98909. * @type {boolean}
  98910. */
  98911. this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;
  98912. /**
  98913. * @private
  98914. * @type {string}
  98915. */
  98916. this.coordKeyPrefix_ = '';
  98917. this.resetCoordKeyPrefix_();
  98918. /**
  98919. * @private
  98920. * @type {ol.Extent}
  98921. */
  98922. this.tmpExtent_ = ol.extent.createEmpty();
  98923. this.updateV13_();
  98924. };
  98925. goog.inherits(ol.source.TileWMS, ol.source.TileImage);
  98926. /**
  98927. * Return the GetFeatureInfo URL for the passed coordinate, resolution, and
  98928. * projection. Return `undefined` if the GetFeatureInfo URL cannot be
  98929. * constructed.
  98930. * @param {ol.Coordinate} coordinate Coordinate.
  98931. * @param {number} resolution Resolution.
  98932. * @param {ol.proj.ProjectionLike} projection Projection.
  98933. * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should
  98934. * be provided. If `QUERY_LAYERS` is not provided then the layers specified
  98935. * in the `LAYERS` parameter will be used. `VERSION` should not be
  98936. * specified here.
  98937. * @return {string|undefined} GetFeatureInfo URL.
  98938. * @api stable
  98939. */
  98940. ol.source.TileWMS.prototype.getGetFeatureInfoUrl =
  98941. function(coordinate, resolution, projection, params) {
  98942. goog.asserts.assert(!('VERSION' in params),
  98943. 'key VERSION is not allowed in params');
  98944. var projectionObj = ol.proj.get(projection);
  98945. var tileGrid = this.getTileGrid();
  98946. if (!tileGrid) {
  98947. tileGrid = this.getTileGridForProjection(projectionObj);
  98948. }
  98949. var tileCoord = tileGrid.getTileCoordForCoordAndResolution(
  98950. coordinate, resolution);
  98951. if (tileGrid.getResolutions().length <= tileCoord[0]) {
  98952. return undefined;
  98953. }
  98954. var tileResolution = tileGrid.getResolution(tileCoord[0]);
  98955. var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);
  98956. var tileSize = ol.size.toSize(
  98957. tileGrid.getTileSize(tileCoord[0]), this.tmpSize);
  98958. var gutter = this.gutter_;
  98959. if (gutter !== 0) {
  98960. tileSize = ol.size.buffer(tileSize, gutter, this.tmpSize);
  98961. tileExtent = ol.extent.buffer(tileExtent,
  98962. tileResolution * gutter, tileExtent);
  98963. }
  98964. var baseParams = {
  98965. 'SERVICE': 'WMS',
  98966. 'VERSION': ol.DEFAULT_WMS_VERSION,
  98967. 'REQUEST': 'GetFeatureInfo',
  98968. 'FORMAT': 'image/png',
  98969. 'TRANSPARENT': true,
  98970. 'QUERY_LAYERS': this.params_['LAYERS']
  98971. };
  98972. goog.object.extend(baseParams, this.params_, params);
  98973. var x = Math.floor((coordinate[0] - tileExtent[0]) / tileResolution);
  98974. var y = Math.floor((tileExtent[3] - coordinate[1]) / tileResolution);
  98975. baseParams[this.v13_ ? 'I' : 'X'] = x;
  98976. baseParams[this.v13_ ? 'J' : 'Y'] = y;
  98977. return this.getRequestUrl_(tileCoord, tileSize, tileExtent,
  98978. 1, projectionObj, baseParams);
  98979. };
  98980. /**
  98981. * @inheritDoc
  98982. */
  98983. ol.source.TileWMS.prototype.getGutter = function() {
  98984. return this.gutter_;
  98985. };
  98986. /**
  98987. * @inheritDoc
  98988. */
  98989. ol.source.TileWMS.prototype.getKeyZXY = function(z, x, y) {
  98990. return this.coordKeyPrefix_ + goog.base(this, 'getKeyZXY', z, x, y);
  98991. };
  98992. /**
  98993. * Get the user-provided params, i.e. those passed to the constructor through
  98994. * the "params" option, and possibly updated using the updateParams method.
  98995. * @return {Object} Params.
  98996. * @api stable
  98997. */
  98998. ol.source.TileWMS.prototype.getParams = function() {
  98999. return this.params_;
  99000. };
  99001. /**
  99002. * @param {ol.TileCoord} tileCoord Tile coordinate.
  99003. * @param {ol.Size} tileSize Tile size.
  99004. * @param {ol.Extent} tileExtent Tile extent.
  99005. * @param {number} pixelRatio Pixel ratio.
  99006. * @param {ol.proj.Projection} projection Projection.
  99007. * @param {Object} params Params.
  99008. * @return {string|undefined} Request URL.
  99009. * @private
  99010. */
  99011. ol.source.TileWMS.prototype.getRequestUrl_ =
  99012. function(tileCoord, tileSize, tileExtent,
  99013. pixelRatio, projection, params) {
  99014. var urls = this.urls_;
  99015. if (urls.length === 0) {
  99016. return undefined;
  99017. }
  99018. params['WIDTH'] = tileSize[0];
  99019. params['HEIGHT'] = tileSize[1];
  99020. params[this.v13_ ? 'CRS' : 'SRS'] = projection.getCode();
  99021. if (!('STYLES' in this.params_)) {
  99022. /* jshint -W053 */
  99023. params['STYLES'] = new String('');
  99024. /* jshint +W053 */
  99025. }
  99026. if (pixelRatio != 1) {
  99027. switch (this.serverType_) {
  99028. case ol.source.wms.ServerType.GEOSERVER:
  99029. var dpi = (90 * pixelRatio + 0.5) | 0;
  99030. if ('FORMAT_OPTIONS' in params) {
  99031. params['FORMAT_OPTIONS'] += ';dpi:' + dpi;
  99032. } else {
  99033. params['FORMAT_OPTIONS'] = 'dpi:' + dpi;
  99034. }
  99035. break;
  99036. case ol.source.wms.ServerType.MAPSERVER:
  99037. params['MAP_RESOLUTION'] = 90 * pixelRatio;
  99038. break;
  99039. case ol.source.wms.ServerType.CARMENTA_SERVER:
  99040. case ol.source.wms.ServerType.QGIS:
  99041. params['DPI'] = 90 * pixelRatio;
  99042. break;
  99043. default:
  99044. goog.asserts.fail('unknown serverType configured');
  99045. break;
  99046. }
  99047. }
  99048. var axisOrientation = projection.getAxisOrientation();
  99049. var bbox = tileExtent;
  99050. if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') {
  99051. var tmp;
  99052. tmp = tileExtent[0];
  99053. bbox[0] = tileExtent[1];
  99054. bbox[1] = tmp;
  99055. tmp = tileExtent[2];
  99056. bbox[2] = tileExtent[3];
  99057. bbox[3] = tmp;
  99058. }
  99059. params['BBOX'] = bbox.join(',');
  99060. var url;
  99061. if (urls.length == 1) {
  99062. url = urls[0];
  99063. } else {
  99064. var index = goog.math.modulo(ol.tilecoord.hash(tileCoord), urls.length);
  99065. url = urls[index];
  99066. }
  99067. return goog.uri.utils.appendParamsFromMap(url, params);
  99068. };
  99069. /**
  99070. * @param {number} z Z.
  99071. * @param {number} pixelRatio Pixel ratio.
  99072. * @param {ol.proj.Projection} projection Projection.
  99073. * @return {ol.Size} Size.
  99074. */
  99075. ol.source.TileWMS.prototype.getTilePixelSize =
  99076. function(z, pixelRatio, projection) {
  99077. var tileSize = goog.base(this, 'getTilePixelSize', z, pixelRatio, projection);
  99078. if (pixelRatio == 1 || !this.hidpi_ || this.serverType_ === undefined) {
  99079. return tileSize;
  99080. } else {
  99081. return ol.size.scale(tileSize, pixelRatio, this.tmpSize);
  99082. }
  99083. };
  99084. /**
  99085. * Return the URLs used for this WMS source.
  99086. * @return {!Array.<string>} URLs.
  99087. * @api stable
  99088. */
  99089. ol.source.TileWMS.prototype.getUrls = function() {
  99090. return this.urls_;
  99091. };
  99092. /**
  99093. * @private
  99094. */
  99095. ol.source.TileWMS.prototype.resetCoordKeyPrefix_ = function() {
  99096. var i = 0;
  99097. var res = [];
  99098. var j, jj;
  99099. for (j = 0, jj = this.urls_.length; j < jj; ++j) {
  99100. res[i++] = this.urls_[j];
  99101. }
  99102. var key;
  99103. for (key in this.params_) {
  99104. res[i++] = key + '-' + this.params_[key];
  99105. }
  99106. this.coordKeyPrefix_ = res.join('#');
  99107. };
  99108. /**
  99109. * Set the URL to use for requests.
  99110. * @param {string|undefined} url URL.
  99111. * @api stable
  99112. */
  99113. ol.source.TileWMS.prototype.setUrl = function(url) {
  99114. var urls = url !== undefined ? ol.TileUrlFunction.expandUrl(url) : null;
  99115. this.setUrls(urls);
  99116. };
  99117. /**
  99118. * Set the URLs to use for requests.
  99119. * @param {Array.<string>|undefined} urls URLs.
  99120. * @api stable
  99121. */
  99122. ol.source.TileWMS.prototype.setUrls = function(urls) {
  99123. this.urls_ = urls || [];
  99124. this.resetCoordKeyPrefix_();
  99125. this.changed();
  99126. };
  99127. /**
  99128. * @param {ol.TileCoord} tileCoord Tile coordinate.
  99129. * @param {number} pixelRatio Pixel ratio.
  99130. * @param {ol.proj.Projection} projection Projection.
  99131. * @return {string|undefined} Tile URL.
  99132. * @private
  99133. */
  99134. ol.source.TileWMS.prototype.tileUrlFunction_ =
  99135. function(tileCoord, pixelRatio, projection) {
  99136. var tileGrid = this.getTileGrid();
  99137. if (!tileGrid) {
  99138. tileGrid = this.getTileGridForProjection(projection);
  99139. }
  99140. if (tileGrid.getResolutions().length <= tileCoord[0]) {
  99141. return undefined;
  99142. }
  99143. if (pixelRatio != 1 && (!this.hidpi_ || this.serverType_ === undefined)) {
  99144. pixelRatio = 1;
  99145. }
  99146. var tileResolution = tileGrid.getResolution(tileCoord[0]);
  99147. var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);
  99148. var tileSize = ol.size.toSize(
  99149. tileGrid.getTileSize(tileCoord[0]), this.tmpSize);
  99150. var gutter = this.gutter_;
  99151. if (gutter !== 0) {
  99152. tileSize = ol.size.buffer(tileSize, gutter, this.tmpSize);
  99153. tileExtent = ol.extent.buffer(tileExtent,
  99154. tileResolution * gutter, tileExtent);
  99155. }
  99156. if (pixelRatio != 1) {
  99157. tileSize = ol.size.scale(tileSize, pixelRatio, this.tmpSize);
  99158. }
  99159. var baseParams = {
  99160. 'SERVICE': 'WMS',
  99161. 'VERSION': ol.DEFAULT_WMS_VERSION,
  99162. 'REQUEST': 'GetMap',
  99163. 'FORMAT': 'image/png',
  99164. 'TRANSPARENT': true
  99165. };
  99166. goog.object.extend(baseParams, this.params_);
  99167. return this.getRequestUrl_(tileCoord, tileSize, tileExtent,
  99168. pixelRatio, projection, baseParams);
  99169. };
  99170. /**
  99171. * Update the user-provided params.
  99172. * @param {Object} params Params.
  99173. * @api stable
  99174. */
  99175. ol.source.TileWMS.prototype.updateParams = function(params) {
  99176. goog.object.extend(this.params_, params);
  99177. this.resetCoordKeyPrefix_();
  99178. this.updateV13_();
  99179. this.changed();
  99180. };
  99181. /**
  99182. * @private
  99183. */
  99184. ol.source.TileWMS.prototype.updateV13_ = function() {
  99185. var version =
  99186. goog.object.get(this.params_, 'VERSION', ol.DEFAULT_WMS_VERSION);
  99187. this.v13_ = goog.string.compareVersions(version, '1.3') >= 0;
  99188. };
  99189. goog.provide('ol.tilegrid.WMTS');
  99190. goog.require('goog.array');
  99191. goog.require('goog.asserts');
  99192. goog.require('ol.proj');
  99193. goog.require('ol.tilegrid.TileGrid');
  99194. /**
  99195. * @classdesc
  99196. * Set the grid pattern for sources accessing WMTS tiled-image servers.
  99197. *
  99198. * @constructor
  99199. * @extends {ol.tilegrid.TileGrid}
  99200. * @param {olx.tilegrid.WMTSOptions} options WMTS options.
  99201. * @struct
  99202. * @api
  99203. */
  99204. ol.tilegrid.WMTS = function(options) {
  99205. goog.asserts.assert(
  99206. options.resolutions.length == options.matrixIds.length,
  99207. 'options resolutions and matrixIds must have equal length (%s == %s)',
  99208. options.resolutions.length, options.matrixIds.length);
  99209. /**
  99210. * @private
  99211. * @type {!Array.<string>}
  99212. */
  99213. this.matrixIds_ = options.matrixIds;
  99214. // FIXME: should the matrixIds become optionnal?
  99215. goog.base(this, {
  99216. extent: options.extent,
  99217. origin: options.origin,
  99218. origins: options.origins,
  99219. resolutions: options.resolutions,
  99220. tileSize: options.tileSize,
  99221. tileSizes: options.tileSizes,
  99222. sizes: options.sizes
  99223. });
  99224. };
  99225. goog.inherits(ol.tilegrid.WMTS, ol.tilegrid.TileGrid);
  99226. /**
  99227. * @param {number} z Z.
  99228. * @return {string} MatrixId..
  99229. */
  99230. ol.tilegrid.WMTS.prototype.getMatrixId = function(z) {
  99231. goog.asserts.assert(0 <= z && z < this.matrixIds_.length,
  99232. 'attempted to retrive matrixId for illegal z (%s)', z);
  99233. return this.matrixIds_[z];
  99234. };
  99235. /**
  99236. * Get the list of matrix identifiers.
  99237. * @return {Array.<string>} MatrixIds.
  99238. * @api
  99239. */
  99240. ol.tilegrid.WMTS.prototype.getMatrixIds = function() {
  99241. return this.matrixIds_;
  99242. };
  99243. /**
  99244. * Create a tile grid from a WMTS capabilities matrix set.
  99245. * @param {Object} matrixSet An object representing a matrixSet in the
  99246. * capabilities document.
  99247. * @param {ol.Extent=} opt_extent An optional extent to restrict the tile
  99248. * ranges the server provides.
  99249. * @return {ol.tilegrid.WMTS} WMTS tileGrid instance.
  99250. * @api
  99251. */
  99252. ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet =
  99253. function(matrixSet, opt_extent) {
  99254. /** @type {!Array.<number>} */
  99255. var resolutions = [];
  99256. /** @type {!Array.<string>} */
  99257. var matrixIds = [];
  99258. /** @type {!Array.<ol.Coordinate>} */
  99259. var origins = [];
  99260. /** @type {!Array.<ol.Size>} */
  99261. var tileSizes = [];
  99262. /** @type {!Array.<ol.Size>} */
  99263. var sizes = [];
  99264. var supportedCRSPropName = 'SupportedCRS';
  99265. var matrixIdsPropName = 'TileMatrix';
  99266. var identifierPropName = 'Identifier';
  99267. var scaleDenominatorPropName = 'ScaleDenominator';
  99268. var topLeftCornerPropName = 'TopLeftCorner';
  99269. var tileWidthPropName = 'TileWidth';
  99270. var tileHeightPropName = 'TileHeight';
  99271. var projection;
  99272. projection = ol.proj.get(matrixSet[supportedCRSPropName].replace(
  99273. /urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3'));
  99274. var metersPerUnit = projection.getMetersPerUnit();
  99275. // swap origin x and y coordinates if axis orientation is lat/long
  99276. var switchOriginXY = projection.getAxisOrientation().substr(0, 2) == 'ne';
  99277. goog.array.sort(matrixSet[matrixIdsPropName], function(a, b) {
  99278. return b[scaleDenominatorPropName] - a[scaleDenominatorPropName];
  99279. });
  99280. matrixSet[matrixIdsPropName].forEach(function(elt, index, array) {
  99281. matrixIds.push(elt[identifierPropName]);
  99282. var resolution = elt[scaleDenominatorPropName] * 0.28E-3 / metersPerUnit;
  99283. var tileWidth = elt[tileWidthPropName];
  99284. var tileHeight = elt[tileHeightPropName];
  99285. if (switchOriginXY) {
  99286. origins.push([elt[topLeftCornerPropName][1],
  99287. elt[topLeftCornerPropName][0]]);
  99288. } else {
  99289. origins.push(elt[topLeftCornerPropName]);
  99290. }
  99291. resolutions.push(resolution);
  99292. tileSizes.push(tileWidth == tileHeight ?
  99293. tileWidth : [tileWidth, tileHeight]);
  99294. // top-left origin, so height is negative
  99295. sizes.push([elt['MatrixWidth'], -elt['MatrixHeight']]);
  99296. });
  99297. return new ol.tilegrid.WMTS({
  99298. extent: opt_extent,
  99299. origins: origins,
  99300. resolutions: resolutions,
  99301. matrixIds: matrixIds,
  99302. tileSizes: tileSizes,
  99303. sizes: sizes
  99304. });
  99305. };
  99306. goog.provide('ol.source.WMTS');
  99307. goog.provide('ol.source.WMTSRequestEncoding');
  99308. goog.require('goog.array');
  99309. goog.require('goog.asserts');
  99310. goog.require('goog.object');
  99311. goog.require('goog.uri.utils');
  99312. goog.require('ol.TileUrlFunction');
  99313. goog.require('ol.TileUrlFunctionType');
  99314. goog.require('ol.array');
  99315. goog.require('ol.extent');
  99316. goog.require('ol.proj');
  99317. goog.require('ol.source.TileImage');
  99318. goog.require('ol.tilegrid.WMTS');
  99319. /**
  99320. * Request encoding. One of 'KVP', 'REST'.
  99321. * @enum {string}
  99322. * @api
  99323. */
  99324. ol.source.WMTSRequestEncoding = {
  99325. KVP: 'KVP', // see spec §8
  99326. REST: 'REST' // see spec §10
  99327. };
  99328. /**
  99329. * @classdesc
  99330. * Layer source for tile data from WMTS servers.
  99331. *
  99332. * @constructor
  99333. * @extends {ol.source.TileImage}
  99334. * @param {olx.source.WMTSOptions} options WMTS options.
  99335. * @api stable
  99336. */
  99337. ol.source.WMTS = function(options) {
  99338. // TODO: add support for TileMatrixLimits
  99339. /**
  99340. * @private
  99341. * @type {string}
  99342. */
  99343. this.version_ = options.version !== undefined ? options.version : '1.0.0';
  99344. /**
  99345. * @private
  99346. * @type {string}
  99347. */
  99348. this.format_ = options.format !== undefined ? options.format : 'image/jpeg';
  99349. /**
  99350. * @private
  99351. * @type {Object}
  99352. */
  99353. this.dimensions_ = options.dimensions !== undefined ? options.dimensions : {};
  99354. /**
  99355. * @private
  99356. * @type {string}
  99357. */
  99358. this.coordKeyPrefix_ = '';
  99359. this.resetCoordKeyPrefix_();
  99360. /**
  99361. * @private
  99362. * @type {string}
  99363. */
  99364. this.layer_ = options.layer;
  99365. /**
  99366. * @private
  99367. * @type {string}
  99368. */
  99369. this.matrixSet_ = options.matrixSet;
  99370. /**
  99371. * @private
  99372. * @type {string}
  99373. */
  99374. this.style_ = options.style;
  99375. var urls = options.urls;
  99376. if (urls === undefined && options.url !== undefined) {
  99377. urls = ol.TileUrlFunction.expandUrl(options.url);
  99378. }
  99379. /**
  99380. * @private
  99381. * @type {!Array.<string>}
  99382. */
  99383. this.urls_ = urls || [];
  99384. // FIXME: should we guess this requestEncoding from options.url(s)
  99385. // structure? that would mean KVP only if a template is not provided.
  99386. /**
  99387. * @private
  99388. * @type {ol.source.WMTSRequestEncoding}
  99389. */
  99390. this.requestEncoding_ = options.requestEncoding !== undefined ?
  99391. /** @type {ol.source.WMTSRequestEncoding} */ (options.requestEncoding) :
  99392. ol.source.WMTSRequestEncoding.KVP;
  99393. var requestEncoding = this.requestEncoding_;
  99394. // FIXME: should we create a default tileGrid?
  99395. // we could issue a getCapabilities xhr to retrieve missing configuration
  99396. var tileGrid = options.tileGrid;
  99397. // context property names are lower case to allow for a case insensitive
  99398. // replacement as some services use different naming conventions
  99399. var context = {
  99400. 'layer': this.layer_,
  99401. 'style': this.style_,
  99402. 'tilematrixset': this.matrixSet_
  99403. };
  99404. if (requestEncoding == ol.source.WMTSRequestEncoding.KVP) {
  99405. goog.object.extend(context, {
  99406. 'Service': 'WMTS',
  99407. 'Request': 'GetTile',
  99408. 'Version': this.version_,
  99409. 'Format': this.format_
  99410. });
  99411. }
  99412. var dimensions = this.dimensions_;
  99413. /**
  99414. * @param {string} template Template.
  99415. * @return {ol.TileUrlFunctionType} Tile URL function.
  99416. */
  99417. function createFromWMTSTemplate(template) {
  99418. // TODO: we may want to create our own appendParams function so that params
  99419. // order conforms to wmts spec guidance, and so that we can avoid to escape
  99420. // special template params
  99421. template = (requestEncoding == ol.source.WMTSRequestEncoding.KVP) ?
  99422. goog.uri.utils.appendParamsFromMap(template, context) :
  99423. template.replace(/\{(\w+?)\}/g, function(m, p) {
  99424. return (p.toLowerCase() in context) ? context[p.toLowerCase()] : m;
  99425. });
  99426. return (
  99427. /**
  99428. * @param {ol.TileCoord} tileCoord Tile coordinate.
  99429. * @param {number} pixelRatio Pixel ratio.
  99430. * @param {ol.proj.Projection} projection Projection.
  99431. * @return {string|undefined} Tile URL.
  99432. */
  99433. function(tileCoord, pixelRatio, projection) {
  99434. if (!tileCoord) {
  99435. return undefined;
  99436. } else {
  99437. var localContext = {
  99438. 'TileMatrix': tileGrid.getMatrixId(tileCoord[0]),
  99439. 'TileCol': tileCoord[1],
  99440. 'TileRow': -tileCoord[2] - 1
  99441. };
  99442. goog.object.extend(localContext, dimensions);
  99443. var url = template;
  99444. if (requestEncoding == ol.source.WMTSRequestEncoding.KVP) {
  99445. url = goog.uri.utils.appendParamsFromMap(url, localContext);
  99446. } else {
  99447. url = url.replace(/\{(\w+?)\}/g, function(m, p) {
  99448. return localContext[p];
  99449. });
  99450. }
  99451. return url;
  99452. }
  99453. });
  99454. }
  99455. var tileUrlFunction = this.urls_.length > 0 ?
  99456. ol.TileUrlFunction.createFromTileUrlFunctions(
  99457. this.urls_.map(createFromWMTSTemplate)) :
  99458. ol.TileUrlFunction.nullTileUrlFunction;
  99459. goog.base(this, {
  99460. attributions: options.attributions,
  99461. crossOrigin: options.crossOrigin,
  99462. logo: options.logo,
  99463. projection: options.projection,
  99464. tileClass: options.tileClass,
  99465. tileGrid: tileGrid,
  99466. tileLoadFunction: options.tileLoadFunction,
  99467. tilePixelRatio: options.tilePixelRatio,
  99468. tileUrlFunction: tileUrlFunction,
  99469. wrapX: options.wrapX !== undefined ? options.wrapX : false
  99470. });
  99471. };
  99472. goog.inherits(ol.source.WMTS, ol.source.TileImage);
  99473. /**
  99474. * Get the dimensions, i.e. those passed to the constructor through the
  99475. * "dimensions" option, and possibly updated using the updateDimensions
  99476. * method.
  99477. * @return {Object} Dimensions.
  99478. * @api
  99479. */
  99480. ol.source.WMTS.prototype.getDimensions = function() {
  99481. return this.dimensions_;
  99482. };
  99483. /**
  99484. * Return the image format of the WMTS source.
  99485. * @return {string} Format.
  99486. * @api
  99487. */
  99488. ol.source.WMTS.prototype.getFormat = function() {
  99489. return this.format_;
  99490. };
  99491. /**
  99492. * @inheritDoc
  99493. */
  99494. ol.source.WMTS.prototype.getKeyZXY = function(z, x, y) {
  99495. return this.coordKeyPrefix_ + goog.base(this, 'getKeyZXY', z, x, y);
  99496. };
  99497. /**
  99498. * Return the layer of the WMTS source.
  99499. * @return {string} Layer.
  99500. * @api
  99501. */
  99502. ol.source.WMTS.prototype.getLayer = function() {
  99503. return this.layer_;
  99504. };
  99505. /**
  99506. * Return the matrix set of the WMTS source.
  99507. * @return {string} MatrixSet.
  99508. * @api
  99509. */
  99510. ol.source.WMTS.prototype.getMatrixSet = function() {
  99511. return this.matrixSet_;
  99512. };
  99513. /**
  99514. * Return the request encoding, either "KVP" or "REST".
  99515. * @return {ol.source.WMTSRequestEncoding} Request encoding.
  99516. * @api
  99517. */
  99518. ol.source.WMTS.prototype.getRequestEncoding = function() {
  99519. return this.requestEncoding_;
  99520. };
  99521. /**
  99522. * Return the style of the WMTS source.
  99523. * @return {string} Style.
  99524. * @api
  99525. */
  99526. ol.source.WMTS.prototype.getStyle = function() {
  99527. return this.style_;
  99528. };
  99529. /**
  99530. * Return the URLs used for this WMTS source.
  99531. * @return {!Array.<string>} URLs.
  99532. * @api
  99533. */
  99534. ol.source.WMTS.prototype.getUrls = function() {
  99535. return this.urls_;
  99536. };
  99537. /**
  99538. * Return the version of the WMTS source.
  99539. * @return {string} Version.
  99540. * @api
  99541. */
  99542. ol.source.WMTS.prototype.getVersion = function() {
  99543. return this.version_;
  99544. };
  99545. /**
  99546. * @private
  99547. */
  99548. ol.source.WMTS.prototype.resetCoordKeyPrefix_ = function() {
  99549. var i = 0;
  99550. var res = [];
  99551. for (var key in this.dimensions_) {
  99552. res[i++] = key + '-' + this.dimensions_[key];
  99553. }
  99554. this.coordKeyPrefix_ = res.join('/');
  99555. };
  99556. /**
  99557. * Update the dimensions.
  99558. * @param {Object} dimensions Dimensions.
  99559. * @api
  99560. */
  99561. ol.source.WMTS.prototype.updateDimensions = function(dimensions) {
  99562. goog.object.extend(this.dimensions_, dimensions);
  99563. this.resetCoordKeyPrefix_();
  99564. this.changed();
  99565. };
  99566. /**
  99567. * Generate source options from a capabilities object.
  99568. * @param {Object} wmtsCap An object representing the capabilities document.
  99569. * @param {Object} config Configuration properties for the layer. Defaults for
  99570. * the layer will apply if not provided.
  99571. *
  99572. * Required config properties:
  99573. * layer - {String} The layer identifier.
  99574. *
  99575. * Optional config properties:
  99576. * matrixSet - {String} The matrix set identifier, required if there is
  99577. * more than one matrix set in the layer capabilities.
  99578. * projection - {String} The desired CRS when no matrixSet is specified.
  99579. * eg: "EPSG:3857". If the desired projection is not available,
  99580. * an error is thrown.
  99581. * requestEncoding - {String} url encoding format for the layer. Default is the
  99582. * first tile url format found in the GetCapabilities response.
  99583. * style - {String} The name of the style
  99584. * format - {String} Image format for the layer. Default is the first
  99585. * format returned in the GetCapabilities response.
  99586. * @return {olx.source.WMTSOptions} WMTS source options object.
  99587. * @api
  99588. */
  99589. ol.source.WMTS.optionsFromCapabilities = function(wmtsCap, config) {
  99590. /* jshint -W069 */
  99591. // TODO: add support for TileMatrixLimits
  99592. goog.asserts.assert(config['layer'],
  99593. 'config "layer" must not be null');
  99594. var layers = wmtsCap['Contents']['Layer'];
  99595. var l = goog.array.find(layers, function(elt, index, array) {
  99596. return elt['Identifier'] == config['layer'];
  99597. });
  99598. goog.asserts.assert(l, 'found a matching layer in Contents/Layer');
  99599. goog.asserts.assert(l['TileMatrixSetLink'].length > 0,
  99600. 'layer has TileMatrixSetLink');
  99601. var tileMatrixSets = wmtsCap['Contents']['TileMatrixSet'];
  99602. var idx, matrixSet;
  99603. if (l['TileMatrixSetLink'].length > 1) {
  99604. if ('projection' in config) {
  99605. idx = goog.array.findIndex(l['TileMatrixSetLink'],
  99606. function(elt, index, array) {
  99607. var tileMatrixSet = goog.array.find(tileMatrixSets, function(el) {
  99608. return el['Identifier'] == elt['TileMatrixSet'];
  99609. });
  99610. return tileMatrixSet['SupportedCRS'].replace(
  99611. /urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3'
  99612. ) == config['projection'];
  99613. });
  99614. } else {
  99615. idx = goog.array.findIndex(l['TileMatrixSetLink'],
  99616. function(elt, index, array) {
  99617. return elt['TileMatrixSet'] == config['matrixSet'];
  99618. });
  99619. }
  99620. } else {
  99621. idx = 0;
  99622. }
  99623. if (idx < 0) {
  99624. idx = 0;
  99625. }
  99626. matrixSet = /** @type {string} */
  99627. (l['TileMatrixSetLink'][idx]['TileMatrixSet']);
  99628. goog.asserts.assert(matrixSet, 'TileMatrixSet must not be null');
  99629. var format = /** @type {string} */ (l['Format'][0]);
  99630. if ('format' in config) {
  99631. format = config['format'];
  99632. }
  99633. idx = goog.array.findIndex(l['Style'], function(elt, index, array) {
  99634. if ('style' in config) {
  99635. return elt['Title'] == config['style'];
  99636. } else {
  99637. return elt['isDefault'];
  99638. }
  99639. });
  99640. if (idx < 0) {
  99641. idx = 0;
  99642. }
  99643. var style = /** @type {string} */ (l['Style'][idx]['Identifier']);
  99644. var dimensions = {};
  99645. if ('Dimension' in l) {
  99646. l['Dimension'].forEach(function(elt, index, array) {
  99647. var key = elt['Identifier'];
  99648. var value = elt['default'];
  99649. if (value !== undefined) {
  99650. goog.asserts.assert(ol.array.includes(elt['values'], value),
  99651. 'default value contained in values');
  99652. } else {
  99653. value = elt['values'][0];
  99654. }
  99655. goog.asserts.assert(value !== undefined, 'value could be found');
  99656. dimensions[key] = value;
  99657. });
  99658. }
  99659. var matrixSets = wmtsCap['Contents']['TileMatrixSet'];
  99660. var matrixSetObj = goog.array.find(matrixSets, function(elt, index, array) {
  99661. return elt['Identifier'] == matrixSet;
  99662. });
  99663. goog.asserts.assert(matrixSetObj,
  99664. 'found matrixSet in Contents/TileMatrixSet');
  99665. var projection;
  99666. if ('projection' in config) {
  99667. projection = ol.proj.get(config['projection']);
  99668. } else {
  99669. projection = ol.proj.get(matrixSetObj['SupportedCRS'].replace(
  99670. /urn:ogc:def:crs:(\w+):(.*:)?(\w+)$/, '$1:$3'));
  99671. }
  99672. var wgs84BoundingBox = l['WGS84BoundingBox'];
  99673. var extent, wrapX;
  99674. if (wgs84BoundingBox !== undefined) {
  99675. var wgs84ProjectionExtent = ol.proj.get('EPSG:4326').getExtent();
  99676. wrapX = (wgs84BoundingBox[0] == wgs84ProjectionExtent[0] &&
  99677. wgs84BoundingBox[2] == wgs84ProjectionExtent[2]);
  99678. extent = ol.proj.transformExtent(
  99679. wgs84BoundingBox, 'EPSG:4326', projection);
  99680. var projectionExtent = projection.getExtent();
  99681. if (projectionExtent) {
  99682. // If possible, do a sanity check on the extent - it should never be
  99683. // bigger than the validity extent of the projection of a matrix set.
  99684. if (!ol.extent.containsExtent(projectionExtent, extent)) {
  99685. extent = undefined;
  99686. }
  99687. }
  99688. }
  99689. var tileGrid = ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet(
  99690. matrixSetObj, extent);
  99691. /** @type {!Array.<string>} */
  99692. var urls = [];
  99693. var requestEncoding = config['requestEncoding'];
  99694. requestEncoding = requestEncoding !== undefined ? requestEncoding : '';
  99695. goog.asserts.assert(
  99696. ol.array.includes(['REST', 'RESTful', 'KVP', ''], requestEncoding),
  99697. 'requestEncoding (%s) is one of "REST", "RESTful", "KVP" or ""',
  99698. requestEncoding);
  99699. if (!wmtsCap.hasOwnProperty('OperationsMetadata') ||
  99700. !wmtsCap['OperationsMetadata'].hasOwnProperty('GetTile') ||
  99701. requestEncoding.indexOf('REST') === 0) {
  99702. // Add REST tile resource url
  99703. requestEncoding = ol.source.WMTSRequestEncoding.REST;
  99704. l['ResourceURL'].forEach(function(elt, index, array) {
  99705. if (elt['resourceType'] == 'tile') {
  99706. format = elt['format'];
  99707. urls.push(/** @type {string} */ (elt['template']));
  99708. }
  99709. });
  99710. } else {
  99711. var gets = wmtsCap['OperationsMetadata']['GetTile']['DCP']['HTTP']['Get'];
  99712. for (var i = 0, ii = gets.length; i < ii; ++i) {
  99713. var constraint = goog.array.find(gets[i]['Constraint'],
  99714. function(elt, index, array) {
  99715. return elt['name'] == 'GetEncoding';
  99716. });
  99717. var encodings = constraint['AllowedValues']['Value'];
  99718. if (encodings.length > 0 && ol.array.includes(encodings, 'KVP')) {
  99719. requestEncoding = ol.source.WMTSRequestEncoding.KVP;
  99720. urls.push(/** @type {string} */ (gets[i]['href']));
  99721. }
  99722. }
  99723. }
  99724. goog.asserts.assert(urls.length > 0, 'At least one URL found');
  99725. return {
  99726. urls: urls,
  99727. layer: config['layer'],
  99728. matrixSet: matrixSet,
  99729. format: format,
  99730. projection: projection,
  99731. requestEncoding: requestEncoding,
  99732. tileGrid: tileGrid,
  99733. style: style,
  99734. dimensions: dimensions,
  99735. wrapX: wrapX
  99736. };
  99737. /* jshint +W069 */
  99738. };
  99739. goog.provide('ol.source.Zoomify');
  99740. goog.require('goog.asserts');
  99741. goog.require('ol');
  99742. goog.require('ol.ImageTile');
  99743. goog.require('ol.TileCoord');
  99744. goog.require('ol.TileState');
  99745. goog.require('ol.dom');
  99746. goog.require('ol.extent');
  99747. goog.require('ol.proj');
  99748. goog.require('ol.source.TileImage');
  99749. goog.require('ol.tilegrid.TileGrid');
  99750. /**
  99751. * @enum {string}
  99752. */
  99753. ol.source.ZoomifyTierSizeCalculation = {
  99754. DEFAULT: 'default',
  99755. TRUNCATED: 'truncated'
  99756. };
  99757. /**
  99758. * @classdesc
  99759. * Layer source for tile data in Zoomify format.
  99760. *
  99761. * @constructor
  99762. * @extends {ol.source.TileImage}
  99763. * @param {olx.source.ZoomifyOptions=} opt_options Options.
  99764. * @api stable
  99765. */
  99766. ol.source.Zoomify = function(opt_options) {
  99767. var options = opt_options || {};
  99768. var size = options.size;
  99769. var tierSizeCalculation = options.tierSizeCalculation !== undefined ?
  99770. options.tierSizeCalculation :
  99771. ol.source.ZoomifyTierSizeCalculation.DEFAULT;
  99772. var imageWidth = size[0];
  99773. var imageHeight = size[1];
  99774. var tierSizeInTiles = [];
  99775. var tileSize = ol.DEFAULT_TILE_SIZE;
  99776. switch (tierSizeCalculation) {
  99777. case ol.source.ZoomifyTierSizeCalculation.DEFAULT:
  99778. while (imageWidth > tileSize || imageHeight > tileSize) {
  99779. tierSizeInTiles.push([
  99780. Math.ceil(imageWidth / tileSize),
  99781. Math.ceil(imageHeight / tileSize)
  99782. ]);
  99783. tileSize += tileSize;
  99784. }
  99785. break;
  99786. case ol.source.ZoomifyTierSizeCalculation.TRUNCATED:
  99787. var width = imageWidth;
  99788. var height = imageHeight;
  99789. while (width > tileSize || height > tileSize) {
  99790. tierSizeInTiles.push([
  99791. Math.ceil(width / tileSize),
  99792. Math.ceil(height / tileSize)
  99793. ]);
  99794. width >>= 1;
  99795. height >>= 1;
  99796. }
  99797. break;
  99798. default:
  99799. goog.asserts.fail();
  99800. break;
  99801. }
  99802. tierSizeInTiles.push([1, 1]);
  99803. tierSizeInTiles.reverse();
  99804. var resolutions = [1];
  99805. var tileCountUpToTier = [0];
  99806. var i, ii;
  99807. for (i = 1, ii = tierSizeInTiles.length; i < ii; i++) {
  99808. resolutions.push(1 << i);
  99809. tileCountUpToTier.push(
  99810. tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] +
  99811. tileCountUpToTier[i - 1]
  99812. );
  99813. }
  99814. resolutions.reverse();
  99815. var extent = [0, -size[1], size[0], 0];
  99816. var tileGrid = new ol.tilegrid.TileGrid({
  99817. extent: extent,
  99818. origin: ol.extent.getTopLeft(extent),
  99819. resolutions: resolutions
  99820. });
  99821. var url = options.url;
  99822. /**
  99823. * @this {ol.source.TileImage}
  99824. * @param {ol.TileCoord} tileCoord Tile Coordinate.
  99825. * @param {number} pixelRatio Pixel ratio.
  99826. * @param {ol.proj.Projection} projection Projection.
  99827. * @return {string|undefined} Tile URL.
  99828. */
  99829. function tileUrlFunction(tileCoord, pixelRatio, projection) {
  99830. if (!tileCoord) {
  99831. return undefined;
  99832. } else {
  99833. var tileCoordZ = tileCoord[0];
  99834. var tileCoordX = tileCoord[1];
  99835. var tileCoordY = -tileCoord[2] - 1;
  99836. var tileIndex =
  99837. tileCoordX +
  99838. tileCoordY * tierSizeInTiles[tileCoordZ][0] +
  99839. tileCountUpToTier[tileCoordZ];
  99840. var tileGroup = (tileIndex / ol.DEFAULT_TILE_SIZE) | 0;
  99841. return url + 'TileGroup' + tileGroup + '/' +
  99842. tileCoordZ + '-' + tileCoordX + '-' + tileCoordY + '.jpg';
  99843. }
  99844. }
  99845. goog.base(this, {
  99846. attributions: options.attributions,
  99847. crossOrigin: options.crossOrigin,
  99848. logo: options.logo,
  99849. tileClass: ol.source.ZoomifyTile_,
  99850. tileGrid: tileGrid,
  99851. tileUrlFunction: tileUrlFunction
  99852. });
  99853. };
  99854. goog.inherits(ol.source.Zoomify, ol.source.TileImage);
  99855. /**
  99856. * @constructor
  99857. * @extends {ol.ImageTile}
  99858. * @param {ol.TileCoord} tileCoord Tile coordinate.
  99859. * @param {ol.TileState} state State.
  99860. * @param {string} src Image source URI.
  99861. * @param {?string} crossOrigin Cross origin.
  99862. * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
  99863. * @private
  99864. */
  99865. ol.source.ZoomifyTile_ = function(
  99866. tileCoord, state, src, crossOrigin, tileLoadFunction) {
  99867. goog.base(this, tileCoord, state, src, crossOrigin, tileLoadFunction);
  99868. /**
  99869. * @private
  99870. * @type {Object.<string,
  99871. * HTMLCanvasElement|HTMLImageElement|HTMLVideoElement>}
  99872. */
  99873. this.zoomifyImageByContext_ = {};
  99874. };
  99875. goog.inherits(ol.source.ZoomifyTile_, ol.ImageTile);
  99876. /**
  99877. * @inheritDoc
  99878. */
  99879. ol.source.ZoomifyTile_.prototype.getImage = function(opt_context) {
  99880. var tileSize = ol.DEFAULT_TILE_SIZE;
  99881. var key = opt_context !== undefined ?
  99882. goog.getUid(opt_context).toString() : '';
  99883. if (key in this.zoomifyImageByContext_) {
  99884. return this.zoomifyImageByContext_[key];
  99885. } else {
  99886. var image = goog.base(this, 'getImage', opt_context);
  99887. if (this.state == ol.TileState.LOADED) {
  99888. if (image.width == tileSize && image.height == tileSize) {
  99889. this.zoomifyImageByContext_[key] = image;
  99890. return image;
  99891. } else {
  99892. var context = ol.dom.createCanvasContext2D(tileSize, tileSize);
  99893. context.drawImage(image, 0, 0);
  99894. this.zoomifyImageByContext_[key] = context.canvas;
  99895. return context.canvas;
  99896. }
  99897. } else {
  99898. return image;
  99899. }
  99900. }
  99901. };
  99902. goog.provide('ol.style.Atlas');
  99903. goog.provide('ol.style.AtlasManager');
  99904. goog.require('goog.asserts');
  99905. goog.require('goog.dom');
  99906. goog.require('goog.dom.TagName');
  99907. goog.require('goog.functions');
  99908. goog.require('goog.object');
  99909. goog.require('ol');
  99910. /**
  99911. * Provides information for an image inside an atlas manager.
  99912. * `offsetX` and `offsetY` is the position of the image inside
  99913. * the atlas image `image` and the position of the hit-detection image
  99914. * inside the hit-detection atlas image `hitImage`.
  99915. * @typedef {{offsetX: number, offsetY: number, image: HTMLCanvasElement,
  99916. * hitImage: HTMLCanvasElement}}
  99917. */
  99918. ol.style.AtlasManagerInfo;
  99919. /**
  99920. * Manages the creation of image atlases.
  99921. *
  99922. * Images added to this manager will be inserted into an atlas, which
  99923. * will be used for rendering.
  99924. * The `size` given in the constructor is the size for the first
  99925. * atlas. After that, when new atlases are created, they will have
  99926. * twice the size as the latest atlas (until `maxSize` is reached).
  99927. *
  99928. * If an application uses many images or very large images, it is recommended
  99929. * to set a higher `size` value to avoid the creation of too many atlases.
  99930. *
  99931. * @constructor
  99932. * @struct
  99933. * @api
  99934. * @param {olx.style.AtlasManagerOptions=} opt_options Options.
  99935. */
  99936. ol.style.AtlasManager = function(opt_options) {
  99937. var options = opt_options || {};
  99938. /**
  99939. * The size in pixels of the latest atlas image.
  99940. * @private
  99941. * @type {number}
  99942. */
  99943. this.currentSize_ = options.initialSize !== undefined ?
  99944. options.initialSize : ol.INITIAL_ATLAS_SIZE;
  99945. /**
  99946. * The maximum size in pixels of atlas images.
  99947. * @private
  99948. * @type {number}
  99949. */
  99950. this.maxSize_ = options.maxSize !== undefined ?
  99951. options.maxSize : ol.MAX_ATLAS_SIZE != -1 ?
  99952. ol.MAX_ATLAS_SIZE : ol.WEBGL_MAX_TEXTURE_SIZE !== undefined ?
  99953. ol.WEBGL_MAX_TEXTURE_SIZE : 2048;
  99954. /**
  99955. * The size in pixels between images.
  99956. * @private
  99957. * @type {number}
  99958. */
  99959. this.space_ = options.space !== undefined ? options.space : 1;
  99960. /**
  99961. * @private
  99962. * @type {Array.<ol.style.Atlas>}
  99963. */
  99964. this.atlases_ = [new ol.style.Atlas(this.currentSize_, this.space_)];
  99965. /**
  99966. * The size in pixels of the latest atlas image for hit-detection images.
  99967. * @private
  99968. * @type {number}
  99969. */
  99970. this.currentHitSize_ = this.currentSize_;
  99971. /**
  99972. * @private
  99973. * @type {Array.<ol.style.Atlas>}
  99974. */
  99975. this.hitAtlases_ = [new ol.style.Atlas(this.currentHitSize_, this.space_)];
  99976. };
  99977. /**
  99978. * @param {string} id The identifier of the entry to check.
  99979. * @return {?ol.style.AtlasManagerInfo} The position and atlas image for the
  99980. * entry, or `null` if the entry is not part of the atlas manager.
  99981. */
  99982. ol.style.AtlasManager.prototype.getInfo = function(id) {
  99983. /** @type {?ol.style.AtlasInfo} */
  99984. var info = this.getInfo_(this.atlases_, id);
  99985. if (!info) {
  99986. return null;
  99987. }
  99988. /** @type {?ol.style.AtlasInfo} */
  99989. var hitInfo = this.getInfo_(this.hitAtlases_, id);
  99990. goog.asserts.assert(hitInfo, 'hitInfo must not be null');
  99991. return this.mergeInfos_(info, hitInfo);
  99992. };
  99993. /**
  99994. * @private
  99995. * @param {Array.<ol.style.Atlas>} atlases The atlases to search.
  99996. * @param {string} id The identifier of the entry to check.
  99997. * @return {?ol.style.AtlasInfo} The position and atlas image for the entry,
  99998. * or `null` if the entry is not part of the atlases.
  99999. */
  100000. ol.style.AtlasManager.prototype.getInfo_ = function(atlases, id) {
  100001. var atlas, info, i, ii;
  100002. for (i = 0, ii = atlases.length; i < ii; ++i) {
  100003. atlas = atlases[i];
  100004. info = atlas.get(id);
  100005. if (info) {
  100006. return info;
  100007. }
  100008. }
  100009. return null;
  100010. };
  100011. /**
  100012. * @private
  100013. * @param {ol.style.AtlasInfo} info The info for the real image.
  100014. * @param {ol.style.AtlasInfo} hitInfo The info for the hit-detection
  100015. * image.
  100016. * @return {?ol.style.AtlasManagerInfo} The position and atlas image for the
  100017. * entry, or `null` if the entry is not part of the atlases.
  100018. */
  100019. ol.style.AtlasManager.prototype.mergeInfos_ = function(info, hitInfo) {
  100020. goog.asserts.assert(info.offsetX === hitInfo.offsetX,
  100021. 'in order to merge, offsetX of info and hitInfo must be equal');
  100022. goog.asserts.assert(info.offsetY === hitInfo.offsetY,
  100023. 'in order to merge, offsetY of info and hitInfo must be equal');
  100024. return /** @type {ol.style.AtlasManagerInfo} */ ({
  100025. offsetX: info.offsetX,
  100026. offsetY: info.offsetY,
  100027. image: info.image,
  100028. hitImage: hitInfo.image
  100029. });
  100030. };
  100031. /**
  100032. * Add an image to the atlas manager.
  100033. *
  100034. * If an entry for the given id already exists, the entry will
  100035. * be overridden (but the space on the atlas graphic will not be freed).
  100036. *
  100037. * If `renderHitCallback` is provided, the image (or the hit-detection version
  100038. * of the image) will be rendered into a separate hit-detection atlas image.
  100039. *
  100040. * @param {string} id The identifier of the entry to add.
  100041. * @param {number} width The width.
  100042. * @param {number} height The height.
  100043. * @param {function(CanvasRenderingContext2D, number, number)} renderCallback
  100044. * Called to render the new image onto an atlas image.
  100045. * @param {function(CanvasRenderingContext2D, number, number)=}
  100046. * opt_renderHitCallback Called to render a hit-detection image onto a hit
  100047. * detection atlas image.
  100048. * @param {Object=} opt_this Value to use as `this` when executing
  100049. * `renderCallback` and `renderHitCallback`.
  100050. * @return {?ol.style.AtlasManagerInfo} The position and atlas image for the
  100051. * entry, or `null` if the image is too big.
  100052. */
  100053. ol.style.AtlasManager.prototype.add =
  100054. function(id, width, height,
  100055. renderCallback, opt_renderHitCallback, opt_this) {
  100056. if (width + this.space_ > this.maxSize_ ||
  100057. height + this.space_ > this.maxSize_) {
  100058. return null;
  100059. }
  100060. /** @type {?ol.style.AtlasInfo} */
  100061. var info = this.add_(false,
  100062. id, width, height, renderCallback, opt_this);
  100063. if (!info) {
  100064. return null;
  100065. }
  100066. // even if no hit-detection entry is requested, we insert a fake entry into
  100067. // the hit-detection atlas, to make sure that the offset is the same for
  100068. // the original image and the hit-detection image.
  100069. var renderHitCallback = opt_renderHitCallback !== undefined ?
  100070. opt_renderHitCallback : goog.functions.NULL;
  100071. /** @type {?ol.style.AtlasInfo} */
  100072. var hitInfo = this.add_(true,
  100073. id, width, height, renderHitCallback, opt_this);
  100074. goog.asserts.assert(hitInfo, 'hitInfo must not be null');
  100075. return this.mergeInfos_(info, hitInfo);
  100076. };
  100077. /**
  100078. * @private
  100079. * @param {boolean} isHitAtlas If the hit-detection atlases are used.
  100080. * @param {string} id The identifier of the entry to add.
  100081. * @param {number} width The width.
  100082. * @param {number} height The height.
  100083. * @param {function(CanvasRenderingContext2D, number, number)} renderCallback
  100084. * Called to render the new image onto an atlas image.
  100085. * @param {Object=} opt_this Value to use as `this` when executing
  100086. * `renderCallback` and `renderHitCallback`.
  100087. * @return {?ol.style.AtlasInfo} The position and atlas image for the entry,
  100088. * or `null` if the image is too big.
  100089. */
  100090. ol.style.AtlasManager.prototype.add_ =
  100091. function(isHitAtlas, id, width, height,
  100092. renderCallback, opt_this) {
  100093. var atlases = (isHitAtlas) ? this.hitAtlases_ : this.atlases_;
  100094. var atlas, info, i, ii;
  100095. for (i = 0, ii = atlases.length; i < ii; ++i) {
  100096. atlas = atlases[i];
  100097. info = atlas.add(id, width, height, renderCallback, opt_this);
  100098. if (info) {
  100099. return info;
  100100. } else if (!info && i === ii - 1) {
  100101. // the entry could not be added to one of the existing atlases,
  100102. // create a new atlas that is twice as big and try to add to this one.
  100103. var size;
  100104. if (isHitAtlas) {
  100105. size = Math.min(this.currentHitSize_ * 2, this.maxSize_);
  100106. this.currentHitSize_ = size;
  100107. } else {
  100108. size = Math.min(this.currentSize_ * 2, this.maxSize_);
  100109. this.currentSize_ = size;
  100110. }
  100111. atlas = new ol.style.Atlas(size, this.space_);
  100112. atlases.push(atlas);
  100113. // run the loop another time
  100114. ++ii;
  100115. }
  100116. }
  100117. goog.asserts.fail('Failed to add to atlasmanager');
  100118. };
  100119. /**
  100120. * Provides information for an image inside an atlas.
  100121. * `offsetX` and `offsetY` are the position of the image inside
  100122. * the atlas image `image`.
  100123. * @typedef {{offsetX: number, offsetY: number, image: HTMLCanvasElement}}
  100124. */
  100125. ol.style.AtlasInfo;
  100126. /**
  100127. * This class facilitates the creation of image atlases.
  100128. *
  100129. * Images added to an atlas will be rendered onto a single
  100130. * atlas canvas. The distribution of images on the canvas is
  100131. * managed with the bin packing algorithm described in:
  100132. * http://www.blackpawn.com/texts/lightmaps/
  100133. *
  100134. * @constructor
  100135. * @struct
  100136. * @param {number} size The size in pixels of the sprite image.
  100137. * @param {number} space The space in pixels between images.
  100138. * Because texture coordinates are float values, the edges of
  100139. * images might not be completely correct (in a way that the
  100140. * edges overlap when being rendered). To avoid this we add a
  100141. * padding around each image.
  100142. */
  100143. ol.style.Atlas = function(size, space) {
  100144. /**
  100145. * @private
  100146. * @type {number}
  100147. */
  100148. this.space_ = space;
  100149. /**
  100150. * @private
  100151. * @type {Array.<ol.style.Atlas.Block>}
  100152. */
  100153. this.emptyBlocks_ = [{x: 0, y: 0, width: size, height: size}];
  100154. /**
  100155. * @private
  100156. * @type {Object.<string, ol.style.AtlasInfo>}
  100157. */
  100158. this.entries_ = {};
  100159. /**
  100160. * @private
  100161. * @type {HTMLCanvasElement}
  100162. */
  100163. this.canvas_ = /** @type {HTMLCanvasElement} */
  100164. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  100165. this.canvas_.width = size;
  100166. this.canvas_.height = size;
  100167. /**
  100168. * @private
  100169. * @type {CanvasRenderingContext2D}
  100170. */
  100171. this.context_ = /** @type {CanvasRenderingContext2D} */
  100172. (this.canvas_.getContext('2d'));
  100173. };
  100174. /**
  100175. * @param {string} id The identifier of the entry to check.
  100176. * @return {?ol.style.AtlasInfo}
  100177. */
  100178. ol.style.Atlas.prototype.get = function(id) {
  100179. return /** @type {?ol.style.AtlasInfo} */ (
  100180. goog.object.get(this.entries_, id, null));
  100181. };
  100182. /**
  100183. * @param {string} id The identifier of the entry to add.
  100184. * @param {number} width The width.
  100185. * @param {number} height The height.
  100186. * @param {function(CanvasRenderingContext2D, number, number)} renderCallback
  100187. * Called to render the new image onto an atlas image.
  100188. * @param {Object=} opt_this Value to use as `this` when executing
  100189. * `renderCallback`.
  100190. * @return {?ol.style.AtlasInfo} The position and atlas image for the entry.
  100191. */
  100192. ol.style.Atlas.prototype.add =
  100193. function(id, width, height, renderCallback, opt_this) {
  100194. var block, i, ii;
  100195. for (i = 0, ii = this.emptyBlocks_.length; i < ii; ++i) {
  100196. block = this.emptyBlocks_[i];
  100197. if (block.width >= width + this.space_ &&
  100198. block.height >= height + this.space_) {
  100199. // we found a block that is big enough for our entry
  100200. var entry = {
  100201. offsetX: block.x + this.space_,
  100202. offsetY: block.y + this.space_,
  100203. image: this.canvas_
  100204. };
  100205. this.entries_[id] = entry;
  100206. // render the image on the atlas image
  100207. renderCallback.call(opt_this, this.context_,
  100208. block.x + this.space_, block.y + this.space_);
  100209. // split the block after the insertion, either horizontally or vertically
  100210. this.split_(i, block, width + this.space_, height + this.space_);
  100211. return entry;
  100212. }
  100213. }
  100214. // there is no space for the new entry in this atlas
  100215. return null;
  100216. };
  100217. /**
  100218. * @private
  100219. * @param {number} index The index of the block.
  100220. * @param {ol.style.Atlas.Block} block The block to split.
  100221. * @param {number} width The width of the entry to insert.
  100222. * @param {number} height The height of the entry to insert.
  100223. */
  100224. ol.style.Atlas.prototype.split_ =
  100225. function(index, block, width, height) {
  100226. var deltaWidth = block.width - width;
  100227. var deltaHeight = block.height - height;
  100228. /** @type {ol.style.Atlas.Block} */
  100229. var newBlock1;
  100230. /** @type {ol.style.Atlas.Block} */
  100231. var newBlock2;
  100232. if (deltaWidth > deltaHeight) {
  100233. // split vertically
  100234. // block right of the inserted entry
  100235. newBlock1 = {
  100236. x: block.x + width,
  100237. y: block.y,
  100238. width: block.width - width,
  100239. height: block.height
  100240. };
  100241. // block below the inserted entry
  100242. newBlock2 = {
  100243. x: block.x,
  100244. y: block.y + height,
  100245. width: width,
  100246. height: block.height - height
  100247. };
  100248. this.updateBlocks_(index, newBlock1, newBlock2);
  100249. } else {
  100250. // split horizontally
  100251. // block right of the inserted entry
  100252. newBlock1 = {
  100253. x: block.x + width,
  100254. y: block.y,
  100255. width: block.width - width,
  100256. height: height
  100257. };
  100258. // block below the inserted entry
  100259. newBlock2 = {
  100260. x: block.x,
  100261. y: block.y + height,
  100262. width: block.width,
  100263. height: block.height - height
  100264. };
  100265. this.updateBlocks_(index, newBlock1, newBlock2);
  100266. }
  100267. };
  100268. /**
  100269. * Remove the old block and insert new blocks at the same array position.
  100270. * The new blocks are inserted at the same position, so that splitted
  100271. * blocks (that are potentially smaller) are filled first.
  100272. * @private
  100273. * @param {number} index The index of the block to remove.
  100274. * @param {ol.style.Atlas.Block} newBlock1 The 1st block to add.
  100275. * @param {ol.style.Atlas.Block} newBlock2 The 2nd block to add.
  100276. */
  100277. ol.style.Atlas.prototype.updateBlocks_ =
  100278. function(index, newBlock1, newBlock2) {
  100279. var args = [index, 1];
  100280. if (newBlock1.width > 0 && newBlock1.height > 0) {
  100281. args.push(newBlock1);
  100282. }
  100283. if (newBlock2.width > 0 && newBlock2.height > 0) {
  100284. args.push(newBlock2);
  100285. }
  100286. this.emptyBlocks_.splice.apply(this.emptyBlocks_, args);
  100287. };
  100288. /**
  100289. * @typedef {{x: number, y: number, width: number, height: number}}
  100290. */
  100291. ol.style.Atlas.Block;
  100292. goog.provide('ol.style.RegularShape');
  100293. goog.require('goog.asserts');
  100294. goog.require('goog.dom');
  100295. goog.require('goog.dom.TagName');
  100296. goog.require('ol');
  100297. goog.require('ol.color');
  100298. goog.require('ol.has');
  100299. goog.require('ol.render.canvas');
  100300. goog.require('ol.structs.IHasChecksum');
  100301. goog.require('ol.style.AtlasManager');
  100302. goog.require('ol.style.Fill');
  100303. goog.require('ol.style.Image');
  100304. goog.require('ol.style.ImageState');
  100305. goog.require('ol.style.Stroke');
  100306. /**
  100307. * @classdesc
  100308. * Set regular shape style for vector features. The resulting shape will be
  100309. * a regular polygon when `radius` is provided, or a star when `radius1` and
  100310. * `radius2` are provided.
  100311. *
  100312. * @constructor
  100313. * @param {olx.style.RegularShapeOptions} options Options.
  100314. * @extends {ol.style.Image}
  100315. * @implements {ol.structs.IHasChecksum}
  100316. * @api
  100317. */
  100318. ol.style.RegularShape = function(options) {
  100319. goog.asserts.assert(
  100320. options.radius !== undefined || options.radius1 !== undefined,
  100321. 'must provide either "radius" or "radius1"');
  100322. /**
  100323. * @private
  100324. * @type {Array.<string>}
  100325. */
  100326. this.checksums_ = null;
  100327. /**
  100328. * @private
  100329. * @type {HTMLCanvasElement}
  100330. */
  100331. this.canvas_ = null;
  100332. /**
  100333. * @private
  100334. * @type {HTMLCanvasElement}
  100335. */
  100336. this.hitDetectionCanvas_ = null;
  100337. /**
  100338. * @private
  100339. * @type {ol.style.Fill}
  100340. */
  100341. this.fill_ = options.fill !== undefined ? options.fill : null;
  100342. /**
  100343. * @private
  100344. * @type {Array.<number>}
  100345. */
  100346. this.origin_ = [0, 0];
  100347. /**
  100348. * @private
  100349. * @type {number}
  100350. */
  100351. this.points_ = options.points;
  100352. /**
  100353. * @private
  100354. * @type {number}
  100355. */
  100356. this.radius_ = /** @type {number} */ (options.radius !== undefined ?
  100357. options.radius : options.radius1);
  100358. /**
  100359. * @private
  100360. * @type {number}
  100361. */
  100362. this.radius2_ =
  100363. options.radius2 !== undefined ? options.radius2 : this.radius_;
  100364. /**
  100365. * @private
  100366. * @type {number}
  100367. */
  100368. this.angle_ = options.angle !== undefined ? options.angle : 0;
  100369. /**
  100370. * @private
  100371. * @type {ol.style.Stroke}
  100372. */
  100373. this.stroke_ = options.stroke !== undefined ? options.stroke : null;
  100374. /**
  100375. * @private
  100376. * @type {Array.<number>}
  100377. */
  100378. this.anchor_ = null;
  100379. /**
  100380. * @private
  100381. * @type {ol.Size}
  100382. */
  100383. this.size_ = null;
  100384. /**
  100385. * @private
  100386. * @type {ol.Size}
  100387. */
  100388. this.imageSize_ = null;
  100389. /**
  100390. * @private
  100391. * @type {ol.Size}
  100392. */
  100393. this.hitDetectionImageSize_ = null;
  100394. this.render_(options.atlasManager);
  100395. /**
  100396. * @type {boolean}
  100397. */
  100398. var snapToPixel = options.snapToPixel !== undefined ?
  100399. options.snapToPixel : true;
  100400. goog.base(this, {
  100401. opacity: 1,
  100402. rotateWithView: false,
  100403. rotation: options.rotation !== undefined ? options.rotation : 0,
  100404. scale: 1,
  100405. snapToPixel: snapToPixel
  100406. });
  100407. };
  100408. goog.inherits(ol.style.RegularShape, ol.style.Image);
  100409. /**
  100410. * @inheritDoc
  100411. * @api
  100412. */
  100413. ol.style.RegularShape.prototype.getAnchor = function() {
  100414. return this.anchor_;
  100415. };
  100416. /**
  100417. * Get the angle used in generating the shape.
  100418. * @return {number} Shape's rotation in radians.
  100419. * @api
  100420. */
  100421. ol.style.RegularShape.prototype.getAngle = function() {
  100422. return this.angle_;
  100423. };
  100424. /**
  100425. * Get the fill style for the shape.
  100426. * @return {ol.style.Fill} Fill style.
  100427. * @api
  100428. */
  100429. ol.style.RegularShape.prototype.getFill = function() {
  100430. return this.fill_;
  100431. };
  100432. /**
  100433. * @inheritDoc
  100434. */
  100435. ol.style.RegularShape.prototype.getHitDetectionImage = function(pixelRatio) {
  100436. return this.hitDetectionCanvas_;
  100437. };
  100438. /**
  100439. * @inheritDoc
  100440. * @api
  100441. */
  100442. ol.style.RegularShape.prototype.getImage = function(pixelRatio) {
  100443. return this.canvas_;
  100444. };
  100445. /**
  100446. * @inheritDoc
  100447. */
  100448. ol.style.RegularShape.prototype.getImageSize = function() {
  100449. return this.imageSize_;
  100450. };
  100451. /**
  100452. * @inheritDoc
  100453. */
  100454. ol.style.RegularShape.prototype.getHitDetectionImageSize = function() {
  100455. return this.hitDetectionImageSize_;
  100456. };
  100457. /**
  100458. * @inheritDoc
  100459. */
  100460. ol.style.RegularShape.prototype.getImageState = function() {
  100461. return ol.style.ImageState.LOADED;
  100462. };
  100463. /**
  100464. * @inheritDoc
  100465. * @api
  100466. */
  100467. ol.style.RegularShape.prototype.getOrigin = function() {
  100468. return this.origin_;
  100469. };
  100470. /**
  100471. * Get the number of points for generating the shape.
  100472. * @return {number} Number of points for stars and regular polygons.
  100473. * @api
  100474. */
  100475. ol.style.RegularShape.prototype.getPoints = function() {
  100476. return this.points_;
  100477. };
  100478. /**
  100479. * Get the (primary) radius for the shape.
  100480. * @return {number} Radius.
  100481. * @api
  100482. */
  100483. ol.style.RegularShape.prototype.getRadius = function() {
  100484. return this.radius_;
  100485. };
  100486. /**
  100487. * Get the secondary radius for the shape.
  100488. * @return {number} Radius2.
  100489. * @api
  100490. */
  100491. ol.style.RegularShape.prototype.getRadius2 = function() {
  100492. return this.radius2_;
  100493. };
  100494. /**
  100495. * @inheritDoc
  100496. * @api
  100497. */
  100498. ol.style.RegularShape.prototype.getSize = function() {
  100499. return this.size_;
  100500. };
  100501. /**
  100502. * Get the stroke style for the shape.
  100503. * @return {ol.style.Stroke} Stroke style.
  100504. * @api
  100505. */
  100506. ol.style.RegularShape.prototype.getStroke = function() {
  100507. return this.stroke_;
  100508. };
  100509. /**
  100510. * @inheritDoc
  100511. */
  100512. ol.style.RegularShape.prototype.listenImageChange = ol.nullFunction;
  100513. /**
  100514. * @inheritDoc
  100515. */
  100516. ol.style.RegularShape.prototype.load = ol.nullFunction;
  100517. /**
  100518. * @inheritDoc
  100519. */
  100520. ol.style.RegularShape.prototype.unlistenImageChange = ol.nullFunction;
  100521. /**
  100522. * @typedef {{
  100523. * strokeStyle: (string|undefined),
  100524. * strokeWidth: number,
  100525. * size: number,
  100526. * lineCap: string,
  100527. * lineDash: Array.<number>,
  100528. * lineJoin: string,
  100529. * miterLimit: number
  100530. * }}
  100531. */
  100532. ol.style.RegularShape.RenderOptions;
  100533. /**
  100534. * @private
  100535. * @param {ol.style.AtlasManager|undefined} atlasManager
  100536. */
  100537. ol.style.RegularShape.prototype.render_ = function(atlasManager) {
  100538. var imageSize;
  100539. var lineCap = '';
  100540. var lineJoin = '';
  100541. var miterLimit = 0;
  100542. var lineDash = null;
  100543. var strokeStyle;
  100544. var strokeWidth = 0;
  100545. if (this.stroke_) {
  100546. strokeStyle = ol.color.asString(this.stroke_.getColor());
  100547. strokeWidth = this.stroke_.getWidth();
  100548. if (strokeWidth === undefined) {
  100549. strokeWidth = ol.render.canvas.defaultLineWidth;
  100550. }
  100551. lineDash = this.stroke_.getLineDash();
  100552. if (!ol.has.CANVAS_LINE_DASH) {
  100553. lineDash = null;
  100554. }
  100555. lineJoin = this.stroke_.getLineJoin();
  100556. if (lineJoin === undefined) {
  100557. lineJoin = ol.render.canvas.defaultLineJoin;
  100558. }
  100559. lineCap = this.stroke_.getLineCap();
  100560. if (lineCap === undefined) {
  100561. lineCap = ol.render.canvas.defaultLineCap;
  100562. }
  100563. miterLimit = this.stroke_.getMiterLimit();
  100564. if (miterLimit === undefined) {
  100565. miterLimit = ol.render.canvas.defaultMiterLimit;
  100566. }
  100567. }
  100568. var size = 2 * (this.radius_ + strokeWidth) + 1;
  100569. /** @type {ol.style.RegularShape.RenderOptions} */
  100570. var renderOptions = {
  100571. strokeStyle: strokeStyle,
  100572. strokeWidth: strokeWidth,
  100573. size: size,
  100574. lineCap: lineCap,
  100575. lineDash: lineDash,
  100576. lineJoin: lineJoin,
  100577. miterLimit: miterLimit
  100578. };
  100579. if (atlasManager === undefined) {
  100580. // no atlas manager is used, create a new canvas
  100581. this.canvas_ = /** @type {HTMLCanvasElement} */
  100582. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  100583. this.canvas_.height = size;
  100584. this.canvas_.width = size;
  100585. // canvas.width and height are rounded to the closest integer
  100586. size = this.canvas_.width;
  100587. imageSize = size;
  100588. var context = /** @type {CanvasRenderingContext2D} */
  100589. (this.canvas_.getContext('2d'));
  100590. this.draw_(renderOptions, context, 0, 0);
  100591. this.createHitDetectionCanvas_(renderOptions);
  100592. } else {
  100593. // an atlas manager is used, add the symbol to an atlas
  100594. size = Math.round(size);
  100595. var hasCustomHitDetectionImage = !this.fill_;
  100596. var renderHitDetectionCallback;
  100597. if (hasCustomHitDetectionImage) {
  100598. // render the hit-detection image into a separate atlas image
  100599. renderHitDetectionCallback =
  100600. goog.bind(this.drawHitDetectionCanvas_, this, renderOptions);
  100601. }
  100602. var id = this.getChecksum();
  100603. var info = atlasManager.add(
  100604. id, size, size, goog.bind(this.draw_, this, renderOptions),
  100605. renderHitDetectionCallback);
  100606. goog.asserts.assert(info, 'shape size is too large');
  100607. this.canvas_ = info.image;
  100608. this.origin_ = [info.offsetX, info.offsetY];
  100609. imageSize = info.image.width;
  100610. if (hasCustomHitDetectionImage) {
  100611. this.hitDetectionCanvas_ = info.hitImage;
  100612. this.hitDetectionImageSize_ =
  100613. [info.hitImage.width, info.hitImage.height];
  100614. } else {
  100615. this.hitDetectionCanvas_ = this.canvas_;
  100616. this.hitDetectionImageSize_ = [imageSize, imageSize];
  100617. }
  100618. }
  100619. this.anchor_ = [size / 2, size / 2];
  100620. this.size_ = [size, size];
  100621. this.imageSize_ = [imageSize, imageSize];
  100622. };
  100623. /**
  100624. * @private
  100625. * @param {ol.style.RegularShape.RenderOptions} renderOptions
  100626. * @param {CanvasRenderingContext2D} context
  100627. * @param {number} x The origin for the symbol (x).
  100628. * @param {number} y The origin for the symbol (y).
  100629. */
  100630. ol.style.RegularShape.prototype.draw_ = function(renderOptions, context, x, y) {
  100631. var i, angle0, radiusC;
  100632. // reset transform
  100633. context.setTransform(1, 0, 0, 1, 0, 0);
  100634. // then move to (x, y)
  100635. context.translate(x, y);
  100636. context.beginPath();
  100637. if (this.radius2_ !== this.radius_) {
  100638. this.points_ = 2 * this.points_;
  100639. }
  100640. for (i = 0; i <= this.points_; i++) {
  100641. angle0 = i * 2 * Math.PI / this.points_ - Math.PI / 2 + this.angle_;
  100642. radiusC = i % 2 === 0 ? this.radius_ : this.radius2_;
  100643. context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
  100644. renderOptions.size / 2 + radiusC * Math.sin(angle0));
  100645. }
  100646. if (this.fill_) {
  100647. context.fillStyle = ol.color.asString(this.fill_.getColor());
  100648. context.fill();
  100649. }
  100650. if (this.stroke_) {
  100651. context.strokeStyle = renderOptions.strokeStyle;
  100652. context.lineWidth = renderOptions.strokeWidth;
  100653. if (renderOptions.lineDash) {
  100654. context.setLineDash(renderOptions.lineDash);
  100655. }
  100656. context.lineCap = renderOptions.lineCap;
  100657. context.lineJoin = renderOptions.lineJoin;
  100658. context.miterLimit = renderOptions.miterLimit;
  100659. context.stroke();
  100660. }
  100661. context.closePath();
  100662. };
  100663. /**
  100664. * @private
  100665. * @param {ol.style.RegularShape.RenderOptions} renderOptions
  100666. */
  100667. ol.style.RegularShape.prototype.createHitDetectionCanvas_ =
  100668. function(renderOptions) {
  100669. this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
  100670. if (this.fill_) {
  100671. this.hitDetectionCanvas_ = this.canvas_;
  100672. return;
  100673. }
  100674. // if no fill style is set, create an extra hit-detection image with a
  100675. // default fill style
  100676. this.hitDetectionCanvas_ = /** @type {HTMLCanvasElement} */
  100677. (goog.dom.createElement(goog.dom.TagName.CANVAS));
  100678. var canvas = this.hitDetectionCanvas_;
  100679. canvas.height = renderOptions.size;
  100680. canvas.width = renderOptions.size;
  100681. var context = /** @type {CanvasRenderingContext2D} */
  100682. (canvas.getContext('2d'));
  100683. this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
  100684. };
  100685. /**
  100686. * @private
  100687. * @param {ol.style.RegularShape.RenderOptions} renderOptions
  100688. * @param {CanvasRenderingContext2D} context
  100689. * @param {number} x The origin for the symbol (x).
  100690. * @param {number} y The origin for the symbol (y).
  100691. */
  100692. ol.style.RegularShape.prototype.drawHitDetectionCanvas_ =
  100693. function(renderOptions, context, x, y) {
  100694. // reset transform
  100695. context.setTransform(1, 0, 0, 1, 0, 0);
  100696. // then move to (x, y)
  100697. context.translate(x, y);
  100698. context.beginPath();
  100699. if (this.radius2_ !== this.radius_) {
  100700. this.points_ = 2 * this.points_;
  100701. }
  100702. var i, radiusC, angle0;
  100703. for (i = 0; i <= this.points_; i++) {
  100704. angle0 = i * 2 * Math.PI / this.points_ - Math.PI / 2 + this.angle_;
  100705. radiusC = i % 2 === 0 ? this.radius_ : this.radius2_;
  100706. context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
  100707. renderOptions.size / 2 + radiusC * Math.sin(angle0));
  100708. }
  100709. context.fillStyle = ol.render.canvas.defaultFillStyle;
  100710. context.fill();
  100711. if (this.stroke_) {
  100712. context.strokeStyle = renderOptions.strokeStyle;
  100713. context.lineWidth = renderOptions.strokeWidth;
  100714. if (renderOptions.lineDash) {
  100715. context.setLineDash(renderOptions.lineDash);
  100716. }
  100717. context.stroke();
  100718. }
  100719. context.closePath();
  100720. };
  100721. /**
  100722. * @inheritDoc
  100723. */
  100724. ol.style.RegularShape.prototype.getChecksum = function() {
  100725. var strokeChecksum = this.stroke_ ?
  100726. this.stroke_.getChecksum() : '-';
  100727. var fillChecksum = this.fill_ ?
  100728. this.fill_.getChecksum() : '-';
  100729. var recalculate = !this.checksums_ ||
  100730. (strokeChecksum != this.checksums_[1] ||
  100731. fillChecksum != this.checksums_[2] ||
  100732. this.radius_ != this.checksums_[3] ||
  100733. this.radius2_ != this.checksums_[4] ||
  100734. this.angle_ != this.checksums_[5] ||
  100735. this.points_ != this.checksums_[6]);
  100736. if (recalculate) {
  100737. var checksum = 'r' + strokeChecksum + fillChecksum +
  100738. (this.radius_ !== undefined ? this.radius_.toString() : '-') +
  100739. (this.radius2_ !== undefined ? this.radius2_.toString() : '-') +
  100740. (this.angle_ !== undefined ? this.angle_.toString() : '-') +
  100741. (this.points_ !== undefined ? this.points_.toString() : '-');
  100742. this.checksums_ = [checksum, strokeChecksum, fillChecksum,
  100743. this.radius_, this.radius2_, this.angle_, this.points_];
  100744. }
  100745. return this.checksums_[0];
  100746. };
  100747. // Copyright 2009 The Closure Library Authors.
  100748. // All Rights Reserved.
  100749. //
  100750. // Licensed under the Apache License, Version 2.0 (the "License");
  100751. // you may not use this file except in compliance with the License.
  100752. // You may obtain a copy of the License at
  100753. //
  100754. // http://www.apache.org/licenses/LICENSE-2.0
  100755. //
  100756. // Unless required by applicable law or agreed to in writing, software
  100757. // distributed under the License is distributed on an "AS-IS" BASIS,
  100758. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  100759. // See the License for the specific language governing permissions and
  100760. // limitations under the License.
  100761. //
  100762. // This file has been auto-generated by GenJsDeps, please do not edit.
  100763. goog.addDependency('demos/editor/equationeditor.js', ['goog.demos.editor.EquationEditor'], ['goog.ui.equation.EquationEditorDialog']);
  100764. goog.addDependency('demos/editor/helloworld.js', ['goog.demos.editor.HelloWorld'], ['goog.dom', 'goog.dom.TagName', 'goog.editor.Plugin']);
  100765. goog.addDependency('demos/editor/helloworlddialog.js', ['goog.demos.editor.HelloWorldDialog', 'goog.demos.editor.HelloWorldDialog.OkEvent'], ['goog.dom.TagName', 'goog.events.Event', 'goog.string', 'goog.ui.editor.AbstractDialog', 'goog.ui.editor.AbstractDialog.Builder', 'goog.ui.editor.AbstractDialog.EventType']);
  100766. goog.addDependency('demos/editor/helloworlddialogplugin.js', ['goog.demos.editor.HelloWorldDialogPlugin', 'goog.demos.editor.HelloWorldDialogPlugin.Command'], ['goog.demos.editor.HelloWorldDialog', 'goog.dom.TagName', 'goog.editor.plugins.AbstractDialogPlugin', 'goog.editor.range', 'goog.functions', 'goog.ui.editor.AbstractDialog.EventType']);
  100767. /**
  100768. * @fileoverview Custom exports file.
  100769. * @suppress {checkVars,extraRequire}
  100770. */
  100771. goog.require('ol');
  100772. goog.require('ol.Attribution');
  100773. goog.require('ol.Collection');
  100774. goog.require('ol.CollectionEvent');
  100775. goog.require('ol.CollectionEventType');
  100776. goog.require('ol.Color');
  100777. goog.require('ol.Coordinate');
  100778. goog.require('ol.CoordinateFormatType');
  100779. goog.require('ol.DeviceOrientation');
  100780. goog.require('ol.DeviceOrientationProperty');
  100781. goog.require('ol.DragBoxEvent');
  100782. goog.require('ol.Extent');
  100783. goog.require('ol.Feature');
  100784. goog.require('ol.FeatureLoader');
  100785. goog.require('ol.FeatureStyleFunction');
  100786. goog.require('ol.FeatureUrlFunction');
  100787. goog.require('ol.Geolocation');
  100788. goog.require('ol.GeolocationProperty');
  100789. goog.require('ol.Graticule');
  100790. goog.require('ol.Image');
  100791. goog.require('ol.ImageTile');
  100792. goog.require('ol.Kinetic');
  100793. goog.require('ol.LoadingStrategy');
  100794. goog.require('ol.Map');
  100795. goog.require('ol.MapBrowserEvent');
  100796. goog.require('ol.MapBrowserEvent.EventType');
  100797. goog.require('ol.MapBrowserEventHandler');
  100798. goog.require('ol.MapBrowserPointerEvent');
  100799. goog.require('ol.MapEvent');
  100800. goog.require('ol.MapEventType');
  100801. goog.require('ol.MapProperty');
  100802. goog.require('ol.Object');
  100803. goog.require('ol.ObjectEvent');
  100804. goog.require('ol.ObjectEventType');
  100805. goog.require('ol.Observable');
  100806. goog.require('ol.Overlay');
  100807. goog.require('ol.OverlayPositioning');
  100808. goog.require('ol.OverlayProperty');
  100809. goog.require('ol.Size');
  100810. goog.require('ol.Sphere');
  100811. goog.require('ol.Tile');
  100812. goog.require('ol.TileState');
  100813. goog.require('ol.View');
  100814. goog.require('ol.ViewHint');
  100815. goog.require('ol.ViewProperty');
  100816. goog.require('ol.animation');
  100817. goog.require('ol.color');
  100818. goog.require('ol.control');
  100819. goog.require('ol.control.Attribution');
  100820. goog.require('ol.control.Control');
  100821. goog.require('ol.control.FullScreen');
  100822. goog.require('ol.control.MousePosition');
  100823. goog.require('ol.control.OverviewMap');
  100824. goog.require('ol.control.Rotate');
  100825. goog.require('ol.control.ScaleLine');
  100826. goog.require('ol.control.ScaleLineProperty');
  100827. goog.require('ol.control.ScaleLineUnits');
  100828. goog.require('ol.control.Zoom');
  100829. goog.require('ol.control.ZoomSlider');
  100830. goog.require('ol.control.ZoomToExtent');
  100831. goog.require('ol.coordinate');
  100832. goog.require('ol.easing');
  100833. goog.require('ol.events.ConditionType');
  100834. goog.require('ol.events.condition');
  100835. goog.require('ol.extent');
  100836. goog.require('ol.extent.Corner');
  100837. goog.require('ol.extent.Relationship');
  100838. goog.require('ol.featureloader');
  100839. goog.require('ol.format.EsriJSON');
  100840. goog.require('ol.format.Feature');
  100841. goog.require('ol.format.GML');
  100842. goog.require('ol.format.GML2');
  100843. goog.require('ol.format.GML3');
  100844. goog.require('ol.format.GMLBase');
  100845. goog.require('ol.format.GPX');
  100846. goog.require('ol.format.GeoJSON');
  100847. goog.require('ol.format.IGC');
  100848. goog.require('ol.format.IGCZ');
  100849. goog.require('ol.format.KML');
  100850. goog.require('ol.format.OSMXML');
  100851. goog.require('ol.format.Polyline');
  100852. goog.require('ol.format.TopoJSON');
  100853. goog.require('ol.format.WFS');
  100854. goog.require('ol.format.WKT');
  100855. goog.require('ol.format.WMSCapabilities');
  100856. goog.require('ol.format.WMSGetFeatureInfo');
  100857. goog.require('ol.format.WMTSCapabilities');
  100858. goog.require('ol.geom.Circle');
  100859. goog.require('ol.geom.Geometry');
  100860. goog.require('ol.geom.GeometryCollection');
  100861. goog.require('ol.geom.GeometryLayout');
  100862. goog.require('ol.geom.GeometryType');
  100863. goog.require('ol.geom.LineString');
  100864. goog.require('ol.geom.LinearRing');
  100865. goog.require('ol.geom.MultiLineString');
  100866. goog.require('ol.geom.MultiPoint');
  100867. goog.require('ol.geom.MultiPolygon');
  100868. goog.require('ol.geom.Point');
  100869. goog.require('ol.geom.Polygon');
  100870. goog.require('ol.geom.SimpleGeometry');
  100871. goog.require('ol.has');
  100872. goog.require('ol.interaction');
  100873. goog.require('ol.interaction.DoubleClickZoom');
  100874. goog.require('ol.interaction.DragAndDrop');
  100875. goog.require('ol.interaction.DragAndDropEvent');
  100876. goog.require('ol.interaction.DragBox');
  100877. goog.require('ol.interaction.DragPan');
  100878. goog.require('ol.interaction.DragRotate');
  100879. goog.require('ol.interaction.DragRotateAndZoom');
  100880. goog.require('ol.interaction.DragZoom');
  100881. goog.require('ol.interaction.Draw');
  100882. goog.require('ol.interaction.DrawEvent');
  100883. goog.require('ol.interaction.DrawEventType');
  100884. goog.require('ol.interaction.DrawGeometryFunctionType');
  100885. goog.require('ol.interaction.DrawMode');
  100886. goog.require('ol.interaction.Interaction');
  100887. goog.require('ol.interaction.InteractionProperty');
  100888. goog.require('ol.interaction.KeyboardPan');
  100889. goog.require('ol.interaction.KeyboardZoom');
  100890. goog.require('ol.interaction.Modify');
  100891. goog.require('ol.interaction.ModifyEvent');
  100892. goog.require('ol.interaction.MouseWheelZoom');
  100893. goog.require('ol.interaction.PinchRotate');
  100894. goog.require('ol.interaction.PinchZoom');
  100895. goog.require('ol.interaction.Pointer');
  100896. goog.require('ol.interaction.Select');
  100897. goog.require('ol.interaction.SelectEvent');
  100898. goog.require('ol.interaction.SelectEventType');
  100899. goog.require('ol.interaction.SelectFilterFunction');
  100900. goog.require('ol.interaction.Snap');
  100901. goog.require('ol.interaction.SnapProperty');
  100902. goog.require('ol.interaction.Translate');
  100903. goog.require('ol.layer.Base');
  100904. goog.require('ol.layer.Group');
  100905. goog.require('ol.layer.Heatmap');
  100906. goog.require('ol.layer.Image');
  100907. goog.require('ol.layer.Layer');
  100908. goog.require('ol.layer.LayerProperty');
  100909. goog.require('ol.layer.LayerState');
  100910. goog.require('ol.layer.Tile');
  100911. goog.require('ol.layer.Vector');
  100912. goog.require('ol.loadingstrategy');
  100913. goog.require('ol.proj');
  100914. goog.require('ol.proj.METERS_PER_UNIT');
  100915. goog.require('ol.proj.Projection');
  100916. goog.require('ol.proj.ProjectionLike');
  100917. goog.require('ol.proj.Units');
  100918. goog.require('ol.proj.common');
  100919. goog.require('ol.render.Event');
  100920. goog.require('ol.render.EventType');
  100921. goog.require('ol.render.VectorContext');
  100922. goog.require('ol.render.canvas.Immediate');
  100923. goog.require('ol.render.webgl.Immediate');
  100924. goog.require('ol.size');
  100925. goog.require('ol.source.BingMaps');
  100926. goog.require('ol.source.Cluster');
  100927. goog.require('ol.source.Image');
  100928. goog.require('ol.source.ImageCanvas');
  100929. goog.require('ol.source.ImageEvent');
  100930. goog.require('ol.source.ImageMapGuide');
  100931. goog.require('ol.source.ImageStatic');
  100932. goog.require('ol.source.ImageVector');
  100933. goog.require('ol.source.ImageWMS');
  100934. goog.require('ol.source.MapQuest');
  100935. goog.require('ol.source.OSM');
  100936. goog.require('ol.source.Raster');
  100937. goog.require('ol.source.RasterEvent');
  100938. goog.require('ol.source.RasterEventType');
  100939. goog.require('ol.source.Source');
  100940. goog.require('ol.source.Stamen');
  100941. goog.require('ol.source.State');
  100942. goog.require('ol.source.Tile');
  100943. goog.require('ol.source.TileArcGISRest');
  100944. goog.require('ol.source.TileDebug');
  100945. goog.require('ol.source.TileEvent');
  100946. goog.require('ol.source.TileImage');
  100947. goog.require('ol.source.TileJSON');
  100948. goog.require('ol.source.TileOptions');
  100949. goog.require('ol.source.TileUTFGrid');
  100950. goog.require('ol.source.TileVector');
  100951. goog.require('ol.source.TileWMS');
  100952. goog.require('ol.source.Vector');
  100953. goog.require('ol.source.VectorEvent');
  100954. goog.require('ol.source.VectorEventType');
  100955. goog.require('ol.source.WMTS');
  100956. goog.require('ol.source.WMTSRequestEncoding');
  100957. goog.require('ol.source.XYZ');
  100958. goog.require('ol.source.Zoomify');
  100959. goog.require('ol.style.Atlas');
  100960. goog.require('ol.style.AtlasManager');
  100961. goog.require('ol.style.Circle');
  100962. goog.require('ol.style.Fill');
  100963. goog.require('ol.style.GeometryFunction');
  100964. goog.require('ol.style.Icon');
  100965. goog.require('ol.style.IconAnchorUnits');
  100966. goog.require('ol.style.IconImageCache');
  100967. goog.require('ol.style.IconOrigin');
  100968. goog.require('ol.style.Image');
  100969. goog.require('ol.style.ImageState');
  100970. goog.require('ol.style.RegularShape');
  100971. goog.require('ol.style.Stroke');
  100972. goog.require('ol.style.Style');
  100973. goog.require('ol.style.StyleFunction');
  100974. goog.require('ol.style.Text');
  100975. goog.require('ol.style.defaultGeometryFunction');
  100976. goog.require('ol.tilegrid.TileGrid');
  100977. goog.require('ol.tilegrid.WMTS');
  100978. goog.require('ol.tilejson');
  100979. goog.require('ol.webgl.Context');
  100980. goog.require('ol.xml');
  100981. goog.exportSymbol(
  100982. 'ol.animation.bounce',
  100983. ol.animation.bounce,
  100984. OPENLAYERS);
  100985. goog.exportSymbol(
  100986. 'ol.animation.pan',
  100987. ol.animation.pan,
  100988. OPENLAYERS);
  100989. goog.exportSymbol(
  100990. 'ol.animation.rotate',
  100991. ol.animation.rotate,
  100992. OPENLAYERS);
  100993. goog.exportSymbol(
  100994. 'ol.animation.zoom',
  100995. ol.animation.zoom,
  100996. OPENLAYERS);
  100997. goog.exportSymbol(
  100998. 'ol.Attribution',
  100999. ol.Attribution,
  101000. OPENLAYERS);
  101001. goog.exportProperty(
  101002. ol.Attribution.prototype,
  101003. 'getHTML',
  101004. ol.Attribution.prototype.getHTML);
  101005. goog.exportProperty(
  101006. ol.CollectionEvent.prototype,
  101007. 'element',
  101008. ol.CollectionEvent.prototype.element);
  101009. goog.exportSymbol(
  101010. 'ol.Collection',
  101011. ol.Collection,
  101012. OPENLAYERS);
  101013. goog.exportProperty(
  101014. ol.Collection.prototype,
  101015. 'clear',
  101016. ol.Collection.prototype.clear);
  101017. goog.exportProperty(
  101018. ol.Collection.prototype,
  101019. 'extend',
  101020. ol.Collection.prototype.extend);
  101021. goog.exportProperty(
  101022. ol.Collection.prototype,
  101023. 'forEach',
  101024. ol.Collection.prototype.forEach);
  101025. goog.exportProperty(
  101026. ol.Collection.prototype,
  101027. 'getArray',
  101028. ol.Collection.prototype.getArray);
  101029. goog.exportProperty(
  101030. ol.Collection.prototype,
  101031. 'item',
  101032. ol.Collection.prototype.item);
  101033. goog.exportProperty(
  101034. ol.Collection.prototype,
  101035. 'getLength',
  101036. ol.Collection.prototype.getLength);
  101037. goog.exportProperty(
  101038. ol.Collection.prototype,
  101039. 'insertAt',
  101040. ol.Collection.prototype.insertAt);
  101041. goog.exportProperty(
  101042. ol.Collection.prototype,
  101043. 'pop',
  101044. ol.Collection.prototype.pop);
  101045. goog.exportProperty(
  101046. ol.Collection.prototype,
  101047. 'push',
  101048. ol.Collection.prototype.push);
  101049. goog.exportProperty(
  101050. ol.Collection.prototype,
  101051. 'remove',
  101052. ol.Collection.prototype.remove);
  101053. goog.exportProperty(
  101054. ol.Collection.prototype,
  101055. 'removeAt',
  101056. ol.Collection.prototype.removeAt);
  101057. goog.exportProperty(
  101058. ol.Collection.prototype,
  101059. 'setAt',
  101060. ol.Collection.prototype.setAt);
  101061. goog.exportSymbol(
  101062. 'ol.coordinate.add',
  101063. ol.coordinate.add,
  101064. OPENLAYERS);
  101065. goog.exportSymbol(
  101066. 'ol.coordinate.createStringXY',
  101067. ol.coordinate.createStringXY,
  101068. OPENLAYERS);
  101069. goog.exportSymbol(
  101070. 'ol.coordinate.format',
  101071. ol.coordinate.format,
  101072. OPENLAYERS);
  101073. goog.exportSymbol(
  101074. 'ol.coordinate.rotate',
  101075. ol.coordinate.rotate,
  101076. OPENLAYERS);
  101077. goog.exportSymbol(
  101078. 'ol.coordinate.toStringHDMS',
  101079. ol.coordinate.toStringHDMS,
  101080. OPENLAYERS);
  101081. goog.exportSymbol(
  101082. 'ol.coordinate.toStringXY',
  101083. ol.coordinate.toStringXY,
  101084. OPENLAYERS);
  101085. goog.exportSymbol(
  101086. 'ol.DeviceOrientation',
  101087. ol.DeviceOrientation,
  101088. OPENLAYERS);
  101089. goog.exportProperty(
  101090. ol.DeviceOrientation.prototype,
  101091. 'getAlpha',
  101092. ol.DeviceOrientation.prototype.getAlpha);
  101093. goog.exportProperty(
  101094. ol.DeviceOrientation.prototype,
  101095. 'getBeta',
  101096. ol.DeviceOrientation.prototype.getBeta);
  101097. goog.exportProperty(
  101098. ol.DeviceOrientation.prototype,
  101099. 'getGamma',
  101100. ol.DeviceOrientation.prototype.getGamma);
  101101. goog.exportProperty(
  101102. ol.DeviceOrientation.prototype,
  101103. 'getHeading',
  101104. ol.DeviceOrientation.prototype.getHeading);
  101105. goog.exportProperty(
  101106. ol.DeviceOrientation.prototype,
  101107. 'getTracking',
  101108. ol.DeviceOrientation.prototype.getTracking);
  101109. goog.exportProperty(
  101110. ol.DeviceOrientation.prototype,
  101111. 'setTracking',
  101112. ol.DeviceOrientation.prototype.setTracking);
  101113. goog.exportSymbol(
  101114. 'ol.easing.easeIn',
  101115. ol.easing.easeIn,
  101116. OPENLAYERS);
  101117. goog.exportSymbol(
  101118. 'ol.easing.easeOut',
  101119. ol.easing.easeOut,
  101120. OPENLAYERS);
  101121. goog.exportSymbol(
  101122. 'ol.easing.inAndOut',
  101123. ol.easing.inAndOut,
  101124. OPENLAYERS);
  101125. goog.exportSymbol(
  101126. 'ol.easing.linear',
  101127. ol.easing.linear,
  101128. OPENLAYERS);
  101129. goog.exportSymbol(
  101130. 'ol.easing.upAndDown',
  101131. ol.easing.upAndDown,
  101132. OPENLAYERS);
  101133. goog.exportSymbol(
  101134. 'ol.extent.boundingExtent',
  101135. ol.extent.boundingExtent,
  101136. OPENLAYERS);
  101137. goog.exportSymbol(
  101138. 'ol.extent.buffer',
  101139. ol.extent.buffer,
  101140. OPENLAYERS);
  101141. goog.exportSymbol(
  101142. 'ol.extent.containsCoordinate',
  101143. ol.extent.containsCoordinate,
  101144. OPENLAYERS);
  101145. goog.exportSymbol(
  101146. 'ol.extent.containsExtent',
  101147. ol.extent.containsExtent,
  101148. OPENLAYERS);
  101149. goog.exportSymbol(
  101150. 'ol.extent.containsXY',
  101151. ol.extent.containsXY,
  101152. OPENLAYERS);
  101153. goog.exportSymbol(
  101154. 'ol.extent.createEmpty',
  101155. ol.extent.createEmpty,
  101156. OPENLAYERS);
  101157. goog.exportSymbol(
  101158. 'ol.extent.equals',
  101159. ol.extent.equals,
  101160. OPENLAYERS);
  101161. goog.exportSymbol(
  101162. 'ol.extent.extend',
  101163. ol.extent.extend,
  101164. OPENLAYERS);
  101165. goog.exportSymbol(
  101166. 'ol.extent.getBottomLeft',
  101167. ol.extent.getBottomLeft,
  101168. OPENLAYERS);
  101169. goog.exportSymbol(
  101170. 'ol.extent.getBottomRight',
  101171. ol.extent.getBottomRight,
  101172. OPENLAYERS);
  101173. goog.exportSymbol(
  101174. 'ol.extent.getCenter',
  101175. ol.extent.getCenter,
  101176. OPENLAYERS);
  101177. goog.exportSymbol(
  101178. 'ol.extent.getHeight',
  101179. ol.extent.getHeight,
  101180. OPENLAYERS);
  101181. goog.exportSymbol(
  101182. 'ol.extent.getIntersection',
  101183. ol.extent.getIntersection,
  101184. OPENLAYERS);
  101185. goog.exportSymbol(
  101186. 'ol.extent.getSize',
  101187. ol.extent.getSize,
  101188. OPENLAYERS);
  101189. goog.exportSymbol(
  101190. 'ol.extent.getTopLeft',
  101191. ol.extent.getTopLeft,
  101192. OPENLAYERS);
  101193. goog.exportSymbol(
  101194. 'ol.extent.getTopRight',
  101195. ol.extent.getTopRight,
  101196. OPENLAYERS);
  101197. goog.exportSymbol(
  101198. 'ol.extent.getWidth',
  101199. ol.extent.getWidth,
  101200. OPENLAYERS);
  101201. goog.exportSymbol(
  101202. 'ol.extent.intersects',
  101203. ol.extent.intersects,
  101204. OPENLAYERS);
  101205. goog.exportSymbol(
  101206. 'ol.extent.isEmpty',
  101207. ol.extent.isEmpty,
  101208. OPENLAYERS);
  101209. goog.exportSymbol(
  101210. 'ol.extent.applyTransform',
  101211. ol.extent.applyTransform,
  101212. OPENLAYERS);
  101213. goog.exportSymbol(
  101214. 'ol.Feature',
  101215. ol.Feature,
  101216. OPENLAYERS);
  101217. goog.exportProperty(
  101218. ol.Feature.prototype,
  101219. 'clone',
  101220. ol.Feature.prototype.clone);
  101221. goog.exportProperty(
  101222. ol.Feature.prototype,
  101223. 'getGeometry',
  101224. ol.Feature.prototype.getGeometry);
  101225. goog.exportProperty(
  101226. ol.Feature.prototype,
  101227. 'getId',
  101228. ol.Feature.prototype.getId);
  101229. goog.exportProperty(
  101230. ol.Feature.prototype,
  101231. 'getGeometryName',
  101232. ol.Feature.prototype.getGeometryName);
  101233. goog.exportProperty(
  101234. ol.Feature.prototype,
  101235. 'getStyle',
  101236. ol.Feature.prototype.getStyle);
  101237. goog.exportProperty(
  101238. ol.Feature.prototype,
  101239. 'getStyleFunction',
  101240. ol.Feature.prototype.getStyleFunction);
  101241. goog.exportProperty(
  101242. ol.Feature.prototype,
  101243. 'setGeometry',
  101244. ol.Feature.prototype.setGeometry);
  101245. goog.exportProperty(
  101246. ol.Feature.prototype,
  101247. 'setStyle',
  101248. ol.Feature.prototype.setStyle);
  101249. goog.exportProperty(
  101250. ol.Feature.prototype,
  101251. 'setId',
  101252. ol.Feature.prototype.setId);
  101253. goog.exportProperty(
  101254. ol.Feature.prototype,
  101255. 'setGeometryName',
  101256. ol.Feature.prototype.setGeometryName);
  101257. goog.exportSymbol(
  101258. 'ol.featureloader.xhr',
  101259. ol.featureloader.xhr,
  101260. OPENLAYERS);
  101261. goog.exportSymbol(
  101262. 'ol.Geolocation',
  101263. ol.Geolocation,
  101264. OPENLAYERS);
  101265. goog.exportProperty(
  101266. ol.Geolocation.prototype,
  101267. 'getAccuracy',
  101268. ol.Geolocation.prototype.getAccuracy);
  101269. goog.exportProperty(
  101270. ol.Geolocation.prototype,
  101271. 'getAccuracyGeometry',
  101272. ol.Geolocation.prototype.getAccuracyGeometry);
  101273. goog.exportProperty(
  101274. ol.Geolocation.prototype,
  101275. 'getAltitude',
  101276. ol.Geolocation.prototype.getAltitude);
  101277. goog.exportProperty(
  101278. ol.Geolocation.prototype,
  101279. 'getAltitudeAccuracy',
  101280. ol.Geolocation.prototype.getAltitudeAccuracy);
  101281. goog.exportProperty(
  101282. ol.Geolocation.prototype,
  101283. 'getHeading',
  101284. ol.Geolocation.prototype.getHeading);
  101285. goog.exportProperty(
  101286. ol.Geolocation.prototype,
  101287. 'getPosition',
  101288. ol.Geolocation.prototype.getPosition);
  101289. goog.exportProperty(
  101290. ol.Geolocation.prototype,
  101291. 'getProjection',
  101292. ol.Geolocation.prototype.getProjection);
  101293. goog.exportProperty(
  101294. ol.Geolocation.prototype,
  101295. 'getSpeed',
  101296. ol.Geolocation.prototype.getSpeed);
  101297. goog.exportProperty(
  101298. ol.Geolocation.prototype,
  101299. 'getTracking',
  101300. ol.Geolocation.prototype.getTracking);
  101301. goog.exportProperty(
  101302. ol.Geolocation.prototype,
  101303. 'getTrackingOptions',
  101304. ol.Geolocation.prototype.getTrackingOptions);
  101305. goog.exportProperty(
  101306. ol.Geolocation.prototype,
  101307. 'setProjection',
  101308. ol.Geolocation.prototype.setProjection);
  101309. goog.exportProperty(
  101310. ol.Geolocation.prototype,
  101311. 'setTracking',
  101312. ol.Geolocation.prototype.setTracking);
  101313. goog.exportProperty(
  101314. ol.Geolocation.prototype,
  101315. 'setTrackingOptions',
  101316. ol.Geolocation.prototype.setTrackingOptions);
  101317. goog.exportSymbol(
  101318. 'ol.Graticule',
  101319. ol.Graticule,
  101320. OPENLAYERS);
  101321. goog.exportProperty(
  101322. ol.Graticule.prototype,
  101323. 'getMap',
  101324. ol.Graticule.prototype.getMap);
  101325. goog.exportProperty(
  101326. ol.Graticule.prototype,
  101327. 'getMeridians',
  101328. ol.Graticule.prototype.getMeridians);
  101329. goog.exportProperty(
  101330. ol.Graticule.prototype,
  101331. 'getParallels',
  101332. ol.Graticule.prototype.getParallels);
  101333. goog.exportProperty(
  101334. ol.Graticule.prototype,
  101335. 'setMap',
  101336. ol.Graticule.prototype.setMap);
  101337. goog.exportSymbol(
  101338. 'ol.has.DEVICE_PIXEL_RATIO',
  101339. ol.has.DEVICE_PIXEL_RATIO,
  101340. OPENLAYERS);
  101341. goog.exportSymbol(
  101342. 'ol.has.CANVAS',
  101343. ol.has.CANVAS,
  101344. OPENLAYERS);
  101345. goog.exportSymbol(
  101346. 'ol.has.DEVICE_ORIENTATION',
  101347. ol.has.DEVICE_ORIENTATION,
  101348. OPENLAYERS);
  101349. goog.exportSymbol(
  101350. 'ol.has.GEOLOCATION',
  101351. ol.has.GEOLOCATION,
  101352. OPENLAYERS);
  101353. goog.exportSymbol(
  101354. 'ol.has.TOUCH',
  101355. ol.has.TOUCH,
  101356. OPENLAYERS);
  101357. goog.exportSymbol(
  101358. 'ol.has.WEBGL',
  101359. ol.has.WEBGL,
  101360. OPENLAYERS);
  101361. goog.exportProperty(
  101362. ol.Image.prototype,
  101363. 'getImage',
  101364. ol.Image.prototype.getImage);
  101365. goog.exportProperty(
  101366. ol.ImageTile.prototype,
  101367. 'getImage',
  101368. ol.ImageTile.prototype.getImage);
  101369. goog.exportSymbol(
  101370. 'ol.Kinetic',
  101371. ol.Kinetic,
  101372. OPENLAYERS);
  101373. goog.exportSymbol(
  101374. 'ol.loadingstrategy.all',
  101375. ol.loadingstrategy.all,
  101376. OPENLAYERS);
  101377. goog.exportSymbol(
  101378. 'ol.loadingstrategy.bbox',
  101379. ol.loadingstrategy.bbox,
  101380. OPENLAYERS);
  101381. goog.exportSymbol(
  101382. 'ol.loadingstrategy.tile',
  101383. ol.loadingstrategy.tile,
  101384. OPENLAYERS);
  101385. goog.exportSymbol(
  101386. 'ol.Map',
  101387. ol.Map,
  101388. OPENLAYERS);
  101389. goog.exportProperty(
  101390. ol.Map.prototype,
  101391. 'addControl',
  101392. ol.Map.prototype.addControl);
  101393. goog.exportProperty(
  101394. ol.Map.prototype,
  101395. 'addInteraction',
  101396. ol.Map.prototype.addInteraction);
  101397. goog.exportProperty(
  101398. ol.Map.prototype,
  101399. 'addLayer',
  101400. ol.Map.prototype.addLayer);
  101401. goog.exportProperty(
  101402. ol.Map.prototype,
  101403. 'addOverlay',
  101404. ol.Map.prototype.addOverlay);
  101405. goog.exportProperty(
  101406. ol.Map.prototype,
  101407. 'beforeRender',
  101408. ol.Map.prototype.beforeRender);
  101409. goog.exportProperty(
  101410. ol.Map.prototype,
  101411. 'forEachFeatureAtPixel',
  101412. ol.Map.prototype.forEachFeatureAtPixel);
  101413. goog.exportProperty(
  101414. ol.Map.prototype,
  101415. 'forEachLayerAtPixel',
  101416. ol.Map.prototype.forEachLayerAtPixel);
  101417. goog.exportProperty(
  101418. ol.Map.prototype,
  101419. 'hasFeatureAtPixel',
  101420. ol.Map.prototype.hasFeatureAtPixel);
  101421. goog.exportProperty(
  101422. ol.Map.prototype,
  101423. 'getEventCoordinate',
  101424. ol.Map.prototype.getEventCoordinate);
  101425. goog.exportProperty(
  101426. ol.Map.prototype,
  101427. 'getEventPixel',
  101428. ol.Map.prototype.getEventPixel);
  101429. goog.exportProperty(
  101430. ol.Map.prototype,
  101431. 'getTarget',
  101432. ol.Map.prototype.getTarget);
  101433. goog.exportProperty(
  101434. ol.Map.prototype,
  101435. 'getTargetElement',
  101436. ol.Map.prototype.getTargetElement);
  101437. goog.exportProperty(
  101438. ol.Map.prototype,
  101439. 'getCoordinateFromPixel',
  101440. ol.Map.prototype.getCoordinateFromPixel);
  101441. goog.exportProperty(
  101442. ol.Map.prototype,
  101443. 'getControls',
  101444. ol.Map.prototype.getControls);
  101445. goog.exportProperty(
  101446. ol.Map.prototype,
  101447. 'getOverlays',
  101448. ol.Map.prototype.getOverlays);
  101449. goog.exportProperty(
  101450. ol.Map.prototype,
  101451. 'getInteractions',
  101452. ol.Map.prototype.getInteractions);
  101453. goog.exportProperty(
  101454. ol.Map.prototype,
  101455. 'getLayerGroup',
  101456. ol.Map.prototype.getLayerGroup);
  101457. goog.exportProperty(
  101458. ol.Map.prototype,
  101459. 'getLayers',
  101460. ol.Map.prototype.getLayers);
  101461. goog.exportProperty(
  101462. ol.Map.prototype,
  101463. 'getPixelFromCoordinate',
  101464. ol.Map.prototype.getPixelFromCoordinate);
  101465. goog.exportProperty(
  101466. ol.Map.prototype,
  101467. 'getSize',
  101468. ol.Map.prototype.getSize);
  101469. goog.exportProperty(
  101470. ol.Map.prototype,
  101471. 'getView',
  101472. ol.Map.prototype.getView);
  101473. goog.exportProperty(
  101474. ol.Map.prototype,
  101475. 'getViewport',
  101476. ol.Map.prototype.getViewport);
  101477. goog.exportProperty(
  101478. ol.Map.prototype,
  101479. 'renderSync',
  101480. ol.Map.prototype.renderSync);
  101481. goog.exportProperty(
  101482. ol.Map.prototype,
  101483. 'render',
  101484. ol.Map.prototype.render);
  101485. goog.exportProperty(
  101486. ol.Map.prototype,
  101487. 'removeControl',
  101488. ol.Map.prototype.removeControl);
  101489. goog.exportProperty(
  101490. ol.Map.prototype,
  101491. 'removeInteraction',
  101492. ol.Map.prototype.removeInteraction);
  101493. goog.exportProperty(
  101494. ol.Map.prototype,
  101495. 'removeLayer',
  101496. ol.Map.prototype.removeLayer);
  101497. goog.exportProperty(
  101498. ol.Map.prototype,
  101499. 'removeOverlay',
  101500. ol.Map.prototype.removeOverlay);
  101501. goog.exportProperty(
  101502. ol.Map.prototype,
  101503. 'setLayerGroup',
  101504. ol.Map.prototype.setLayerGroup);
  101505. goog.exportProperty(
  101506. ol.Map.prototype,
  101507. 'setSize',
  101508. ol.Map.prototype.setSize);
  101509. goog.exportProperty(
  101510. ol.Map.prototype,
  101511. 'setTarget',
  101512. ol.Map.prototype.setTarget);
  101513. goog.exportProperty(
  101514. ol.Map.prototype,
  101515. 'setView',
  101516. ol.Map.prototype.setView);
  101517. goog.exportProperty(
  101518. ol.Map.prototype,
  101519. 'updateSize',
  101520. ol.Map.prototype.updateSize);
  101521. goog.exportProperty(
  101522. ol.MapBrowserEvent.prototype,
  101523. 'originalEvent',
  101524. ol.MapBrowserEvent.prototype.originalEvent);
  101525. goog.exportProperty(
  101526. ol.MapBrowserEvent.prototype,
  101527. 'pixel',
  101528. ol.MapBrowserEvent.prototype.pixel);
  101529. goog.exportProperty(
  101530. ol.MapBrowserEvent.prototype,
  101531. 'coordinate',
  101532. ol.MapBrowserEvent.prototype.coordinate);
  101533. goog.exportProperty(
  101534. ol.MapBrowserEvent.prototype,
  101535. 'dragging',
  101536. ol.MapBrowserEvent.prototype.dragging);
  101537. goog.exportProperty(
  101538. ol.MapBrowserEvent.prototype,
  101539. 'preventDefault',
  101540. ol.MapBrowserEvent.prototype.preventDefault);
  101541. goog.exportProperty(
  101542. ol.MapBrowserEvent.prototype,
  101543. 'stopPropagation',
  101544. ol.MapBrowserEvent.prototype.stopPropagation);
  101545. goog.exportProperty(
  101546. ol.MapEvent.prototype,
  101547. 'map',
  101548. ol.MapEvent.prototype.map);
  101549. goog.exportProperty(
  101550. ol.MapEvent.prototype,
  101551. 'frameState',
  101552. ol.MapEvent.prototype.frameState);
  101553. goog.exportProperty(
  101554. ol.ObjectEvent.prototype,
  101555. 'key',
  101556. ol.ObjectEvent.prototype.key);
  101557. goog.exportProperty(
  101558. ol.ObjectEvent.prototype,
  101559. 'oldValue',
  101560. ol.ObjectEvent.prototype.oldValue);
  101561. goog.exportSymbol(
  101562. 'ol.Object',
  101563. ol.Object,
  101564. OPENLAYERS);
  101565. goog.exportProperty(
  101566. ol.Object.prototype,
  101567. 'get',
  101568. ol.Object.prototype.get);
  101569. goog.exportProperty(
  101570. ol.Object.prototype,
  101571. 'getKeys',
  101572. ol.Object.prototype.getKeys);
  101573. goog.exportProperty(
  101574. ol.Object.prototype,
  101575. 'getProperties',
  101576. ol.Object.prototype.getProperties);
  101577. goog.exportProperty(
  101578. ol.Object.prototype,
  101579. 'set',
  101580. ol.Object.prototype.set);
  101581. goog.exportProperty(
  101582. ol.Object.prototype,
  101583. 'setProperties',
  101584. ol.Object.prototype.setProperties);
  101585. goog.exportProperty(
  101586. ol.Object.prototype,
  101587. 'unset',
  101588. ol.Object.prototype.unset);
  101589. goog.exportSymbol(
  101590. 'ol.Observable',
  101591. ol.Observable,
  101592. OPENLAYERS);
  101593. goog.exportSymbol(
  101594. 'ol.Observable.unByKey',
  101595. ol.Observable.unByKey,
  101596. OPENLAYERS);
  101597. goog.exportProperty(
  101598. ol.Observable.prototype,
  101599. 'changed',
  101600. ol.Observable.prototype.changed);
  101601. goog.exportProperty(
  101602. ol.Observable.prototype,
  101603. 'getRevision',
  101604. ol.Observable.prototype.getRevision);
  101605. goog.exportProperty(
  101606. ol.Observable.prototype,
  101607. 'on',
  101608. ol.Observable.prototype.on);
  101609. goog.exportProperty(
  101610. ol.Observable.prototype,
  101611. 'once',
  101612. ol.Observable.prototype.once);
  101613. goog.exportProperty(
  101614. ol.Observable.prototype,
  101615. 'un',
  101616. ol.Observable.prototype.un);
  101617. goog.exportProperty(
  101618. ol.Observable.prototype,
  101619. 'unByKey',
  101620. ol.Observable.prototype.unByKey);
  101621. goog.exportSymbol(
  101622. 'ol.inherits',
  101623. ol.inherits,
  101624. OPENLAYERS);
  101625. goog.exportSymbol(
  101626. 'ol.Overlay',
  101627. ol.Overlay,
  101628. OPENLAYERS);
  101629. goog.exportProperty(
  101630. ol.Overlay.prototype,
  101631. 'getElement',
  101632. ol.Overlay.prototype.getElement);
  101633. goog.exportProperty(
  101634. ol.Overlay.prototype,
  101635. 'getMap',
  101636. ol.Overlay.prototype.getMap);
  101637. goog.exportProperty(
  101638. ol.Overlay.prototype,
  101639. 'getOffset',
  101640. ol.Overlay.prototype.getOffset);
  101641. goog.exportProperty(
  101642. ol.Overlay.prototype,
  101643. 'getPosition',
  101644. ol.Overlay.prototype.getPosition);
  101645. goog.exportProperty(
  101646. ol.Overlay.prototype,
  101647. 'getPositioning',
  101648. ol.Overlay.prototype.getPositioning);
  101649. goog.exportProperty(
  101650. ol.Overlay.prototype,
  101651. 'setElement',
  101652. ol.Overlay.prototype.setElement);
  101653. goog.exportProperty(
  101654. ol.Overlay.prototype,
  101655. 'setMap',
  101656. ol.Overlay.prototype.setMap);
  101657. goog.exportProperty(
  101658. ol.Overlay.prototype,
  101659. 'setOffset',
  101660. ol.Overlay.prototype.setOffset);
  101661. goog.exportProperty(
  101662. ol.Overlay.prototype,
  101663. 'setPosition',
  101664. ol.Overlay.prototype.setPosition);
  101665. goog.exportProperty(
  101666. ol.Overlay.prototype,
  101667. 'setPositioning',
  101668. ol.Overlay.prototype.setPositioning);
  101669. goog.exportSymbol(
  101670. 'ol.size.toSize',
  101671. ol.size.toSize,
  101672. OPENLAYERS);
  101673. goog.exportProperty(
  101674. ol.Tile.prototype,
  101675. 'getTileCoord',
  101676. ol.Tile.prototype.getTileCoord);
  101677. goog.exportSymbol(
  101678. 'ol.View',
  101679. ol.View,
  101680. OPENLAYERS);
  101681. goog.exportProperty(
  101682. ol.View.prototype,
  101683. 'constrainCenter',
  101684. ol.View.prototype.constrainCenter);
  101685. goog.exportProperty(
  101686. ol.View.prototype,
  101687. 'constrainResolution',
  101688. ol.View.prototype.constrainResolution);
  101689. goog.exportProperty(
  101690. ol.View.prototype,
  101691. 'constrainRotation',
  101692. ol.View.prototype.constrainRotation);
  101693. goog.exportProperty(
  101694. ol.View.prototype,
  101695. 'getCenter',
  101696. ol.View.prototype.getCenter);
  101697. goog.exportProperty(
  101698. ol.View.prototype,
  101699. 'calculateExtent',
  101700. ol.View.prototype.calculateExtent);
  101701. goog.exportProperty(
  101702. ol.View.prototype,
  101703. 'getProjection',
  101704. ol.View.prototype.getProjection);
  101705. goog.exportProperty(
  101706. ol.View.prototype,
  101707. 'getResolution',
  101708. ol.View.prototype.getResolution);
  101709. goog.exportProperty(
  101710. ol.View.prototype,
  101711. 'getRotation',
  101712. ol.View.prototype.getRotation);
  101713. goog.exportProperty(
  101714. ol.View.prototype,
  101715. 'getZoom',
  101716. ol.View.prototype.getZoom);
  101717. goog.exportProperty(
  101718. ol.View.prototype,
  101719. 'fit',
  101720. ol.View.prototype.fit);
  101721. goog.exportProperty(
  101722. ol.View.prototype,
  101723. 'centerOn',
  101724. ol.View.prototype.centerOn);
  101725. goog.exportProperty(
  101726. ol.View.prototype,
  101727. 'rotate',
  101728. ol.View.prototype.rotate);
  101729. goog.exportProperty(
  101730. ol.View.prototype,
  101731. 'setCenter',
  101732. ol.View.prototype.setCenter);
  101733. goog.exportProperty(
  101734. ol.View.prototype,
  101735. 'setResolution',
  101736. ol.View.prototype.setResolution);
  101737. goog.exportProperty(
  101738. ol.View.prototype,
  101739. 'setRotation',
  101740. ol.View.prototype.setRotation);
  101741. goog.exportProperty(
  101742. ol.View.prototype,
  101743. 'setZoom',
  101744. ol.View.prototype.setZoom);
  101745. goog.exportSymbol(
  101746. 'ol.xml.getAllTextContent',
  101747. ol.xml.getAllTextContent,
  101748. OPENLAYERS);
  101749. goog.exportSymbol(
  101750. 'ol.xml.parse',
  101751. ol.xml.parse,
  101752. OPENLAYERS);
  101753. goog.exportSymbol(
  101754. 'ol.webgl.Context',
  101755. ol.webgl.Context,
  101756. OPENLAYERS);
  101757. goog.exportProperty(
  101758. ol.webgl.Context.prototype,
  101759. 'getGL',
  101760. ol.webgl.Context.prototype.getGL);
  101761. goog.exportProperty(
  101762. ol.webgl.Context.prototype,
  101763. 'useProgram',
  101764. ol.webgl.Context.prototype.useProgram);
  101765. goog.exportSymbol(
  101766. 'ol.tilegrid.TileGrid',
  101767. ol.tilegrid.TileGrid,
  101768. OPENLAYERS);
  101769. goog.exportProperty(
  101770. ol.tilegrid.TileGrid.prototype,
  101771. 'getMaxZoom',
  101772. ol.tilegrid.TileGrid.prototype.getMaxZoom);
  101773. goog.exportProperty(
  101774. ol.tilegrid.TileGrid.prototype,
  101775. 'getMinZoom',
  101776. ol.tilegrid.TileGrid.prototype.getMinZoom);
  101777. goog.exportProperty(
  101778. ol.tilegrid.TileGrid.prototype,
  101779. 'getOrigin',
  101780. ol.tilegrid.TileGrid.prototype.getOrigin);
  101781. goog.exportProperty(
  101782. ol.tilegrid.TileGrid.prototype,
  101783. 'getResolution',
  101784. ol.tilegrid.TileGrid.prototype.getResolution);
  101785. goog.exportProperty(
  101786. ol.tilegrid.TileGrid.prototype,
  101787. 'getResolutions',
  101788. ol.tilegrid.TileGrid.prototype.getResolutions);
  101789. goog.exportProperty(
  101790. ol.tilegrid.TileGrid.prototype,
  101791. 'getTileCoordForCoordAndResolution',
  101792. ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndResolution);
  101793. goog.exportProperty(
  101794. ol.tilegrid.TileGrid.prototype,
  101795. 'getTileCoordForCoordAndZ',
  101796. ol.tilegrid.TileGrid.prototype.getTileCoordForCoordAndZ);
  101797. goog.exportProperty(
  101798. ol.tilegrid.TileGrid.prototype,
  101799. 'getTileSize',
  101800. ol.tilegrid.TileGrid.prototype.getTileSize);
  101801. goog.exportSymbol(
  101802. 'ol.tilegrid.createXYZ',
  101803. ol.tilegrid.createXYZ,
  101804. OPENLAYERS);
  101805. goog.exportSymbol(
  101806. 'ol.tilegrid.WMTS',
  101807. ol.tilegrid.WMTS,
  101808. OPENLAYERS);
  101809. goog.exportProperty(
  101810. ol.tilegrid.WMTS.prototype,
  101811. 'getMatrixIds',
  101812. ol.tilegrid.WMTS.prototype.getMatrixIds);
  101813. goog.exportSymbol(
  101814. 'ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet',
  101815. ol.tilegrid.WMTS.createFromCapabilitiesMatrixSet,
  101816. OPENLAYERS);
  101817. goog.exportSymbol(
  101818. 'ol.style.AtlasManager',
  101819. ol.style.AtlasManager,
  101820. OPENLAYERS);
  101821. goog.exportSymbol(
  101822. 'ol.style.Circle',
  101823. ol.style.Circle,
  101824. OPENLAYERS);
  101825. goog.exportProperty(
  101826. ol.style.Circle.prototype,
  101827. 'getFill',
  101828. ol.style.Circle.prototype.getFill);
  101829. goog.exportProperty(
  101830. ol.style.Circle.prototype,
  101831. 'getImage',
  101832. ol.style.Circle.prototype.getImage);
  101833. goog.exportProperty(
  101834. ol.style.Circle.prototype,
  101835. 'getRadius',
  101836. ol.style.Circle.prototype.getRadius);
  101837. goog.exportProperty(
  101838. ol.style.Circle.prototype,
  101839. 'getStroke',
  101840. ol.style.Circle.prototype.getStroke);
  101841. goog.exportSymbol(
  101842. 'ol.style.Fill',
  101843. ol.style.Fill,
  101844. OPENLAYERS);
  101845. goog.exportProperty(
  101846. ol.style.Fill.prototype,
  101847. 'getColor',
  101848. ol.style.Fill.prototype.getColor);
  101849. goog.exportProperty(
  101850. ol.style.Fill.prototype,
  101851. 'setColor',
  101852. ol.style.Fill.prototype.setColor);
  101853. goog.exportSymbol(
  101854. 'ol.style.Icon',
  101855. ol.style.Icon,
  101856. OPENLAYERS);
  101857. goog.exportProperty(
  101858. ol.style.Icon.prototype,
  101859. 'getAnchor',
  101860. ol.style.Icon.prototype.getAnchor);
  101861. goog.exportProperty(
  101862. ol.style.Icon.prototype,
  101863. 'getImage',
  101864. ol.style.Icon.prototype.getImage);
  101865. goog.exportProperty(
  101866. ol.style.Icon.prototype,
  101867. 'getOrigin',
  101868. ol.style.Icon.prototype.getOrigin);
  101869. goog.exportProperty(
  101870. ol.style.Icon.prototype,
  101871. 'getSrc',
  101872. ol.style.Icon.prototype.getSrc);
  101873. goog.exportProperty(
  101874. ol.style.Icon.prototype,
  101875. 'getSize',
  101876. ol.style.Icon.prototype.getSize);
  101877. goog.exportProperty(
  101878. ol.style.Icon.prototype,
  101879. 'load',
  101880. ol.style.Icon.prototype.load);
  101881. goog.exportSymbol(
  101882. 'ol.style.Image',
  101883. ol.style.Image,
  101884. OPENLAYERS);
  101885. goog.exportProperty(
  101886. ol.style.Image.prototype,
  101887. 'getOpacity',
  101888. ol.style.Image.prototype.getOpacity);
  101889. goog.exportProperty(
  101890. ol.style.Image.prototype,
  101891. 'getRotateWithView',
  101892. ol.style.Image.prototype.getRotateWithView);
  101893. goog.exportProperty(
  101894. ol.style.Image.prototype,
  101895. 'getRotation',
  101896. ol.style.Image.prototype.getRotation);
  101897. goog.exportProperty(
  101898. ol.style.Image.prototype,
  101899. 'getScale',
  101900. ol.style.Image.prototype.getScale);
  101901. goog.exportProperty(
  101902. ol.style.Image.prototype,
  101903. 'getSnapToPixel',
  101904. ol.style.Image.prototype.getSnapToPixel);
  101905. goog.exportProperty(
  101906. ol.style.Image.prototype,
  101907. 'setOpacity',
  101908. ol.style.Image.prototype.setOpacity);
  101909. goog.exportProperty(
  101910. ol.style.Image.prototype,
  101911. 'setRotation',
  101912. ol.style.Image.prototype.setRotation);
  101913. goog.exportProperty(
  101914. ol.style.Image.prototype,
  101915. 'setScale',
  101916. ol.style.Image.prototype.setScale);
  101917. goog.exportSymbol(
  101918. 'ol.style.RegularShape',
  101919. ol.style.RegularShape,
  101920. OPENLAYERS);
  101921. goog.exportProperty(
  101922. ol.style.RegularShape.prototype,
  101923. 'getAnchor',
  101924. ol.style.RegularShape.prototype.getAnchor);
  101925. goog.exportProperty(
  101926. ol.style.RegularShape.prototype,
  101927. 'getAngle',
  101928. ol.style.RegularShape.prototype.getAngle);
  101929. goog.exportProperty(
  101930. ol.style.RegularShape.prototype,
  101931. 'getFill',
  101932. ol.style.RegularShape.prototype.getFill);
  101933. goog.exportProperty(
  101934. ol.style.RegularShape.prototype,
  101935. 'getImage',
  101936. ol.style.RegularShape.prototype.getImage);
  101937. goog.exportProperty(
  101938. ol.style.RegularShape.prototype,
  101939. 'getOrigin',
  101940. ol.style.RegularShape.prototype.getOrigin);
  101941. goog.exportProperty(
  101942. ol.style.RegularShape.prototype,
  101943. 'getPoints',
  101944. ol.style.RegularShape.prototype.getPoints);
  101945. goog.exportProperty(
  101946. ol.style.RegularShape.prototype,
  101947. 'getRadius',
  101948. ol.style.RegularShape.prototype.getRadius);
  101949. goog.exportProperty(
  101950. ol.style.RegularShape.prototype,
  101951. 'getRadius2',
  101952. ol.style.RegularShape.prototype.getRadius2);
  101953. goog.exportProperty(
  101954. ol.style.RegularShape.prototype,
  101955. 'getSize',
  101956. ol.style.RegularShape.prototype.getSize);
  101957. goog.exportProperty(
  101958. ol.style.RegularShape.prototype,
  101959. 'getStroke',
  101960. ol.style.RegularShape.prototype.getStroke);
  101961. goog.exportSymbol(
  101962. 'ol.style.Stroke',
  101963. ol.style.Stroke,
  101964. OPENLAYERS);
  101965. goog.exportProperty(
  101966. ol.style.Stroke.prototype,
  101967. 'getColor',
  101968. ol.style.Stroke.prototype.getColor);
  101969. goog.exportProperty(
  101970. ol.style.Stroke.prototype,
  101971. 'getLineCap',
  101972. ol.style.Stroke.prototype.getLineCap);
  101973. goog.exportProperty(
  101974. ol.style.Stroke.prototype,
  101975. 'getLineDash',
  101976. ol.style.Stroke.prototype.getLineDash);
  101977. goog.exportProperty(
  101978. ol.style.Stroke.prototype,
  101979. 'getLineJoin',
  101980. ol.style.Stroke.prototype.getLineJoin);
  101981. goog.exportProperty(
  101982. ol.style.Stroke.prototype,
  101983. 'getMiterLimit',
  101984. ol.style.Stroke.prototype.getMiterLimit);
  101985. goog.exportProperty(
  101986. ol.style.Stroke.prototype,
  101987. 'getWidth',
  101988. ol.style.Stroke.prototype.getWidth);
  101989. goog.exportProperty(
  101990. ol.style.Stroke.prototype,
  101991. 'setColor',
  101992. ol.style.Stroke.prototype.setColor);
  101993. goog.exportProperty(
  101994. ol.style.Stroke.prototype,
  101995. 'setLineCap',
  101996. ol.style.Stroke.prototype.setLineCap);
  101997. goog.exportProperty(
  101998. ol.style.Stroke.prototype,
  101999. 'setLineDash',
  102000. ol.style.Stroke.prototype.setLineDash);
  102001. goog.exportProperty(
  102002. ol.style.Stroke.prototype,
  102003. 'setLineJoin',
  102004. ol.style.Stroke.prototype.setLineJoin);
  102005. goog.exportProperty(
  102006. ol.style.Stroke.prototype,
  102007. 'setMiterLimit',
  102008. ol.style.Stroke.prototype.setMiterLimit);
  102009. goog.exportProperty(
  102010. ol.style.Stroke.prototype,
  102011. 'setWidth',
  102012. ol.style.Stroke.prototype.setWidth);
  102013. goog.exportSymbol(
  102014. 'ol.style.Style',
  102015. ol.style.Style,
  102016. OPENLAYERS);
  102017. goog.exportProperty(
  102018. ol.style.Style.prototype,
  102019. 'getGeometry',
  102020. ol.style.Style.prototype.getGeometry);
  102021. goog.exportProperty(
  102022. ol.style.Style.prototype,
  102023. 'getGeometryFunction',
  102024. ol.style.Style.prototype.getGeometryFunction);
  102025. goog.exportProperty(
  102026. ol.style.Style.prototype,
  102027. 'getFill',
  102028. ol.style.Style.prototype.getFill);
  102029. goog.exportProperty(
  102030. ol.style.Style.prototype,
  102031. 'getImage',
  102032. ol.style.Style.prototype.getImage);
  102033. goog.exportProperty(
  102034. ol.style.Style.prototype,
  102035. 'getStroke',
  102036. ol.style.Style.prototype.getStroke);
  102037. goog.exportProperty(
  102038. ol.style.Style.prototype,
  102039. 'getText',
  102040. ol.style.Style.prototype.getText);
  102041. goog.exportProperty(
  102042. ol.style.Style.prototype,
  102043. 'getZIndex',
  102044. ol.style.Style.prototype.getZIndex);
  102045. goog.exportProperty(
  102046. ol.style.Style.prototype,
  102047. 'setGeometry',
  102048. ol.style.Style.prototype.setGeometry);
  102049. goog.exportProperty(
  102050. ol.style.Style.prototype,
  102051. 'setZIndex',
  102052. ol.style.Style.prototype.setZIndex);
  102053. goog.exportSymbol(
  102054. 'ol.style.Text',
  102055. ol.style.Text,
  102056. OPENLAYERS);
  102057. goog.exportProperty(
  102058. ol.style.Text.prototype,
  102059. 'getFont',
  102060. ol.style.Text.prototype.getFont);
  102061. goog.exportProperty(
  102062. ol.style.Text.prototype,
  102063. 'getOffsetX',
  102064. ol.style.Text.prototype.getOffsetX);
  102065. goog.exportProperty(
  102066. ol.style.Text.prototype,
  102067. 'getOffsetY',
  102068. ol.style.Text.prototype.getOffsetY);
  102069. goog.exportProperty(
  102070. ol.style.Text.prototype,
  102071. 'getFill',
  102072. ol.style.Text.prototype.getFill);
  102073. goog.exportProperty(
  102074. ol.style.Text.prototype,
  102075. 'getRotation',
  102076. ol.style.Text.prototype.getRotation);
  102077. goog.exportProperty(
  102078. ol.style.Text.prototype,
  102079. 'getScale',
  102080. ol.style.Text.prototype.getScale);
  102081. goog.exportProperty(
  102082. ol.style.Text.prototype,
  102083. 'getStroke',
  102084. ol.style.Text.prototype.getStroke);
  102085. goog.exportProperty(
  102086. ol.style.Text.prototype,
  102087. 'getText',
  102088. ol.style.Text.prototype.getText);
  102089. goog.exportProperty(
  102090. ol.style.Text.prototype,
  102091. 'getTextAlign',
  102092. ol.style.Text.prototype.getTextAlign);
  102093. goog.exportProperty(
  102094. ol.style.Text.prototype,
  102095. 'getTextBaseline',
  102096. ol.style.Text.prototype.getTextBaseline);
  102097. goog.exportProperty(
  102098. ol.style.Text.prototype,
  102099. 'setFont',
  102100. ol.style.Text.prototype.setFont);
  102101. goog.exportProperty(
  102102. ol.style.Text.prototype,
  102103. 'setFill',
  102104. ol.style.Text.prototype.setFill);
  102105. goog.exportProperty(
  102106. ol.style.Text.prototype,
  102107. 'setRotation',
  102108. ol.style.Text.prototype.setRotation);
  102109. goog.exportProperty(
  102110. ol.style.Text.prototype,
  102111. 'setScale',
  102112. ol.style.Text.prototype.setScale);
  102113. goog.exportProperty(
  102114. ol.style.Text.prototype,
  102115. 'setStroke',
  102116. ol.style.Text.prototype.setStroke);
  102117. goog.exportProperty(
  102118. ol.style.Text.prototype,
  102119. 'setText',
  102120. ol.style.Text.prototype.setText);
  102121. goog.exportProperty(
  102122. ol.style.Text.prototype,
  102123. 'setTextAlign',
  102124. ol.style.Text.prototype.setTextAlign);
  102125. goog.exportProperty(
  102126. ol.style.Text.prototype,
  102127. 'setTextBaseline',
  102128. ol.style.Text.prototype.setTextBaseline);
  102129. goog.exportSymbol(
  102130. 'ol.Sphere',
  102131. ol.Sphere,
  102132. OPENLAYERS);
  102133. goog.exportProperty(
  102134. ol.Sphere.prototype,
  102135. 'geodesicArea',
  102136. ol.Sphere.prototype.geodesicArea);
  102137. goog.exportProperty(
  102138. ol.Sphere.prototype,
  102139. 'haversineDistance',
  102140. ol.Sphere.prototype.haversineDistance);
  102141. goog.exportSymbol(
  102142. 'ol.source.BingMaps',
  102143. ol.source.BingMaps,
  102144. OPENLAYERS);
  102145. goog.exportSymbol(
  102146. 'ol.source.BingMaps.TOS_ATTRIBUTION',
  102147. ol.source.BingMaps.TOS_ATTRIBUTION,
  102148. OPENLAYERS);
  102149. goog.exportSymbol(
  102150. 'ol.source.Cluster',
  102151. ol.source.Cluster,
  102152. OPENLAYERS);
  102153. goog.exportProperty(
  102154. ol.source.Cluster.prototype,
  102155. 'getSource',
  102156. ol.source.Cluster.prototype.getSource);
  102157. goog.exportSymbol(
  102158. 'ol.source.ImageCanvas',
  102159. ol.source.ImageCanvas,
  102160. OPENLAYERS);
  102161. goog.exportSymbol(
  102162. 'ol.source.ImageMapGuide',
  102163. ol.source.ImageMapGuide,
  102164. OPENLAYERS);
  102165. goog.exportProperty(
  102166. ol.source.ImageMapGuide.prototype,
  102167. 'getParams',
  102168. ol.source.ImageMapGuide.prototype.getParams);
  102169. goog.exportProperty(
  102170. ol.source.ImageMapGuide.prototype,
  102171. 'getImageLoadFunction',
  102172. ol.source.ImageMapGuide.prototype.getImageLoadFunction);
  102173. goog.exportProperty(
  102174. ol.source.ImageMapGuide.prototype,
  102175. 'updateParams',
  102176. ol.source.ImageMapGuide.prototype.updateParams);
  102177. goog.exportProperty(
  102178. ol.source.ImageMapGuide.prototype,
  102179. 'setImageLoadFunction',
  102180. ol.source.ImageMapGuide.prototype.setImageLoadFunction);
  102181. goog.exportSymbol(
  102182. 'ol.source.Image',
  102183. ol.source.Image,
  102184. OPENLAYERS);
  102185. goog.exportProperty(
  102186. ol.source.ImageEvent.prototype,
  102187. 'image',
  102188. ol.source.ImageEvent.prototype.image);
  102189. goog.exportSymbol(
  102190. 'ol.source.ImageStatic',
  102191. ol.source.ImageStatic,
  102192. OPENLAYERS);
  102193. goog.exportSymbol(
  102194. 'ol.source.ImageVector',
  102195. ol.source.ImageVector,
  102196. OPENLAYERS);
  102197. goog.exportProperty(
  102198. ol.source.ImageVector.prototype,
  102199. 'getSource',
  102200. ol.source.ImageVector.prototype.getSource);
  102201. goog.exportProperty(
  102202. ol.source.ImageVector.prototype,
  102203. 'getStyle',
  102204. ol.source.ImageVector.prototype.getStyle);
  102205. goog.exportProperty(
  102206. ol.source.ImageVector.prototype,
  102207. 'getStyleFunction',
  102208. ol.source.ImageVector.prototype.getStyleFunction);
  102209. goog.exportProperty(
  102210. ol.source.ImageVector.prototype,
  102211. 'setStyle',
  102212. ol.source.ImageVector.prototype.setStyle);
  102213. goog.exportSymbol(
  102214. 'ol.source.ImageWMS',
  102215. ol.source.ImageWMS,
  102216. OPENLAYERS);
  102217. goog.exportProperty(
  102218. ol.source.ImageWMS.prototype,
  102219. 'getGetFeatureInfoUrl',
  102220. ol.source.ImageWMS.prototype.getGetFeatureInfoUrl);
  102221. goog.exportProperty(
  102222. ol.source.ImageWMS.prototype,
  102223. 'getParams',
  102224. ol.source.ImageWMS.prototype.getParams);
  102225. goog.exportProperty(
  102226. ol.source.ImageWMS.prototype,
  102227. 'getImageLoadFunction',
  102228. ol.source.ImageWMS.prototype.getImageLoadFunction);
  102229. goog.exportProperty(
  102230. ol.source.ImageWMS.prototype,
  102231. 'getUrl',
  102232. ol.source.ImageWMS.prototype.getUrl);
  102233. goog.exportProperty(
  102234. ol.source.ImageWMS.prototype,
  102235. 'setImageLoadFunction',
  102236. ol.source.ImageWMS.prototype.setImageLoadFunction);
  102237. goog.exportProperty(
  102238. ol.source.ImageWMS.prototype,
  102239. 'setUrl',
  102240. ol.source.ImageWMS.prototype.setUrl);
  102241. goog.exportProperty(
  102242. ol.source.ImageWMS.prototype,
  102243. 'updateParams',
  102244. ol.source.ImageWMS.prototype.updateParams);
  102245. goog.exportSymbol(
  102246. 'ol.source.MapQuest',
  102247. ol.source.MapQuest,
  102248. OPENLAYERS);
  102249. goog.exportProperty(
  102250. ol.source.MapQuest.prototype,
  102251. 'getLayer',
  102252. ol.source.MapQuest.prototype.getLayer);
  102253. goog.exportSymbol(
  102254. 'ol.source.OSM',
  102255. ol.source.OSM,
  102256. OPENLAYERS);
  102257. goog.exportSymbol(
  102258. 'ol.source.OSM.ATTRIBUTION',
  102259. ol.source.OSM.ATTRIBUTION,
  102260. OPENLAYERS);
  102261. goog.exportSymbol(
  102262. 'ol.source.Raster',
  102263. ol.source.Raster,
  102264. OPENLAYERS);
  102265. goog.exportProperty(
  102266. ol.source.Raster.prototype,
  102267. 'setOperation',
  102268. ol.source.Raster.prototype.setOperation);
  102269. goog.exportProperty(
  102270. ol.source.RasterEvent.prototype,
  102271. 'extent',
  102272. ol.source.RasterEvent.prototype.extent);
  102273. goog.exportProperty(
  102274. ol.source.RasterEvent.prototype,
  102275. 'resolution',
  102276. ol.source.RasterEvent.prototype.resolution);
  102277. goog.exportProperty(
  102278. ol.source.RasterEvent.prototype,
  102279. 'data',
  102280. ol.source.RasterEvent.prototype.data);
  102281. goog.exportSymbol(
  102282. 'ol.source.Source',
  102283. ol.source.Source,
  102284. OPENLAYERS);
  102285. goog.exportProperty(
  102286. ol.source.Source.prototype,
  102287. 'getAttributions',
  102288. ol.source.Source.prototype.getAttributions);
  102289. goog.exportProperty(
  102290. ol.source.Source.prototype,
  102291. 'getLogo',
  102292. ol.source.Source.prototype.getLogo);
  102293. goog.exportProperty(
  102294. ol.source.Source.prototype,
  102295. 'getProjection',
  102296. ol.source.Source.prototype.getProjection);
  102297. goog.exportProperty(
  102298. ol.source.Source.prototype,
  102299. 'getState',
  102300. ol.source.Source.prototype.getState);
  102301. goog.exportProperty(
  102302. ol.source.Source.prototype,
  102303. 'setAttributions',
  102304. ol.source.Source.prototype.setAttributions);
  102305. goog.exportSymbol(
  102306. 'ol.source.Stamen',
  102307. ol.source.Stamen,
  102308. OPENLAYERS);
  102309. goog.exportSymbol(
  102310. 'ol.source.TileArcGISRest',
  102311. ol.source.TileArcGISRest,
  102312. OPENLAYERS);
  102313. goog.exportProperty(
  102314. ol.source.TileArcGISRest.prototype,
  102315. 'getParams',
  102316. ol.source.TileArcGISRest.prototype.getParams);
  102317. goog.exportProperty(
  102318. ol.source.TileArcGISRest.prototype,
  102319. 'getUrls',
  102320. ol.source.TileArcGISRest.prototype.getUrls);
  102321. goog.exportProperty(
  102322. ol.source.TileArcGISRest.prototype,
  102323. 'setUrl',
  102324. ol.source.TileArcGISRest.prototype.setUrl);
  102325. goog.exportProperty(
  102326. ol.source.TileArcGISRest.prototype,
  102327. 'setUrls',
  102328. ol.source.TileArcGISRest.prototype.setUrls);
  102329. goog.exportProperty(
  102330. ol.source.TileArcGISRest.prototype,
  102331. 'updateParams',
  102332. ol.source.TileArcGISRest.prototype.updateParams);
  102333. goog.exportSymbol(
  102334. 'ol.source.TileDebug',
  102335. ol.source.TileDebug,
  102336. OPENLAYERS);
  102337. goog.exportSymbol(
  102338. 'ol.source.TileImage',
  102339. ol.source.TileImage,
  102340. OPENLAYERS);
  102341. goog.exportProperty(
  102342. ol.source.TileImage.prototype,
  102343. 'getTileLoadFunction',
  102344. ol.source.TileImage.prototype.getTileLoadFunction);
  102345. goog.exportProperty(
  102346. ol.source.TileImage.prototype,
  102347. 'getTileUrlFunction',
  102348. ol.source.TileImage.prototype.getTileUrlFunction);
  102349. goog.exportProperty(
  102350. ol.source.TileImage.prototype,
  102351. 'setTileLoadFunction',
  102352. ol.source.TileImage.prototype.setTileLoadFunction);
  102353. goog.exportProperty(
  102354. ol.source.TileImage.prototype,
  102355. 'setTileUrlFunction',
  102356. ol.source.TileImage.prototype.setTileUrlFunction);
  102357. goog.exportSymbol(
  102358. 'ol.source.TileJSON',
  102359. ol.source.TileJSON,
  102360. OPENLAYERS);
  102361. goog.exportSymbol(
  102362. 'ol.source.Tile',
  102363. ol.source.Tile,
  102364. OPENLAYERS);
  102365. goog.exportProperty(
  102366. ol.source.Tile.prototype,
  102367. 'getTileGrid',
  102368. ol.source.Tile.prototype.getTileGrid);
  102369. goog.exportProperty(
  102370. ol.source.TileEvent.prototype,
  102371. 'tile',
  102372. ol.source.TileEvent.prototype.tile);
  102373. goog.exportSymbol(
  102374. 'ol.source.TileUTFGrid',
  102375. ol.source.TileUTFGrid,
  102376. OPENLAYERS);
  102377. goog.exportProperty(
  102378. ol.source.TileUTFGrid.prototype,
  102379. 'getTemplate',
  102380. ol.source.TileUTFGrid.prototype.getTemplate);
  102381. goog.exportProperty(
  102382. ol.source.TileUTFGrid.prototype,
  102383. 'forDataAtCoordinateAndResolution',
  102384. ol.source.TileUTFGrid.prototype.forDataAtCoordinateAndResolution);
  102385. goog.exportSymbol(
  102386. 'ol.source.TileVector',
  102387. ol.source.TileVector,
  102388. OPENLAYERS);
  102389. goog.exportProperty(
  102390. ol.source.TileVector.prototype,
  102391. 'getFeaturesAtCoordinateAndResolution',
  102392. ol.source.TileVector.prototype.getFeaturesAtCoordinateAndResolution);
  102393. goog.exportSymbol(
  102394. 'ol.source.TileWMS',
  102395. ol.source.TileWMS,
  102396. OPENLAYERS);
  102397. goog.exportProperty(
  102398. ol.source.TileWMS.prototype,
  102399. 'getGetFeatureInfoUrl',
  102400. ol.source.TileWMS.prototype.getGetFeatureInfoUrl);
  102401. goog.exportProperty(
  102402. ol.source.TileWMS.prototype,
  102403. 'getParams',
  102404. ol.source.TileWMS.prototype.getParams);
  102405. goog.exportProperty(
  102406. ol.source.TileWMS.prototype,
  102407. 'getUrls',
  102408. ol.source.TileWMS.prototype.getUrls);
  102409. goog.exportProperty(
  102410. ol.source.TileWMS.prototype,
  102411. 'setUrl',
  102412. ol.source.TileWMS.prototype.setUrl);
  102413. goog.exportProperty(
  102414. ol.source.TileWMS.prototype,
  102415. 'setUrls',
  102416. ol.source.TileWMS.prototype.setUrls);
  102417. goog.exportProperty(
  102418. ol.source.TileWMS.prototype,
  102419. 'updateParams',
  102420. ol.source.TileWMS.prototype.updateParams);
  102421. goog.exportSymbol(
  102422. 'ol.source.Vector',
  102423. ol.source.Vector,
  102424. OPENLAYERS);
  102425. goog.exportProperty(
  102426. ol.source.Vector.prototype,
  102427. 'addFeature',
  102428. ol.source.Vector.prototype.addFeature);
  102429. goog.exportProperty(
  102430. ol.source.Vector.prototype,
  102431. 'addFeatures',
  102432. ol.source.Vector.prototype.addFeatures);
  102433. goog.exportProperty(
  102434. ol.source.Vector.prototype,
  102435. 'clear',
  102436. ol.source.Vector.prototype.clear);
  102437. goog.exportProperty(
  102438. ol.source.Vector.prototype,
  102439. 'forEachFeature',
  102440. ol.source.Vector.prototype.forEachFeature);
  102441. goog.exportProperty(
  102442. ol.source.Vector.prototype,
  102443. 'forEachFeatureInExtent',
  102444. ol.source.Vector.prototype.forEachFeatureInExtent);
  102445. goog.exportProperty(
  102446. ol.source.Vector.prototype,
  102447. 'forEachFeatureIntersectingExtent',
  102448. ol.source.Vector.prototype.forEachFeatureIntersectingExtent);
  102449. goog.exportProperty(
  102450. ol.source.Vector.prototype,
  102451. 'getFeaturesCollection',
  102452. ol.source.Vector.prototype.getFeaturesCollection);
  102453. goog.exportProperty(
  102454. ol.source.Vector.prototype,
  102455. 'getFeatures',
  102456. ol.source.Vector.prototype.getFeatures);
  102457. goog.exportProperty(
  102458. ol.source.Vector.prototype,
  102459. 'getFeaturesAtCoordinate',
  102460. ol.source.Vector.prototype.getFeaturesAtCoordinate);
  102461. goog.exportProperty(
  102462. ol.source.Vector.prototype,
  102463. 'getFeaturesInExtent',
  102464. ol.source.Vector.prototype.getFeaturesInExtent);
  102465. goog.exportProperty(
  102466. ol.source.Vector.prototype,
  102467. 'getClosestFeatureToCoordinate',
  102468. ol.source.Vector.prototype.getClosestFeatureToCoordinate);
  102469. goog.exportProperty(
  102470. ol.source.Vector.prototype,
  102471. 'getExtent',
  102472. ol.source.Vector.prototype.getExtent);
  102473. goog.exportProperty(
  102474. ol.source.Vector.prototype,
  102475. 'getFeatureById',
  102476. ol.source.Vector.prototype.getFeatureById);
  102477. goog.exportProperty(
  102478. ol.source.Vector.prototype,
  102479. 'removeFeature',
  102480. ol.source.Vector.prototype.removeFeature);
  102481. goog.exportProperty(
  102482. ol.source.VectorEvent.prototype,
  102483. 'feature',
  102484. ol.source.VectorEvent.prototype.feature);
  102485. goog.exportSymbol(
  102486. 'ol.source.WMTS',
  102487. ol.source.WMTS,
  102488. OPENLAYERS);
  102489. goog.exportProperty(
  102490. ol.source.WMTS.prototype,
  102491. 'getDimensions',
  102492. ol.source.WMTS.prototype.getDimensions);
  102493. goog.exportProperty(
  102494. ol.source.WMTS.prototype,
  102495. 'getFormat',
  102496. ol.source.WMTS.prototype.getFormat);
  102497. goog.exportProperty(
  102498. ol.source.WMTS.prototype,
  102499. 'getLayer',
  102500. ol.source.WMTS.prototype.getLayer);
  102501. goog.exportProperty(
  102502. ol.source.WMTS.prototype,
  102503. 'getMatrixSet',
  102504. ol.source.WMTS.prototype.getMatrixSet);
  102505. goog.exportProperty(
  102506. ol.source.WMTS.prototype,
  102507. 'getRequestEncoding',
  102508. ol.source.WMTS.prototype.getRequestEncoding);
  102509. goog.exportProperty(
  102510. ol.source.WMTS.prototype,
  102511. 'getStyle',
  102512. ol.source.WMTS.prototype.getStyle);
  102513. goog.exportProperty(
  102514. ol.source.WMTS.prototype,
  102515. 'getUrls',
  102516. ol.source.WMTS.prototype.getUrls);
  102517. goog.exportProperty(
  102518. ol.source.WMTS.prototype,
  102519. 'getVersion',
  102520. ol.source.WMTS.prototype.getVersion);
  102521. goog.exportProperty(
  102522. ol.source.WMTS.prototype,
  102523. 'updateDimensions',
  102524. ol.source.WMTS.prototype.updateDimensions);
  102525. goog.exportSymbol(
  102526. 'ol.source.WMTS.optionsFromCapabilities',
  102527. ol.source.WMTS.optionsFromCapabilities,
  102528. OPENLAYERS);
  102529. goog.exportSymbol(
  102530. 'ol.source.XYZ',
  102531. ol.source.XYZ,
  102532. OPENLAYERS);
  102533. goog.exportProperty(
  102534. ol.source.XYZ.prototype,
  102535. 'getUrls',
  102536. ol.source.XYZ.prototype.getUrls);
  102537. goog.exportProperty(
  102538. ol.source.XYZ.prototype,
  102539. 'setUrl',
  102540. ol.source.XYZ.prototype.setUrl);
  102541. goog.exportSymbol(
  102542. 'ol.source.Zoomify',
  102543. ol.source.Zoomify,
  102544. OPENLAYERS);
  102545. goog.exportProperty(
  102546. ol.render.Event.prototype,
  102547. 'vectorContext',
  102548. ol.render.Event.prototype.vectorContext);
  102549. goog.exportProperty(
  102550. ol.render.Event.prototype,
  102551. 'frameState',
  102552. ol.render.Event.prototype.frameState);
  102553. goog.exportProperty(
  102554. ol.render.Event.prototype,
  102555. 'context',
  102556. ol.render.Event.prototype.context);
  102557. goog.exportProperty(
  102558. ol.render.Event.prototype,
  102559. 'glContext',
  102560. ol.render.Event.prototype.glContext);
  102561. goog.exportSymbol(
  102562. 'ol.render.VectorContext',
  102563. ol.render.VectorContext,
  102564. OPENLAYERS);
  102565. goog.exportProperty(
  102566. ol.render.webgl.Immediate.prototype,
  102567. 'drawAsync',
  102568. ol.render.webgl.Immediate.prototype.drawAsync);
  102569. goog.exportProperty(
  102570. ol.render.webgl.Immediate.prototype,
  102571. 'drawCircleGeometry',
  102572. ol.render.webgl.Immediate.prototype.drawCircleGeometry);
  102573. goog.exportProperty(
  102574. ol.render.webgl.Immediate.prototype,
  102575. 'drawFeature',
  102576. ol.render.webgl.Immediate.prototype.drawFeature);
  102577. goog.exportProperty(
  102578. ol.render.webgl.Immediate.prototype,
  102579. 'drawGeometryCollectionGeometry',
  102580. ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry);
  102581. goog.exportProperty(
  102582. ol.render.webgl.Immediate.prototype,
  102583. 'drawPointGeometry',
  102584. ol.render.webgl.Immediate.prototype.drawPointGeometry);
  102585. goog.exportProperty(
  102586. ol.render.webgl.Immediate.prototype,
  102587. 'drawLineStringGeometry',
  102588. ol.render.webgl.Immediate.prototype.drawLineStringGeometry);
  102589. goog.exportProperty(
  102590. ol.render.webgl.Immediate.prototype,
  102591. 'drawMultiLineStringGeometry',
  102592. ol.render.webgl.Immediate.prototype.drawMultiLineStringGeometry);
  102593. goog.exportProperty(
  102594. ol.render.webgl.Immediate.prototype,
  102595. 'drawMultiPointGeometry',
  102596. ol.render.webgl.Immediate.prototype.drawMultiPointGeometry);
  102597. goog.exportProperty(
  102598. ol.render.webgl.Immediate.prototype,
  102599. 'drawMultiPolygonGeometry',
  102600. ol.render.webgl.Immediate.prototype.drawMultiPolygonGeometry);
  102601. goog.exportProperty(
  102602. ol.render.webgl.Immediate.prototype,
  102603. 'drawPolygonGeometry',
  102604. ol.render.webgl.Immediate.prototype.drawPolygonGeometry);
  102605. goog.exportProperty(
  102606. ol.render.webgl.Immediate.prototype,
  102607. 'drawText',
  102608. ol.render.webgl.Immediate.prototype.drawText);
  102609. goog.exportProperty(
  102610. ol.render.webgl.Immediate.prototype,
  102611. 'setFillStrokeStyle',
  102612. ol.render.webgl.Immediate.prototype.setFillStrokeStyle);
  102613. goog.exportProperty(
  102614. ol.render.webgl.Immediate.prototype,
  102615. 'setImageStyle',
  102616. ol.render.webgl.Immediate.prototype.setImageStyle);
  102617. goog.exportProperty(
  102618. ol.render.webgl.Immediate.prototype,
  102619. 'setTextStyle',
  102620. ol.render.webgl.Immediate.prototype.setTextStyle);
  102621. goog.exportProperty(
  102622. ol.render.canvas.Immediate.prototype,
  102623. 'drawAsync',
  102624. ol.render.canvas.Immediate.prototype.drawAsync);
  102625. goog.exportProperty(
  102626. ol.render.canvas.Immediate.prototype,
  102627. 'drawCircleGeometry',
  102628. ol.render.canvas.Immediate.prototype.drawCircleGeometry);
  102629. goog.exportProperty(
  102630. ol.render.canvas.Immediate.prototype,
  102631. 'drawFeature',
  102632. ol.render.canvas.Immediate.prototype.drawFeature);
  102633. goog.exportProperty(
  102634. ol.render.canvas.Immediate.prototype,
  102635. 'drawPointGeometry',
  102636. ol.render.canvas.Immediate.prototype.drawPointGeometry);
  102637. goog.exportProperty(
  102638. ol.render.canvas.Immediate.prototype,
  102639. 'drawMultiPointGeometry',
  102640. ol.render.canvas.Immediate.prototype.drawMultiPointGeometry);
  102641. goog.exportProperty(
  102642. ol.render.canvas.Immediate.prototype,
  102643. 'drawLineStringGeometry',
  102644. ol.render.canvas.Immediate.prototype.drawLineStringGeometry);
  102645. goog.exportProperty(
  102646. ol.render.canvas.Immediate.prototype,
  102647. 'drawMultiLineStringGeometry',
  102648. ol.render.canvas.Immediate.prototype.drawMultiLineStringGeometry);
  102649. goog.exportProperty(
  102650. ol.render.canvas.Immediate.prototype,
  102651. 'drawPolygonGeometry',
  102652. ol.render.canvas.Immediate.prototype.drawPolygonGeometry);
  102653. goog.exportProperty(
  102654. ol.render.canvas.Immediate.prototype,
  102655. 'drawMultiPolygonGeometry',
  102656. ol.render.canvas.Immediate.prototype.drawMultiPolygonGeometry);
  102657. goog.exportProperty(
  102658. ol.render.canvas.Immediate.prototype,
  102659. 'setFillStrokeStyle',
  102660. ol.render.canvas.Immediate.prototype.setFillStrokeStyle);
  102661. goog.exportProperty(
  102662. ol.render.canvas.Immediate.prototype,
  102663. 'setImageStyle',
  102664. ol.render.canvas.Immediate.prototype.setImageStyle);
  102665. goog.exportProperty(
  102666. ol.render.canvas.Immediate.prototype,
  102667. 'setTextStyle',
  102668. ol.render.canvas.Immediate.prototype.setTextStyle);
  102669. goog.exportSymbol(
  102670. 'ol.proj.common.add',
  102671. ol.proj.common.add,
  102672. OPENLAYERS);
  102673. goog.exportSymbol(
  102674. 'ol.proj.METERS_PER_UNIT',
  102675. ol.proj.METERS_PER_UNIT,
  102676. OPENLAYERS);
  102677. goog.exportSymbol(
  102678. 'ol.proj.Projection',
  102679. ol.proj.Projection,
  102680. OPENLAYERS);
  102681. goog.exportProperty(
  102682. ol.proj.Projection.prototype,
  102683. 'getCode',
  102684. ol.proj.Projection.prototype.getCode);
  102685. goog.exportProperty(
  102686. ol.proj.Projection.prototype,
  102687. 'getExtent',
  102688. ol.proj.Projection.prototype.getExtent);
  102689. goog.exportProperty(
  102690. ol.proj.Projection.prototype,
  102691. 'getUnits',
  102692. ol.proj.Projection.prototype.getUnits);
  102693. goog.exportProperty(
  102694. ol.proj.Projection.prototype,
  102695. 'getMetersPerUnit',
  102696. ol.proj.Projection.prototype.getMetersPerUnit);
  102697. goog.exportProperty(
  102698. ol.proj.Projection.prototype,
  102699. 'getWorldExtent',
  102700. ol.proj.Projection.prototype.getWorldExtent);
  102701. goog.exportProperty(
  102702. ol.proj.Projection.prototype,
  102703. 'isGlobal',
  102704. ol.proj.Projection.prototype.isGlobal);
  102705. goog.exportProperty(
  102706. ol.proj.Projection.prototype,
  102707. 'setGlobal',
  102708. ol.proj.Projection.prototype.setGlobal);
  102709. goog.exportProperty(
  102710. ol.proj.Projection.prototype,
  102711. 'setExtent',
  102712. ol.proj.Projection.prototype.setExtent);
  102713. goog.exportProperty(
  102714. ol.proj.Projection.prototype,
  102715. 'setWorldExtent',
  102716. ol.proj.Projection.prototype.setWorldExtent);
  102717. goog.exportProperty(
  102718. ol.proj.Projection.prototype,
  102719. 'setGetPointResolution',
  102720. ol.proj.Projection.prototype.setGetPointResolution);
  102721. goog.exportProperty(
  102722. ol.proj.Projection.prototype,
  102723. 'getPointResolution',
  102724. ol.proj.Projection.prototype.getPointResolution);
  102725. goog.exportSymbol(
  102726. 'ol.proj.addEquivalentProjections',
  102727. ol.proj.addEquivalentProjections,
  102728. OPENLAYERS);
  102729. goog.exportSymbol(
  102730. 'ol.proj.addProjection',
  102731. ol.proj.addProjection,
  102732. OPENLAYERS);
  102733. goog.exportSymbol(
  102734. 'ol.proj.addCoordinateTransforms',
  102735. ol.proj.addCoordinateTransforms,
  102736. OPENLAYERS);
  102737. goog.exportSymbol(
  102738. 'ol.proj.fromLonLat',
  102739. ol.proj.fromLonLat,
  102740. OPENLAYERS);
  102741. goog.exportSymbol(
  102742. 'ol.proj.toLonLat',
  102743. ol.proj.toLonLat,
  102744. OPENLAYERS);
  102745. goog.exportSymbol(
  102746. 'ol.proj.get',
  102747. ol.proj.get,
  102748. OPENLAYERS);
  102749. goog.exportSymbol(
  102750. 'ol.proj.getTransform',
  102751. ol.proj.getTransform,
  102752. OPENLAYERS);
  102753. goog.exportSymbol(
  102754. 'ol.proj.transform',
  102755. ol.proj.transform,
  102756. OPENLAYERS);
  102757. goog.exportSymbol(
  102758. 'ol.proj.transformExtent',
  102759. ol.proj.transformExtent,
  102760. OPENLAYERS);
  102761. goog.exportSymbol(
  102762. 'ol.layer.Heatmap',
  102763. ol.layer.Heatmap,
  102764. OPENLAYERS);
  102765. goog.exportProperty(
  102766. ol.layer.Heatmap.prototype,
  102767. 'getBlur',
  102768. ol.layer.Heatmap.prototype.getBlur);
  102769. goog.exportProperty(
  102770. ol.layer.Heatmap.prototype,
  102771. 'getGradient',
  102772. ol.layer.Heatmap.prototype.getGradient);
  102773. goog.exportProperty(
  102774. ol.layer.Heatmap.prototype,
  102775. 'getRadius',
  102776. ol.layer.Heatmap.prototype.getRadius);
  102777. goog.exportProperty(
  102778. ol.layer.Heatmap.prototype,
  102779. 'setBlur',
  102780. ol.layer.Heatmap.prototype.setBlur);
  102781. goog.exportProperty(
  102782. ol.layer.Heatmap.prototype,
  102783. 'setGradient',
  102784. ol.layer.Heatmap.prototype.setGradient);
  102785. goog.exportProperty(
  102786. ol.layer.Heatmap.prototype,
  102787. 'setRadius',
  102788. ol.layer.Heatmap.prototype.setRadius);
  102789. goog.exportSymbol(
  102790. 'ol.layer.Image',
  102791. ol.layer.Image,
  102792. OPENLAYERS);
  102793. goog.exportProperty(
  102794. ol.layer.Image.prototype,
  102795. 'getSource',
  102796. ol.layer.Image.prototype.getSource);
  102797. goog.exportSymbol(
  102798. 'ol.layer.Layer',
  102799. ol.layer.Layer,
  102800. OPENLAYERS);
  102801. goog.exportProperty(
  102802. ol.layer.Layer.prototype,
  102803. 'getSource',
  102804. ol.layer.Layer.prototype.getSource);
  102805. goog.exportProperty(
  102806. ol.layer.Layer.prototype,
  102807. 'setMap',
  102808. ol.layer.Layer.prototype.setMap);
  102809. goog.exportProperty(
  102810. ol.layer.Layer.prototype,
  102811. 'setSource',
  102812. ol.layer.Layer.prototype.setSource);
  102813. goog.exportSymbol(
  102814. 'ol.layer.Base',
  102815. ol.layer.Base,
  102816. OPENLAYERS);
  102817. goog.exportProperty(
  102818. ol.layer.Base.prototype,
  102819. 'getExtent',
  102820. ol.layer.Base.prototype.getExtent);
  102821. goog.exportProperty(
  102822. ol.layer.Base.prototype,
  102823. 'getMaxResolution',
  102824. ol.layer.Base.prototype.getMaxResolution);
  102825. goog.exportProperty(
  102826. ol.layer.Base.prototype,
  102827. 'getMinResolution',
  102828. ol.layer.Base.prototype.getMinResolution);
  102829. goog.exportProperty(
  102830. ol.layer.Base.prototype,
  102831. 'getOpacity',
  102832. ol.layer.Base.prototype.getOpacity);
  102833. goog.exportProperty(
  102834. ol.layer.Base.prototype,
  102835. 'getVisible',
  102836. ol.layer.Base.prototype.getVisible);
  102837. goog.exportProperty(
  102838. ol.layer.Base.prototype,
  102839. 'getZIndex',
  102840. ol.layer.Base.prototype.getZIndex);
  102841. goog.exportProperty(
  102842. ol.layer.Base.prototype,
  102843. 'setExtent',
  102844. ol.layer.Base.prototype.setExtent);
  102845. goog.exportProperty(
  102846. ol.layer.Base.prototype,
  102847. 'setMaxResolution',
  102848. ol.layer.Base.prototype.setMaxResolution);
  102849. goog.exportProperty(
  102850. ol.layer.Base.prototype,
  102851. 'setMinResolution',
  102852. ol.layer.Base.prototype.setMinResolution);
  102853. goog.exportProperty(
  102854. ol.layer.Base.prototype,
  102855. 'setOpacity',
  102856. ol.layer.Base.prototype.setOpacity);
  102857. goog.exportProperty(
  102858. ol.layer.Base.prototype,
  102859. 'setVisible',
  102860. ol.layer.Base.prototype.setVisible);
  102861. goog.exportProperty(
  102862. ol.layer.Base.prototype,
  102863. 'setZIndex',
  102864. ol.layer.Base.prototype.setZIndex);
  102865. goog.exportSymbol(
  102866. 'ol.layer.Group',
  102867. ol.layer.Group,
  102868. OPENLAYERS);
  102869. goog.exportProperty(
  102870. ol.layer.Group.prototype,
  102871. 'getLayers',
  102872. ol.layer.Group.prototype.getLayers);
  102873. goog.exportProperty(
  102874. ol.layer.Group.prototype,
  102875. 'setLayers',
  102876. ol.layer.Group.prototype.setLayers);
  102877. goog.exportSymbol(
  102878. 'ol.layer.Tile',
  102879. ol.layer.Tile,
  102880. OPENLAYERS);
  102881. goog.exportProperty(
  102882. ol.layer.Tile.prototype,
  102883. 'getPreload',
  102884. ol.layer.Tile.prototype.getPreload);
  102885. goog.exportProperty(
  102886. ol.layer.Tile.prototype,
  102887. 'getSource',
  102888. ol.layer.Tile.prototype.getSource);
  102889. goog.exportProperty(
  102890. ol.layer.Tile.prototype,
  102891. 'setPreload',
  102892. ol.layer.Tile.prototype.setPreload);
  102893. goog.exportProperty(
  102894. ol.layer.Tile.prototype,
  102895. 'getUseInterimTilesOnError',
  102896. ol.layer.Tile.prototype.getUseInterimTilesOnError);
  102897. goog.exportProperty(
  102898. ol.layer.Tile.prototype,
  102899. 'setUseInterimTilesOnError',
  102900. ol.layer.Tile.prototype.setUseInterimTilesOnError);
  102901. goog.exportSymbol(
  102902. 'ol.layer.Vector',
  102903. ol.layer.Vector,
  102904. OPENLAYERS);
  102905. goog.exportProperty(
  102906. ol.layer.Vector.prototype,
  102907. 'getSource',
  102908. ol.layer.Vector.prototype.getSource);
  102909. goog.exportProperty(
  102910. ol.layer.Vector.prototype,
  102911. 'getStyle',
  102912. ol.layer.Vector.prototype.getStyle);
  102913. goog.exportProperty(
  102914. ol.layer.Vector.prototype,
  102915. 'getStyleFunction',
  102916. ol.layer.Vector.prototype.getStyleFunction);
  102917. goog.exportProperty(
  102918. ol.layer.Vector.prototype,
  102919. 'setStyle',
  102920. ol.layer.Vector.prototype.setStyle);
  102921. goog.exportSymbol(
  102922. 'ol.interaction.DoubleClickZoom',
  102923. ol.interaction.DoubleClickZoom,
  102924. OPENLAYERS);
  102925. goog.exportSymbol(
  102926. 'ol.interaction.DoubleClickZoom.handleEvent',
  102927. ol.interaction.DoubleClickZoom.handleEvent,
  102928. OPENLAYERS);
  102929. goog.exportSymbol(
  102930. 'ol.interaction.DragAndDrop',
  102931. ol.interaction.DragAndDrop,
  102932. OPENLAYERS);
  102933. goog.exportSymbol(
  102934. 'ol.interaction.DragAndDrop.handleEvent',
  102935. ol.interaction.DragAndDrop.handleEvent,
  102936. OPENLAYERS);
  102937. goog.exportProperty(
  102938. ol.interaction.DragAndDropEvent.prototype,
  102939. 'features',
  102940. ol.interaction.DragAndDropEvent.prototype.features);
  102941. goog.exportProperty(
  102942. ol.interaction.DragAndDropEvent.prototype,
  102943. 'file',
  102944. ol.interaction.DragAndDropEvent.prototype.file);
  102945. goog.exportProperty(
  102946. ol.interaction.DragAndDropEvent.prototype,
  102947. 'projection',
  102948. ol.interaction.DragAndDropEvent.prototype.projection);
  102949. goog.exportProperty(
  102950. ol.DragBoxEvent.prototype,
  102951. 'coordinate',
  102952. ol.DragBoxEvent.prototype.coordinate);
  102953. goog.exportSymbol(
  102954. 'ol.interaction.DragBox',
  102955. ol.interaction.DragBox,
  102956. OPENLAYERS);
  102957. goog.exportProperty(
  102958. ol.interaction.DragBox.prototype,
  102959. 'getGeometry',
  102960. ol.interaction.DragBox.prototype.getGeometry);
  102961. goog.exportSymbol(
  102962. 'ol.interaction.DragPan',
  102963. ol.interaction.DragPan,
  102964. OPENLAYERS);
  102965. goog.exportSymbol(
  102966. 'ol.interaction.DragRotateAndZoom',
  102967. ol.interaction.DragRotateAndZoom,
  102968. OPENLAYERS);
  102969. goog.exportSymbol(
  102970. 'ol.interaction.DragRotate',
  102971. ol.interaction.DragRotate,
  102972. OPENLAYERS);
  102973. goog.exportSymbol(
  102974. 'ol.interaction.DragZoom',
  102975. ol.interaction.DragZoom,
  102976. OPENLAYERS);
  102977. goog.exportProperty(
  102978. ol.interaction.DrawEvent.prototype,
  102979. 'feature',
  102980. ol.interaction.DrawEvent.prototype.feature);
  102981. goog.exportSymbol(
  102982. 'ol.interaction.Draw',
  102983. ol.interaction.Draw,
  102984. OPENLAYERS);
  102985. goog.exportSymbol(
  102986. 'ol.interaction.Draw.handleEvent',
  102987. ol.interaction.Draw.handleEvent,
  102988. OPENLAYERS);
  102989. goog.exportProperty(
  102990. ol.interaction.Draw.prototype,
  102991. 'removeLastPoint',
  102992. ol.interaction.Draw.prototype.removeLastPoint);
  102993. goog.exportProperty(
  102994. ol.interaction.Draw.prototype,
  102995. 'finishDrawing',
  102996. ol.interaction.Draw.prototype.finishDrawing);
  102997. goog.exportProperty(
  102998. ol.interaction.Draw.prototype,
  102999. 'extend',
  103000. ol.interaction.Draw.prototype.extend);
  103001. goog.exportSymbol(
  103002. 'ol.interaction.Draw.createRegularPolygon',
  103003. ol.interaction.Draw.createRegularPolygon,
  103004. OPENLAYERS);
  103005. goog.exportSymbol(
  103006. 'ol.interaction.Interaction',
  103007. ol.interaction.Interaction,
  103008. OPENLAYERS);
  103009. goog.exportProperty(
  103010. ol.interaction.Interaction.prototype,
  103011. 'getActive',
  103012. ol.interaction.Interaction.prototype.getActive);
  103013. goog.exportProperty(
  103014. ol.interaction.Interaction.prototype,
  103015. 'setActive',
  103016. ol.interaction.Interaction.prototype.setActive);
  103017. goog.exportSymbol(
  103018. 'ol.interaction.defaults',
  103019. ol.interaction.defaults,
  103020. OPENLAYERS);
  103021. goog.exportSymbol(
  103022. 'ol.interaction.KeyboardPan',
  103023. ol.interaction.KeyboardPan,
  103024. OPENLAYERS);
  103025. goog.exportSymbol(
  103026. 'ol.interaction.KeyboardPan.handleEvent',
  103027. ol.interaction.KeyboardPan.handleEvent,
  103028. OPENLAYERS);
  103029. goog.exportSymbol(
  103030. 'ol.interaction.KeyboardZoom',
  103031. ol.interaction.KeyboardZoom,
  103032. OPENLAYERS);
  103033. goog.exportSymbol(
  103034. 'ol.interaction.KeyboardZoom.handleEvent',
  103035. ol.interaction.KeyboardZoom.handleEvent,
  103036. OPENLAYERS);
  103037. goog.exportProperty(
  103038. ol.interaction.ModifyEvent.prototype,
  103039. 'features',
  103040. ol.interaction.ModifyEvent.prototype.features);
  103041. goog.exportProperty(
  103042. ol.interaction.ModifyEvent.prototype,
  103043. 'mapBrowserPointerEvent',
  103044. ol.interaction.ModifyEvent.prototype.mapBrowserPointerEvent);
  103045. goog.exportSymbol(
  103046. 'ol.interaction.Modify',
  103047. ol.interaction.Modify,
  103048. OPENLAYERS);
  103049. goog.exportSymbol(
  103050. 'ol.interaction.Modify.handleEvent',
  103051. ol.interaction.Modify.handleEvent,
  103052. OPENLAYERS);
  103053. goog.exportSymbol(
  103054. 'ol.interaction.MouseWheelZoom',
  103055. ol.interaction.MouseWheelZoom,
  103056. OPENLAYERS);
  103057. goog.exportSymbol(
  103058. 'ol.interaction.MouseWheelZoom.handleEvent',
  103059. ol.interaction.MouseWheelZoom.handleEvent,
  103060. OPENLAYERS);
  103061. goog.exportProperty(
  103062. ol.interaction.MouseWheelZoom.prototype,
  103063. 'setMouseAnchor',
  103064. ol.interaction.MouseWheelZoom.prototype.setMouseAnchor);
  103065. goog.exportSymbol(
  103066. 'ol.interaction.PinchRotate',
  103067. ol.interaction.PinchRotate,
  103068. OPENLAYERS);
  103069. goog.exportSymbol(
  103070. 'ol.interaction.PinchZoom',
  103071. ol.interaction.PinchZoom,
  103072. OPENLAYERS);
  103073. goog.exportSymbol(
  103074. 'ol.interaction.Pointer',
  103075. ol.interaction.Pointer,
  103076. OPENLAYERS);
  103077. goog.exportSymbol(
  103078. 'ol.interaction.Pointer.handleEvent',
  103079. ol.interaction.Pointer.handleEvent,
  103080. OPENLAYERS);
  103081. goog.exportProperty(
  103082. ol.interaction.SelectEvent.prototype,
  103083. 'selected',
  103084. ol.interaction.SelectEvent.prototype.selected);
  103085. goog.exportProperty(
  103086. ol.interaction.SelectEvent.prototype,
  103087. 'deselected',
  103088. ol.interaction.SelectEvent.prototype.deselected);
  103089. goog.exportProperty(
  103090. ol.interaction.SelectEvent.prototype,
  103091. 'mapBrowserEvent',
  103092. ol.interaction.SelectEvent.prototype.mapBrowserEvent);
  103093. goog.exportSymbol(
  103094. 'ol.interaction.Select',
  103095. ol.interaction.Select,
  103096. OPENLAYERS);
  103097. goog.exportProperty(
  103098. ol.interaction.Select.prototype,
  103099. 'getFeatures',
  103100. ol.interaction.Select.prototype.getFeatures);
  103101. goog.exportProperty(
  103102. ol.interaction.Select.prototype,
  103103. 'getLayer',
  103104. ol.interaction.Select.prototype.getLayer);
  103105. goog.exportSymbol(
  103106. 'ol.interaction.Select.handleEvent',
  103107. ol.interaction.Select.handleEvent,
  103108. OPENLAYERS);
  103109. goog.exportProperty(
  103110. ol.interaction.Select.prototype,
  103111. 'setMap',
  103112. ol.interaction.Select.prototype.setMap);
  103113. goog.exportSymbol(
  103114. 'ol.interaction.Snap',
  103115. ol.interaction.Snap,
  103116. OPENLAYERS);
  103117. goog.exportProperty(
  103118. ol.interaction.Snap.prototype,
  103119. 'addFeature',
  103120. ol.interaction.Snap.prototype.addFeature);
  103121. goog.exportProperty(
  103122. ol.interaction.Snap.prototype,
  103123. 'removeFeature',
  103124. ol.interaction.Snap.prototype.removeFeature);
  103125. goog.exportSymbol(
  103126. 'ol.interaction.Translate',
  103127. ol.interaction.Translate,
  103128. OPENLAYERS);
  103129. goog.exportSymbol(
  103130. 'ol.geom.Circle',
  103131. ol.geom.Circle,
  103132. OPENLAYERS);
  103133. goog.exportProperty(
  103134. ol.geom.Circle.prototype,
  103135. 'clone',
  103136. ol.geom.Circle.prototype.clone);
  103137. goog.exportProperty(
  103138. ol.geom.Circle.prototype,
  103139. 'getCenter',
  103140. ol.geom.Circle.prototype.getCenter);
  103141. goog.exportProperty(
  103142. ol.geom.Circle.prototype,
  103143. 'getRadius',
  103144. ol.geom.Circle.prototype.getRadius);
  103145. goog.exportProperty(
  103146. ol.geom.Circle.prototype,
  103147. 'getType',
  103148. ol.geom.Circle.prototype.getType);
  103149. goog.exportProperty(
  103150. ol.geom.Circle.prototype,
  103151. 'intersectsExtent',
  103152. ol.geom.Circle.prototype.intersectsExtent);
  103153. goog.exportProperty(
  103154. ol.geom.Circle.prototype,
  103155. 'setCenter',
  103156. ol.geom.Circle.prototype.setCenter);
  103157. goog.exportProperty(
  103158. ol.geom.Circle.prototype,
  103159. 'setCenterAndRadius',
  103160. ol.geom.Circle.prototype.setCenterAndRadius);
  103161. goog.exportProperty(
  103162. ol.geom.Circle.prototype,
  103163. 'setRadius',
  103164. ol.geom.Circle.prototype.setRadius);
  103165. goog.exportProperty(
  103166. ol.geom.Circle.prototype,
  103167. 'transform',
  103168. ol.geom.Circle.prototype.transform);
  103169. goog.exportSymbol(
  103170. 'ol.geom.Geometry',
  103171. ol.geom.Geometry,
  103172. OPENLAYERS);
  103173. goog.exportProperty(
  103174. ol.geom.Geometry.prototype,
  103175. 'getClosestPoint',
  103176. ol.geom.Geometry.prototype.getClosestPoint);
  103177. goog.exportProperty(
  103178. ol.geom.Geometry.prototype,
  103179. 'getExtent',
  103180. ol.geom.Geometry.prototype.getExtent);
  103181. goog.exportProperty(
  103182. ol.geom.Geometry.prototype,
  103183. 'simplify',
  103184. ol.geom.Geometry.prototype.simplify);
  103185. goog.exportProperty(
  103186. ol.geom.Geometry.prototype,
  103187. 'transform',
  103188. ol.geom.Geometry.prototype.transform);
  103189. goog.exportSymbol(
  103190. 'ol.geom.GeometryCollection',
  103191. ol.geom.GeometryCollection,
  103192. OPENLAYERS);
  103193. goog.exportProperty(
  103194. ol.geom.GeometryCollection.prototype,
  103195. 'clone',
  103196. ol.geom.GeometryCollection.prototype.clone);
  103197. goog.exportProperty(
  103198. ol.geom.GeometryCollection.prototype,
  103199. 'getGeometries',
  103200. ol.geom.GeometryCollection.prototype.getGeometries);
  103201. goog.exportProperty(
  103202. ol.geom.GeometryCollection.prototype,
  103203. 'getType',
  103204. ol.geom.GeometryCollection.prototype.getType);
  103205. goog.exportProperty(
  103206. ol.geom.GeometryCollection.prototype,
  103207. 'intersectsExtent',
  103208. ol.geom.GeometryCollection.prototype.intersectsExtent);
  103209. goog.exportProperty(
  103210. ol.geom.GeometryCollection.prototype,
  103211. 'setGeometries',
  103212. ol.geom.GeometryCollection.prototype.setGeometries);
  103213. goog.exportProperty(
  103214. ol.geom.GeometryCollection.prototype,
  103215. 'applyTransform',
  103216. ol.geom.GeometryCollection.prototype.applyTransform);
  103217. goog.exportProperty(
  103218. ol.geom.GeometryCollection.prototype,
  103219. 'translate',
  103220. ol.geom.GeometryCollection.prototype.translate);
  103221. goog.exportSymbol(
  103222. 'ol.geom.LinearRing',
  103223. ol.geom.LinearRing,
  103224. OPENLAYERS);
  103225. goog.exportProperty(
  103226. ol.geom.LinearRing.prototype,
  103227. 'clone',
  103228. ol.geom.LinearRing.prototype.clone);
  103229. goog.exportProperty(
  103230. ol.geom.LinearRing.prototype,
  103231. 'getArea',
  103232. ol.geom.LinearRing.prototype.getArea);
  103233. goog.exportProperty(
  103234. ol.geom.LinearRing.prototype,
  103235. 'getCoordinates',
  103236. ol.geom.LinearRing.prototype.getCoordinates);
  103237. goog.exportProperty(
  103238. ol.geom.LinearRing.prototype,
  103239. 'getType',
  103240. ol.geom.LinearRing.prototype.getType);
  103241. goog.exportProperty(
  103242. ol.geom.LinearRing.prototype,
  103243. 'setCoordinates',
  103244. ol.geom.LinearRing.prototype.setCoordinates);
  103245. goog.exportSymbol(
  103246. 'ol.geom.LineString',
  103247. ol.geom.LineString,
  103248. OPENLAYERS);
  103249. goog.exportProperty(
  103250. ol.geom.LineString.prototype,
  103251. 'appendCoordinate',
  103252. ol.geom.LineString.prototype.appendCoordinate);
  103253. goog.exportProperty(
  103254. ol.geom.LineString.prototype,
  103255. 'clone',
  103256. ol.geom.LineString.prototype.clone);
  103257. goog.exportProperty(
  103258. ol.geom.LineString.prototype,
  103259. 'forEachSegment',
  103260. ol.geom.LineString.prototype.forEachSegment);
  103261. goog.exportProperty(
  103262. ol.geom.LineString.prototype,
  103263. 'getCoordinateAtM',
  103264. ol.geom.LineString.prototype.getCoordinateAtM);
  103265. goog.exportProperty(
  103266. ol.geom.LineString.prototype,
  103267. 'getCoordinates',
  103268. ol.geom.LineString.prototype.getCoordinates);
  103269. goog.exportProperty(
  103270. ol.geom.LineString.prototype,
  103271. 'getLength',
  103272. ol.geom.LineString.prototype.getLength);
  103273. goog.exportProperty(
  103274. ol.geom.LineString.prototype,
  103275. 'getType',
  103276. ol.geom.LineString.prototype.getType);
  103277. goog.exportProperty(
  103278. ol.geom.LineString.prototype,
  103279. 'intersectsExtent',
  103280. ol.geom.LineString.prototype.intersectsExtent);
  103281. goog.exportProperty(
  103282. ol.geom.LineString.prototype,
  103283. 'setCoordinates',
  103284. ol.geom.LineString.prototype.setCoordinates);
  103285. goog.exportSymbol(
  103286. 'ol.geom.MultiLineString',
  103287. ol.geom.MultiLineString,
  103288. OPENLAYERS);
  103289. goog.exportProperty(
  103290. ol.geom.MultiLineString.prototype,
  103291. 'appendLineString',
  103292. ol.geom.MultiLineString.prototype.appendLineString);
  103293. goog.exportProperty(
  103294. ol.geom.MultiLineString.prototype,
  103295. 'clone',
  103296. ol.geom.MultiLineString.prototype.clone);
  103297. goog.exportProperty(
  103298. ol.geom.MultiLineString.prototype,
  103299. 'getCoordinateAtM',
  103300. ol.geom.MultiLineString.prototype.getCoordinateAtM);
  103301. goog.exportProperty(
  103302. ol.geom.MultiLineString.prototype,
  103303. 'getCoordinates',
  103304. ol.geom.MultiLineString.prototype.getCoordinates);
  103305. goog.exportProperty(
  103306. ol.geom.MultiLineString.prototype,
  103307. 'getLineString',
  103308. ol.geom.MultiLineString.prototype.getLineString);
  103309. goog.exportProperty(
  103310. ol.geom.MultiLineString.prototype,
  103311. 'getLineStrings',
  103312. ol.geom.MultiLineString.prototype.getLineStrings);
  103313. goog.exportProperty(
  103314. ol.geom.MultiLineString.prototype,
  103315. 'getType',
  103316. ol.geom.MultiLineString.prototype.getType);
  103317. goog.exportProperty(
  103318. ol.geom.MultiLineString.prototype,
  103319. 'intersectsExtent',
  103320. ol.geom.MultiLineString.prototype.intersectsExtent);
  103321. goog.exportProperty(
  103322. ol.geom.MultiLineString.prototype,
  103323. 'setCoordinates',
  103324. ol.geom.MultiLineString.prototype.setCoordinates);
  103325. goog.exportSymbol(
  103326. 'ol.geom.MultiPoint',
  103327. ol.geom.MultiPoint,
  103328. OPENLAYERS);
  103329. goog.exportProperty(
  103330. ol.geom.MultiPoint.prototype,
  103331. 'appendPoint',
  103332. ol.geom.MultiPoint.prototype.appendPoint);
  103333. goog.exportProperty(
  103334. ol.geom.MultiPoint.prototype,
  103335. 'clone',
  103336. ol.geom.MultiPoint.prototype.clone);
  103337. goog.exportProperty(
  103338. ol.geom.MultiPoint.prototype,
  103339. 'getCoordinates',
  103340. ol.geom.MultiPoint.prototype.getCoordinates);
  103341. goog.exportProperty(
  103342. ol.geom.MultiPoint.prototype,
  103343. 'getPoint',
  103344. ol.geom.MultiPoint.prototype.getPoint);
  103345. goog.exportProperty(
  103346. ol.geom.MultiPoint.prototype,
  103347. 'getPoints',
  103348. ol.geom.MultiPoint.prototype.getPoints);
  103349. goog.exportProperty(
  103350. ol.geom.MultiPoint.prototype,
  103351. 'getType',
  103352. ol.geom.MultiPoint.prototype.getType);
  103353. goog.exportProperty(
  103354. ol.geom.MultiPoint.prototype,
  103355. 'intersectsExtent',
  103356. ol.geom.MultiPoint.prototype.intersectsExtent);
  103357. goog.exportProperty(
  103358. ol.geom.MultiPoint.prototype,
  103359. 'setCoordinates',
  103360. ol.geom.MultiPoint.prototype.setCoordinates);
  103361. goog.exportSymbol(
  103362. 'ol.geom.MultiPolygon',
  103363. ol.geom.MultiPolygon,
  103364. OPENLAYERS);
  103365. goog.exportProperty(
  103366. ol.geom.MultiPolygon.prototype,
  103367. 'appendPolygon',
  103368. ol.geom.MultiPolygon.prototype.appendPolygon);
  103369. goog.exportProperty(
  103370. ol.geom.MultiPolygon.prototype,
  103371. 'clone',
  103372. ol.geom.MultiPolygon.prototype.clone);
  103373. goog.exportProperty(
  103374. ol.geom.MultiPolygon.prototype,
  103375. 'getArea',
  103376. ol.geom.MultiPolygon.prototype.getArea);
  103377. goog.exportProperty(
  103378. ol.geom.MultiPolygon.prototype,
  103379. 'getCoordinates',
  103380. ol.geom.MultiPolygon.prototype.getCoordinates);
  103381. goog.exportProperty(
  103382. ol.geom.MultiPolygon.prototype,
  103383. 'getInteriorPoints',
  103384. ol.geom.MultiPolygon.prototype.getInteriorPoints);
  103385. goog.exportProperty(
  103386. ol.geom.MultiPolygon.prototype,
  103387. 'getPolygon',
  103388. ol.geom.MultiPolygon.prototype.getPolygon);
  103389. goog.exportProperty(
  103390. ol.geom.MultiPolygon.prototype,
  103391. 'getPolygons',
  103392. ol.geom.MultiPolygon.prototype.getPolygons);
  103393. goog.exportProperty(
  103394. ol.geom.MultiPolygon.prototype,
  103395. 'getType',
  103396. ol.geom.MultiPolygon.prototype.getType);
  103397. goog.exportProperty(
  103398. ol.geom.MultiPolygon.prototype,
  103399. 'intersectsExtent',
  103400. ol.geom.MultiPolygon.prototype.intersectsExtent);
  103401. goog.exportProperty(
  103402. ol.geom.MultiPolygon.prototype,
  103403. 'setCoordinates',
  103404. ol.geom.MultiPolygon.prototype.setCoordinates);
  103405. goog.exportSymbol(
  103406. 'ol.geom.Point',
  103407. ol.geom.Point,
  103408. OPENLAYERS);
  103409. goog.exportProperty(
  103410. ol.geom.Point.prototype,
  103411. 'clone',
  103412. ol.geom.Point.prototype.clone);
  103413. goog.exportProperty(
  103414. ol.geom.Point.prototype,
  103415. 'getCoordinates',
  103416. ol.geom.Point.prototype.getCoordinates);
  103417. goog.exportProperty(
  103418. ol.geom.Point.prototype,
  103419. 'getType',
  103420. ol.geom.Point.prototype.getType);
  103421. goog.exportProperty(
  103422. ol.geom.Point.prototype,
  103423. 'intersectsExtent',
  103424. ol.geom.Point.prototype.intersectsExtent);
  103425. goog.exportProperty(
  103426. ol.geom.Point.prototype,
  103427. 'setCoordinates',
  103428. ol.geom.Point.prototype.setCoordinates);
  103429. goog.exportSymbol(
  103430. 'ol.geom.Polygon',
  103431. ol.geom.Polygon,
  103432. OPENLAYERS);
  103433. goog.exportProperty(
  103434. ol.geom.Polygon.prototype,
  103435. 'appendLinearRing',
  103436. ol.geom.Polygon.prototype.appendLinearRing);
  103437. goog.exportProperty(
  103438. ol.geom.Polygon.prototype,
  103439. 'clone',
  103440. ol.geom.Polygon.prototype.clone);
  103441. goog.exportProperty(
  103442. ol.geom.Polygon.prototype,
  103443. 'getArea',
  103444. ol.geom.Polygon.prototype.getArea);
  103445. goog.exportProperty(
  103446. ol.geom.Polygon.prototype,
  103447. 'getCoordinates',
  103448. ol.geom.Polygon.prototype.getCoordinates);
  103449. goog.exportProperty(
  103450. ol.geom.Polygon.prototype,
  103451. 'getInteriorPoint',
  103452. ol.geom.Polygon.prototype.getInteriorPoint);
  103453. goog.exportProperty(
  103454. ol.geom.Polygon.prototype,
  103455. 'getLinearRingCount',
  103456. ol.geom.Polygon.prototype.getLinearRingCount);
  103457. goog.exportProperty(
  103458. ol.geom.Polygon.prototype,
  103459. 'getLinearRing',
  103460. ol.geom.Polygon.prototype.getLinearRing);
  103461. goog.exportProperty(
  103462. ol.geom.Polygon.prototype,
  103463. 'getLinearRings',
  103464. ol.geom.Polygon.prototype.getLinearRings);
  103465. goog.exportProperty(
  103466. ol.geom.Polygon.prototype,
  103467. 'getType',
  103468. ol.geom.Polygon.prototype.getType);
  103469. goog.exportProperty(
  103470. ol.geom.Polygon.prototype,
  103471. 'intersectsExtent',
  103472. ol.geom.Polygon.prototype.intersectsExtent);
  103473. goog.exportProperty(
  103474. ol.geom.Polygon.prototype,
  103475. 'setCoordinates',
  103476. ol.geom.Polygon.prototype.setCoordinates);
  103477. goog.exportSymbol(
  103478. 'ol.geom.Polygon.circular',
  103479. ol.geom.Polygon.circular,
  103480. OPENLAYERS);
  103481. goog.exportSymbol(
  103482. 'ol.geom.Polygon.fromExtent',
  103483. ol.geom.Polygon.fromExtent,
  103484. OPENLAYERS);
  103485. goog.exportSymbol(
  103486. 'ol.geom.Polygon.fromCircle',
  103487. ol.geom.Polygon.fromCircle,
  103488. OPENLAYERS);
  103489. goog.exportSymbol(
  103490. 'ol.geom.SimpleGeometry',
  103491. ol.geom.SimpleGeometry,
  103492. OPENLAYERS);
  103493. goog.exportProperty(
  103494. ol.geom.SimpleGeometry.prototype,
  103495. 'getFirstCoordinate',
  103496. ol.geom.SimpleGeometry.prototype.getFirstCoordinate);
  103497. goog.exportProperty(
  103498. ol.geom.SimpleGeometry.prototype,
  103499. 'getLastCoordinate',
  103500. ol.geom.SimpleGeometry.prototype.getLastCoordinate);
  103501. goog.exportProperty(
  103502. ol.geom.SimpleGeometry.prototype,
  103503. 'getLayout',
  103504. ol.geom.SimpleGeometry.prototype.getLayout);
  103505. goog.exportProperty(
  103506. ol.geom.SimpleGeometry.prototype,
  103507. 'applyTransform',
  103508. ol.geom.SimpleGeometry.prototype.applyTransform);
  103509. goog.exportProperty(
  103510. ol.geom.SimpleGeometry.prototype,
  103511. 'translate',
  103512. ol.geom.SimpleGeometry.prototype.translate);
  103513. goog.exportSymbol(
  103514. 'ol.format.EsriJSON',
  103515. ol.format.EsriJSON,
  103516. OPENLAYERS);
  103517. goog.exportProperty(
  103518. ol.format.EsriJSON.prototype,
  103519. 'readFeature',
  103520. ol.format.EsriJSON.prototype.readFeature);
  103521. goog.exportProperty(
  103522. ol.format.EsriJSON.prototype,
  103523. 'readFeatures',
  103524. ol.format.EsriJSON.prototype.readFeatures);
  103525. goog.exportProperty(
  103526. ol.format.EsriJSON.prototype,
  103527. 'readGeometry',
  103528. ol.format.EsriJSON.prototype.readGeometry);
  103529. goog.exportProperty(
  103530. ol.format.EsriJSON.prototype,
  103531. 'readProjection',
  103532. ol.format.EsriJSON.prototype.readProjection);
  103533. goog.exportProperty(
  103534. ol.format.EsriJSON.prototype,
  103535. 'writeGeometry',
  103536. ol.format.EsriJSON.prototype.writeGeometry);
  103537. goog.exportProperty(
  103538. ol.format.EsriJSON.prototype,
  103539. 'writeGeometryObject',
  103540. ol.format.EsriJSON.prototype.writeGeometryObject);
  103541. goog.exportProperty(
  103542. ol.format.EsriJSON.prototype,
  103543. 'writeFeature',
  103544. ol.format.EsriJSON.prototype.writeFeature);
  103545. goog.exportProperty(
  103546. ol.format.EsriJSON.prototype,
  103547. 'writeFeatureObject',
  103548. ol.format.EsriJSON.prototype.writeFeatureObject);
  103549. goog.exportProperty(
  103550. ol.format.EsriJSON.prototype,
  103551. 'writeFeatures',
  103552. ol.format.EsriJSON.prototype.writeFeatures);
  103553. goog.exportProperty(
  103554. ol.format.EsriJSON.prototype,
  103555. 'writeFeaturesObject',
  103556. ol.format.EsriJSON.prototype.writeFeaturesObject);
  103557. goog.exportSymbol(
  103558. 'ol.format.Feature',
  103559. ol.format.Feature,
  103560. OPENLAYERS);
  103561. goog.exportSymbol(
  103562. 'ol.format.GeoJSON',
  103563. ol.format.GeoJSON,
  103564. OPENLAYERS);
  103565. goog.exportProperty(
  103566. ol.format.GeoJSON.prototype,
  103567. 'readFeature',
  103568. ol.format.GeoJSON.prototype.readFeature);
  103569. goog.exportProperty(
  103570. ol.format.GeoJSON.prototype,
  103571. 'readFeatures',
  103572. ol.format.GeoJSON.prototype.readFeatures);
  103573. goog.exportProperty(
  103574. ol.format.GeoJSON.prototype,
  103575. 'readGeometry',
  103576. ol.format.GeoJSON.prototype.readGeometry);
  103577. goog.exportProperty(
  103578. ol.format.GeoJSON.prototype,
  103579. 'readProjection',
  103580. ol.format.GeoJSON.prototype.readProjection);
  103581. goog.exportProperty(
  103582. ol.format.GeoJSON.prototype,
  103583. 'writeFeature',
  103584. ol.format.GeoJSON.prototype.writeFeature);
  103585. goog.exportProperty(
  103586. ol.format.GeoJSON.prototype,
  103587. 'writeFeatureObject',
  103588. ol.format.GeoJSON.prototype.writeFeatureObject);
  103589. goog.exportProperty(
  103590. ol.format.GeoJSON.prototype,
  103591. 'writeFeatures',
  103592. ol.format.GeoJSON.prototype.writeFeatures);
  103593. goog.exportProperty(
  103594. ol.format.GeoJSON.prototype,
  103595. 'writeFeaturesObject',
  103596. ol.format.GeoJSON.prototype.writeFeaturesObject);
  103597. goog.exportProperty(
  103598. ol.format.GeoJSON.prototype,
  103599. 'writeGeometry',
  103600. ol.format.GeoJSON.prototype.writeGeometry);
  103601. goog.exportProperty(
  103602. ol.format.GeoJSON.prototype,
  103603. 'writeGeometryObject',
  103604. ol.format.GeoJSON.prototype.writeGeometryObject);
  103605. goog.exportSymbol(
  103606. 'ol.format.GPX',
  103607. ol.format.GPX,
  103608. OPENLAYERS);
  103609. goog.exportProperty(
  103610. ol.format.GPX.prototype,
  103611. 'readFeature',
  103612. ol.format.GPX.prototype.readFeature);
  103613. goog.exportProperty(
  103614. ol.format.GPX.prototype,
  103615. 'readFeatures',
  103616. ol.format.GPX.prototype.readFeatures);
  103617. goog.exportProperty(
  103618. ol.format.GPX.prototype,
  103619. 'readProjection',
  103620. ol.format.GPX.prototype.readProjection);
  103621. goog.exportProperty(
  103622. ol.format.GPX.prototype,
  103623. 'writeFeatures',
  103624. ol.format.GPX.prototype.writeFeatures);
  103625. goog.exportProperty(
  103626. ol.format.GPX.prototype,
  103627. 'writeFeaturesNode',
  103628. ol.format.GPX.prototype.writeFeaturesNode);
  103629. goog.exportSymbol(
  103630. 'ol.format.IGC',
  103631. ol.format.IGC,
  103632. OPENLAYERS);
  103633. goog.exportProperty(
  103634. ol.format.IGC.prototype,
  103635. 'readFeature',
  103636. ol.format.IGC.prototype.readFeature);
  103637. goog.exportProperty(
  103638. ol.format.IGC.prototype,
  103639. 'readFeatures',
  103640. ol.format.IGC.prototype.readFeatures);
  103641. goog.exportProperty(
  103642. ol.format.IGC.prototype,
  103643. 'readProjection',
  103644. ol.format.IGC.prototype.readProjection);
  103645. goog.exportSymbol(
  103646. 'ol.format.KML',
  103647. ol.format.KML,
  103648. OPENLAYERS);
  103649. goog.exportProperty(
  103650. ol.format.KML.prototype,
  103651. 'readFeature',
  103652. ol.format.KML.prototype.readFeature);
  103653. goog.exportProperty(
  103654. ol.format.KML.prototype,
  103655. 'readFeatures',
  103656. ol.format.KML.prototype.readFeatures);
  103657. goog.exportProperty(
  103658. ol.format.KML.prototype,
  103659. 'readName',
  103660. ol.format.KML.prototype.readName);
  103661. goog.exportProperty(
  103662. ol.format.KML.prototype,
  103663. 'readNetworkLinks',
  103664. ol.format.KML.prototype.readNetworkLinks);
  103665. goog.exportProperty(
  103666. ol.format.KML.prototype,
  103667. 'readProjection',
  103668. ol.format.KML.prototype.readProjection);
  103669. goog.exportProperty(
  103670. ol.format.KML.prototype,
  103671. 'writeFeatures',
  103672. ol.format.KML.prototype.writeFeatures);
  103673. goog.exportProperty(
  103674. ol.format.KML.prototype,
  103675. 'writeFeaturesNode',
  103676. ol.format.KML.prototype.writeFeaturesNode);
  103677. goog.exportSymbol(
  103678. 'ol.format.OSMXML',
  103679. ol.format.OSMXML,
  103680. OPENLAYERS);
  103681. goog.exportProperty(
  103682. ol.format.OSMXML.prototype,
  103683. 'readFeatures',
  103684. ol.format.OSMXML.prototype.readFeatures);
  103685. goog.exportProperty(
  103686. ol.format.OSMXML.prototype,
  103687. 'readProjection',
  103688. ol.format.OSMXML.prototype.readProjection);
  103689. goog.exportSymbol(
  103690. 'ol.format.Polyline',
  103691. ol.format.Polyline,
  103692. OPENLAYERS);
  103693. goog.exportSymbol(
  103694. 'ol.format.Polyline.encodeDeltas',
  103695. ol.format.Polyline.encodeDeltas,
  103696. OPENLAYERS);
  103697. goog.exportSymbol(
  103698. 'ol.format.Polyline.decodeDeltas',
  103699. ol.format.Polyline.decodeDeltas,
  103700. OPENLAYERS);
  103701. goog.exportSymbol(
  103702. 'ol.format.Polyline.encodeFloats',
  103703. ol.format.Polyline.encodeFloats,
  103704. OPENLAYERS);
  103705. goog.exportSymbol(
  103706. 'ol.format.Polyline.decodeFloats',
  103707. ol.format.Polyline.decodeFloats,
  103708. OPENLAYERS);
  103709. goog.exportProperty(
  103710. ol.format.Polyline.prototype,
  103711. 'readFeature',
  103712. ol.format.Polyline.prototype.readFeature);
  103713. goog.exportProperty(
  103714. ol.format.Polyline.prototype,
  103715. 'readFeatures',
  103716. ol.format.Polyline.prototype.readFeatures);
  103717. goog.exportProperty(
  103718. ol.format.Polyline.prototype,
  103719. 'readGeometry',
  103720. ol.format.Polyline.prototype.readGeometry);
  103721. goog.exportProperty(
  103722. ol.format.Polyline.prototype,
  103723. 'readProjection',
  103724. ol.format.Polyline.prototype.readProjection);
  103725. goog.exportProperty(
  103726. ol.format.Polyline.prototype,
  103727. 'writeGeometry',
  103728. ol.format.Polyline.prototype.writeGeometry);
  103729. goog.exportSymbol(
  103730. 'ol.format.TopoJSON',
  103731. ol.format.TopoJSON,
  103732. OPENLAYERS);
  103733. goog.exportProperty(
  103734. ol.format.TopoJSON.prototype,
  103735. 'readFeatures',
  103736. ol.format.TopoJSON.prototype.readFeatures);
  103737. goog.exportProperty(
  103738. ol.format.TopoJSON.prototype,
  103739. 'readProjection',
  103740. ol.format.TopoJSON.prototype.readProjection);
  103741. goog.exportSymbol(
  103742. 'ol.format.WFS',
  103743. ol.format.WFS,
  103744. OPENLAYERS);
  103745. goog.exportProperty(
  103746. ol.format.WFS.prototype,
  103747. 'readFeatures',
  103748. ol.format.WFS.prototype.readFeatures);
  103749. goog.exportProperty(
  103750. ol.format.WFS.prototype,
  103751. 'readTransactionResponse',
  103752. ol.format.WFS.prototype.readTransactionResponse);
  103753. goog.exportProperty(
  103754. ol.format.WFS.prototype,
  103755. 'readFeatureCollectionMetadata',
  103756. ol.format.WFS.prototype.readFeatureCollectionMetadata);
  103757. goog.exportProperty(
  103758. ol.format.WFS.prototype,
  103759. 'writeGetFeature',
  103760. ol.format.WFS.prototype.writeGetFeature);
  103761. goog.exportProperty(
  103762. ol.format.WFS.prototype,
  103763. 'writeTransaction',
  103764. ol.format.WFS.prototype.writeTransaction);
  103765. goog.exportProperty(
  103766. ol.format.WFS.prototype,
  103767. 'readProjection',
  103768. ol.format.WFS.prototype.readProjection);
  103769. goog.exportSymbol(
  103770. 'ol.format.WKT',
  103771. ol.format.WKT,
  103772. OPENLAYERS);
  103773. goog.exportProperty(
  103774. ol.format.WKT.prototype,
  103775. 'readFeature',
  103776. ol.format.WKT.prototype.readFeature);
  103777. goog.exportProperty(
  103778. ol.format.WKT.prototype,
  103779. 'readFeatures',
  103780. ol.format.WKT.prototype.readFeatures);
  103781. goog.exportProperty(
  103782. ol.format.WKT.prototype,
  103783. 'readGeometry',
  103784. ol.format.WKT.prototype.readGeometry);
  103785. goog.exportProperty(
  103786. ol.format.WKT.prototype,
  103787. 'writeFeature',
  103788. ol.format.WKT.prototype.writeFeature);
  103789. goog.exportProperty(
  103790. ol.format.WKT.prototype,
  103791. 'writeFeatures',
  103792. ol.format.WKT.prototype.writeFeatures);
  103793. goog.exportProperty(
  103794. ol.format.WKT.prototype,
  103795. 'writeGeometry',
  103796. ol.format.WKT.prototype.writeGeometry);
  103797. goog.exportSymbol(
  103798. 'ol.format.WMSCapabilities',
  103799. ol.format.WMSCapabilities,
  103800. OPENLAYERS);
  103801. goog.exportProperty(
  103802. ol.format.WMSCapabilities.prototype,
  103803. 'read',
  103804. ol.format.WMSCapabilities.prototype.read);
  103805. goog.exportSymbol(
  103806. 'ol.format.WMSGetFeatureInfo',
  103807. ol.format.WMSGetFeatureInfo,
  103808. OPENLAYERS);
  103809. goog.exportProperty(
  103810. ol.format.WMSGetFeatureInfo.prototype,
  103811. 'readFeatures',
  103812. ol.format.WMSGetFeatureInfo.prototype.readFeatures);
  103813. goog.exportSymbol(
  103814. 'ol.format.WMTSCapabilities',
  103815. ol.format.WMTSCapabilities,
  103816. OPENLAYERS);
  103817. goog.exportProperty(
  103818. ol.format.WMTSCapabilities.prototype,
  103819. 'read',
  103820. ol.format.WMTSCapabilities.prototype.read);
  103821. goog.exportSymbol(
  103822. 'ol.format.GML2',
  103823. ol.format.GML2,
  103824. OPENLAYERS);
  103825. goog.exportSymbol(
  103826. 'ol.format.GML3',
  103827. ol.format.GML3,
  103828. OPENLAYERS);
  103829. goog.exportProperty(
  103830. ol.format.GML3.prototype,
  103831. 'writeGeometryNode',
  103832. ol.format.GML3.prototype.writeGeometryNode);
  103833. goog.exportProperty(
  103834. ol.format.GML3.prototype,
  103835. 'writeFeatures',
  103836. ol.format.GML3.prototype.writeFeatures);
  103837. goog.exportProperty(
  103838. ol.format.GML3.prototype,
  103839. 'writeFeaturesNode',
  103840. ol.format.GML3.prototype.writeFeaturesNode);
  103841. goog.exportSymbol(
  103842. 'ol.format.GML',
  103843. ol.format.GML,
  103844. OPENLAYERS);
  103845. goog.exportProperty(
  103846. ol.format.GML.prototype,
  103847. 'writeFeatures',
  103848. ol.format.GML.prototype.writeFeatures);
  103849. goog.exportProperty(
  103850. ol.format.GML.prototype,
  103851. 'writeFeaturesNode',
  103852. ol.format.GML.prototype.writeFeaturesNode);
  103853. goog.exportProperty(
  103854. ol.format.GMLBase.prototype,
  103855. 'readFeatures',
  103856. ol.format.GMLBase.prototype.readFeatures);
  103857. goog.exportSymbol(
  103858. 'ol.events.condition.altKeyOnly',
  103859. ol.events.condition.altKeyOnly,
  103860. OPENLAYERS);
  103861. goog.exportSymbol(
  103862. 'ol.events.condition.altShiftKeysOnly',
  103863. ol.events.condition.altShiftKeysOnly,
  103864. OPENLAYERS);
  103865. goog.exportSymbol(
  103866. 'ol.events.condition.always',
  103867. ol.events.condition.always,
  103868. OPENLAYERS);
  103869. goog.exportSymbol(
  103870. 'ol.events.condition.click',
  103871. ol.events.condition.click,
  103872. OPENLAYERS);
  103873. goog.exportSymbol(
  103874. 'ol.events.condition.never',
  103875. ol.events.condition.never,
  103876. OPENLAYERS);
  103877. goog.exportSymbol(
  103878. 'ol.events.condition.pointerMove',
  103879. ol.events.condition.pointerMove,
  103880. OPENLAYERS);
  103881. goog.exportSymbol(
  103882. 'ol.events.condition.singleClick',
  103883. ol.events.condition.singleClick,
  103884. OPENLAYERS);
  103885. goog.exportSymbol(
  103886. 'ol.events.condition.doubleClick',
  103887. ol.events.condition.doubleClick,
  103888. OPENLAYERS);
  103889. goog.exportSymbol(
  103890. 'ol.events.condition.noModifierKeys',
  103891. ol.events.condition.noModifierKeys,
  103892. OPENLAYERS);
  103893. goog.exportSymbol(
  103894. 'ol.events.condition.platformModifierKeyOnly',
  103895. ol.events.condition.platformModifierKeyOnly,
  103896. OPENLAYERS);
  103897. goog.exportSymbol(
  103898. 'ol.events.condition.shiftKeyOnly',
  103899. ol.events.condition.shiftKeyOnly,
  103900. OPENLAYERS);
  103901. goog.exportSymbol(
  103902. 'ol.events.condition.targetNotEditable',
  103903. ol.events.condition.targetNotEditable,
  103904. OPENLAYERS);
  103905. goog.exportSymbol(
  103906. 'ol.events.condition.mouseOnly',
  103907. ol.events.condition.mouseOnly,
  103908. OPENLAYERS);
  103909. goog.exportSymbol(
  103910. 'ol.control.Attribution',
  103911. ol.control.Attribution,
  103912. OPENLAYERS);
  103913. goog.exportSymbol(
  103914. 'ol.control.Attribution.render',
  103915. ol.control.Attribution.render,
  103916. OPENLAYERS);
  103917. goog.exportProperty(
  103918. ol.control.Attribution.prototype,
  103919. 'getCollapsible',
  103920. ol.control.Attribution.prototype.getCollapsible);
  103921. goog.exportProperty(
  103922. ol.control.Attribution.prototype,
  103923. 'setCollapsible',
  103924. ol.control.Attribution.prototype.setCollapsible);
  103925. goog.exportProperty(
  103926. ol.control.Attribution.prototype,
  103927. 'setCollapsed',
  103928. ol.control.Attribution.prototype.setCollapsed);
  103929. goog.exportProperty(
  103930. ol.control.Attribution.prototype,
  103931. 'getCollapsed',
  103932. ol.control.Attribution.prototype.getCollapsed);
  103933. goog.exportSymbol(
  103934. 'ol.control.Control',
  103935. ol.control.Control,
  103936. OPENLAYERS);
  103937. goog.exportProperty(
  103938. ol.control.Control.prototype,
  103939. 'getMap',
  103940. ol.control.Control.prototype.getMap);
  103941. goog.exportProperty(
  103942. ol.control.Control.prototype,
  103943. 'setMap',
  103944. ol.control.Control.prototype.setMap);
  103945. goog.exportProperty(
  103946. ol.control.Control.prototype,
  103947. 'setTarget',
  103948. ol.control.Control.prototype.setTarget);
  103949. goog.exportSymbol(
  103950. 'ol.control.defaults',
  103951. ol.control.defaults,
  103952. OPENLAYERS);
  103953. goog.exportSymbol(
  103954. 'ol.control.FullScreen',
  103955. ol.control.FullScreen,
  103956. OPENLAYERS);
  103957. goog.exportSymbol(
  103958. 'ol.control.MousePosition',
  103959. ol.control.MousePosition,
  103960. OPENLAYERS);
  103961. goog.exportSymbol(
  103962. 'ol.control.MousePosition.render',
  103963. ol.control.MousePosition.render,
  103964. OPENLAYERS);
  103965. goog.exportProperty(
  103966. ol.control.MousePosition.prototype,
  103967. 'getCoordinateFormat',
  103968. ol.control.MousePosition.prototype.getCoordinateFormat);
  103969. goog.exportProperty(
  103970. ol.control.MousePosition.prototype,
  103971. 'getProjection',
  103972. ol.control.MousePosition.prototype.getProjection);
  103973. goog.exportProperty(
  103974. ol.control.MousePosition.prototype,
  103975. 'setCoordinateFormat',
  103976. ol.control.MousePosition.prototype.setCoordinateFormat);
  103977. goog.exportProperty(
  103978. ol.control.MousePosition.prototype,
  103979. 'setProjection',
  103980. ol.control.MousePosition.prototype.setProjection);
  103981. goog.exportSymbol(
  103982. 'ol.control.OverviewMap',
  103983. ol.control.OverviewMap,
  103984. OPENLAYERS);
  103985. goog.exportSymbol(
  103986. 'ol.control.OverviewMap.render',
  103987. ol.control.OverviewMap.render,
  103988. OPENLAYERS);
  103989. goog.exportProperty(
  103990. ol.control.OverviewMap.prototype,
  103991. 'getCollapsible',
  103992. ol.control.OverviewMap.prototype.getCollapsible);
  103993. goog.exportProperty(
  103994. ol.control.OverviewMap.prototype,
  103995. 'setCollapsible',
  103996. ol.control.OverviewMap.prototype.setCollapsible);
  103997. goog.exportProperty(
  103998. ol.control.OverviewMap.prototype,
  103999. 'setCollapsed',
  104000. ol.control.OverviewMap.prototype.setCollapsed);
  104001. goog.exportProperty(
  104002. ol.control.OverviewMap.prototype,
  104003. 'getCollapsed',
  104004. ol.control.OverviewMap.prototype.getCollapsed);
  104005. goog.exportSymbol(
  104006. 'ol.control.Rotate',
  104007. ol.control.Rotate,
  104008. OPENLAYERS);
  104009. goog.exportSymbol(
  104010. 'ol.control.Rotate.render',
  104011. ol.control.Rotate.render,
  104012. OPENLAYERS);
  104013. goog.exportSymbol(
  104014. 'ol.control.ScaleLine',
  104015. ol.control.ScaleLine,
  104016. OPENLAYERS);
  104017. goog.exportProperty(
  104018. ol.control.ScaleLine.prototype,
  104019. 'getUnits',
  104020. ol.control.ScaleLine.prototype.getUnits);
  104021. goog.exportSymbol(
  104022. 'ol.control.ScaleLine.render',
  104023. ol.control.ScaleLine.render,
  104024. OPENLAYERS);
  104025. goog.exportProperty(
  104026. ol.control.ScaleLine.prototype,
  104027. 'setUnits',
  104028. ol.control.ScaleLine.prototype.setUnits);
  104029. goog.exportSymbol(
  104030. 'ol.control.Zoom',
  104031. ol.control.Zoom,
  104032. OPENLAYERS);
  104033. goog.exportSymbol(
  104034. 'ol.control.ZoomSlider',
  104035. ol.control.ZoomSlider,
  104036. OPENLAYERS);
  104037. goog.exportSymbol(
  104038. 'ol.control.ZoomSlider.render',
  104039. ol.control.ZoomSlider.render,
  104040. OPENLAYERS);
  104041. goog.exportSymbol(
  104042. 'ol.control.ZoomToExtent',
  104043. ol.control.ZoomToExtent,
  104044. OPENLAYERS);
  104045. goog.exportSymbol(
  104046. 'ol.color.asArray',
  104047. ol.color.asArray,
  104048. OPENLAYERS);
  104049. goog.exportSymbol(
  104050. 'ol.color.asString',
  104051. ol.color.asString,
  104052. OPENLAYERS);
  104053. goog.exportProperty(
  104054. ol.Object.prototype,
  104055. 'changed',
  104056. ol.Object.prototype.changed);
  104057. goog.exportProperty(
  104058. ol.Object.prototype,
  104059. 'getRevision',
  104060. ol.Object.prototype.getRevision);
  104061. goog.exportProperty(
  104062. ol.Object.prototype,
  104063. 'on',
  104064. ol.Object.prototype.on);
  104065. goog.exportProperty(
  104066. ol.Object.prototype,
  104067. 'once',
  104068. ol.Object.prototype.once);
  104069. goog.exportProperty(
  104070. ol.Object.prototype,
  104071. 'un',
  104072. ol.Object.prototype.un);
  104073. goog.exportProperty(
  104074. ol.Object.prototype,
  104075. 'unByKey',
  104076. ol.Object.prototype.unByKey);
  104077. goog.exportProperty(
  104078. ol.Collection.prototype,
  104079. 'get',
  104080. ol.Collection.prototype.get);
  104081. goog.exportProperty(
  104082. ol.Collection.prototype,
  104083. 'getKeys',
  104084. ol.Collection.prototype.getKeys);
  104085. goog.exportProperty(
  104086. ol.Collection.prototype,
  104087. 'getProperties',
  104088. ol.Collection.prototype.getProperties);
  104089. goog.exportProperty(
  104090. ol.Collection.prototype,
  104091. 'set',
  104092. ol.Collection.prototype.set);
  104093. goog.exportProperty(
  104094. ol.Collection.prototype,
  104095. 'setProperties',
  104096. ol.Collection.prototype.setProperties);
  104097. goog.exportProperty(
  104098. ol.Collection.prototype,
  104099. 'unset',
  104100. ol.Collection.prototype.unset);
  104101. goog.exportProperty(
  104102. ol.Collection.prototype,
  104103. 'changed',
  104104. ol.Collection.prototype.changed);
  104105. goog.exportProperty(
  104106. ol.Collection.prototype,
  104107. 'getRevision',
  104108. ol.Collection.prototype.getRevision);
  104109. goog.exportProperty(
  104110. ol.Collection.prototype,
  104111. 'on',
  104112. ol.Collection.prototype.on);
  104113. goog.exportProperty(
  104114. ol.Collection.prototype,
  104115. 'once',
  104116. ol.Collection.prototype.once);
  104117. goog.exportProperty(
  104118. ol.Collection.prototype,
  104119. 'un',
  104120. ol.Collection.prototype.un);
  104121. goog.exportProperty(
  104122. ol.Collection.prototype,
  104123. 'unByKey',
  104124. ol.Collection.prototype.unByKey);
  104125. goog.exportProperty(
  104126. ol.DeviceOrientation.prototype,
  104127. 'get',
  104128. ol.DeviceOrientation.prototype.get);
  104129. goog.exportProperty(
  104130. ol.DeviceOrientation.prototype,
  104131. 'getKeys',
  104132. ol.DeviceOrientation.prototype.getKeys);
  104133. goog.exportProperty(
  104134. ol.DeviceOrientation.prototype,
  104135. 'getProperties',
  104136. ol.DeviceOrientation.prototype.getProperties);
  104137. goog.exportProperty(
  104138. ol.DeviceOrientation.prototype,
  104139. 'set',
  104140. ol.DeviceOrientation.prototype.set);
  104141. goog.exportProperty(
  104142. ol.DeviceOrientation.prototype,
  104143. 'setProperties',
  104144. ol.DeviceOrientation.prototype.setProperties);
  104145. goog.exportProperty(
  104146. ol.DeviceOrientation.prototype,
  104147. 'unset',
  104148. ol.DeviceOrientation.prototype.unset);
  104149. goog.exportProperty(
  104150. ol.DeviceOrientation.prototype,
  104151. 'changed',
  104152. ol.DeviceOrientation.prototype.changed);
  104153. goog.exportProperty(
  104154. ol.DeviceOrientation.prototype,
  104155. 'getRevision',
  104156. ol.DeviceOrientation.prototype.getRevision);
  104157. goog.exportProperty(
  104158. ol.DeviceOrientation.prototype,
  104159. 'on',
  104160. ol.DeviceOrientation.prototype.on);
  104161. goog.exportProperty(
  104162. ol.DeviceOrientation.prototype,
  104163. 'once',
  104164. ol.DeviceOrientation.prototype.once);
  104165. goog.exportProperty(
  104166. ol.DeviceOrientation.prototype,
  104167. 'un',
  104168. ol.DeviceOrientation.prototype.un);
  104169. goog.exportProperty(
  104170. ol.DeviceOrientation.prototype,
  104171. 'unByKey',
  104172. ol.DeviceOrientation.prototype.unByKey);
  104173. goog.exportProperty(
  104174. ol.Feature.prototype,
  104175. 'get',
  104176. ol.Feature.prototype.get);
  104177. goog.exportProperty(
  104178. ol.Feature.prototype,
  104179. 'getKeys',
  104180. ol.Feature.prototype.getKeys);
  104181. goog.exportProperty(
  104182. ol.Feature.prototype,
  104183. 'getProperties',
  104184. ol.Feature.prototype.getProperties);
  104185. goog.exportProperty(
  104186. ol.Feature.prototype,
  104187. 'set',
  104188. ol.Feature.prototype.set);
  104189. goog.exportProperty(
  104190. ol.Feature.prototype,
  104191. 'setProperties',
  104192. ol.Feature.prototype.setProperties);
  104193. goog.exportProperty(
  104194. ol.Feature.prototype,
  104195. 'unset',
  104196. ol.Feature.prototype.unset);
  104197. goog.exportProperty(
  104198. ol.Feature.prototype,
  104199. 'changed',
  104200. ol.Feature.prototype.changed);
  104201. goog.exportProperty(
  104202. ol.Feature.prototype,
  104203. 'getRevision',
  104204. ol.Feature.prototype.getRevision);
  104205. goog.exportProperty(
  104206. ol.Feature.prototype,
  104207. 'on',
  104208. ol.Feature.prototype.on);
  104209. goog.exportProperty(
  104210. ol.Feature.prototype,
  104211. 'once',
  104212. ol.Feature.prototype.once);
  104213. goog.exportProperty(
  104214. ol.Feature.prototype,
  104215. 'un',
  104216. ol.Feature.prototype.un);
  104217. goog.exportProperty(
  104218. ol.Feature.prototype,
  104219. 'unByKey',
  104220. ol.Feature.prototype.unByKey);
  104221. goog.exportProperty(
  104222. ol.Geolocation.prototype,
  104223. 'get',
  104224. ol.Geolocation.prototype.get);
  104225. goog.exportProperty(
  104226. ol.Geolocation.prototype,
  104227. 'getKeys',
  104228. ol.Geolocation.prototype.getKeys);
  104229. goog.exportProperty(
  104230. ol.Geolocation.prototype,
  104231. 'getProperties',
  104232. ol.Geolocation.prototype.getProperties);
  104233. goog.exportProperty(
  104234. ol.Geolocation.prototype,
  104235. 'set',
  104236. ol.Geolocation.prototype.set);
  104237. goog.exportProperty(
  104238. ol.Geolocation.prototype,
  104239. 'setProperties',
  104240. ol.Geolocation.prototype.setProperties);
  104241. goog.exportProperty(
  104242. ol.Geolocation.prototype,
  104243. 'unset',
  104244. ol.Geolocation.prototype.unset);
  104245. goog.exportProperty(
  104246. ol.Geolocation.prototype,
  104247. 'changed',
  104248. ol.Geolocation.prototype.changed);
  104249. goog.exportProperty(
  104250. ol.Geolocation.prototype,
  104251. 'getRevision',
  104252. ol.Geolocation.prototype.getRevision);
  104253. goog.exportProperty(
  104254. ol.Geolocation.prototype,
  104255. 'on',
  104256. ol.Geolocation.prototype.on);
  104257. goog.exportProperty(
  104258. ol.Geolocation.prototype,
  104259. 'once',
  104260. ol.Geolocation.prototype.once);
  104261. goog.exportProperty(
  104262. ol.Geolocation.prototype,
  104263. 'un',
  104264. ol.Geolocation.prototype.un);
  104265. goog.exportProperty(
  104266. ol.Geolocation.prototype,
  104267. 'unByKey',
  104268. ol.Geolocation.prototype.unByKey);
  104269. goog.exportProperty(
  104270. ol.ImageTile.prototype,
  104271. 'getTileCoord',
  104272. ol.ImageTile.prototype.getTileCoord);
  104273. goog.exportProperty(
  104274. ol.Map.prototype,
  104275. 'get',
  104276. ol.Map.prototype.get);
  104277. goog.exportProperty(
  104278. ol.Map.prototype,
  104279. 'getKeys',
  104280. ol.Map.prototype.getKeys);
  104281. goog.exportProperty(
  104282. ol.Map.prototype,
  104283. 'getProperties',
  104284. ol.Map.prototype.getProperties);
  104285. goog.exportProperty(
  104286. ol.Map.prototype,
  104287. 'set',
  104288. ol.Map.prototype.set);
  104289. goog.exportProperty(
  104290. ol.Map.prototype,
  104291. 'setProperties',
  104292. ol.Map.prototype.setProperties);
  104293. goog.exportProperty(
  104294. ol.Map.prototype,
  104295. 'unset',
  104296. ol.Map.prototype.unset);
  104297. goog.exportProperty(
  104298. ol.Map.prototype,
  104299. 'changed',
  104300. ol.Map.prototype.changed);
  104301. goog.exportProperty(
  104302. ol.Map.prototype,
  104303. 'getRevision',
  104304. ol.Map.prototype.getRevision);
  104305. goog.exportProperty(
  104306. ol.Map.prototype,
  104307. 'on',
  104308. ol.Map.prototype.on);
  104309. goog.exportProperty(
  104310. ol.Map.prototype,
  104311. 'once',
  104312. ol.Map.prototype.once);
  104313. goog.exportProperty(
  104314. ol.Map.prototype,
  104315. 'un',
  104316. ol.Map.prototype.un);
  104317. goog.exportProperty(
  104318. ol.Map.prototype,
  104319. 'unByKey',
  104320. ol.Map.prototype.unByKey);
  104321. goog.exportProperty(
  104322. ol.MapBrowserEvent.prototype,
  104323. 'map',
  104324. ol.MapBrowserEvent.prototype.map);
  104325. goog.exportProperty(
  104326. ol.MapBrowserEvent.prototype,
  104327. 'frameState',
  104328. ol.MapBrowserEvent.prototype.frameState);
  104329. goog.exportProperty(
  104330. ol.MapBrowserPointerEvent.prototype,
  104331. 'originalEvent',
  104332. ol.MapBrowserPointerEvent.prototype.originalEvent);
  104333. goog.exportProperty(
  104334. ol.MapBrowserPointerEvent.prototype,
  104335. 'pixel',
  104336. ol.MapBrowserPointerEvent.prototype.pixel);
  104337. goog.exportProperty(
  104338. ol.MapBrowserPointerEvent.prototype,
  104339. 'coordinate',
  104340. ol.MapBrowserPointerEvent.prototype.coordinate);
  104341. goog.exportProperty(
  104342. ol.MapBrowserPointerEvent.prototype,
  104343. 'dragging',
  104344. ol.MapBrowserPointerEvent.prototype.dragging);
  104345. goog.exportProperty(
  104346. ol.MapBrowserPointerEvent.prototype,
  104347. 'preventDefault',
  104348. ol.MapBrowserPointerEvent.prototype.preventDefault);
  104349. goog.exportProperty(
  104350. ol.MapBrowserPointerEvent.prototype,
  104351. 'stopPropagation',
  104352. ol.MapBrowserPointerEvent.prototype.stopPropagation);
  104353. goog.exportProperty(
  104354. ol.MapBrowserPointerEvent.prototype,
  104355. 'map',
  104356. ol.MapBrowserPointerEvent.prototype.map);
  104357. goog.exportProperty(
  104358. ol.MapBrowserPointerEvent.prototype,
  104359. 'frameState',
  104360. ol.MapBrowserPointerEvent.prototype.frameState);
  104361. goog.exportProperty(
  104362. ol.Overlay.prototype,
  104363. 'get',
  104364. ol.Overlay.prototype.get);
  104365. goog.exportProperty(
  104366. ol.Overlay.prototype,
  104367. 'getKeys',
  104368. ol.Overlay.prototype.getKeys);
  104369. goog.exportProperty(
  104370. ol.Overlay.prototype,
  104371. 'getProperties',
  104372. ol.Overlay.prototype.getProperties);
  104373. goog.exportProperty(
  104374. ol.Overlay.prototype,
  104375. 'set',
  104376. ol.Overlay.prototype.set);
  104377. goog.exportProperty(
  104378. ol.Overlay.prototype,
  104379. 'setProperties',
  104380. ol.Overlay.prototype.setProperties);
  104381. goog.exportProperty(
  104382. ol.Overlay.prototype,
  104383. 'unset',
  104384. ol.Overlay.prototype.unset);
  104385. goog.exportProperty(
  104386. ol.Overlay.prototype,
  104387. 'changed',
  104388. ol.Overlay.prototype.changed);
  104389. goog.exportProperty(
  104390. ol.Overlay.prototype,
  104391. 'getRevision',
  104392. ol.Overlay.prototype.getRevision);
  104393. goog.exportProperty(
  104394. ol.Overlay.prototype,
  104395. 'on',
  104396. ol.Overlay.prototype.on);
  104397. goog.exportProperty(
  104398. ol.Overlay.prototype,
  104399. 'once',
  104400. ol.Overlay.prototype.once);
  104401. goog.exportProperty(
  104402. ol.Overlay.prototype,
  104403. 'un',
  104404. ol.Overlay.prototype.un);
  104405. goog.exportProperty(
  104406. ol.Overlay.prototype,
  104407. 'unByKey',
  104408. ol.Overlay.prototype.unByKey);
  104409. goog.exportProperty(
  104410. ol.View.prototype,
  104411. 'get',
  104412. ol.View.prototype.get);
  104413. goog.exportProperty(
  104414. ol.View.prototype,
  104415. 'getKeys',
  104416. ol.View.prototype.getKeys);
  104417. goog.exportProperty(
  104418. ol.View.prototype,
  104419. 'getProperties',
  104420. ol.View.prototype.getProperties);
  104421. goog.exportProperty(
  104422. ol.View.prototype,
  104423. 'set',
  104424. ol.View.prototype.set);
  104425. goog.exportProperty(
  104426. ol.View.prototype,
  104427. 'setProperties',
  104428. ol.View.prototype.setProperties);
  104429. goog.exportProperty(
  104430. ol.View.prototype,
  104431. 'unset',
  104432. ol.View.prototype.unset);
  104433. goog.exportProperty(
  104434. ol.View.prototype,
  104435. 'changed',
  104436. ol.View.prototype.changed);
  104437. goog.exportProperty(
  104438. ol.View.prototype,
  104439. 'getRevision',
  104440. ol.View.prototype.getRevision);
  104441. goog.exportProperty(
  104442. ol.View.prototype,
  104443. 'on',
  104444. ol.View.prototype.on);
  104445. goog.exportProperty(
  104446. ol.View.prototype,
  104447. 'once',
  104448. ol.View.prototype.once);
  104449. goog.exportProperty(
  104450. ol.View.prototype,
  104451. 'un',
  104452. ol.View.prototype.un);
  104453. goog.exportProperty(
  104454. ol.View.prototype,
  104455. 'unByKey',
  104456. ol.View.prototype.unByKey);
  104457. goog.exportProperty(
  104458. ol.tilegrid.WMTS.prototype,
  104459. 'getMaxZoom',
  104460. ol.tilegrid.WMTS.prototype.getMaxZoom);
  104461. goog.exportProperty(
  104462. ol.tilegrid.WMTS.prototype,
  104463. 'getMinZoom',
  104464. ol.tilegrid.WMTS.prototype.getMinZoom);
  104465. goog.exportProperty(
  104466. ol.tilegrid.WMTS.prototype,
  104467. 'getOrigin',
  104468. ol.tilegrid.WMTS.prototype.getOrigin);
  104469. goog.exportProperty(
  104470. ol.tilegrid.WMTS.prototype,
  104471. 'getResolution',
  104472. ol.tilegrid.WMTS.prototype.getResolution);
  104473. goog.exportProperty(
  104474. ol.tilegrid.WMTS.prototype,
  104475. 'getResolutions',
  104476. ol.tilegrid.WMTS.prototype.getResolutions);
  104477. goog.exportProperty(
  104478. ol.tilegrid.WMTS.prototype,
  104479. 'getTileCoordForCoordAndResolution',
  104480. ol.tilegrid.WMTS.prototype.getTileCoordForCoordAndResolution);
  104481. goog.exportProperty(
  104482. ol.tilegrid.WMTS.prototype,
  104483. 'getTileCoordForCoordAndZ',
  104484. ol.tilegrid.WMTS.prototype.getTileCoordForCoordAndZ);
  104485. goog.exportProperty(
  104486. ol.tilegrid.WMTS.prototype,
  104487. 'getTileSize',
  104488. ol.tilegrid.WMTS.prototype.getTileSize);
  104489. goog.exportProperty(
  104490. ol.style.Circle.prototype,
  104491. 'getOpacity',
  104492. ol.style.Circle.prototype.getOpacity);
  104493. goog.exportProperty(
  104494. ol.style.Circle.prototype,
  104495. 'getRotateWithView',
  104496. ol.style.Circle.prototype.getRotateWithView);
  104497. goog.exportProperty(
  104498. ol.style.Circle.prototype,
  104499. 'getRotation',
  104500. ol.style.Circle.prototype.getRotation);
  104501. goog.exportProperty(
  104502. ol.style.Circle.prototype,
  104503. 'getScale',
  104504. ol.style.Circle.prototype.getScale);
  104505. goog.exportProperty(
  104506. ol.style.Circle.prototype,
  104507. 'getSnapToPixel',
  104508. ol.style.Circle.prototype.getSnapToPixel);
  104509. goog.exportProperty(
  104510. ol.style.Circle.prototype,
  104511. 'setOpacity',
  104512. ol.style.Circle.prototype.setOpacity);
  104513. goog.exportProperty(
  104514. ol.style.Circle.prototype,
  104515. 'setRotation',
  104516. ol.style.Circle.prototype.setRotation);
  104517. goog.exportProperty(
  104518. ol.style.Circle.prototype,
  104519. 'setScale',
  104520. ol.style.Circle.prototype.setScale);
  104521. goog.exportProperty(
  104522. ol.style.Icon.prototype,
  104523. 'getOpacity',
  104524. ol.style.Icon.prototype.getOpacity);
  104525. goog.exportProperty(
  104526. ol.style.Icon.prototype,
  104527. 'getRotateWithView',
  104528. ol.style.Icon.prototype.getRotateWithView);
  104529. goog.exportProperty(
  104530. ol.style.Icon.prototype,
  104531. 'getRotation',
  104532. ol.style.Icon.prototype.getRotation);
  104533. goog.exportProperty(
  104534. ol.style.Icon.prototype,
  104535. 'getScale',
  104536. ol.style.Icon.prototype.getScale);
  104537. goog.exportProperty(
  104538. ol.style.Icon.prototype,
  104539. 'getSnapToPixel',
  104540. ol.style.Icon.prototype.getSnapToPixel);
  104541. goog.exportProperty(
  104542. ol.style.Icon.prototype,
  104543. 'setOpacity',
  104544. ol.style.Icon.prototype.setOpacity);
  104545. goog.exportProperty(
  104546. ol.style.Icon.prototype,
  104547. 'setRotation',
  104548. ol.style.Icon.prototype.setRotation);
  104549. goog.exportProperty(
  104550. ol.style.Icon.prototype,
  104551. 'setScale',
  104552. ol.style.Icon.prototype.setScale);
  104553. goog.exportProperty(
  104554. ol.style.RegularShape.prototype,
  104555. 'getOpacity',
  104556. ol.style.RegularShape.prototype.getOpacity);
  104557. goog.exportProperty(
  104558. ol.style.RegularShape.prototype,
  104559. 'getRotateWithView',
  104560. ol.style.RegularShape.prototype.getRotateWithView);
  104561. goog.exportProperty(
  104562. ol.style.RegularShape.prototype,
  104563. 'getRotation',
  104564. ol.style.RegularShape.prototype.getRotation);
  104565. goog.exportProperty(
  104566. ol.style.RegularShape.prototype,
  104567. 'getScale',
  104568. ol.style.RegularShape.prototype.getScale);
  104569. goog.exportProperty(
  104570. ol.style.RegularShape.prototype,
  104571. 'getSnapToPixel',
  104572. ol.style.RegularShape.prototype.getSnapToPixel);
  104573. goog.exportProperty(
  104574. ol.style.RegularShape.prototype,
  104575. 'setOpacity',
  104576. ol.style.RegularShape.prototype.setOpacity);
  104577. goog.exportProperty(
  104578. ol.style.RegularShape.prototype,
  104579. 'setRotation',
  104580. ol.style.RegularShape.prototype.setRotation);
  104581. goog.exportProperty(
  104582. ol.style.RegularShape.prototype,
  104583. 'setScale',
  104584. ol.style.RegularShape.prototype.setScale);
  104585. goog.exportProperty(
  104586. ol.source.Source.prototype,
  104587. 'get',
  104588. ol.source.Source.prototype.get);
  104589. goog.exportProperty(
  104590. ol.source.Source.prototype,
  104591. 'getKeys',
  104592. ol.source.Source.prototype.getKeys);
  104593. goog.exportProperty(
  104594. ol.source.Source.prototype,
  104595. 'getProperties',
  104596. ol.source.Source.prototype.getProperties);
  104597. goog.exportProperty(
  104598. ol.source.Source.prototype,
  104599. 'set',
  104600. ol.source.Source.prototype.set);
  104601. goog.exportProperty(
  104602. ol.source.Source.prototype,
  104603. 'setProperties',
  104604. ol.source.Source.prototype.setProperties);
  104605. goog.exportProperty(
  104606. ol.source.Source.prototype,
  104607. 'unset',
  104608. ol.source.Source.prototype.unset);
  104609. goog.exportProperty(
  104610. ol.source.Source.prototype,
  104611. 'changed',
  104612. ol.source.Source.prototype.changed);
  104613. goog.exportProperty(
  104614. ol.source.Source.prototype,
  104615. 'getRevision',
  104616. ol.source.Source.prototype.getRevision);
  104617. goog.exportProperty(
  104618. ol.source.Source.prototype,
  104619. 'on',
  104620. ol.source.Source.prototype.on);
  104621. goog.exportProperty(
  104622. ol.source.Source.prototype,
  104623. 'once',
  104624. ol.source.Source.prototype.once);
  104625. goog.exportProperty(
  104626. ol.source.Source.prototype,
  104627. 'un',
  104628. ol.source.Source.prototype.un);
  104629. goog.exportProperty(
  104630. ol.source.Source.prototype,
  104631. 'unByKey',
  104632. ol.source.Source.prototype.unByKey);
  104633. goog.exportProperty(
  104634. ol.source.Tile.prototype,
  104635. 'getAttributions',
  104636. ol.source.Tile.prototype.getAttributions);
  104637. goog.exportProperty(
  104638. ol.source.Tile.prototype,
  104639. 'getLogo',
  104640. ol.source.Tile.prototype.getLogo);
  104641. goog.exportProperty(
  104642. ol.source.Tile.prototype,
  104643. 'getProjection',
  104644. ol.source.Tile.prototype.getProjection);
  104645. goog.exportProperty(
  104646. ol.source.Tile.prototype,
  104647. 'getState',
  104648. ol.source.Tile.prototype.getState);
  104649. goog.exportProperty(
  104650. ol.source.Tile.prototype,
  104651. 'setAttributions',
  104652. ol.source.Tile.prototype.setAttributions);
  104653. goog.exportProperty(
  104654. ol.source.Tile.prototype,
  104655. 'get',
  104656. ol.source.Tile.prototype.get);
  104657. goog.exportProperty(
  104658. ol.source.Tile.prototype,
  104659. 'getKeys',
  104660. ol.source.Tile.prototype.getKeys);
  104661. goog.exportProperty(
  104662. ol.source.Tile.prototype,
  104663. 'getProperties',
  104664. ol.source.Tile.prototype.getProperties);
  104665. goog.exportProperty(
  104666. ol.source.Tile.prototype,
  104667. 'set',
  104668. ol.source.Tile.prototype.set);
  104669. goog.exportProperty(
  104670. ol.source.Tile.prototype,
  104671. 'setProperties',
  104672. ol.source.Tile.prototype.setProperties);
  104673. goog.exportProperty(
  104674. ol.source.Tile.prototype,
  104675. 'unset',
  104676. ol.source.Tile.prototype.unset);
  104677. goog.exportProperty(
  104678. ol.source.Tile.prototype,
  104679. 'changed',
  104680. ol.source.Tile.prototype.changed);
  104681. goog.exportProperty(
  104682. ol.source.Tile.prototype,
  104683. 'getRevision',
  104684. ol.source.Tile.prototype.getRevision);
  104685. goog.exportProperty(
  104686. ol.source.Tile.prototype,
  104687. 'on',
  104688. ol.source.Tile.prototype.on);
  104689. goog.exportProperty(
  104690. ol.source.Tile.prototype,
  104691. 'once',
  104692. ol.source.Tile.prototype.once);
  104693. goog.exportProperty(
  104694. ol.source.Tile.prototype,
  104695. 'un',
  104696. ol.source.Tile.prototype.un);
  104697. goog.exportProperty(
  104698. ol.source.Tile.prototype,
  104699. 'unByKey',
  104700. ol.source.Tile.prototype.unByKey);
  104701. goog.exportProperty(
  104702. ol.source.TileImage.prototype,
  104703. 'getTileGrid',
  104704. ol.source.TileImage.prototype.getTileGrid);
  104705. goog.exportProperty(
  104706. ol.source.TileImage.prototype,
  104707. 'getAttributions',
  104708. ol.source.TileImage.prototype.getAttributions);
  104709. goog.exportProperty(
  104710. ol.source.TileImage.prototype,
  104711. 'getLogo',
  104712. ol.source.TileImage.prototype.getLogo);
  104713. goog.exportProperty(
  104714. ol.source.TileImage.prototype,
  104715. 'getProjection',
  104716. ol.source.TileImage.prototype.getProjection);
  104717. goog.exportProperty(
  104718. ol.source.TileImage.prototype,
  104719. 'getState',
  104720. ol.source.TileImage.prototype.getState);
  104721. goog.exportProperty(
  104722. ol.source.TileImage.prototype,
  104723. 'setAttributions',
  104724. ol.source.TileImage.prototype.setAttributions);
  104725. goog.exportProperty(
  104726. ol.source.TileImage.prototype,
  104727. 'get',
  104728. ol.source.TileImage.prototype.get);
  104729. goog.exportProperty(
  104730. ol.source.TileImage.prototype,
  104731. 'getKeys',
  104732. ol.source.TileImage.prototype.getKeys);
  104733. goog.exportProperty(
  104734. ol.source.TileImage.prototype,
  104735. 'getProperties',
  104736. ol.source.TileImage.prototype.getProperties);
  104737. goog.exportProperty(
  104738. ol.source.TileImage.prototype,
  104739. 'set',
  104740. ol.source.TileImage.prototype.set);
  104741. goog.exportProperty(
  104742. ol.source.TileImage.prototype,
  104743. 'setProperties',
  104744. ol.source.TileImage.prototype.setProperties);
  104745. goog.exportProperty(
  104746. ol.source.TileImage.prototype,
  104747. 'unset',
  104748. ol.source.TileImage.prototype.unset);
  104749. goog.exportProperty(
  104750. ol.source.TileImage.prototype,
  104751. 'changed',
  104752. ol.source.TileImage.prototype.changed);
  104753. goog.exportProperty(
  104754. ol.source.TileImage.prototype,
  104755. 'getRevision',
  104756. ol.source.TileImage.prototype.getRevision);
  104757. goog.exportProperty(
  104758. ol.source.TileImage.prototype,
  104759. 'on',
  104760. ol.source.TileImage.prototype.on);
  104761. goog.exportProperty(
  104762. ol.source.TileImage.prototype,
  104763. 'once',
  104764. ol.source.TileImage.prototype.once);
  104765. goog.exportProperty(
  104766. ol.source.TileImage.prototype,
  104767. 'un',
  104768. ol.source.TileImage.prototype.un);
  104769. goog.exportProperty(
  104770. ol.source.TileImage.prototype,
  104771. 'unByKey',
  104772. ol.source.TileImage.prototype.unByKey);
  104773. goog.exportProperty(
  104774. ol.source.BingMaps.prototype,
  104775. 'getTileLoadFunction',
  104776. ol.source.BingMaps.prototype.getTileLoadFunction);
  104777. goog.exportProperty(
  104778. ol.source.BingMaps.prototype,
  104779. 'getTileUrlFunction',
  104780. ol.source.BingMaps.prototype.getTileUrlFunction);
  104781. goog.exportProperty(
  104782. ol.source.BingMaps.prototype,
  104783. 'setTileLoadFunction',
  104784. ol.source.BingMaps.prototype.setTileLoadFunction);
  104785. goog.exportProperty(
  104786. ol.source.BingMaps.prototype,
  104787. 'setTileUrlFunction',
  104788. ol.source.BingMaps.prototype.setTileUrlFunction);
  104789. goog.exportProperty(
  104790. ol.source.BingMaps.prototype,
  104791. 'getTileGrid',
  104792. ol.source.BingMaps.prototype.getTileGrid);
  104793. goog.exportProperty(
  104794. ol.source.BingMaps.prototype,
  104795. 'getAttributions',
  104796. ol.source.BingMaps.prototype.getAttributions);
  104797. goog.exportProperty(
  104798. ol.source.BingMaps.prototype,
  104799. 'getLogo',
  104800. ol.source.BingMaps.prototype.getLogo);
  104801. goog.exportProperty(
  104802. ol.source.BingMaps.prototype,
  104803. 'getProjection',
  104804. ol.source.BingMaps.prototype.getProjection);
  104805. goog.exportProperty(
  104806. ol.source.BingMaps.prototype,
  104807. 'getState',
  104808. ol.source.BingMaps.prototype.getState);
  104809. goog.exportProperty(
  104810. ol.source.BingMaps.prototype,
  104811. 'setAttributions',
  104812. ol.source.BingMaps.prototype.setAttributions);
  104813. goog.exportProperty(
  104814. ol.source.BingMaps.prototype,
  104815. 'get',
  104816. ol.source.BingMaps.prototype.get);
  104817. goog.exportProperty(
  104818. ol.source.BingMaps.prototype,
  104819. 'getKeys',
  104820. ol.source.BingMaps.prototype.getKeys);
  104821. goog.exportProperty(
  104822. ol.source.BingMaps.prototype,
  104823. 'getProperties',
  104824. ol.source.BingMaps.prototype.getProperties);
  104825. goog.exportProperty(
  104826. ol.source.BingMaps.prototype,
  104827. 'set',
  104828. ol.source.BingMaps.prototype.set);
  104829. goog.exportProperty(
  104830. ol.source.BingMaps.prototype,
  104831. 'setProperties',
  104832. ol.source.BingMaps.prototype.setProperties);
  104833. goog.exportProperty(
  104834. ol.source.BingMaps.prototype,
  104835. 'unset',
  104836. ol.source.BingMaps.prototype.unset);
  104837. goog.exportProperty(
  104838. ol.source.BingMaps.prototype,
  104839. 'changed',
  104840. ol.source.BingMaps.prototype.changed);
  104841. goog.exportProperty(
  104842. ol.source.BingMaps.prototype,
  104843. 'getRevision',
  104844. ol.source.BingMaps.prototype.getRevision);
  104845. goog.exportProperty(
  104846. ol.source.BingMaps.prototype,
  104847. 'on',
  104848. ol.source.BingMaps.prototype.on);
  104849. goog.exportProperty(
  104850. ol.source.BingMaps.prototype,
  104851. 'once',
  104852. ol.source.BingMaps.prototype.once);
  104853. goog.exportProperty(
  104854. ol.source.BingMaps.prototype,
  104855. 'un',
  104856. ol.source.BingMaps.prototype.un);
  104857. goog.exportProperty(
  104858. ol.source.BingMaps.prototype,
  104859. 'unByKey',
  104860. ol.source.BingMaps.prototype.unByKey);
  104861. goog.exportProperty(
  104862. ol.source.Vector.prototype,
  104863. 'getAttributions',
  104864. ol.source.Vector.prototype.getAttributions);
  104865. goog.exportProperty(
  104866. ol.source.Vector.prototype,
  104867. 'getLogo',
  104868. ol.source.Vector.prototype.getLogo);
  104869. goog.exportProperty(
  104870. ol.source.Vector.prototype,
  104871. 'getProjection',
  104872. ol.source.Vector.prototype.getProjection);
  104873. goog.exportProperty(
  104874. ol.source.Vector.prototype,
  104875. 'getState',
  104876. ol.source.Vector.prototype.getState);
  104877. goog.exportProperty(
  104878. ol.source.Vector.prototype,
  104879. 'setAttributions',
  104880. ol.source.Vector.prototype.setAttributions);
  104881. goog.exportProperty(
  104882. ol.source.Vector.prototype,
  104883. 'get',
  104884. ol.source.Vector.prototype.get);
  104885. goog.exportProperty(
  104886. ol.source.Vector.prototype,
  104887. 'getKeys',
  104888. ol.source.Vector.prototype.getKeys);
  104889. goog.exportProperty(
  104890. ol.source.Vector.prototype,
  104891. 'getProperties',
  104892. ol.source.Vector.prototype.getProperties);
  104893. goog.exportProperty(
  104894. ol.source.Vector.prototype,
  104895. 'set',
  104896. ol.source.Vector.prototype.set);
  104897. goog.exportProperty(
  104898. ol.source.Vector.prototype,
  104899. 'setProperties',
  104900. ol.source.Vector.prototype.setProperties);
  104901. goog.exportProperty(
  104902. ol.source.Vector.prototype,
  104903. 'unset',
  104904. ol.source.Vector.prototype.unset);
  104905. goog.exportProperty(
  104906. ol.source.Vector.prototype,
  104907. 'changed',
  104908. ol.source.Vector.prototype.changed);
  104909. goog.exportProperty(
  104910. ol.source.Vector.prototype,
  104911. 'getRevision',
  104912. ol.source.Vector.prototype.getRevision);
  104913. goog.exportProperty(
  104914. ol.source.Vector.prototype,
  104915. 'on',
  104916. ol.source.Vector.prototype.on);
  104917. goog.exportProperty(
  104918. ol.source.Vector.prototype,
  104919. 'once',
  104920. ol.source.Vector.prototype.once);
  104921. goog.exportProperty(
  104922. ol.source.Vector.prototype,
  104923. 'un',
  104924. ol.source.Vector.prototype.un);
  104925. goog.exportProperty(
  104926. ol.source.Vector.prototype,
  104927. 'unByKey',
  104928. ol.source.Vector.prototype.unByKey);
  104929. goog.exportProperty(
  104930. ol.source.Cluster.prototype,
  104931. 'addFeature',
  104932. ol.source.Cluster.prototype.addFeature);
  104933. goog.exportProperty(
  104934. ol.source.Cluster.prototype,
  104935. 'addFeatures',
  104936. ol.source.Cluster.prototype.addFeatures);
  104937. goog.exportProperty(
  104938. ol.source.Cluster.prototype,
  104939. 'clear',
  104940. ol.source.Cluster.prototype.clear);
  104941. goog.exportProperty(
  104942. ol.source.Cluster.prototype,
  104943. 'forEachFeature',
  104944. ol.source.Cluster.prototype.forEachFeature);
  104945. goog.exportProperty(
  104946. ol.source.Cluster.prototype,
  104947. 'forEachFeatureInExtent',
  104948. ol.source.Cluster.prototype.forEachFeatureInExtent);
  104949. goog.exportProperty(
  104950. ol.source.Cluster.prototype,
  104951. 'forEachFeatureIntersectingExtent',
  104952. ol.source.Cluster.prototype.forEachFeatureIntersectingExtent);
  104953. goog.exportProperty(
  104954. ol.source.Cluster.prototype,
  104955. 'getFeaturesCollection',
  104956. ol.source.Cluster.prototype.getFeaturesCollection);
  104957. goog.exportProperty(
  104958. ol.source.Cluster.prototype,
  104959. 'getFeatures',
  104960. ol.source.Cluster.prototype.getFeatures);
  104961. goog.exportProperty(
  104962. ol.source.Cluster.prototype,
  104963. 'getFeaturesAtCoordinate',
  104964. ol.source.Cluster.prototype.getFeaturesAtCoordinate);
  104965. goog.exportProperty(
  104966. ol.source.Cluster.prototype,
  104967. 'getFeaturesInExtent',
  104968. ol.source.Cluster.prototype.getFeaturesInExtent);
  104969. goog.exportProperty(
  104970. ol.source.Cluster.prototype,
  104971. 'getClosestFeatureToCoordinate',
  104972. ol.source.Cluster.prototype.getClosestFeatureToCoordinate);
  104973. goog.exportProperty(
  104974. ol.source.Cluster.prototype,
  104975. 'getExtent',
  104976. ol.source.Cluster.prototype.getExtent);
  104977. goog.exportProperty(
  104978. ol.source.Cluster.prototype,
  104979. 'getFeatureById',
  104980. ol.source.Cluster.prototype.getFeatureById);
  104981. goog.exportProperty(
  104982. ol.source.Cluster.prototype,
  104983. 'removeFeature',
  104984. ol.source.Cluster.prototype.removeFeature);
  104985. goog.exportProperty(
  104986. ol.source.Cluster.prototype,
  104987. 'getAttributions',
  104988. ol.source.Cluster.prototype.getAttributions);
  104989. goog.exportProperty(
  104990. ol.source.Cluster.prototype,
  104991. 'getLogo',
  104992. ol.source.Cluster.prototype.getLogo);
  104993. goog.exportProperty(
  104994. ol.source.Cluster.prototype,
  104995. 'getProjection',
  104996. ol.source.Cluster.prototype.getProjection);
  104997. goog.exportProperty(
  104998. ol.source.Cluster.prototype,
  104999. 'getState',
  105000. ol.source.Cluster.prototype.getState);
  105001. goog.exportProperty(
  105002. ol.source.Cluster.prototype,
  105003. 'setAttributions',
  105004. ol.source.Cluster.prototype.setAttributions);
  105005. goog.exportProperty(
  105006. ol.source.Cluster.prototype,
  105007. 'get',
  105008. ol.source.Cluster.prototype.get);
  105009. goog.exportProperty(
  105010. ol.source.Cluster.prototype,
  105011. 'getKeys',
  105012. ol.source.Cluster.prototype.getKeys);
  105013. goog.exportProperty(
  105014. ol.source.Cluster.prototype,
  105015. 'getProperties',
  105016. ol.source.Cluster.prototype.getProperties);
  105017. goog.exportProperty(
  105018. ol.source.Cluster.prototype,
  105019. 'set',
  105020. ol.source.Cluster.prototype.set);
  105021. goog.exportProperty(
  105022. ol.source.Cluster.prototype,
  105023. 'setProperties',
  105024. ol.source.Cluster.prototype.setProperties);
  105025. goog.exportProperty(
  105026. ol.source.Cluster.prototype,
  105027. 'unset',
  105028. ol.source.Cluster.prototype.unset);
  105029. goog.exportProperty(
  105030. ol.source.Cluster.prototype,
  105031. 'changed',
  105032. ol.source.Cluster.prototype.changed);
  105033. goog.exportProperty(
  105034. ol.source.Cluster.prototype,
  105035. 'getRevision',
  105036. ol.source.Cluster.prototype.getRevision);
  105037. goog.exportProperty(
  105038. ol.source.Cluster.prototype,
  105039. 'on',
  105040. ol.source.Cluster.prototype.on);
  105041. goog.exportProperty(
  105042. ol.source.Cluster.prototype,
  105043. 'once',
  105044. ol.source.Cluster.prototype.once);
  105045. goog.exportProperty(
  105046. ol.source.Cluster.prototype,
  105047. 'un',
  105048. ol.source.Cluster.prototype.un);
  105049. goog.exportProperty(
  105050. ol.source.Cluster.prototype,
  105051. 'unByKey',
  105052. ol.source.Cluster.prototype.unByKey);
  105053. goog.exportProperty(
  105054. ol.source.Image.prototype,
  105055. 'getAttributions',
  105056. ol.source.Image.prototype.getAttributions);
  105057. goog.exportProperty(
  105058. ol.source.Image.prototype,
  105059. 'getLogo',
  105060. ol.source.Image.prototype.getLogo);
  105061. goog.exportProperty(
  105062. ol.source.Image.prototype,
  105063. 'getProjection',
  105064. ol.source.Image.prototype.getProjection);
  105065. goog.exportProperty(
  105066. ol.source.Image.prototype,
  105067. 'getState',
  105068. ol.source.Image.prototype.getState);
  105069. goog.exportProperty(
  105070. ol.source.Image.prototype,
  105071. 'setAttributions',
  105072. ol.source.Image.prototype.setAttributions);
  105073. goog.exportProperty(
  105074. ol.source.Image.prototype,
  105075. 'get',
  105076. ol.source.Image.prototype.get);
  105077. goog.exportProperty(
  105078. ol.source.Image.prototype,
  105079. 'getKeys',
  105080. ol.source.Image.prototype.getKeys);
  105081. goog.exportProperty(
  105082. ol.source.Image.prototype,
  105083. 'getProperties',
  105084. ol.source.Image.prototype.getProperties);
  105085. goog.exportProperty(
  105086. ol.source.Image.prototype,
  105087. 'set',
  105088. ol.source.Image.prototype.set);
  105089. goog.exportProperty(
  105090. ol.source.Image.prototype,
  105091. 'setProperties',
  105092. ol.source.Image.prototype.setProperties);
  105093. goog.exportProperty(
  105094. ol.source.Image.prototype,
  105095. 'unset',
  105096. ol.source.Image.prototype.unset);
  105097. goog.exportProperty(
  105098. ol.source.Image.prototype,
  105099. 'changed',
  105100. ol.source.Image.prototype.changed);
  105101. goog.exportProperty(
  105102. ol.source.Image.prototype,
  105103. 'getRevision',
  105104. ol.source.Image.prototype.getRevision);
  105105. goog.exportProperty(
  105106. ol.source.Image.prototype,
  105107. 'on',
  105108. ol.source.Image.prototype.on);
  105109. goog.exportProperty(
  105110. ol.source.Image.prototype,
  105111. 'once',
  105112. ol.source.Image.prototype.once);
  105113. goog.exportProperty(
  105114. ol.source.Image.prototype,
  105115. 'un',
  105116. ol.source.Image.prototype.un);
  105117. goog.exportProperty(
  105118. ol.source.Image.prototype,
  105119. 'unByKey',
  105120. ol.source.Image.prototype.unByKey);
  105121. goog.exportProperty(
  105122. ol.source.ImageCanvas.prototype,
  105123. 'getAttributions',
  105124. ol.source.ImageCanvas.prototype.getAttributions);
  105125. goog.exportProperty(
  105126. ol.source.ImageCanvas.prototype,
  105127. 'getLogo',
  105128. ol.source.ImageCanvas.prototype.getLogo);
  105129. goog.exportProperty(
  105130. ol.source.ImageCanvas.prototype,
  105131. 'getProjection',
  105132. ol.source.ImageCanvas.prototype.getProjection);
  105133. goog.exportProperty(
  105134. ol.source.ImageCanvas.prototype,
  105135. 'getState',
  105136. ol.source.ImageCanvas.prototype.getState);
  105137. goog.exportProperty(
  105138. ol.source.ImageCanvas.prototype,
  105139. 'setAttributions',
  105140. ol.source.ImageCanvas.prototype.setAttributions);
  105141. goog.exportProperty(
  105142. ol.source.ImageCanvas.prototype,
  105143. 'get',
  105144. ol.source.ImageCanvas.prototype.get);
  105145. goog.exportProperty(
  105146. ol.source.ImageCanvas.prototype,
  105147. 'getKeys',
  105148. ol.source.ImageCanvas.prototype.getKeys);
  105149. goog.exportProperty(
  105150. ol.source.ImageCanvas.prototype,
  105151. 'getProperties',
  105152. ol.source.ImageCanvas.prototype.getProperties);
  105153. goog.exportProperty(
  105154. ol.source.ImageCanvas.prototype,
  105155. 'set',
  105156. ol.source.ImageCanvas.prototype.set);
  105157. goog.exportProperty(
  105158. ol.source.ImageCanvas.prototype,
  105159. 'setProperties',
  105160. ol.source.ImageCanvas.prototype.setProperties);
  105161. goog.exportProperty(
  105162. ol.source.ImageCanvas.prototype,
  105163. 'unset',
  105164. ol.source.ImageCanvas.prototype.unset);
  105165. goog.exportProperty(
  105166. ol.source.ImageCanvas.prototype,
  105167. 'changed',
  105168. ol.source.ImageCanvas.prototype.changed);
  105169. goog.exportProperty(
  105170. ol.source.ImageCanvas.prototype,
  105171. 'getRevision',
  105172. ol.source.ImageCanvas.prototype.getRevision);
  105173. goog.exportProperty(
  105174. ol.source.ImageCanvas.prototype,
  105175. 'on',
  105176. ol.source.ImageCanvas.prototype.on);
  105177. goog.exportProperty(
  105178. ol.source.ImageCanvas.prototype,
  105179. 'once',
  105180. ol.source.ImageCanvas.prototype.once);
  105181. goog.exportProperty(
  105182. ol.source.ImageCanvas.prototype,
  105183. 'un',
  105184. ol.source.ImageCanvas.prototype.un);
  105185. goog.exportProperty(
  105186. ol.source.ImageCanvas.prototype,
  105187. 'unByKey',
  105188. ol.source.ImageCanvas.prototype.unByKey);
  105189. goog.exportProperty(
  105190. ol.source.ImageMapGuide.prototype,
  105191. 'getAttributions',
  105192. ol.source.ImageMapGuide.prototype.getAttributions);
  105193. goog.exportProperty(
  105194. ol.source.ImageMapGuide.prototype,
  105195. 'getLogo',
  105196. ol.source.ImageMapGuide.prototype.getLogo);
  105197. goog.exportProperty(
  105198. ol.source.ImageMapGuide.prototype,
  105199. 'getProjection',
  105200. ol.source.ImageMapGuide.prototype.getProjection);
  105201. goog.exportProperty(
  105202. ol.source.ImageMapGuide.prototype,
  105203. 'getState',
  105204. ol.source.ImageMapGuide.prototype.getState);
  105205. goog.exportProperty(
  105206. ol.source.ImageMapGuide.prototype,
  105207. 'setAttributions',
  105208. ol.source.ImageMapGuide.prototype.setAttributions);
  105209. goog.exportProperty(
  105210. ol.source.ImageMapGuide.prototype,
  105211. 'get',
  105212. ol.source.ImageMapGuide.prototype.get);
  105213. goog.exportProperty(
  105214. ol.source.ImageMapGuide.prototype,
  105215. 'getKeys',
  105216. ol.source.ImageMapGuide.prototype.getKeys);
  105217. goog.exportProperty(
  105218. ol.source.ImageMapGuide.prototype,
  105219. 'getProperties',
  105220. ol.source.ImageMapGuide.prototype.getProperties);
  105221. goog.exportProperty(
  105222. ol.source.ImageMapGuide.prototype,
  105223. 'set',
  105224. ol.source.ImageMapGuide.prototype.set);
  105225. goog.exportProperty(
  105226. ol.source.ImageMapGuide.prototype,
  105227. 'setProperties',
  105228. ol.source.ImageMapGuide.prototype.setProperties);
  105229. goog.exportProperty(
  105230. ol.source.ImageMapGuide.prototype,
  105231. 'unset',
  105232. ol.source.ImageMapGuide.prototype.unset);
  105233. goog.exportProperty(
  105234. ol.source.ImageMapGuide.prototype,
  105235. 'changed',
  105236. ol.source.ImageMapGuide.prototype.changed);
  105237. goog.exportProperty(
  105238. ol.source.ImageMapGuide.prototype,
  105239. 'getRevision',
  105240. ol.source.ImageMapGuide.prototype.getRevision);
  105241. goog.exportProperty(
  105242. ol.source.ImageMapGuide.prototype,
  105243. 'on',
  105244. ol.source.ImageMapGuide.prototype.on);
  105245. goog.exportProperty(
  105246. ol.source.ImageMapGuide.prototype,
  105247. 'once',
  105248. ol.source.ImageMapGuide.prototype.once);
  105249. goog.exportProperty(
  105250. ol.source.ImageMapGuide.prototype,
  105251. 'un',
  105252. ol.source.ImageMapGuide.prototype.un);
  105253. goog.exportProperty(
  105254. ol.source.ImageMapGuide.prototype,
  105255. 'unByKey',
  105256. ol.source.ImageMapGuide.prototype.unByKey);
  105257. goog.exportProperty(
  105258. ol.source.ImageStatic.prototype,
  105259. 'getAttributions',
  105260. ol.source.ImageStatic.prototype.getAttributions);
  105261. goog.exportProperty(
  105262. ol.source.ImageStatic.prototype,
  105263. 'getLogo',
  105264. ol.source.ImageStatic.prototype.getLogo);
  105265. goog.exportProperty(
  105266. ol.source.ImageStatic.prototype,
  105267. 'getProjection',
  105268. ol.source.ImageStatic.prototype.getProjection);
  105269. goog.exportProperty(
  105270. ol.source.ImageStatic.prototype,
  105271. 'getState',
  105272. ol.source.ImageStatic.prototype.getState);
  105273. goog.exportProperty(
  105274. ol.source.ImageStatic.prototype,
  105275. 'setAttributions',
  105276. ol.source.ImageStatic.prototype.setAttributions);
  105277. goog.exportProperty(
  105278. ol.source.ImageStatic.prototype,
  105279. 'get',
  105280. ol.source.ImageStatic.prototype.get);
  105281. goog.exportProperty(
  105282. ol.source.ImageStatic.prototype,
  105283. 'getKeys',
  105284. ol.source.ImageStatic.prototype.getKeys);
  105285. goog.exportProperty(
  105286. ol.source.ImageStatic.prototype,
  105287. 'getProperties',
  105288. ol.source.ImageStatic.prototype.getProperties);
  105289. goog.exportProperty(
  105290. ol.source.ImageStatic.prototype,
  105291. 'set',
  105292. ol.source.ImageStatic.prototype.set);
  105293. goog.exportProperty(
  105294. ol.source.ImageStatic.prototype,
  105295. 'setProperties',
  105296. ol.source.ImageStatic.prototype.setProperties);
  105297. goog.exportProperty(
  105298. ol.source.ImageStatic.prototype,
  105299. 'unset',
  105300. ol.source.ImageStatic.prototype.unset);
  105301. goog.exportProperty(
  105302. ol.source.ImageStatic.prototype,
  105303. 'changed',
  105304. ol.source.ImageStatic.prototype.changed);
  105305. goog.exportProperty(
  105306. ol.source.ImageStatic.prototype,
  105307. 'getRevision',
  105308. ol.source.ImageStatic.prototype.getRevision);
  105309. goog.exportProperty(
  105310. ol.source.ImageStatic.prototype,
  105311. 'on',
  105312. ol.source.ImageStatic.prototype.on);
  105313. goog.exportProperty(
  105314. ol.source.ImageStatic.prototype,
  105315. 'once',
  105316. ol.source.ImageStatic.prototype.once);
  105317. goog.exportProperty(
  105318. ol.source.ImageStatic.prototype,
  105319. 'un',
  105320. ol.source.ImageStatic.prototype.un);
  105321. goog.exportProperty(
  105322. ol.source.ImageStatic.prototype,
  105323. 'unByKey',
  105324. ol.source.ImageStatic.prototype.unByKey);
  105325. goog.exportProperty(
  105326. ol.source.ImageVector.prototype,
  105327. 'getAttributions',
  105328. ol.source.ImageVector.prototype.getAttributions);
  105329. goog.exportProperty(
  105330. ol.source.ImageVector.prototype,
  105331. 'getLogo',
  105332. ol.source.ImageVector.prototype.getLogo);
  105333. goog.exportProperty(
  105334. ol.source.ImageVector.prototype,
  105335. 'getProjection',
  105336. ol.source.ImageVector.prototype.getProjection);
  105337. goog.exportProperty(
  105338. ol.source.ImageVector.prototype,
  105339. 'getState',
  105340. ol.source.ImageVector.prototype.getState);
  105341. goog.exportProperty(
  105342. ol.source.ImageVector.prototype,
  105343. 'setAttributions',
  105344. ol.source.ImageVector.prototype.setAttributions);
  105345. goog.exportProperty(
  105346. ol.source.ImageVector.prototype,
  105347. 'get',
  105348. ol.source.ImageVector.prototype.get);
  105349. goog.exportProperty(
  105350. ol.source.ImageVector.prototype,
  105351. 'getKeys',
  105352. ol.source.ImageVector.prototype.getKeys);
  105353. goog.exportProperty(
  105354. ol.source.ImageVector.prototype,
  105355. 'getProperties',
  105356. ol.source.ImageVector.prototype.getProperties);
  105357. goog.exportProperty(
  105358. ol.source.ImageVector.prototype,
  105359. 'set',
  105360. ol.source.ImageVector.prototype.set);
  105361. goog.exportProperty(
  105362. ol.source.ImageVector.prototype,
  105363. 'setProperties',
  105364. ol.source.ImageVector.prototype.setProperties);
  105365. goog.exportProperty(
  105366. ol.source.ImageVector.prototype,
  105367. 'unset',
  105368. ol.source.ImageVector.prototype.unset);
  105369. goog.exportProperty(
  105370. ol.source.ImageVector.prototype,
  105371. 'changed',
  105372. ol.source.ImageVector.prototype.changed);
  105373. goog.exportProperty(
  105374. ol.source.ImageVector.prototype,
  105375. 'getRevision',
  105376. ol.source.ImageVector.prototype.getRevision);
  105377. goog.exportProperty(
  105378. ol.source.ImageVector.prototype,
  105379. 'on',
  105380. ol.source.ImageVector.prototype.on);
  105381. goog.exportProperty(
  105382. ol.source.ImageVector.prototype,
  105383. 'once',
  105384. ol.source.ImageVector.prototype.once);
  105385. goog.exportProperty(
  105386. ol.source.ImageVector.prototype,
  105387. 'un',
  105388. ol.source.ImageVector.prototype.un);
  105389. goog.exportProperty(
  105390. ol.source.ImageVector.prototype,
  105391. 'unByKey',
  105392. ol.source.ImageVector.prototype.unByKey);
  105393. goog.exportProperty(
  105394. ol.source.ImageWMS.prototype,
  105395. 'getAttributions',
  105396. ol.source.ImageWMS.prototype.getAttributions);
  105397. goog.exportProperty(
  105398. ol.source.ImageWMS.prototype,
  105399. 'getLogo',
  105400. ol.source.ImageWMS.prototype.getLogo);
  105401. goog.exportProperty(
  105402. ol.source.ImageWMS.prototype,
  105403. 'getProjection',
  105404. ol.source.ImageWMS.prototype.getProjection);
  105405. goog.exportProperty(
  105406. ol.source.ImageWMS.prototype,
  105407. 'getState',
  105408. ol.source.ImageWMS.prototype.getState);
  105409. goog.exportProperty(
  105410. ol.source.ImageWMS.prototype,
  105411. 'setAttributions',
  105412. ol.source.ImageWMS.prototype.setAttributions);
  105413. goog.exportProperty(
  105414. ol.source.ImageWMS.prototype,
  105415. 'get',
  105416. ol.source.ImageWMS.prototype.get);
  105417. goog.exportProperty(
  105418. ol.source.ImageWMS.prototype,
  105419. 'getKeys',
  105420. ol.source.ImageWMS.prototype.getKeys);
  105421. goog.exportProperty(
  105422. ol.source.ImageWMS.prototype,
  105423. 'getProperties',
  105424. ol.source.ImageWMS.prototype.getProperties);
  105425. goog.exportProperty(
  105426. ol.source.ImageWMS.prototype,
  105427. 'set',
  105428. ol.source.ImageWMS.prototype.set);
  105429. goog.exportProperty(
  105430. ol.source.ImageWMS.prototype,
  105431. 'setProperties',
  105432. ol.source.ImageWMS.prototype.setProperties);
  105433. goog.exportProperty(
  105434. ol.source.ImageWMS.prototype,
  105435. 'unset',
  105436. ol.source.ImageWMS.prototype.unset);
  105437. goog.exportProperty(
  105438. ol.source.ImageWMS.prototype,
  105439. 'changed',
  105440. ol.source.ImageWMS.prototype.changed);
  105441. goog.exportProperty(
  105442. ol.source.ImageWMS.prototype,
  105443. 'getRevision',
  105444. ol.source.ImageWMS.prototype.getRevision);
  105445. goog.exportProperty(
  105446. ol.source.ImageWMS.prototype,
  105447. 'on',
  105448. ol.source.ImageWMS.prototype.on);
  105449. goog.exportProperty(
  105450. ol.source.ImageWMS.prototype,
  105451. 'once',
  105452. ol.source.ImageWMS.prototype.once);
  105453. goog.exportProperty(
  105454. ol.source.ImageWMS.prototype,
  105455. 'un',
  105456. ol.source.ImageWMS.prototype.un);
  105457. goog.exportProperty(
  105458. ol.source.ImageWMS.prototype,
  105459. 'unByKey',
  105460. ol.source.ImageWMS.prototype.unByKey);
  105461. goog.exportProperty(
  105462. ol.source.XYZ.prototype,
  105463. 'getTileLoadFunction',
  105464. ol.source.XYZ.prototype.getTileLoadFunction);
  105465. goog.exportProperty(
  105466. ol.source.XYZ.prototype,
  105467. 'getTileUrlFunction',
  105468. ol.source.XYZ.prototype.getTileUrlFunction);
  105469. goog.exportProperty(
  105470. ol.source.XYZ.prototype,
  105471. 'setTileLoadFunction',
  105472. ol.source.XYZ.prototype.setTileLoadFunction);
  105473. goog.exportProperty(
  105474. ol.source.XYZ.prototype,
  105475. 'setTileUrlFunction',
  105476. ol.source.XYZ.prototype.setTileUrlFunction);
  105477. goog.exportProperty(
  105478. ol.source.XYZ.prototype,
  105479. 'getTileGrid',
  105480. ol.source.XYZ.prototype.getTileGrid);
  105481. goog.exportProperty(
  105482. ol.source.XYZ.prototype,
  105483. 'getAttributions',
  105484. ol.source.XYZ.prototype.getAttributions);
  105485. goog.exportProperty(
  105486. ol.source.XYZ.prototype,
  105487. 'getLogo',
  105488. ol.source.XYZ.prototype.getLogo);
  105489. goog.exportProperty(
  105490. ol.source.XYZ.prototype,
  105491. 'getProjection',
  105492. ol.source.XYZ.prototype.getProjection);
  105493. goog.exportProperty(
  105494. ol.source.XYZ.prototype,
  105495. 'getState',
  105496. ol.source.XYZ.prototype.getState);
  105497. goog.exportProperty(
  105498. ol.source.XYZ.prototype,
  105499. 'setAttributions',
  105500. ol.source.XYZ.prototype.setAttributions);
  105501. goog.exportProperty(
  105502. ol.source.XYZ.prototype,
  105503. 'get',
  105504. ol.source.XYZ.prototype.get);
  105505. goog.exportProperty(
  105506. ol.source.XYZ.prototype,
  105507. 'getKeys',
  105508. ol.source.XYZ.prototype.getKeys);
  105509. goog.exportProperty(
  105510. ol.source.XYZ.prototype,
  105511. 'getProperties',
  105512. ol.source.XYZ.prototype.getProperties);
  105513. goog.exportProperty(
  105514. ol.source.XYZ.prototype,
  105515. 'set',
  105516. ol.source.XYZ.prototype.set);
  105517. goog.exportProperty(
  105518. ol.source.XYZ.prototype,
  105519. 'setProperties',
  105520. ol.source.XYZ.prototype.setProperties);
  105521. goog.exportProperty(
  105522. ol.source.XYZ.prototype,
  105523. 'unset',
  105524. ol.source.XYZ.prototype.unset);
  105525. goog.exportProperty(
  105526. ol.source.XYZ.prototype,
  105527. 'changed',
  105528. ol.source.XYZ.prototype.changed);
  105529. goog.exportProperty(
  105530. ol.source.XYZ.prototype,
  105531. 'getRevision',
  105532. ol.source.XYZ.prototype.getRevision);
  105533. goog.exportProperty(
  105534. ol.source.XYZ.prototype,
  105535. 'on',
  105536. ol.source.XYZ.prototype.on);
  105537. goog.exportProperty(
  105538. ol.source.XYZ.prototype,
  105539. 'once',
  105540. ol.source.XYZ.prototype.once);
  105541. goog.exportProperty(
  105542. ol.source.XYZ.prototype,
  105543. 'un',
  105544. ol.source.XYZ.prototype.un);
  105545. goog.exportProperty(
  105546. ol.source.XYZ.prototype,
  105547. 'unByKey',
  105548. ol.source.XYZ.prototype.unByKey);
  105549. goog.exportProperty(
  105550. ol.source.MapQuest.prototype,
  105551. 'getUrls',
  105552. ol.source.MapQuest.prototype.getUrls);
  105553. goog.exportProperty(
  105554. ol.source.MapQuest.prototype,
  105555. 'setUrl',
  105556. ol.source.MapQuest.prototype.setUrl);
  105557. goog.exportProperty(
  105558. ol.source.MapQuest.prototype,
  105559. 'getTileLoadFunction',
  105560. ol.source.MapQuest.prototype.getTileLoadFunction);
  105561. goog.exportProperty(
  105562. ol.source.MapQuest.prototype,
  105563. 'getTileUrlFunction',
  105564. ol.source.MapQuest.prototype.getTileUrlFunction);
  105565. goog.exportProperty(
  105566. ol.source.MapQuest.prototype,
  105567. 'setTileLoadFunction',
  105568. ol.source.MapQuest.prototype.setTileLoadFunction);
  105569. goog.exportProperty(
  105570. ol.source.MapQuest.prototype,
  105571. 'setTileUrlFunction',
  105572. ol.source.MapQuest.prototype.setTileUrlFunction);
  105573. goog.exportProperty(
  105574. ol.source.MapQuest.prototype,
  105575. 'getTileGrid',
  105576. ol.source.MapQuest.prototype.getTileGrid);
  105577. goog.exportProperty(
  105578. ol.source.MapQuest.prototype,
  105579. 'getAttributions',
  105580. ol.source.MapQuest.prototype.getAttributions);
  105581. goog.exportProperty(
  105582. ol.source.MapQuest.prototype,
  105583. 'getLogo',
  105584. ol.source.MapQuest.prototype.getLogo);
  105585. goog.exportProperty(
  105586. ol.source.MapQuest.prototype,
  105587. 'getProjection',
  105588. ol.source.MapQuest.prototype.getProjection);
  105589. goog.exportProperty(
  105590. ol.source.MapQuest.prototype,
  105591. 'getState',
  105592. ol.source.MapQuest.prototype.getState);
  105593. goog.exportProperty(
  105594. ol.source.MapQuest.prototype,
  105595. 'setAttributions',
  105596. ol.source.MapQuest.prototype.setAttributions);
  105597. goog.exportProperty(
  105598. ol.source.MapQuest.prototype,
  105599. 'get',
  105600. ol.source.MapQuest.prototype.get);
  105601. goog.exportProperty(
  105602. ol.source.MapQuest.prototype,
  105603. 'getKeys',
  105604. ol.source.MapQuest.prototype.getKeys);
  105605. goog.exportProperty(
  105606. ol.source.MapQuest.prototype,
  105607. 'getProperties',
  105608. ol.source.MapQuest.prototype.getProperties);
  105609. goog.exportProperty(
  105610. ol.source.MapQuest.prototype,
  105611. 'set',
  105612. ol.source.MapQuest.prototype.set);
  105613. goog.exportProperty(
  105614. ol.source.MapQuest.prototype,
  105615. 'setProperties',
  105616. ol.source.MapQuest.prototype.setProperties);
  105617. goog.exportProperty(
  105618. ol.source.MapQuest.prototype,
  105619. 'unset',
  105620. ol.source.MapQuest.prototype.unset);
  105621. goog.exportProperty(
  105622. ol.source.MapQuest.prototype,
  105623. 'changed',
  105624. ol.source.MapQuest.prototype.changed);
  105625. goog.exportProperty(
  105626. ol.source.MapQuest.prototype,
  105627. 'getRevision',
  105628. ol.source.MapQuest.prototype.getRevision);
  105629. goog.exportProperty(
  105630. ol.source.MapQuest.prototype,
  105631. 'on',
  105632. ol.source.MapQuest.prototype.on);
  105633. goog.exportProperty(
  105634. ol.source.MapQuest.prototype,
  105635. 'once',
  105636. ol.source.MapQuest.prototype.once);
  105637. goog.exportProperty(
  105638. ol.source.MapQuest.prototype,
  105639. 'un',
  105640. ol.source.MapQuest.prototype.un);
  105641. goog.exportProperty(
  105642. ol.source.MapQuest.prototype,
  105643. 'unByKey',
  105644. ol.source.MapQuest.prototype.unByKey);
  105645. goog.exportProperty(
  105646. ol.source.OSM.prototype,
  105647. 'getUrls',
  105648. ol.source.OSM.prototype.getUrls);
  105649. goog.exportProperty(
  105650. ol.source.OSM.prototype,
  105651. 'setUrl',
  105652. ol.source.OSM.prototype.setUrl);
  105653. goog.exportProperty(
  105654. ol.source.OSM.prototype,
  105655. 'getTileLoadFunction',
  105656. ol.source.OSM.prototype.getTileLoadFunction);
  105657. goog.exportProperty(
  105658. ol.source.OSM.prototype,
  105659. 'getTileUrlFunction',
  105660. ol.source.OSM.prototype.getTileUrlFunction);
  105661. goog.exportProperty(
  105662. ol.source.OSM.prototype,
  105663. 'setTileLoadFunction',
  105664. ol.source.OSM.prototype.setTileLoadFunction);
  105665. goog.exportProperty(
  105666. ol.source.OSM.prototype,
  105667. 'setTileUrlFunction',
  105668. ol.source.OSM.prototype.setTileUrlFunction);
  105669. goog.exportProperty(
  105670. ol.source.OSM.prototype,
  105671. 'getTileGrid',
  105672. ol.source.OSM.prototype.getTileGrid);
  105673. goog.exportProperty(
  105674. ol.source.OSM.prototype,
  105675. 'getAttributions',
  105676. ol.source.OSM.prototype.getAttributions);
  105677. goog.exportProperty(
  105678. ol.source.OSM.prototype,
  105679. 'getLogo',
  105680. ol.source.OSM.prototype.getLogo);
  105681. goog.exportProperty(
  105682. ol.source.OSM.prototype,
  105683. 'getProjection',
  105684. ol.source.OSM.prototype.getProjection);
  105685. goog.exportProperty(
  105686. ol.source.OSM.prototype,
  105687. 'getState',
  105688. ol.source.OSM.prototype.getState);
  105689. goog.exportProperty(
  105690. ol.source.OSM.prototype,
  105691. 'setAttributions',
  105692. ol.source.OSM.prototype.setAttributions);
  105693. goog.exportProperty(
  105694. ol.source.OSM.prototype,
  105695. 'get',
  105696. ol.source.OSM.prototype.get);
  105697. goog.exportProperty(
  105698. ol.source.OSM.prototype,
  105699. 'getKeys',
  105700. ol.source.OSM.prototype.getKeys);
  105701. goog.exportProperty(
  105702. ol.source.OSM.prototype,
  105703. 'getProperties',
  105704. ol.source.OSM.prototype.getProperties);
  105705. goog.exportProperty(
  105706. ol.source.OSM.prototype,
  105707. 'set',
  105708. ol.source.OSM.prototype.set);
  105709. goog.exportProperty(
  105710. ol.source.OSM.prototype,
  105711. 'setProperties',
  105712. ol.source.OSM.prototype.setProperties);
  105713. goog.exportProperty(
  105714. ol.source.OSM.prototype,
  105715. 'unset',
  105716. ol.source.OSM.prototype.unset);
  105717. goog.exportProperty(
  105718. ol.source.OSM.prototype,
  105719. 'changed',
  105720. ol.source.OSM.prototype.changed);
  105721. goog.exportProperty(
  105722. ol.source.OSM.prototype,
  105723. 'getRevision',
  105724. ol.source.OSM.prototype.getRevision);
  105725. goog.exportProperty(
  105726. ol.source.OSM.prototype,
  105727. 'on',
  105728. ol.source.OSM.prototype.on);
  105729. goog.exportProperty(
  105730. ol.source.OSM.prototype,
  105731. 'once',
  105732. ol.source.OSM.prototype.once);
  105733. goog.exportProperty(
  105734. ol.source.OSM.prototype,
  105735. 'un',
  105736. ol.source.OSM.prototype.un);
  105737. goog.exportProperty(
  105738. ol.source.OSM.prototype,
  105739. 'unByKey',
  105740. ol.source.OSM.prototype.unByKey);
  105741. goog.exportProperty(
  105742. ol.source.Raster.prototype,
  105743. 'getAttributions',
  105744. ol.source.Raster.prototype.getAttributions);
  105745. goog.exportProperty(
  105746. ol.source.Raster.prototype,
  105747. 'getLogo',
  105748. ol.source.Raster.prototype.getLogo);
  105749. goog.exportProperty(
  105750. ol.source.Raster.prototype,
  105751. 'getProjection',
  105752. ol.source.Raster.prototype.getProjection);
  105753. goog.exportProperty(
  105754. ol.source.Raster.prototype,
  105755. 'getState',
  105756. ol.source.Raster.prototype.getState);
  105757. goog.exportProperty(
  105758. ol.source.Raster.prototype,
  105759. 'setAttributions',
  105760. ol.source.Raster.prototype.setAttributions);
  105761. goog.exportProperty(
  105762. ol.source.Raster.prototype,
  105763. 'get',
  105764. ol.source.Raster.prototype.get);
  105765. goog.exportProperty(
  105766. ol.source.Raster.prototype,
  105767. 'getKeys',
  105768. ol.source.Raster.prototype.getKeys);
  105769. goog.exportProperty(
  105770. ol.source.Raster.prototype,
  105771. 'getProperties',
  105772. ol.source.Raster.prototype.getProperties);
  105773. goog.exportProperty(
  105774. ol.source.Raster.prototype,
  105775. 'set',
  105776. ol.source.Raster.prototype.set);
  105777. goog.exportProperty(
  105778. ol.source.Raster.prototype,
  105779. 'setProperties',
  105780. ol.source.Raster.prototype.setProperties);
  105781. goog.exportProperty(
  105782. ol.source.Raster.prototype,
  105783. 'unset',
  105784. ol.source.Raster.prototype.unset);
  105785. goog.exportProperty(
  105786. ol.source.Raster.prototype,
  105787. 'changed',
  105788. ol.source.Raster.prototype.changed);
  105789. goog.exportProperty(
  105790. ol.source.Raster.prototype,
  105791. 'getRevision',
  105792. ol.source.Raster.prototype.getRevision);
  105793. goog.exportProperty(
  105794. ol.source.Raster.prototype,
  105795. 'on',
  105796. ol.source.Raster.prototype.on);
  105797. goog.exportProperty(
  105798. ol.source.Raster.prototype,
  105799. 'once',
  105800. ol.source.Raster.prototype.once);
  105801. goog.exportProperty(
  105802. ol.source.Raster.prototype,
  105803. 'un',
  105804. ol.source.Raster.prototype.un);
  105805. goog.exportProperty(
  105806. ol.source.Raster.prototype,
  105807. 'unByKey',
  105808. ol.source.Raster.prototype.unByKey);
  105809. goog.exportProperty(
  105810. ol.source.Stamen.prototype,
  105811. 'getUrls',
  105812. ol.source.Stamen.prototype.getUrls);
  105813. goog.exportProperty(
  105814. ol.source.Stamen.prototype,
  105815. 'setUrl',
  105816. ol.source.Stamen.prototype.setUrl);
  105817. goog.exportProperty(
  105818. ol.source.Stamen.prototype,
  105819. 'getTileLoadFunction',
  105820. ol.source.Stamen.prototype.getTileLoadFunction);
  105821. goog.exportProperty(
  105822. ol.source.Stamen.prototype,
  105823. 'getTileUrlFunction',
  105824. ol.source.Stamen.prototype.getTileUrlFunction);
  105825. goog.exportProperty(
  105826. ol.source.Stamen.prototype,
  105827. 'setTileLoadFunction',
  105828. ol.source.Stamen.prototype.setTileLoadFunction);
  105829. goog.exportProperty(
  105830. ol.source.Stamen.prototype,
  105831. 'setTileUrlFunction',
  105832. ol.source.Stamen.prototype.setTileUrlFunction);
  105833. goog.exportProperty(
  105834. ol.source.Stamen.prototype,
  105835. 'getTileGrid',
  105836. ol.source.Stamen.prototype.getTileGrid);
  105837. goog.exportProperty(
  105838. ol.source.Stamen.prototype,
  105839. 'getAttributions',
  105840. ol.source.Stamen.prototype.getAttributions);
  105841. goog.exportProperty(
  105842. ol.source.Stamen.prototype,
  105843. 'getLogo',
  105844. ol.source.Stamen.prototype.getLogo);
  105845. goog.exportProperty(
  105846. ol.source.Stamen.prototype,
  105847. 'getProjection',
  105848. ol.source.Stamen.prototype.getProjection);
  105849. goog.exportProperty(
  105850. ol.source.Stamen.prototype,
  105851. 'getState',
  105852. ol.source.Stamen.prototype.getState);
  105853. goog.exportProperty(
  105854. ol.source.Stamen.prototype,
  105855. 'setAttributions',
  105856. ol.source.Stamen.prototype.setAttributions);
  105857. goog.exportProperty(
  105858. ol.source.Stamen.prototype,
  105859. 'get',
  105860. ol.source.Stamen.prototype.get);
  105861. goog.exportProperty(
  105862. ol.source.Stamen.prototype,
  105863. 'getKeys',
  105864. ol.source.Stamen.prototype.getKeys);
  105865. goog.exportProperty(
  105866. ol.source.Stamen.prototype,
  105867. 'getProperties',
  105868. ol.source.Stamen.prototype.getProperties);
  105869. goog.exportProperty(
  105870. ol.source.Stamen.prototype,
  105871. 'set',
  105872. ol.source.Stamen.prototype.set);
  105873. goog.exportProperty(
  105874. ol.source.Stamen.prototype,
  105875. 'setProperties',
  105876. ol.source.Stamen.prototype.setProperties);
  105877. goog.exportProperty(
  105878. ol.source.Stamen.prototype,
  105879. 'unset',
  105880. ol.source.Stamen.prototype.unset);
  105881. goog.exportProperty(
  105882. ol.source.Stamen.prototype,
  105883. 'changed',
  105884. ol.source.Stamen.prototype.changed);
  105885. goog.exportProperty(
  105886. ol.source.Stamen.prototype,
  105887. 'getRevision',
  105888. ol.source.Stamen.prototype.getRevision);
  105889. goog.exportProperty(
  105890. ol.source.Stamen.prototype,
  105891. 'on',
  105892. ol.source.Stamen.prototype.on);
  105893. goog.exportProperty(
  105894. ol.source.Stamen.prototype,
  105895. 'once',
  105896. ol.source.Stamen.prototype.once);
  105897. goog.exportProperty(
  105898. ol.source.Stamen.prototype,
  105899. 'un',
  105900. ol.source.Stamen.prototype.un);
  105901. goog.exportProperty(
  105902. ol.source.Stamen.prototype,
  105903. 'unByKey',
  105904. ol.source.Stamen.prototype.unByKey);
  105905. goog.exportProperty(
  105906. ol.source.TileArcGISRest.prototype,
  105907. 'getTileLoadFunction',
  105908. ol.source.TileArcGISRest.prototype.getTileLoadFunction);
  105909. goog.exportProperty(
  105910. ol.source.TileArcGISRest.prototype,
  105911. 'getTileUrlFunction',
  105912. ol.source.TileArcGISRest.prototype.getTileUrlFunction);
  105913. goog.exportProperty(
  105914. ol.source.TileArcGISRest.prototype,
  105915. 'setTileLoadFunction',
  105916. ol.source.TileArcGISRest.prototype.setTileLoadFunction);
  105917. goog.exportProperty(
  105918. ol.source.TileArcGISRest.prototype,
  105919. 'setTileUrlFunction',
  105920. ol.source.TileArcGISRest.prototype.setTileUrlFunction);
  105921. goog.exportProperty(
  105922. ol.source.TileArcGISRest.prototype,
  105923. 'getTileGrid',
  105924. ol.source.TileArcGISRest.prototype.getTileGrid);
  105925. goog.exportProperty(
  105926. ol.source.TileArcGISRest.prototype,
  105927. 'getAttributions',
  105928. ol.source.TileArcGISRest.prototype.getAttributions);
  105929. goog.exportProperty(
  105930. ol.source.TileArcGISRest.prototype,
  105931. 'getLogo',
  105932. ol.source.TileArcGISRest.prototype.getLogo);
  105933. goog.exportProperty(
  105934. ol.source.TileArcGISRest.prototype,
  105935. 'getProjection',
  105936. ol.source.TileArcGISRest.prototype.getProjection);
  105937. goog.exportProperty(
  105938. ol.source.TileArcGISRest.prototype,
  105939. 'getState',
  105940. ol.source.TileArcGISRest.prototype.getState);
  105941. goog.exportProperty(
  105942. ol.source.TileArcGISRest.prototype,
  105943. 'setAttributions',
  105944. ol.source.TileArcGISRest.prototype.setAttributions);
  105945. goog.exportProperty(
  105946. ol.source.TileArcGISRest.prototype,
  105947. 'get',
  105948. ol.source.TileArcGISRest.prototype.get);
  105949. goog.exportProperty(
  105950. ol.source.TileArcGISRest.prototype,
  105951. 'getKeys',
  105952. ol.source.TileArcGISRest.prototype.getKeys);
  105953. goog.exportProperty(
  105954. ol.source.TileArcGISRest.prototype,
  105955. 'getProperties',
  105956. ol.source.TileArcGISRest.prototype.getProperties);
  105957. goog.exportProperty(
  105958. ol.source.TileArcGISRest.prototype,
  105959. 'set',
  105960. ol.source.TileArcGISRest.prototype.set);
  105961. goog.exportProperty(
  105962. ol.source.TileArcGISRest.prototype,
  105963. 'setProperties',
  105964. ol.source.TileArcGISRest.prototype.setProperties);
  105965. goog.exportProperty(
  105966. ol.source.TileArcGISRest.prototype,
  105967. 'unset',
  105968. ol.source.TileArcGISRest.prototype.unset);
  105969. goog.exportProperty(
  105970. ol.source.TileArcGISRest.prototype,
  105971. 'changed',
  105972. ol.source.TileArcGISRest.prototype.changed);
  105973. goog.exportProperty(
  105974. ol.source.TileArcGISRest.prototype,
  105975. 'getRevision',
  105976. ol.source.TileArcGISRest.prototype.getRevision);
  105977. goog.exportProperty(
  105978. ol.source.TileArcGISRest.prototype,
  105979. 'on',
  105980. ol.source.TileArcGISRest.prototype.on);
  105981. goog.exportProperty(
  105982. ol.source.TileArcGISRest.prototype,
  105983. 'once',
  105984. ol.source.TileArcGISRest.prototype.once);
  105985. goog.exportProperty(
  105986. ol.source.TileArcGISRest.prototype,
  105987. 'un',
  105988. ol.source.TileArcGISRest.prototype.un);
  105989. goog.exportProperty(
  105990. ol.source.TileArcGISRest.prototype,
  105991. 'unByKey',
  105992. ol.source.TileArcGISRest.prototype.unByKey);
  105993. goog.exportProperty(
  105994. ol.source.TileDebug.prototype,
  105995. 'getTileGrid',
  105996. ol.source.TileDebug.prototype.getTileGrid);
  105997. goog.exportProperty(
  105998. ol.source.TileDebug.prototype,
  105999. 'getAttributions',
  106000. ol.source.TileDebug.prototype.getAttributions);
  106001. goog.exportProperty(
  106002. ol.source.TileDebug.prototype,
  106003. 'getLogo',
  106004. ol.source.TileDebug.prototype.getLogo);
  106005. goog.exportProperty(
  106006. ol.source.TileDebug.prototype,
  106007. 'getProjection',
  106008. ol.source.TileDebug.prototype.getProjection);
  106009. goog.exportProperty(
  106010. ol.source.TileDebug.prototype,
  106011. 'getState',
  106012. ol.source.TileDebug.prototype.getState);
  106013. goog.exportProperty(
  106014. ol.source.TileDebug.prototype,
  106015. 'setAttributions',
  106016. ol.source.TileDebug.prototype.setAttributions);
  106017. goog.exportProperty(
  106018. ol.source.TileDebug.prototype,
  106019. 'get',
  106020. ol.source.TileDebug.prototype.get);
  106021. goog.exportProperty(
  106022. ol.source.TileDebug.prototype,
  106023. 'getKeys',
  106024. ol.source.TileDebug.prototype.getKeys);
  106025. goog.exportProperty(
  106026. ol.source.TileDebug.prototype,
  106027. 'getProperties',
  106028. ol.source.TileDebug.prototype.getProperties);
  106029. goog.exportProperty(
  106030. ol.source.TileDebug.prototype,
  106031. 'set',
  106032. ol.source.TileDebug.prototype.set);
  106033. goog.exportProperty(
  106034. ol.source.TileDebug.prototype,
  106035. 'setProperties',
  106036. ol.source.TileDebug.prototype.setProperties);
  106037. goog.exportProperty(
  106038. ol.source.TileDebug.prototype,
  106039. 'unset',
  106040. ol.source.TileDebug.prototype.unset);
  106041. goog.exportProperty(
  106042. ol.source.TileDebug.prototype,
  106043. 'changed',
  106044. ol.source.TileDebug.prototype.changed);
  106045. goog.exportProperty(
  106046. ol.source.TileDebug.prototype,
  106047. 'getRevision',
  106048. ol.source.TileDebug.prototype.getRevision);
  106049. goog.exportProperty(
  106050. ol.source.TileDebug.prototype,
  106051. 'on',
  106052. ol.source.TileDebug.prototype.on);
  106053. goog.exportProperty(
  106054. ol.source.TileDebug.prototype,
  106055. 'once',
  106056. ol.source.TileDebug.prototype.once);
  106057. goog.exportProperty(
  106058. ol.source.TileDebug.prototype,
  106059. 'un',
  106060. ol.source.TileDebug.prototype.un);
  106061. goog.exportProperty(
  106062. ol.source.TileDebug.prototype,
  106063. 'unByKey',
  106064. ol.source.TileDebug.prototype.unByKey);
  106065. goog.exportProperty(
  106066. ol.source.TileJSON.prototype,
  106067. 'getTileLoadFunction',
  106068. ol.source.TileJSON.prototype.getTileLoadFunction);
  106069. goog.exportProperty(
  106070. ol.source.TileJSON.prototype,
  106071. 'getTileUrlFunction',
  106072. ol.source.TileJSON.prototype.getTileUrlFunction);
  106073. goog.exportProperty(
  106074. ol.source.TileJSON.prototype,
  106075. 'setTileLoadFunction',
  106076. ol.source.TileJSON.prototype.setTileLoadFunction);
  106077. goog.exportProperty(
  106078. ol.source.TileJSON.prototype,
  106079. 'setTileUrlFunction',
  106080. ol.source.TileJSON.prototype.setTileUrlFunction);
  106081. goog.exportProperty(
  106082. ol.source.TileJSON.prototype,
  106083. 'getTileGrid',
  106084. ol.source.TileJSON.prototype.getTileGrid);
  106085. goog.exportProperty(
  106086. ol.source.TileJSON.prototype,
  106087. 'getAttributions',
  106088. ol.source.TileJSON.prototype.getAttributions);
  106089. goog.exportProperty(
  106090. ol.source.TileJSON.prototype,
  106091. 'getLogo',
  106092. ol.source.TileJSON.prototype.getLogo);
  106093. goog.exportProperty(
  106094. ol.source.TileJSON.prototype,
  106095. 'getProjection',
  106096. ol.source.TileJSON.prototype.getProjection);
  106097. goog.exportProperty(
  106098. ol.source.TileJSON.prototype,
  106099. 'getState',
  106100. ol.source.TileJSON.prototype.getState);
  106101. goog.exportProperty(
  106102. ol.source.TileJSON.prototype,
  106103. 'setAttributions',
  106104. ol.source.TileJSON.prototype.setAttributions);
  106105. goog.exportProperty(
  106106. ol.source.TileJSON.prototype,
  106107. 'get',
  106108. ol.source.TileJSON.prototype.get);
  106109. goog.exportProperty(
  106110. ol.source.TileJSON.prototype,
  106111. 'getKeys',
  106112. ol.source.TileJSON.prototype.getKeys);
  106113. goog.exportProperty(
  106114. ol.source.TileJSON.prototype,
  106115. 'getProperties',
  106116. ol.source.TileJSON.prototype.getProperties);
  106117. goog.exportProperty(
  106118. ol.source.TileJSON.prototype,
  106119. 'set',
  106120. ol.source.TileJSON.prototype.set);
  106121. goog.exportProperty(
  106122. ol.source.TileJSON.prototype,
  106123. 'setProperties',
  106124. ol.source.TileJSON.prototype.setProperties);
  106125. goog.exportProperty(
  106126. ol.source.TileJSON.prototype,
  106127. 'unset',
  106128. ol.source.TileJSON.prototype.unset);
  106129. goog.exportProperty(
  106130. ol.source.TileJSON.prototype,
  106131. 'changed',
  106132. ol.source.TileJSON.prototype.changed);
  106133. goog.exportProperty(
  106134. ol.source.TileJSON.prototype,
  106135. 'getRevision',
  106136. ol.source.TileJSON.prototype.getRevision);
  106137. goog.exportProperty(
  106138. ol.source.TileJSON.prototype,
  106139. 'on',
  106140. ol.source.TileJSON.prototype.on);
  106141. goog.exportProperty(
  106142. ol.source.TileJSON.prototype,
  106143. 'once',
  106144. ol.source.TileJSON.prototype.once);
  106145. goog.exportProperty(
  106146. ol.source.TileJSON.prototype,
  106147. 'un',
  106148. ol.source.TileJSON.prototype.un);
  106149. goog.exportProperty(
  106150. ol.source.TileJSON.prototype,
  106151. 'unByKey',
  106152. ol.source.TileJSON.prototype.unByKey);
  106153. goog.exportProperty(
  106154. ol.source.TileUTFGrid.prototype,
  106155. 'getTileGrid',
  106156. ol.source.TileUTFGrid.prototype.getTileGrid);
  106157. goog.exportProperty(
  106158. ol.source.TileUTFGrid.prototype,
  106159. 'getAttributions',
  106160. ol.source.TileUTFGrid.prototype.getAttributions);
  106161. goog.exportProperty(
  106162. ol.source.TileUTFGrid.prototype,
  106163. 'getLogo',
  106164. ol.source.TileUTFGrid.prototype.getLogo);
  106165. goog.exportProperty(
  106166. ol.source.TileUTFGrid.prototype,
  106167. 'getProjection',
  106168. ol.source.TileUTFGrid.prototype.getProjection);
  106169. goog.exportProperty(
  106170. ol.source.TileUTFGrid.prototype,
  106171. 'getState',
  106172. ol.source.TileUTFGrid.prototype.getState);
  106173. goog.exportProperty(
  106174. ol.source.TileUTFGrid.prototype,
  106175. 'setAttributions',
  106176. ol.source.TileUTFGrid.prototype.setAttributions);
  106177. goog.exportProperty(
  106178. ol.source.TileUTFGrid.prototype,
  106179. 'get',
  106180. ol.source.TileUTFGrid.prototype.get);
  106181. goog.exportProperty(
  106182. ol.source.TileUTFGrid.prototype,
  106183. 'getKeys',
  106184. ol.source.TileUTFGrid.prototype.getKeys);
  106185. goog.exportProperty(
  106186. ol.source.TileUTFGrid.prototype,
  106187. 'getProperties',
  106188. ol.source.TileUTFGrid.prototype.getProperties);
  106189. goog.exportProperty(
  106190. ol.source.TileUTFGrid.prototype,
  106191. 'set',
  106192. ol.source.TileUTFGrid.prototype.set);
  106193. goog.exportProperty(
  106194. ol.source.TileUTFGrid.prototype,
  106195. 'setProperties',
  106196. ol.source.TileUTFGrid.prototype.setProperties);
  106197. goog.exportProperty(
  106198. ol.source.TileUTFGrid.prototype,
  106199. 'unset',
  106200. ol.source.TileUTFGrid.prototype.unset);
  106201. goog.exportProperty(
  106202. ol.source.TileUTFGrid.prototype,
  106203. 'changed',
  106204. ol.source.TileUTFGrid.prototype.changed);
  106205. goog.exportProperty(
  106206. ol.source.TileUTFGrid.prototype,
  106207. 'getRevision',
  106208. ol.source.TileUTFGrid.prototype.getRevision);
  106209. goog.exportProperty(
  106210. ol.source.TileUTFGrid.prototype,
  106211. 'on',
  106212. ol.source.TileUTFGrid.prototype.on);
  106213. goog.exportProperty(
  106214. ol.source.TileUTFGrid.prototype,
  106215. 'once',
  106216. ol.source.TileUTFGrid.prototype.once);
  106217. goog.exportProperty(
  106218. ol.source.TileUTFGrid.prototype,
  106219. 'un',
  106220. ol.source.TileUTFGrid.prototype.un);
  106221. goog.exportProperty(
  106222. ol.source.TileUTFGrid.prototype,
  106223. 'unByKey',
  106224. ol.source.TileUTFGrid.prototype.unByKey);
  106225. goog.exportProperty(
  106226. ol.source.TileVector.prototype,
  106227. 'addFeature',
  106228. ol.source.TileVector.prototype.addFeature);
  106229. goog.exportProperty(
  106230. ol.source.TileVector.prototype,
  106231. 'addFeatures',
  106232. ol.source.TileVector.prototype.addFeatures);
  106233. goog.exportProperty(
  106234. ol.source.TileVector.prototype,
  106235. 'clear',
  106236. ol.source.TileVector.prototype.clear);
  106237. goog.exportProperty(
  106238. ol.source.TileVector.prototype,
  106239. 'forEachFeature',
  106240. ol.source.TileVector.prototype.forEachFeature);
  106241. goog.exportProperty(
  106242. ol.source.TileVector.prototype,
  106243. 'forEachFeatureInExtent',
  106244. ol.source.TileVector.prototype.forEachFeatureInExtent);
  106245. goog.exportProperty(
  106246. ol.source.TileVector.prototype,
  106247. 'forEachFeatureIntersectingExtent',
  106248. ol.source.TileVector.prototype.forEachFeatureIntersectingExtent);
  106249. goog.exportProperty(
  106250. ol.source.TileVector.prototype,
  106251. 'getFeaturesCollection',
  106252. ol.source.TileVector.prototype.getFeaturesCollection);
  106253. goog.exportProperty(
  106254. ol.source.TileVector.prototype,
  106255. 'getFeatures',
  106256. ol.source.TileVector.prototype.getFeatures);
  106257. goog.exportProperty(
  106258. ol.source.TileVector.prototype,
  106259. 'getFeaturesAtCoordinate',
  106260. ol.source.TileVector.prototype.getFeaturesAtCoordinate);
  106261. goog.exportProperty(
  106262. ol.source.TileVector.prototype,
  106263. 'getFeaturesInExtent',
  106264. ol.source.TileVector.prototype.getFeaturesInExtent);
  106265. goog.exportProperty(
  106266. ol.source.TileVector.prototype,
  106267. 'getClosestFeatureToCoordinate',
  106268. ol.source.TileVector.prototype.getClosestFeatureToCoordinate);
  106269. goog.exportProperty(
  106270. ol.source.TileVector.prototype,
  106271. 'getExtent',
  106272. ol.source.TileVector.prototype.getExtent);
  106273. goog.exportProperty(
  106274. ol.source.TileVector.prototype,
  106275. 'getFeatureById',
  106276. ol.source.TileVector.prototype.getFeatureById);
  106277. goog.exportProperty(
  106278. ol.source.TileVector.prototype,
  106279. 'removeFeature',
  106280. ol.source.TileVector.prototype.removeFeature);
  106281. goog.exportProperty(
  106282. ol.source.TileVector.prototype,
  106283. 'getAttributions',
  106284. ol.source.TileVector.prototype.getAttributions);
  106285. goog.exportProperty(
  106286. ol.source.TileVector.prototype,
  106287. 'getLogo',
  106288. ol.source.TileVector.prototype.getLogo);
  106289. goog.exportProperty(
  106290. ol.source.TileVector.prototype,
  106291. 'getProjection',
  106292. ol.source.TileVector.prototype.getProjection);
  106293. goog.exportProperty(
  106294. ol.source.TileVector.prototype,
  106295. 'getState',
  106296. ol.source.TileVector.prototype.getState);
  106297. goog.exportProperty(
  106298. ol.source.TileVector.prototype,
  106299. 'setAttributions',
  106300. ol.source.TileVector.prototype.setAttributions);
  106301. goog.exportProperty(
  106302. ol.source.TileVector.prototype,
  106303. 'get',
  106304. ol.source.TileVector.prototype.get);
  106305. goog.exportProperty(
  106306. ol.source.TileVector.prototype,
  106307. 'getKeys',
  106308. ol.source.TileVector.prototype.getKeys);
  106309. goog.exportProperty(
  106310. ol.source.TileVector.prototype,
  106311. 'getProperties',
  106312. ol.source.TileVector.prototype.getProperties);
  106313. goog.exportProperty(
  106314. ol.source.TileVector.prototype,
  106315. 'set',
  106316. ol.source.TileVector.prototype.set);
  106317. goog.exportProperty(
  106318. ol.source.TileVector.prototype,
  106319. 'setProperties',
  106320. ol.source.TileVector.prototype.setProperties);
  106321. goog.exportProperty(
  106322. ol.source.TileVector.prototype,
  106323. 'unset',
  106324. ol.source.TileVector.prototype.unset);
  106325. goog.exportProperty(
  106326. ol.source.TileVector.prototype,
  106327. 'changed',
  106328. ol.source.TileVector.prototype.changed);
  106329. goog.exportProperty(
  106330. ol.source.TileVector.prototype,
  106331. 'getRevision',
  106332. ol.source.TileVector.prototype.getRevision);
  106333. goog.exportProperty(
  106334. ol.source.TileVector.prototype,
  106335. 'on',
  106336. ol.source.TileVector.prototype.on);
  106337. goog.exportProperty(
  106338. ol.source.TileVector.prototype,
  106339. 'once',
  106340. ol.source.TileVector.prototype.once);
  106341. goog.exportProperty(
  106342. ol.source.TileVector.prototype,
  106343. 'un',
  106344. ol.source.TileVector.prototype.un);
  106345. goog.exportProperty(
  106346. ol.source.TileVector.prototype,
  106347. 'unByKey',
  106348. ol.source.TileVector.prototype.unByKey);
  106349. goog.exportProperty(
  106350. ol.source.TileWMS.prototype,
  106351. 'getTileLoadFunction',
  106352. ol.source.TileWMS.prototype.getTileLoadFunction);
  106353. goog.exportProperty(
  106354. ol.source.TileWMS.prototype,
  106355. 'getTileUrlFunction',
  106356. ol.source.TileWMS.prototype.getTileUrlFunction);
  106357. goog.exportProperty(
  106358. ol.source.TileWMS.prototype,
  106359. 'setTileLoadFunction',
  106360. ol.source.TileWMS.prototype.setTileLoadFunction);
  106361. goog.exportProperty(
  106362. ol.source.TileWMS.prototype,
  106363. 'setTileUrlFunction',
  106364. ol.source.TileWMS.prototype.setTileUrlFunction);
  106365. goog.exportProperty(
  106366. ol.source.TileWMS.prototype,
  106367. 'getTileGrid',
  106368. ol.source.TileWMS.prototype.getTileGrid);
  106369. goog.exportProperty(
  106370. ol.source.TileWMS.prototype,
  106371. 'getAttributions',
  106372. ol.source.TileWMS.prototype.getAttributions);
  106373. goog.exportProperty(
  106374. ol.source.TileWMS.prototype,
  106375. 'getLogo',
  106376. ol.source.TileWMS.prototype.getLogo);
  106377. goog.exportProperty(
  106378. ol.source.TileWMS.prototype,
  106379. 'getProjection',
  106380. ol.source.TileWMS.prototype.getProjection);
  106381. goog.exportProperty(
  106382. ol.source.TileWMS.prototype,
  106383. 'getState',
  106384. ol.source.TileWMS.prototype.getState);
  106385. goog.exportProperty(
  106386. ol.source.TileWMS.prototype,
  106387. 'setAttributions',
  106388. ol.source.TileWMS.prototype.setAttributions);
  106389. goog.exportProperty(
  106390. ol.source.TileWMS.prototype,
  106391. 'get',
  106392. ol.source.TileWMS.prototype.get);
  106393. goog.exportProperty(
  106394. ol.source.TileWMS.prototype,
  106395. 'getKeys',
  106396. ol.source.TileWMS.prototype.getKeys);
  106397. goog.exportProperty(
  106398. ol.source.TileWMS.prototype,
  106399. 'getProperties',
  106400. ol.source.TileWMS.prototype.getProperties);
  106401. goog.exportProperty(
  106402. ol.source.TileWMS.prototype,
  106403. 'set',
  106404. ol.source.TileWMS.prototype.set);
  106405. goog.exportProperty(
  106406. ol.source.TileWMS.prototype,
  106407. 'setProperties',
  106408. ol.source.TileWMS.prototype.setProperties);
  106409. goog.exportProperty(
  106410. ol.source.TileWMS.prototype,
  106411. 'unset',
  106412. ol.source.TileWMS.prototype.unset);
  106413. goog.exportProperty(
  106414. ol.source.TileWMS.prototype,
  106415. 'changed',
  106416. ol.source.TileWMS.prototype.changed);
  106417. goog.exportProperty(
  106418. ol.source.TileWMS.prototype,
  106419. 'getRevision',
  106420. ol.source.TileWMS.prototype.getRevision);
  106421. goog.exportProperty(
  106422. ol.source.TileWMS.prototype,
  106423. 'on',
  106424. ol.source.TileWMS.prototype.on);
  106425. goog.exportProperty(
  106426. ol.source.TileWMS.prototype,
  106427. 'once',
  106428. ol.source.TileWMS.prototype.once);
  106429. goog.exportProperty(
  106430. ol.source.TileWMS.prototype,
  106431. 'un',
  106432. ol.source.TileWMS.prototype.un);
  106433. goog.exportProperty(
  106434. ol.source.TileWMS.prototype,
  106435. 'unByKey',
  106436. ol.source.TileWMS.prototype.unByKey);
  106437. goog.exportProperty(
  106438. ol.source.WMTS.prototype,
  106439. 'getTileLoadFunction',
  106440. ol.source.WMTS.prototype.getTileLoadFunction);
  106441. goog.exportProperty(
  106442. ol.source.WMTS.prototype,
  106443. 'getTileUrlFunction',
  106444. ol.source.WMTS.prototype.getTileUrlFunction);
  106445. goog.exportProperty(
  106446. ol.source.WMTS.prototype,
  106447. 'setTileLoadFunction',
  106448. ol.source.WMTS.prototype.setTileLoadFunction);
  106449. goog.exportProperty(
  106450. ol.source.WMTS.prototype,
  106451. 'setTileUrlFunction',
  106452. ol.source.WMTS.prototype.setTileUrlFunction);
  106453. goog.exportProperty(
  106454. ol.source.WMTS.prototype,
  106455. 'getTileGrid',
  106456. ol.source.WMTS.prototype.getTileGrid);
  106457. goog.exportProperty(
  106458. ol.source.WMTS.prototype,
  106459. 'getAttributions',
  106460. ol.source.WMTS.prototype.getAttributions);
  106461. goog.exportProperty(
  106462. ol.source.WMTS.prototype,
  106463. 'getLogo',
  106464. ol.source.WMTS.prototype.getLogo);
  106465. goog.exportProperty(
  106466. ol.source.WMTS.prototype,
  106467. 'getProjection',
  106468. ol.source.WMTS.prototype.getProjection);
  106469. goog.exportProperty(
  106470. ol.source.WMTS.prototype,
  106471. 'getState',
  106472. ol.source.WMTS.prototype.getState);
  106473. goog.exportProperty(
  106474. ol.source.WMTS.prototype,
  106475. 'setAttributions',
  106476. ol.source.WMTS.prototype.setAttributions);
  106477. goog.exportProperty(
  106478. ol.source.WMTS.prototype,
  106479. 'get',
  106480. ol.source.WMTS.prototype.get);
  106481. goog.exportProperty(
  106482. ol.source.WMTS.prototype,
  106483. 'getKeys',
  106484. ol.source.WMTS.prototype.getKeys);
  106485. goog.exportProperty(
  106486. ol.source.WMTS.prototype,
  106487. 'getProperties',
  106488. ol.source.WMTS.prototype.getProperties);
  106489. goog.exportProperty(
  106490. ol.source.WMTS.prototype,
  106491. 'set',
  106492. ol.source.WMTS.prototype.set);
  106493. goog.exportProperty(
  106494. ol.source.WMTS.prototype,
  106495. 'setProperties',
  106496. ol.source.WMTS.prototype.setProperties);
  106497. goog.exportProperty(
  106498. ol.source.WMTS.prototype,
  106499. 'unset',
  106500. ol.source.WMTS.prototype.unset);
  106501. goog.exportProperty(
  106502. ol.source.WMTS.prototype,
  106503. 'changed',
  106504. ol.source.WMTS.prototype.changed);
  106505. goog.exportProperty(
  106506. ol.source.WMTS.prototype,
  106507. 'getRevision',
  106508. ol.source.WMTS.prototype.getRevision);
  106509. goog.exportProperty(
  106510. ol.source.WMTS.prototype,
  106511. 'on',
  106512. ol.source.WMTS.prototype.on);
  106513. goog.exportProperty(
  106514. ol.source.WMTS.prototype,
  106515. 'once',
  106516. ol.source.WMTS.prototype.once);
  106517. goog.exportProperty(
  106518. ol.source.WMTS.prototype,
  106519. 'un',
  106520. ol.source.WMTS.prototype.un);
  106521. goog.exportProperty(
  106522. ol.source.WMTS.prototype,
  106523. 'unByKey',
  106524. ol.source.WMTS.prototype.unByKey);
  106525. goog.exportProperty(
  106526. ol.source.Zoomify.prototype,
  106527. 'getTileLoadFunction',
  106528. ol.source.Zoomify.prototype.getTileLoadFunction);
  106529. goog.exportProperty(
  106530. ol.source.Zoomify.prototype,
  106531. 'getTileUrlFunction',
  106532. ol.source.Zoomify.prototype.getTileUrlFunction);
  106533. goog.exportProperty(
  106534. ol.source.Zoomify.prototype,
  106535. 'setTileLoadFunction',
  106536. ol.source.Zoomify.prototype.setTileLoadFunction);
  106537. goog.exportProperty(
  106538. ol.source.Zoomify.prototype,
  106539. 'setTileUrlFunction',
  106540. ol.source.Zoomify.prototype.setTileUrlFunction);
  106541. goog.exportProperty(
  106542. ol.source.Zoomify.prototype,
  106543. 'getTileGrid',
  106544. ol.source.Zoomify.prototype.getTileGrid);
  106545. goog.exportProperty(
  106546. ol.source.Zoomify.prototype,
  106547. 'getAttributions',
  106548. ol.source.Zoomify.prototype.getAttributions);
  106549. goog.exportProperty(
  106550. ol.source.Zoomify.prototype,
  106551. 'getLogo',
  106552. ol.source.Zoomify.prototype.getLogo);
  106553. goog.exportProperty(
  106554. ol.source.Zoomify.prototype,
  106555. 'getProjection',
  106556. ol.source.Zoomify.prototype.getProjection);
  106557. goog.exportProperty(
  106558. ol.source.Zoomify.prototype,
  106559. 'getState',
  106560. ol.source.Zoomify.prototype.getState);
  106561. goog.exportProperty(
  106562. ol.source.Zoomify.prototype,
  106563. 'setAttributions',
  106564. ol.source.Zoomify.prototype.setAttributions);
  106565. goog.exportProperty(
  106566. ol.source.Zoomify.prototype,
  106567. 'get',
  106568. ol.source.Zoomify.prototype.get);
  106569. goog.exportProperty(
  106570. ol.source.Zoomify.prototype,
  106571. 'getKeys',
  106572. ol.source.Zoomify.prototype.getKeys);
  106573. goog.exportProperty(
  106574. ol.source.Zoomify.prototype,
  106575. 'getProperties',
  106576. ol.source.Zoomify.prototype.getProperties);
  106577. goog.exportProperty(
  106578. ol.source.Zoomify.prototype,
  106579. 'set',
  106580. ol.source.Zoomify.prototype.set);
  106581. goog.exportProperty(
  106582. ol.source.Zoomify.prototype,
  106583. 'setProperties',
  106584. ol.source.Zoomify.prototype.setProperties);
  106585. goog.exportProperty(
  106586. ol.source.Zoomify.prototype,
  106587. 'unset',
  106588. ol.source.Zoomify.prototype.unset);
  106589. goog.exportProperty(
  106590. ol.source.Zoomify.prototype,
  106591. 'changed',
  106592. ol.source.Zoomify.prototype.changed);
  106593. goog.exportProperty(
  106594. ol.source.Zoomify.prototype,
  106595. 'getRevision',
  106596. ol.source.Zoomify.prototype.getRevision);
  106597. goog.exportProperty(
  106598. ol.source.Zoomify.prototype,
  106599. 'on',
  106600. ol.source.Zoomify.prototype.on);
  106601. goog.exportProperty(
  106602. ol.source.Zoomify.prototype,
  106603. 'once',
  106604. ol.source.Zoomify.prototype.once);
  106605. goog.exportProperty(
  106606. ol.source.Zoomify.prototype,
  106607. 'un',
  106608. ol.source.Zoomify.prototype.un);
  106609. goog.exportProperty(
  106610. ol.source.Zoomify.prototype,
  106611. 'unByKey',
  106612. ol.source.Zoomify.prototype.unByKey);
  106613. goog.exportProperty(
  106614. ol.renderer.Layer.prototype,
  106615. 'changed',
  106616. ol.renderer.Layer.prototype.changed);
  106617. goog.exportProperty(
  106618. ol.renderer.Layer.prototype,
  106619. 'getRevision',
  106620. ol.renderer.Layer.prototype.getRevision);
  106621. goog.exportProperty(
  106622. ol.renderer.Layer.prototype,
  106623. 'on',
  106624. ol.renderer.Layer.prototype.on);
  106625. goog.exportProperty(
  106626. ol.renderer.Layer.prototype,
  106627. 'once',
  106628. ol.renderer.Layer.prototype.once);
  106629. goog.exportProperty(
  106630. ol.renderer.Layer.prototype,
  106631. 'un',
  106632. ol.renderer.Layer.prototype.un);
  106633. goog.exportProperty(
  106634. ol.renderer.Layer.prototype,
  106635. 'unByKey',
  106636. ol.renderer.Layer.prototype.unByKey);
  106637. goog.exportProperty(
  106638. ol.renderer.webgl.Layer.prototype,
  106639. 'changed',
  106640. ol.renderer.webgl.Layer.prototype.changed);
  106641. goog.exportProperty(
  106642. ol.renderer.webgl.Layer.prototype,
  106643. 'getRevision',
  106644. ol.renderer.webgl.Layer.prototype.getRevision);
  106645. goog.exportProperty(
  106646. ol.renderer.webgl.Layer.prototype,
  106647. 'on',
  106648. ol.renderer.webgl.Layer.prototype.on);
  106649. goog.exportProperty(
  106650. ol.renderer.webgl.Layer.prototype,
  106651. 'once',
  106652. ol.renderer.webgl.Layer.prototype.once);
  106653. goog.exportProperty(
  106654. ol.renderer.webgl.Layer.prototype,
  106655. 'un',
  106656. ol.renderer.webgl.Layer.prototype.un);
  106657. goog.exportProperty(
  106658. ol.renderer.webgl.Layer.prototype,
  106659. 'unByKey',
  106660. ol.renderer.webgl.Layer.prototype.unByKey);
  106661. goog.exportProperty(
  106662. ol.renderer.webgl.ImageLayer.prototype,
  106663. 'changed',
  106664. ol.renderer.webgl.ImageLayer.prototype.changed);
  106665. goog.exportProperty(
  106666. ol.renderer.webgl.ImageLayer.prototype,
  106667. 'getRevision',
  106668. ol.renderer.webgl.ImageLayer.prototype.getRevision);
  106669. goog.exportProperty(
  106670. ol.renderer.webgl.ImageLayer.prototype,
  106671. 'on',
  106672. ol.renderer.webgl.ImageLayer.prototype.on);
  106673. goog.exportProperty(
  106674. ol.renderer.webgl.ImageLayer.prototype,
  106675. 'once',
  106676. ol.renderer.webgl.ImageLayer.prototype.once);
  106677. goog.exportProperty(
  106678. ol.renderer.webgl.ImageLayer.prototype,
  106679. 'un',
  106680. ol.renderer.webgl.ImageLayer.prototype.un);
  106681. goog.exportProperty(
  106682. ol.renderer.webgl.ImageLayer.prototype,
  106683. 'unByKey',
  106684. ol.renderer.webgl.ImageLayer.prototype.unByKey);
  106685. goog.exportProperty(
  106686. ol.renderer.webgl.TileLayer.prototype,
  106687. 'changed',
  106688. ol.renderer.webgl.TileLayer.prototype.changed);
  106689. goog.exportProperty(
  106690. ol.renderer.webgl.TileLayer.prototype,
  106691. 'getRevision',
  106692. ol.renderer.webgl.TileLayer.prototype.getRevision);
  106693. goog.exportProperty(
  106694. ol.renderer.webgl.TileLayer.prototype,
  106695. 'on',
  106696. ol.renderer.webgl.TileLayer.prototype.on);
  106697. goog.exportProperty(
  106698. ol.renderer.webgl.TileLayer.prototype,
  106699. 'once',
  106700. ol.renderer.webgl.TileLayer.prototype.once);
  106701. goog.exportProperty(
  106702. ol.renderer.webgl.TileLayer.prototype,
  106703. 'un',
  106704. ol.renderer.webgl.TileLayer.prototype.un);
  106705. goog.exportProperty(
  106706. ol.renderer.webgl.TileLayer.prototype,
  106707. 'unByKey',
  106708. ol.renderer.webgl.TileLayer.prototype.unByKey);
  106709. goog.exportProperty(
  106710. ol.renderer.webgl.VectorLayer.prototype,
  106711. 'changed',
  106712. ol.renderer.webgl.VectorLayer.prototype.changed);
  106713. goog.exportProperty(
  106714. ol.renderer.webgl.VectorLayer.prototype,
  106715. 'getRevision',
  106716. ol.renderer.webgl.VectorLayer.prototype.getRevision);
  106717. goog.exportProperty(
  106718. ol.renderer.webgl.VectorLayer.prototype,
  106719. 'on',
  106720. ol.renderer.webgl.VectorLayer.prototype.on);
  106721. goog.exportProperty(
  106722. ol.renderer.webgl.VectorLayer.prototype,
  106723. 'once',
  106724. ol.renderer.webgl.VectorLayer.prototype.once);
  106725. goog.exportProperty(
  106726. ol.renderer.webgl.VectorLayer.prototype,
  106727. 'un',
  106728. ol.renderer.webgl.VectorLayer.prototype.un);
  106729. goog.exportProperty(
  106730. ol.renderer.webgl.VectorLayer.prototype,
  106731. 'unByKey',
  106732. ol.renderer.webgl.VectorLayer.prototype.unByKey);
  106733. goog.exportProperty(
  106734. ol.renderer.dom.Layer.prototype,
  106735. 'changed',
  106736. ol.renderer.dom.Layer.prototype.changed);
  106737. goog.exportProperty(
  106738. ol.renderer.dom.Layer.prototype,
  106739. 'getRevision',
  106740. ol.renderer.dom.Layer.prototype.getRevision);
  106741. goog.exportProperty(
  106742. ol.renderer.dom.Layer.prototype,
  106743. 'on',
  106744. ol.renderer.dom.Layer.prototype.on);
  106745. goog.exportProperty(
  106746. ol.renderer.dom.Layer.prototype,
  106747. 'once',
  106748. ol.renderer.dom.Layer.prototype.once);
  106749. goog.exportProperty(
  106750. ol.renderer.dom.Layer.prototype,
  106751. 'un',
  106752. ol.renderer.dom.Layer.prototype.un);
  106753. goog.exportProperty(
  106754. ol.renderer.dom.Layer.prototype,
  106755. 'unByKey',
  106756. ol.renderer.dom.Layer.prototype.unByKey);
  106757. goog.exportProperty(
  106758. ol.renderer.dom.ImageLayer.prototype,
  106759. 'changed',
  106760. ol.renderer.dom.ImageLayer.prototype.changed);
  106761. goog.exportProperty(
  106762. ol.renderer.dom.ImageLayer.prototype,
  106763. 'getRevision',
  106764. ol.renderer.dom.ImageLayer.prototype.getRevision);
  106765. goog.exportProperty(
  106766. ol.renderer.dom.ImageLayer.prototype,
  106767. 'on',
  106768. ol.renderer.dom.ImageLayer.prototype.on);
  106769. goog.exportProperty(
  106770. ol.renderer.dom.ImageLayer.prototype,
  106771. 'once',
  106772. ol.renderer.dom.ImageLayer.prototype.once);
  106773. goog.exportProperty(
  106774. ol.renderer.dom.ImageLayer.prototype,
  106775. 'un',
  106776. ol.renderer.dom.ImageLayer.prototype.un);
  106777. goog.exportProperty(
  106778. ol.renderer.dom.ImageLayer.prototype,
  106779. 'unByKey',
  106780. ol.renderer.dom.ImageLayer.prototype.unByKey);
  106781. goog.exportProperty(
  106782. ol.renderer.dom.TileLayer.prototype,
  106783. 'changed',
  106784. ol.renderer.dom.TileLayer.prototype.changed);
  106785. goog.exportProperty(
  106786. ol.renderer.dom.TileLayer.prototype,
  106787. 'getRevision',
  106788. ol.renderer.dom.TileLayer.prototype.getRevision);
  106789. goog.exportProperty(
  106790. ol.renderer.dom.TileLayer.prototype,
  106791. 'on',
  106792. ol.renderer.dom.TileLayer.prototype.on);
  106793. goog.exportProperty(
  106794. ol.renderer.dom.TileLayer.prototype,
  106795. 'once',
  106796. ol.renderer.dom.TileLayer.prototype.once);
  106797. goog.exportProperty(
  106798. ol.renderer.dom.TileLayer.prototype,
  106799. 'un',
  106800. ol.renderer.dom.TileLayer.prototype.un);
  106801. goog.exportProperty(
  106802. ol.renderer.dom.TileLayer.prototype,
  106803. 'unByKey',
  106804. ol.renderer.dom.TileLayer.prototype.unByKey);
  106805. goog.exportProperty(
  106806. ol.renderer.dom.VectorLayer.prototype,
  106807. 'changed',
  106808. ol.renderer.dom.VectorLayer.prototype.changed);
  106809. goog.exportProperty(
  106810. ol.renderer.dom.VectorLayer.prototype,
  106811. 'getRevision',
  106812. ol.renderer.dom.VectorLayer.prototype.getRevision);
  106813. goog.exportProperty(
  106814. ol.renderer.dom.VectorLayer.prototype,
  106815. 'on',
  106816. ol.renderer.dom.VectorLayer.prototype.on);
  106817. goog.exportProperty(
  106818. ol.renderer.dom.VectorLayer.prototype,
  106819. 'once',
  106820. ol.renderer.dom.VectorLayer.prototype.once);
  106821. goog.exportProperty(
  106822. ol.renderer.dom.VectorLayer.prototype,
  106823. 'un',
  106824. ol.renderer.dom.VectorLayer.prototype.un);
  106825. goog.exportProperty(
  106826. ol.renderer.dom.VectorLayer.prototype,
  106827. 'unByKey',
  106828. ol.renderer.dom.VectorLayer.prototype.unByKey);
  106829. goog.exportProperty(
  106830. ol.renderer.canvas.Layer.prototype,
  106831. 'changed',
  106832. ol.renderer.canvas.Layer.prototype.changed);
  106833. goog.exportProperty(
  106834. ol.renderer.canvas.Layer.prototype,
  106835. 'getRevision',
  106836. ol.renderer.canvas.Layer.prototype.getRevision);
  106837. goog.exportProperty(
  106838. ol.renderer.canvas.Layer.prototype,
  106839. 'on',
  106840. ol.renderer.canvas.Layer.prototype.on);
  106841. goog.exportProperty(
  106842. ol.renderer.canvas.Layer.prototype,
  106843. 'once',
  106844. ol.renderer.canvas.Layer.prototype.once);
  106845. goog.exportProperty(
  106846. ol.renderer.canvas.Layer.prototype,
  106847. 'un',
  106848. ol.renderer.canvas.Layer.prototype.un);
  106849. goog.exportProperty(
  106850. ol.renderer.canvas.Layer.prototype,
  106851. 'unByKey',
  106852. ol.renderer.canvas.Layer.prototype.unByKey);
  106853. goog.exportProperty(
  106854. ol.renderer.canvas.ImageLayer.prototype,
  106855. 'changed',
  106856. ol.renderer.canvas.ImageLayer.prototype.changed);
  106857. goog.exportProperty(
  106858. ol.renderer.canvas.ImageLayer.prototype,
  106859. 'getRevision',
  106860. ol.renderer.canvas.ImageLayer.prototype.getRevision);
  106861. goog.exportProperty(
  106862. ol.renderer.canvas.ImageLayer.prototype,
  106863. 'on',
  106864. ol.renderer.canvas.ImageLayer.prototype.on);
  106865. goog.exportProperty(
  106866. ol.renderer.canvas.ImageLayer.prototype,
  106867. 'once',
  106868. ol.renderer.canvas.ImageLayer.prototype.once);
  106869. goog.exportProperty(
  106870. ol.renderer.canvas.ImageLayer.prototype,
  106871. 'un',
  106872. ol.renderer.canvas.ImageLayer.prototype.un);
  106873. goog.exportProperty(
  106874. ol.renderer.canvas.ImageLayer.prototype,
  106875. 'unByKey',
  106876. ol.renderer.canvas.ImageLayer.prototype.unByKey);
  106877. goog.exportProperty(
  106878. ol.renderer.canvas.TileLayer.prototype,
  106879. 'changed',
  106880. ol.renderer.canvas.TileLayer.prototype.changed);
  106881. goog.exportProperty(
  106882. ol.renderer.canvas.TileLayer.prototype,
  106883. 'getRevision',
  106884. ol.renderer.canvas.TileLayer.prototype.getRevision);
  106885. goog.exportProperty(
  106886. ol.renderer.canvas.TileLayer.prototype,
  106887. 'on',
  106888. ol.renderer.canvas.TileLayer.prototype.on);
  106889. goog.exportProperty(
  106890. ol.renderer.canvas.TileLayer.prototype,
  106891. 'once',
  106892. ol.renderer.canvas.TileLayer.prototype.once);
  106893. goog.exportProperty(
  106894. ol.renderer.canvas.TileLayer.prototype,
  106895. 'un',
  106896. ol.renderer.canvas.TileLayer.prototype.un);
  106897. goog.exportProperty(
  106898. ol.renderer.canvas.TileLayer.prototype,
  106899. 'unByKey',
  106900. ol.renderer.canvas.TileLayer.prototype.unByKey);
  106901. goog.exportProperty(
  106902. ol.renderer.canvas.VectorLayer.prototype,
  106903. 'changed',
  106904. ol.renderer.canvas.VectorLayer.prototype.changed);
  106905. goog.exportProperty(
  106906. ol.renderer.canvas.VectorLayer.prototype,
  106907. 'getRevision',
  106908. ol.renderer.canvas.VectorLayer.prototype.getRevision);
  106909. goog.exportProperty(
  106910. ol.renderer.canvas.VectorLayer.prototype,
  106911. 'on',
  106912. ol.renderer.canvas.VectorLayer.prototype.on);
  106913. goog.exportProperty(
  106914. ol.renderer.canvas.VectorLayer.prototype,
  106915. 'once',
  106916. ol.renderer.canvas.VectorLayer.prototype.once);
  106917. goog.exportProperty(
  106918. ol.renderer.canvas.VectorLayer.prototype,
  106919. 'un',
  106920. ol.renderer.canvas.VectorLayer.prototype.un);
  106921. goog.exportProperty(
  106922. ol.renderer.canvas.VectorLayer.prototype,
  106923. 'unByKey',
  106924. ol.renderer.canvas.VectorLayer.prototype.unByKey);
  106925. goog.exportProperty(
  106926. ol.layer.Base.prototype,
  106927. 'get',
  106928. ol.layer.Base.prototype.get);
  106929. goog.exportProperty(
  106930. ol.layer.Base.prototype,
  106931. 'getKeys',
  106932. ol.layer.Base.prototype.getKeys);
  106933. goog.exportProperty(
  106934. ol.layer.Base.prototype,
  106935. 'getProperties',
  106936. ol.layer.Base.prototype.getProperties);
  106937. goog.exportProperty(
  106938. ol.layer.Base.prototype,
  106939. 'set',
  106940. ol.layer.Base.prototype.set);
  106941. goog.exportProperty(
  106942. ol.layer.Base.prototype,
  106943. 'setProperties',
  106944. ol.layer.Base.prototype.setProperties);
  106945. goog.exportProperty(
  106946. ol.layer.Base.prototype,
  106947. 'unset',
  106948. ol.layer.Base.prototype.unset);
  106949. goog.exportProperty(
  106950. ol.layer.Base.prototype,
  106951. 'changed',
  106952. ol.layer.Base.prototype.changed);
  106953. goog.exportProperty(
  106954. ol.layer.Base.prototype,
  106955. 'getRevision',
  106956. ol.layer.Base.prototype.getRevision);
  106957. goog.exportProperty(
  106958. ol.layer.Base.prototype,
  106959. 'on',
  106960. ol.layer.Base.prototype.on);
  106961. goog.exportProperty(
  106962. ol.layer.Base.prototype,
  106963. 'once',
  106964. ol.layer.Base.prototype.once);
  106965. goog.exportProperty(
  106966. ol.layer.Base.prototype,
  106967. 'un',
  106968. ol.layer.Base.prototype.un);
  106969. goog.exportProperty(
  106970. ol.layer.Base.prototype,
  106971. 'unByKey',
  106972. ol.layer.Base.prototype.unByKey);
  106973. goog.exportProperty(
  106974. ol.layer.Layer.prototype,
  106975. 'getExtent',
  106976. ol.layer.Layer.prototype.getExtent);
  106977. goog.exportProperty(
  106978. ol.layer.Layer.prototype,
  106979. 'getMaxResolution',
  106980. ol.layer.Layer.prototype.getMaxResolution);
  106981. goog.exportProperty(
  106982. ol.layer.Layer.prototype,
  106983. 'getMinResolution',
  106984. ol.layer.Layer.prototype.getMinResolution);
  106985. goog.exportProperty(
  106986. ol.layer.Layer.prototype,
  106987. 'getOpacity',
  106988. ol.layer.Layer.prototype.getOpacity);
  106989. goog.exportProperty(
  106990. ol.layer.Layer.prototype,
  106991. 'getVisible',
  106992. ol.layer.Layer.prototype.getVisible);
  106993. goog.exportProperty(
  106994. ol.layer.Layer.prototype,
  106995. 'getZIndex',
  106996. ol.layer.Layer.prototype.getZIndex);
  106997. goog.exportProperty(
  106998. ol.layer.Layer.prototype,
  106999. 'setExtent',
  107000. ol.layer.Layer.prototype.setExtent);
  107001. goog.exportProperty(
  107002. ol.layer.Layer.prototype,
  107003. 'setMaxResolution',
  107004. ol.layer.Layer.prototype.setMaxResolution);
  107005. goog.exportProperty(
  107006. ol.layer.Layer.prototype,
  107007. 'setMinResolution',
  107008. ol.layer.Layer.prototype.setMinResolution);
  107009. goog.exportProperty(
  107010. ol.layer.Layer.prototype,
  107011. 'setOpacity',
  107012. ol.layer.Layer.prototype.setOpacity);
  107013. goog.exportProperty(
  107014. ol.layer.Layer.prototype,
  107015. 'setVisible',
  107016. ol.layer.Layer.prototype.setVisible);
  107017. goog.exportProperty(
  107018. ol.layer.Layer.prototype,
  107019. 'setZIndex',
  107020. ol.layer.Layer.prototype.setZIndex);
  107021. goog.exportProperty(
  107022. ol.layer.Layer.prototype,
  107023. 'get',
  107024. ol.layer.Layer.prototype.get);
  107025. goog.exportProperty(
  107026. ol.layer.Layer.prototype,
  107027. 'getKeys',
  107028. ol.layer.Layer.prototype.getKeys);
  107029. goog.exportProperty(
  107030. ol.layer.Layer.prototype,
  107031. 'getProperties',
  107032. ol.layer.Layer.prototype.getProperties);
  107033. goog.exportProperty(
  107034. ol.layer.Layer.prototype,
  107035. 'set',
  107036. ol.layer.Layer.prototype.set);
  107037. goog.exportProperty(
  107038. ol.layer.Layer.prototype,
  107039. 'setProperties',
  107040. ol.layer.Layer.prototype.setProperties);
  107041. goog.exportProperty(
  107042. ol.layer.Layer.prototype,
  107043. 'unset',
  107044. ol.layer.Layer.prototype.unset);
  107045. goog.exportProperty(
  107046. ol.layer.Layer.prototype,
  107047. 'changed',
  107048. ol.layer.Layer.prototype.changed);
  107049. goog.exportProperty(
  107050. ol.layer.Layer.prototype,
  107051. 'getRevision',
  107052. ol.layer.Layer.prototype.getRevision);
  107053. goog.exportProperty(
  107054. ol.layer.Layer.prototype,
  107055. 'on',
  107056. ol.layer.Layer.prototype.on);
  107057. goog.exportProperty(
  107058. ol.layer.Layer.prototype,
  107059. 'once',
  107060. ol.layer.Layer.prototype.once);
  107061. goog.exportProperty(
  107062. ol.layer.Layer.prototype,
  107063. 'un',
  107064. ol.layer.Layer.prototype.un);
  107065. goog.exportProperty(
  107066. ol.layer.Layer.prototype,
  107067. 'unByKey',
  107068. ol.layer.Layer.prototype.unByKey);
  107069. goog.exportProperty(
  107070. ol.layer.Vector.prototype,
  107071. 'setMap',
  107072. ol.layer.Vector.prototype.setMap);
  107073. goog.exportProperty(
  107074. ol.layer.Vector.prototype,
  107075. 'setSource',
  107076. ol.layer.Vector.prototype.setSource);
  107077. goog.exportProperty(
  107078. ol.layer.Vector.prototype,
  107079. 'getExtent',
  107080. ol.layer.Vector.prototype.getExtent);
  107081. goog.exportProperty(
  107082. ol.layer.Vector.prototype,
  107083. 'getMaxResolution',
  107084. ol.layer.Vector.prototype.getMaxResolution);
  107085. goog.exportProperty(
  107086. ol.layer.Vector.prototype,
  107087. 'getMinResolution',
  107088. ol.layer.Vector.prototype.getMinResolution);
  107089. goog.exportProperty(
  107090. ol.layer.Vector.prototype,
  107091. 'getOpacity',
  107092. ol.layer.Vector.prototype.getOpacity);
  107093. goog.exportProperty(
  107094. ol.layer.Vector.prototype,
  107095. 'getVisible',
  107096. ol.layer.Vector.prototype.getVisible);
  107097. goog.exportProperty(
  107098. ol.layer.Vector.prototype,
  107099. 'getZIndex',
  107100. ol.layer.Vector.prototype.getZIndex);
  107101. goog.exportProperty(
  107102. ol.layer.Vector.prototype,
  107103. 'setExtent',
  107104. ol.layer.Vector.prototype.setExtent);
  107105. goog.exportProperty(
  107106. ol.layer.Vector.prototype,
  107107. 'setMaxResolution',
  107108. ol.layer.Vector.prototype.setMaxResolution);
  107109. goog.exportProperty(
  107110. ol.layer.Vector.prototype,
  107111. 'setMinResolution',
  107112. ol.layer.Vector.prototype.setMinResolution);
  107113. goog.exportProperty(
  107114. ol.layer.Vector.prototype,
  107115. 'setOpacity',
  107116. ol.layer.Vector.prototype.setOpacity);
  107117. goog.exportProperty(
  107118. ol.layer.Vector.prototype,
  107119. 'setVisible',
  107120. ol.layer.Vector.prototype.setVisible);
  107121. goog.exportProperty(
  107122. ol.layer.Vector.prototype,
  107123. 'setZIndex',
  107124. ol.layer.Vector.prototype.setZIndex);
  107125. goog.exportProperty(
  107126. ol.layer.Vector.prototype,
  107127. 'get',
  107128. ol.layer.Vector.prototype.get);
  107129. goog.exportProperty(
  107130. ol.layer.Vector.prototype,
  107131. 'getKeys',
  107132. ol.layer.Vector.prototype.getKeys);
  107133. goog.exportProperty(
  107134. ol.layer.Vector.prototype,
  107135. 'getProperties',
  107136. ol.layer.Vector.prototype.getProperties);
  107137. goog.exportProperty(
  107138. ol.layer.Vector.prototype,
  107139. 'set',
  107140. ol.layer.Vector.prototype.set);
  107141. goog.exportProperty(
  107142. ol.layer.Vector.prototype,
  107143. 'setProperties',
  107144. ol.layer.Vector.prototype.setProperties);
  107145. goog.exportProperty(
  107146. ol.layer.Vector.prototype,
  107147. 'unset',
  107148. ol.layer.Vector.prototype.unset);
  107149. goog.exportProperty(
  107150. ol.layer.Vector.prototype,
  107151. 'changed',
  107152. ol.layer.Vector.prototype.changed);
  107153. goog.exportProperty(
  107154. ol.layer.Vector.prototype,
  107155. 'getRevision',
  107156. ol.layer.Vector.prototype.getRevision);
  107157. goog.exportProperty(
  107158. ol.layer.Vector.prototype,
  107159. 'on',
  107160. ol.layer.Vector.prototype.on);
  107161. goog.exportProperty(
  107162. ol.layer.Vector.prototype,
  107163. 'once',
  107164. ol.layer.Vector.prototype.once);
  107165. goog.exportProperty(
  107166. ol.layer.Vector.prototype,
  107167. 'un',
  107168. ol.layer.Vector.prototype.un);
  107169. goog.exportProperty(
  107170. ol.layer.Vector.prototype,
  107171. 'unByKey',
  107172. ol.layer.Vector.prototype.unByKey);
  107173. goog.exportProperty(
  107174. ol.layer.Heatmap.prototype,
  107175. 'getSource',
  107176. ol.layer.Heatmap.prototype.getSource);
  107177. goog.exportProperty(
  107178. ol.layer.Heatmap.prototype,
  107179. 'getStyle',
  107180. ol.layer.Heatmap.prototype.getStyle);
  107181. goog.exportProperty(
  107182. ol.layer.Heatmap.prototype,
  107183. 'getStyleFunction',
  107184. ol.layer.Heatmap.prototype.getStyleFunction);
  107185. goog.exportProperty(
  107186. ol.layer.Heatmap.prototype,
  107187. 'setStyle',
  107188. ol.layer.Heatmap.prototype.setStyle);
  107189. goog.exportProperty(
  107190. ol.layer.Heatmap.prototype,
  107191. 'setMap',
  107192. ol.layer.Heatmap.prototype.setMap);
  107193. goog.exportProperty(
  107194. ol.layer.Heatmap.prototype,
  107195. 'setSource',
  107196. ol.layer.Heatmap.prototype.setSource);
  107197. goog.exportProperty(
  107198. ol.layer.Heatmap.prototype,
  107199. 'getExtent',
  107200. ol.layer.Heatmap.prototype.getExtent);
  107201. goog.exportProperty(
  107202. ol.layer.Heatmap.prototype,
  107203. 'getMaxResolution',
  107204. ol.layer.Heatmap.prototype.getMaxResolution);
  107205. goog.exportProperty(
  107206. ol.layer.Heatmap.prototype,
  107207. 'getMinResolution',
  107208. ol.layer.Heatmap.prototype.getMinResolution);
  107209. goog.exportProperty(
  107210. ol.layer.Heatmap.prototype,
  107211. 'getOpacity',
  107212. ol.layer.Heatmap.prototype.getOpacity);
  107213. goog.exportProperty(
  107214. ol.layer.Heatmap.prototype,
  107215. 'getVisible',
  107216. ol.layer.Heatmap.prototype.getVisible);
  107217. goog.exportProperty(
  107218. ol.layer.Heatmap.prototype,
  107219. 'getZIndex',
  107220. ol.layer.Heatmap.prototype.getZIndex);
  107221. goog.exportProperty(
  107222. ol.layer.Heatmap.prototype,
  107223. 'setExtent',
  107224. ol.layer.Heatmap.prototype.setExtent);
  107225. goog.exportProperty(
  107226. ol.layer.Heatmap.prototype,
  107227. 'setMaxResolution',
  107228. ol.layer.Heatmap.prototype.setMaxResolution);
  107229. goog.exportProperty(
  107230. ol.layer.Heatmap.prototype,
  107231. 'setMinResolution',
  107232. ol.layer.Heatmap.prototype.setMinResolution);
  107233. goog.exportProperty(
  107234. ol.layer.Heatmap.prototype,
  107235. 'setOpacity',
  107236. ol.layer.Heatmap.prototype.setOpacity);
  107237. goog.exportProperty(
  107238. ol.layer.Heatmap.prototype,
  107239. 'setVisible',
  107240. ol.layer.Heatmap.prototype.setVisible);
  107241. goog.exportProperty(
  107242. ol.layer.Heatmap.prototype,
  107243. 'setZIndex',
  107244. ol.layer.Heatmap.prototype.setZIndex);
  107245. goog.exportProperty(
  107246. ol.layer.Heatmap.prototype,
  107247. 'get',
  107248. ol.layer.Heatmap.prototype.get);
  107249. goog.exportProperty(
  107250. ol.layer.Heatmap.prototype,
  107251. 'getKeys',
  107252. ol.layer.Heatmap.prototype.getKeys);
  107253. goog.exportProperty(
  107254. ol.layer.Heatmap.prototype,
  107255. 'getProperties',
  107256. ol.layer.Heatmap.prototype.getProperties);
  107257. goog.exportProperty(
  107258. ol.layer.Heatmap.prototype,
  107259. 'set',
  107260. ol.layer.Heatmap.prototype.set);
  107261. goog.exportProperty(
  107262. ol.layer.Heatmap.prototype,
  107263. 'setProperties',
  107264. ol.layer.Heatmap.prototype.setProperties);
  107265. goog.exportProperty(
  107266. ol.layer.Heatmap.prototype,
  107267. 'unset',
  107268. ol.layer.Heatmap.prototype.unset);
  107269. goog.exportProperty(
  107270. ol.layer.Heatmap.prototype,
  107271. 'changed',
  107272. ol.layer.Heatmap.prototype.changed);
  107273. goog.exportProperty(
  107274. ol.layer.Heatmap.prototype,
  107275. 'getRevision',
  107276. ol.layer.Heatmap.prototype.getRevision);
  107277. goog.exportProperty(
  107278. ol.layer.Heatmap.prototype,
  107279. 'on',
  107280. ol.layer.Heatmap.prototype.on);
  107281. goog.exportProperty(
  107282. ol.layer.Heatmap.prototype,
  107283. 'once',
  107284. ol.layer.Heatmap.prototype.once);
  107285. goog.exportProperty(
  107286. ol.layer.Heatmap.prototype,
  107287. 'un',
  107288. ol.layer.Heatmap.prototype.un);
  107289. goog.exportProperty(
  107290. ol.layer.Heatmap.prototype,
  107291. 'unByKey',
  107292. ol.layer.Heatmap.prototype.unByKey);
  107293. goog.exportProperty(
  107294. ol.layer.Image.prototype,
  107295. 'setMap',
  107296. ol.layer.Image.prototype.setMap);
  107297. goog.exportProperty(
  107298. ol.layer.Image.prototype,
  107299. 'setSource',
  107300. ol.layer.Image.prototype.setSource);
  107301. goog.exportProperty(
  107302. ol.layer.Image.prototype,
  107303. 'getExtent',
  107304. ol.layer.Image.prototype.getExtent);
  107305. goog.exportProperty(
  107306. ol.layer.Image.prototype,
  107307. 'getMaxResolution',
  107308. ol.layer.Image.prototype.getMaxResolution);
  107309. goog.exportProperty(
  107310. ol.layer.Image.prototype,
  107311. 'getMinResolution',
  107312. ol.layer.Image.prototype.getMinResolution);
  107313. goog.exportProperty(
  107314. ol.layer.Image.prototype,
  107315. 'getOpacity',
  107316. ol.layer.Image.prototype.getOpacity);
  107317. goog.exportProperty(
  107318. ol.layer.Image.prototype,
  107319. 'getVisible',
  107320. ol.layer.Image.prototype.getVisible);
  107321. goog.exportProperty(
  107322. ol.layer.Image.prototype,
  107323. 'getZIndex',
  107324. ol.layer.Image.prototype.getZIndex);
  107325. goog.exportProperty(
  107326. ol.layer.Image.prototype,
  107327. 'setExtent',
  107328. ol.layer.Image.prototype.setExtent);
  107329. goog.exportProperty(
  107330. ol.layer.Image.prototype,
  107331. 'setMaxResolution',
  107332. ol.layer.Image.prototype.setMaxResolution);
  107333. goog.exportProperty(
  107334. ol.layer.Image.prototype,
  107335. 'setMinResolution',
  107336. ol.layer.Image.prototype.setMinResolution);
  107337. goog.exportProperty(
  107338. ol.layer.Image.prototype,
  107339. 'setOpacity',
  107340. ol.layer.Image.prototype.setOpacity);
  107341. goog.exportProperty(
  107342. ol.layer.Image.prototype,
  107343. 'setVisible',
  107344. ol.layer.Image.prototype.setVisible);
  107345. goog.exportProperty(
  107346. ol.layer.Image.prototype,
  107347. 'setZIndex',
  107348. ol.layer.Image.prototype.setZIndex);
  107349. goog.exportProperty(
  107350. ol.layer.Image.prototype,
  107351. 'get',
  107352. ol.layer.Image.prototype.get);
  107353. goog.exportProperty(
  107354. ol.layer.Image.prototype,
  107355. 'getKeys',
  107356. ol.layer.Image.prototype.getKeys);
  107357. goog.exportProperty(
  107358. ol.layer.Image.prototype,
  107359. 'getProperties',
  107360. ol.layer.Image.prototype.getProperties);
  107361. goog.exportProperty(
  107362. ol.layer.Image.prototype,
  107363. 'set',
  107364. ol.layer.Image.prototype.set);
  107365. goog.exportProperty(
  107366. ol.layer.Image.prototype,
  107367. 'setProperties',
  107368. ol.layer.Image.prototype.setProperties);
  107369. goog.exportProperty(
  107370. ol.layer.Image.prototype,
  107371. 'unset',
  107372. ol.layer.Image.prototype.unset);
  107373. goog.exportProperty(
  107374. ol.layer.Image.prototype,
  107375. 'changed',
  107376. ol.layer.Image.prototype.changed);
  107377. goog.exportProperty(
  107378. ol.layer.Image.prototype,
  107379. 'getRevision',
  107380. ol.layer.Image.prototype.getRevision);
  107381. goog.exportProperty(
  107382. ol.layer.Image.prototype,
  107383. 'on',
  107384. ol.layer.Image.prototype.on);
  107385. goog.exportProperty(
  107386. ol.layer.Image.prototype,
  107387. 'once',
  107388. ol.layer.Image.prototype.once);
  107389. goog.exportProperty(
  107390. ol.layer.Image.prototype,
  107391. 'un',
  107392. ol.layer.Image.prototype.un);
  107393. goog.exportProperty(
  107394. ol.layer.Image.prototype,
  107395. 'unByKey',
  107396. ol.layer.Image.prototype.unByKey);
  107397. goog.exportProperty(
  107398. ol.layer.Group.prototype,
  107399. 'getExtent',
  107400. ol.layer.Group.prototype.getExtent);
  107401. goog.exportProperty(
  107402. ol.layer.Group.prototype,
  107403. 'getMaxResolution',
  107404. ol.layer.Group.prototype.getMaxResolution);
  107405. goog.exportProperty(
  107406. ol.layer.Group.prototype,
  107407. 'getMinResolution',
  107408. ol.layer.Group.prototype.getMinResolution);
  107409. goog.exportProperty(
  107410. ol.layer.Group.prototype,
  107411. 'getOpacity',
  107412. ol.layer.Group.prototype.getOpacity);
  107413. goog.exportProperty(
  107414. ol.layer.Group.prototype,
  107415. 'getVisible',
  107416. ol.layer.Group.prototype.getVisible);
  107417. goog.exportProperty(
  107418. ol.layer.Group.prototype,
  107419. 'getZIndex',
  107420. ol.layer.Group.prototype.getZIndex);
  107421. goog.exportProperty(
  107422. ol.layer.Group.prototype,
  107423. 'setExtent',
  107424. ol.layer.Group.prototype.setExtent);
  107425. goog.exportProperty(
  107426. ol.layer.Group.prototype,
  107427. 'setMaxResolution',
  107428. ol.layer.Group.prototype.setMaxResolution);
  107429. goog.exportProperty(
  107430. ol.layer.Group.prototype,
  107431. 'setMinResolution',
  107432. ol.layer.Group.prototype.setMinResolution);
  107433. goog.exportProperty(
  107434. ol.layer.Group.prototype,
  107435. 'setOpacity',
  107436. ol.layer.Group.prototype.setOpacity);
  107437. goog.exportProperty(
  107438. ol.layer.Group.prototype,
  107439. 'setVisible',
  107440. ol.layer.Group.prototype.setVisible);
  107441. goog.exportProperty(
  107442. ol.layer.Group.prototype,
  107443. 'setZIndex',
  107444. ol.layer.Group.prototype.setZIndex);
  107445. goog.exportProperty(
  107446. ol.layer.Group.prototype,
  107447. 'get',
  107448. ol.layer.Group.prototype.get);
  107449. goog.exportProperty(
  107450. ol.layer.Group.prototype,
  107451. 'getKeys',
  107452. ol.layer.Group.prototype.getKeys);
  107453. goog.exportProperty(
  107454. ol.layer.Group.prototype,
  107455. 'getProperties',
  107456. ol.layer.Group.prototype.getProperties);
  107457. goog.exportProperty(
  107458. ol.layer.Group.prototype,
  107459. 'set',
  107460. ol.layer.Group.prototype.set);
  107461. goog.exportProperty(
  107462. ol.layer.Group.prototype,
  107463. 'setProperties',
  107464. ol.layer.Group.prototype.setProperties);
  107465. goog.exportProperty(
  107466. ol.layer.Group.prototype,
  107467. 'unset',
  107468. ol.layer.Group.prototype.unset);
  107469. goog.exportProperty(
  107470. ol.layer.Group.prototype,
  107471. 'changed',
  107472. ol.layer.Group.prototype.changed);
  107473. goog.exportProperty(
  107474. ol.layer.Group.prototype,
  107475. 'getRevision',
  107476. ol.layer.Group.prototype.getRevision);
  107477. goog.exportProperty(
  107478. ol.layer.Group.prototype,
  107479. 'on',
  107480. ol.layer.Group.prototype.on);
  107481. goog.exportProperty(
  107482. ol.layer.Group.prototype,
  107483. 'once',
  107484. ol.layer.Group.prototype.once);
  107485. goog.exportProperty(
  107486. ol.layer.Group.prototype,
  107487. 'un',
  107488. ol.layer.Group.prototype.un);
  107489. goog.exportProperty(
  107490. ol.layer.Group.prototype,
  107491. 'unByKey',
  107492. ol.layer.Group.prototype.unByKey);
  107493. goog.exportProperty(
  107494. ol.layer.Tile.prototype,
  107495. 'setMap',
  107496. ol.layer.Tile.prototype.setMap);
  107497. goog.exportProperty(
  107498. ol.layer.Tile.prototype,
  107499. 'setSource',
  107500. ol.layer.Tile.prototype.setSource);
  107501. goog.exportProperty(
  107502. ol.layer.Tile.prototype,
  107503. 'getExtent',
  107504. ol.layer.Tile.prototype.getExtent);
  107505. goog.exportProperty(
  107506. ol.layer.Tile.prototype,
  107507. 'getMaxResolution',
  107508. ol.layer.Tile.prototype.getMaxResolution);
  107509. goog.exportProperty(
  107510. ol.layer.Tile.prototype,
  107511. 'getMinResolution',
  107512. ol.layer.Tile.prototype.getMinResolution);
  107513. goog.exportProperty(
  107514. ol.layer.Tile.prototype,
  107515. 'getOpacity',
  107516. ol.layer.Tile.prototype.getOpacity);
  107517. goog.exportProperty(
  107518. ol.layer.Tile.prototype,
  107519. 'getVisible',
  107520. ol.layer.Tile.prototype.getVisible);
  107521. goog.exportProperty(
  107522. ol.layer.Tile.prototype,
  107523. 'getZIndex',
  107524. ol.layer.Tile.prototype.getZIndex);
  107525. goog.exportProperty(
  107526. ol.layer.Tile.prototype,
  107527. 'setExtent',
  107528. ol.layer.Tile.prototype.setExtent);
  107529. goog.exportProperty(
  107530. ol.layer.Tile.prototype,
  107531. 'setMaxResolution',
  107532. ol.layer.Tile.prototype.setMaxResolution);
  107533. goog.exportProperty(
  107534. ol.layer.Tile.prototype,
  107535. 'setMinResolution',
  107536. ol.layer.Tile.prototype.setMinResolution);
  107537. goog.exportProperty(
  107538. ol.layer.Tile.prototype,
  107539. 'setOpacity',
  107540. ol.layer.Tile.prototype.setOpacity);
  107541. goog.exportProperty(
  107542. ol.layer.Tile.prototype,
  107543. 'setVisible',
  107544. ol.layer.Tile.prototype.setVisible);
  107545. goog.exportProperty(
  107546. ol.layer.Tile.prototype,
  107547. 'setZIndex',
  107548. ol.layer.Tile.prototype.setZIndex);
  107549. goog.exportProperty(
  107550. ol.layer.Tile.prototype,
  107551. 'get',
  107552. ol.layer.Tile.prototype.get);
  107553. goog.exportProperty(
  107554. ol.layer.Tile.prototype,
  107555. 'getKeys',
  107556. ol.layer.Tile.prototype.getKeys);
  107557. goog.exportProperty(
  107558. ol.layer.Tile.prototype,
  107559. 'getProperties',
  107560. ol.layer.Tile.prototype.getProperties);
  107561. goog.exportProperty(
  107562. ol.layer.Tile.prototype,
  107563. 'set',
  107564. ol.layer.Tile.prototype.set);
  107565. goog.exportProperty(
  107566. ol.layer.Tile.prototype,
  107567. 'setProperties',
  107568. ol.layer.Tile.prototype.setProperties);
  107569. goog.exportProperty(
  107570. ol.layer.Tile.prototype,
  107571. 'unset',
  107572. ol.layer.Tile.prototype.unset);
  107573. goog.exportProperty(
  107574. ol.layer.Tile.prototype,
  107575. 'changed',
  107576. ol.layer.Tile.prototype.changed);
  107577. goog.exportProperty(
  107578. ol.layer.Tile.prototype,
  107579. 'getRevision',
  107580. ol.layer.Tile.prototype.getRevision);
  107581. goog.exportProperty(
  107582. ol.layer.Tile.prototype,
  107583. 'on',
  107584. ol.layer.Tile.prototype.on);
  107585. goog.exportProperty(
  107586. ol.layer.Tile.prototype,
  107587. 'once',
  107588. ol.layer.Tile.prototype.once);
  107589. goog.exportProperty(
  107590. ol.layer.Tile.prototype,
  107591. 'un',
  107592. ol.layer.Tile.prototype.un);
  107593. goog.exportProperty(
  107594. ol.layer.Tile.prototype,
  107595. 'unByKey',
  107596. ol.layer.Tile.prototype.unByKey);
  107597. goog.exportProperty(
  107598. ol.interaction.Interaction.prototype,
  107599. 'get',
  107600. ol.interaction.Interaction.prototype.get);
  107601. goog.exportProperty(
  107602. ol.interaction.Interaction.prototype,
  107603. 'getKeys',
  107604. ol.interaction.Interaction.prototype.getKeys);
  107605. goog.exportProperty(
  107606. ol.interaction.Interaction.prototype,
  107607. 'getProperties',
  107608. ol.interaction.Interaction.prototype.getProperties);
  107609. goog.exportProperty(
  107610. ol.interaction.Interaction.prototype,
  107611. 'set',
  107612. ol.interaction.Interaction.prototype.set);
  107613. goog.exportProperty(
  107614. ol.interaction.Interaction.prototype,
  107615. 'setProperties',
  107616. ol.interaction.Interaction.prototype.setProperties);
  107617. goog.exportProperty(
  107618. ol.interaction.Interaction.prototype,
  107619. 'unset',
  107620. ol.interaction.Interaction.prototype.unset);
  107621. goog.exportProperty(
  107622. ol.interaction.Interaction.prototype,
  107623. 'changed',
  107624. ol.interaction.Interaction.prototype.changed);
  107625. goog.exportProperty(
  107626. ol.interaction.Interaction.prototype,
  107627. 'getRevision',
  107628. ol.interaction.Interaction.prototype.getRevision);
  107629. goog.exportProperty(
  107630. ol.interaction.Interaction.prototype,
  107631. 'on',
  107632. ol.interaction.Interaction.prototype.on);
  107633. goog.exportProperty(
  107634. ol.interaction.Interaction.prototype,
  107635. 'once',
  107636. ol.interaction.Interaction.prototype.once);
  107637. goog.exportProperty(
  107638. ol.interaction.Interaction.prototype,
  107639. 'un',
  107640. ol.interaction.Interaction.prototype.un);
  107641. goog.exportProperty(
  107642. ol.interaction.Interaction.prototype,
  107643. 'unByKey',
  107644. ol.interaction.Interaction.prototype.unByKey);
  107645. goog.exportProperty(
  107646. ol.interaction.DoubleClickZoom.prototype,
  107647. 'getActive',
  107648. ol.interaction.DoubleClickZoom.prototype.getActive);
  107649. goog.exportProperty(
  107650. ol.interaction.DoubleClickZoom.prototype,
  107651. 'setActive',
  107652. ol.interaction.DoubleClickZoom.prototype.setActive);
  107653. goog.exportProperty(
  107654. ol.interaction.DoubleClickZoom.prototype,
  107655. 'get',
  107656. ol.interaction.DoubleClickZoom.prototype.get);
  107657. goog.exportProperty(
  107658. ol.interaction.DoubleClickZoom.prototype,
  107659. 'getKeys',
  107660. ol.interaction.DoubleClickZoom.prototype.getKeys);
  107661. goog.exportProperty(
  107662. ol.interaction.DoubleClickZoom.prototype,
  107663. 'getProperties',
  107664. ol.interaction.DoubleClickZoom.prototype.getProperties);
  107665. goog.exportProperty(
  107666. ol.interaction.DoubleClickZoom.prototype,
  107667. 'set',
  107668. ol.interaction.DoubleClickZoom.prototype.set);
  107669. goog.exportProperty(
  107670. ol.interaction.DoubleClickZoom.prototype,
  107671. 'setProperties',
  107672. ol.interaction.DoubleClickZoom.prototype.setProperties);
  107673. goog.exportProperty(
  107674. ol.interaction.DoubleClickZoom.prototype,
  107675. 'unset',
  107676. ol.interaction.DoubleClickZoom.prototype.unset);
  107677. goog.exportProperty(
  107678. ol.interaction.DoubleClickZoom.prototype,
  107679. 'changed',
  107680. ol.interaction.DoubleClickZoom.prototype.changed);
  107681. goog.exportProperty(
  107682. ol.interaction.DoubleClickZoom.prototype,
  107683. 'getRevision',
  107684. ol.interaction.DoubleClickZoom.prototype.getRevision);
  107685. goog.exportProperty(
  107686. ol.interaction.DoubleClickZoom.prototype,
  107687. 'on',
  107688. ol.interaction.DoubleClickZoom.prototype.on);
  107689. goog.exportProperty(
  107690. ol.interaction.DoubleClickZoom.prototype,
  107691. 'once',
  107692. ol.interaction.DoubleClickZoom.prototype.once);
  107693. goog.exportProperty(
  107694. ol.interaction.DoubleClickZoom.prototype,
  107695. 'un',
  107696. ol.interaction.DoubleClickZoom.prototype.un);
  107697. goog.exportProperty(
  107698. ol.interaction.DoubleClickZoom.prototype,
  107699. 'unByKey',
  107700. ol.interaction.DoubleClickZoom.prototype.unByKey);
  107701. goog.exportProperty(
  107702. ol.interaction.DragAndDrop.prototype,
  107703. 'getActive',
  107704. ol.interaction.DragAndDrop.prototype.getActive);
  107705. goog.exportProperty(
  107706. ol.interaction.DragAndDrop.prototype,
  107707. 'setActive',
  107708. ol.interaction.DragAndDrop.prototype.setActive);
  107709. goog.exportProperty(
  107710. ol.interaction.DragAndDrop.prototype,
  107711. 'get',
  107712. ol.interaction.DragAndDrop.prototype.get);
  107713. goog.exportProperty(
  107714. ol.interaction.DragAndDrop.prototype,
  107715. 'getKeys',
  107716. ol.interaction.DragAndDrop.prototype.getKeys);
  107717. goog.exportProperty(
  107718. ol.interaction.DragAndDrop.prototype,
  107719. 'getProperties',
  107720. ol.interaction.DragAndDrop.prototype.getProperties);
  107721. goog.exportProperty(
  107722. ol.interaction.DragAndDrop.prototype,
  107723. 'set',
  107724. ol.interaction.DragAndDrop.prototype.set);
  107725. goog.exportProperty(
  107726. ol.interaction.DragAndDrop.prototype,
  107727. 'setProperties',
  107728. ol.interaction.DragAndDrop.prototype.setProperties);
  107729. goog.exportProperty(
  107730. ol.interaction.DragAndDrop.prototype,
  107731. 'unset',
  107732. ol.interaction.DragAndDrop.prototype.unset);
  107733. goog.exportProperty(
  107734. ol.interaction.DragAndDrop.prototype,
  107735. 'changed',
  107736. ol.interaction.DragAndDrop.prototype.changed);
  107737. goog.exportProperty(
  107738. ol.interaction.DragAndDrop.prototype,
  107739. 'getRevision',
  107740. ol.interaction.DragAndDrop.prototype.getRevision);
  107741. goog.exportProperty(
  107742. ol.interaction.DragAndDrop.prototype,
  107743. 'on',
  107744. ol.interaction.DragAndDrop.prototype.on);
  107745. goog.exportProperty(
  107746. ol.interaction.DragAndDrop.prototype,
  107747. 'once',
  107748. ol.interaction.DragAndDrop.prototype.once);
  107749. goog.exportProperty(
  107750. ol.interaction.DragAndDrop.prototype,
  107751. 'un',
  107752. ol.interaction.DragAndDrop.prototype.un);
  107753. goog.exportProperty(
  107754. ol.interaction.DragAndDrop.prototype,
  107755. 'unByKey',
  107756. ol.interaction.DragAndDrop.prototype.unByKey);
  107757. goog.exportProperty(
  107758. ol.interaction.Pointer.prototype,
  107759. 'getActive',
  107760. ol.interaction.Pointer.prototype.getActive);
  107761. goog.exportProperty(
  107762. ol.interaction.Pointer.prototype,
  107763. 'setActive',
  107764. ol.interaction.Pointer.prototype.setActive);
  107765. goog.exportProperty(
  107766. ol.interaction.Pointer.prototype,
  107767. 'get',
  107768. ol.interaction.Pointer.prototype.get);
  107769. goog.exportProperty(
  107770. ol.interaction.Pointer.prototype,
  107771. 'getKeys',
  107772. ol.interaction.Pointer.prototype.getKeys);
  107773. goog.exportProperty(
  107774. ol.interaction.Pointer.prototype,
  107775. 'getProperties',
  107776. ol.interaction.Pointer.prototype.getProperties);
  107777. goog.exportProperty(
  107778. ol.interaction.Pointer.prototype,
  107779. 'set',
  107780. ol.interaction.Pointer.prototype.set);
  107781. goog.exportProperty(
  107782. ol.interaction.Pointer.prototype,
  107783. 'setProperties',
  107784. ol.interaction.Pointer.prototype.setProperties);
  107785. goog.exportProperty(
  107786. ol.interaction.Pointer.prototype,
  107787. 'unset',
  107788. ol.interaction.Pointer.prototype.unset);
  107789. goog.exportProperty(
  107790. ol.interaction.Pointer.prototype,
  107791. 'changed',
  107792. ol.interaction.Pointer.prototype.changed);
  107793. goog.exportProperty(
  107794. ol.interaction.Pointer.prototype,
  107795. 'getRevision',
  107796. ol.interaction.Pointer.prototype.getRevision);
  107797. goog.exportProperty(
  107798. ol.interaction.Pointer.prototype,
  107799. 'on',
  107800. ol.interaction.Pointer.prototype.on);
  107801. goog.exportProperty(
  107802. ol.interaction.Pointer.prototype,
  107803. 'once',
  107804. ol.interaction.Pointer.prototype.once);
  107805. goog.exportProperty(
  107806. ol.interaction.Pointer.prototype,
  107807. 'un',
  107808. ol.interaction.Pointer.prototype.un);
  107809. goog.exportProperty(
  107810. ol.interaction.Pointer.prototype,
  107811. 'unByKey',
  107812. ol.interaction.Pointer.prototype.unByKey);
  107813. goog.exportProperty(
  107814. ol.interaction.DragBox.prototype,
  107815. 'getActive',
  107816. ol.interaction.DragBox.prototype.getActive);
  107817. goog.exportProperty(
  107818. ol.interaction.DragBox.prototype,
  107819. 'setActive',
  107820. ol.interaction.DragBox.prototype.setActive);
  107821. goog.exportProperty(
  107822. ol.interaction.DragBox.prototype,
  107823. 'get',
  107824. ol.interaction.DragBox.prototype.get);
  107825. goog.exportProperty(
  107826. ol.interaction.DragBox.prototype,
  107827. 'getKeys',
  107828. ol.interaction.DragBox.prototype.getKeys);
  107829. goog.exportProperty(
  107830. ol.interaction.DragBox.prototype,
  107831. 'getProperties',
  107832. ol.interaction.DragBox.prototype.getProperties);
  107833. goog.exportProperty(
  107834. ol.interaction.DragBox.prototype,
  107835. 'set',
  107836. ol.interaction.DragBox.prototype.set);
  107837. goog.exportProperty(
  107838. ol.interaction.DragBox.prototype,
  107839. 'setProperties',
  107840. ol.interaction.DragBox.prototype.setProperties);
  107841. goog.exportProperty(
  107842. ol.interaction.DragBox.prototype,
  107843. 'unset',
  107844. ol.interaction.DragBox.prototype.unset);
  107845. goog.exportProperty(
  107846. ol.interaction.DragBox.prototype,
  107847. 'changed',
  107848. ol.interaction.DragBox.prototype.changed);
  107849. goog.exportProperty(
  107850. ol.interaction.DragBox.prototype,
  107851. 'getRevision',
  107852. ol.interaction.DragBox.prototype.getRevision);
  107853. goog.exportProperty(
  107854. ol.interaction.DragBox.prototype,
  107855. 'on',
  107856. ol.interaction.DragBox.prototype.on);
  107857. goog.exportProperty(
  107858. ol.interaction.DragBox.prototype,
  107859. 'once',
  107860. ol.interaction.DragBox.prototype.once);
  107861. goog.exportProperty(
  107862. ol.interaction.DragBox.prototype,
  107863. 'un',
  107864. ol.interaction.DragBox.prototype.un);
  107865. goog.exportProperty(
  107866. ol.interaction.DragBox.prototype,
  107867. 'unByKey',
  107868. ol.interaction.DragBox.prototype.unByKey);
  107869. goog.exportProperty(
  107870. ol.interaction.DragPan.prototype,
  107871. 'getActive',
  107872. ol.interaction.DragPan.prototype.getActive);
  107873. goog.exportProperty(
  107874. ol.interaction.DragPan.prototype,
  107875. 'setActive',
  107876. ol.interaction.DragPan.prototype.setActive);
  107877. goog.exportProperty(
  107878. ol.interaction.DragPan.prototype,
  107879. 'get',
  107880. ol.interaction.DragPan.prototype.get);
  107881. goog.exportProperty(
  107882. ol.interaction.DragPan.prototype,
  107883. 'getKeys',
  107884. ol.interaction.DragPan.prototype.getKeys);
  107885. goog.exportProperty(
  107886. ol.interaction.DragPan.prototype,
  107887. 'getProperties',
  107888. ol.interaction.DragPan.prototype.getProperties);
  107889. goog.exportProperty(
  107890. ol.interaction.DragPan.prototype,
  107891. 'set',
  107892. ol.interaction.DragPan.prototype.set);
  107893. goog.exportProperty(
  107894. ol.interaction.DragPan.prototype,
  107895. 'setProperties',
  107896. ol.interaction.DragPan.prototype.setProperties);
  107897. goog.exportProperty(
  107898. ol.interaction.DragPan.prototype,
  107899. 'unset',
  107900. ol.interaction.DragPan.prototype.unset);
  107901. goog.exportProperty(
  107902. ol.interaction.DragPan.prototype,
  107903. 'changed',
  107904. ol.interaction.DragPan.prototype.changed);
  107905. goog.exportProperty(
  107906. ol.interaction.DragPan.prototype,
  107907. 'getRevision',
  107908. ol.interaction.DragPan.prototype.getRevision);
  107909. goog.exportProperty(
  107910. ol.interaction.DragPan.prototype,
  107911. 'on',
  107912. ol.interaction.DragPan.prototype.on);
  107913. goog.exportProperty(
  107914. ol.interaction.DragPan.prototype,
  107915. 'once',
  107916. ol.interaction.DragPan.prototype.once);
  107917. goog.exportProperty(
  107918. ol.interaction.DragPan.prototype,
  107919. 'un',
  107920. ol.interaction.DragPan.prototype.un);
  107921. goog.exportProperty(
  107922. ol.interaction.DragPan.prototype,
  107923. 'unByKey',
  107924. ol.interaction.DragPan.prototype.unByKey);
  107925. goog.exportProperty(
  107926. ol.interaction.DragRotateAndZoom.prototype,
  107927. 'getActive',
  107928. ol.interaction.DragRotateAndZoom.prototype.getActive);
  107929. goog.exportProperty(
  107930. ol.interaction.DragRotateAndZoom.prototype,
  107931. 'setActive',
  107932. ol.interaction.DragRotateAndZoom.prototype.setActive);
  107933. goog.exportProperty(
  107934. ol.interaction.DragRotateAndZoom.prototype,
  107935. 'get',
  107936. ol.interaction.DragRotateAndZoom.prototype.get);
  107937. goog.exportProperty(
  107938. ol.interaction.DragRotateAndZoom.prototype,
  107939. 'getKeys',
  107940. ol.interaction.DragRotateAndZoom.prototype.getKeys);
  107941. goog.exportProperty(
  107942. ol.interaction.DragRotateAndZoom.prototype,
  107943. 'getProperties',
  107944. ol.interaction.DragRotateAndZoom.prototype.getProperties);
  107945. goog.exportProperty(
  107946. ol.interaction.DragRotateAndZoom.prototype,
  107947. 'set',
  107948. ol.interaction.DragRotateAndZoom.prototype.set);
  107949. goog.exportProperty(
  107950. ol.interaction.DragRotateAndZoom.prototype,
  107951. 'setProperties',
  107952. ol.interaction.DragRotateAndZoom.prototype.setProperties);
  107953. goog.exportProperty(
  107954. ol.interaction.DragRotateAndZoom.prototype,
  107955. 'unset',
  107956. ol.interaction.DragRotateAndZoom.prototype.unset);
  107957. goog.exportProperty(
  107958. ol.interaction.DragRotateAndZoom.prototype,
  107959. 'changed',
  107960. ol.interaction.DragRotateAndZoom.prototype.changed);
  107961. goog.exportProperty(
  107962. ol.interaction.DragRotateAndZoom.prototype,
  107963. 'getRevision',
  107964. ol.interaction.DragRotateAndZoom.prototype.getRevision);
  107965. goog.exportProperty(
  107966. ol.interaction.DragRotateAndZoom.prototype,
  107967. 'on',
  107968. ol.interaction.DragRotateAndZoom.prototype.on);
  107969. goog.exportProperty(
  107970. ol.interaction.DragRotateAndZoom.prototype,
  107971. 'once',
  107972. ol.interaction.DragRotateAndZoom.prototype.once);
  107973. goog.exportProperty(
  107974. ol.interaction.DragRotateAndZoom.prototype,
  107975. 'un',
  107976. ol.interaction.DragRotateAndZoom.prototype.un);
  107977. goog.exportProperty(
  107978. ol.interaction.DragRotateAndZoom.prototype,
  107979. 'unByKey',
  107980. ol.interaction.DragRotateAndZoom.prototype.unByKey);
  107981. goog.exportProperty(
  107982. ol.interaction.DragRotate.prototype,
  107983. 'getActive',
  107984. ol.interaction.DragRotate.prototype.getActive);
  107985. goog.exportProperty(
  107986. ol.interaction.DragRotate.prototype,
  107987. 'setActive',
  107988. ol.interaction.DragRotate.prototype.setActive);
  107989. goog.exportProperty(
  107990. ol.interaction.DragRotate.prototype,
  107991. 'get',
  107992. ol.interaction.DragRotate.prototype.get);
  107993. goog.exportProperty(
  107994. ol.interaction.DragRotate.prototype,
  107995. 'getKeys',
  107996. ol.interaction.DragRotate.prototype.getKeys);
  107997. goog.exportProperty(
  107998. ol.interaction.DragRotate.prototype,
  107999. 'getProperties',
  108000. ol.interaction.DragRotate.prototype.getProperties);
  108001. goog.exportProperty(
  108002. ol.interaction.DragRotate.prototype,
  108003. 'set',
  108004. ol.interaction.DragRotate.prototype.set);
  108005. goog.exportProperty(
  108006. ol.interaction.DragRotate.prototype,
  108007. 'setProperties',
  108008. ol.interaction.DragRotate.prototype.setProperties);
  108009. goog.exportProperty(
  108010. ol.interaction.DragRotate.prototype,
  108011. 'unset',
  108012. ol.interaction.DragRotate.prototype.unset);
  108013. goog.exportProperty(
  108014. ol.interaction.DragRotate.prototype,
  108015. 'changed',
  108016. ol.interaction.DragRotate.prototype.changed);
  108017. goog.exportProperty(
  108018. ol.interaction.DragRotate.prototype,
  108019. 'getRevision',
  108020. ol.interaction.DragRotate.prototype.getRevision);
  108021. goog.exportProperty(
  108022. ol.interaction.DragRotate.prototype,
  108023. 'on',
  108024. ol.interaction.DragRotate.prototype.on);
  108025. goog.exportProperty(
  108026. ol.interaction.DragRotate.prototype,
  108027. 'once',
  108028. ol.interaction.DragRotate.prototype.once);
  108029. goog.exportProperty(
  108030. ol.interaction.DragRotate.prototype,
  108031. 'un',
  108032. ol.interaction.DragRotate.prototype.un);
  108033. goog.exportProperty(
  108034. ol.interaction.DragRotate.prototype,
  108035. 'unByKey',
  108036. ol.interaction.DragRotate.prototype.unByKey);
  108037. goog.exportProperty(
  108038. ol.interaction.DragZoom.prototype,
  108039. 'getGeometry',
  108040. ol.interaction.DragZoom.prototype.getGeometry);
  108041. goog.exportProperty(
  108042. ol.interaction.DragZoom.prototype,
  108043. 'getActive',
  108044. ol.interaction.DragZoom.prototype.getActive);
  108045. goog.exportProperty(
  108046. ol.interaction.DragZoom.prototype,
  108047. 'setActive',
  108048. ol.interaction.DragZoom.prototype.setActive);
  108049. goog.exportProperty(
  108050. ol.interaction.DragZoom.prototype,
  108051. 'get',
  108052. ol.interaction.DragZoom.prototype.get);
  108053. goog.exportProperty(
  108054. ol.interaction.DragZoom.prototype,
  108055. 'getKeys',
  108056. ol.interaction.DragZoom.prototype.getKeys);
  108057. goog.exportProperty(
  108058. ol.interaction.DragZoom.prototype,
  108059. 'getProperties',
  108060. ol.interaction.DragZoom.prototype.getProperties);
  108061. goog.exportProperty(
  108062. ol.interaction.DragZoom.prototype,
  108063. 'set',
  108064. ol.interaction.DragZoom.prototype.set);
  108065. goog.exportProperty(
  108066. ol.interaction.DragZoom.prototype,
  108067. 'setProperties',
  108068. ol.interaction.DragZoom.prototype.setProperties);
  108069. goog.exportProperty(
  108070. ol.interaction.DragZoom.prototype,
  108071. 'unset',
  108072. ol.interaction.DragZoom.prototype.unset);
  108073. goog.exportProperty(
  108074. ol.interaction.DragZoom.prototype,
  108075. 'changed',
  108076. ol.interaction.DragZoom.prototype.changed);
  108077. goog.exportProperty(
  108078. ol.interaction.DragZoom.prototype,
  108079. 'getRevision',
  108080. ol.interaction.DragZoom.prototype.getRevision);
  108081. goog.exportProperty(
  108082. ol.interaction.DragZoom.prototype,
  108083. 'on',
  108084. ol.interaction.DragZoom.prototype.on);
  108085. goog.exportProperty(
  108086. ol.interaction.DragZoom.prototype,
  108087. 'once',
  108088. ol.interaction.DragZoom.prototype.once);
  108089. goog.exportProperty(
  108090. ol.interaction.DragZoom.prototype,
  108091. 'un',
  108092. ol.interaction.DragZoom.prototype.un);
  108093. goog.exportProperty(
  108094. ol.interaction.DragZoom.prototype,
  108095. 'unByKey',
  108096. ol.interaction.DragZoom.prototype.unByKey);
  108097. goog.exportProperty(
  108098. ol.interaction.Draw.prototype,
  108099. 'getActive',
  108100. ol.interaction.Draw.prototype.getActive);
  108101. goog.exportProperty(
  108102. ol.interaction.Draw.prototype,
  108103. 'setActive',
  108104. ol.interaction.Draw.prototype.setActive);
  108105. goog.exportProperty(
  108106. ol.interaction.Draw.prototype,
  108107. 'get',
  108108. ol.interaction.Draw.prototype.get);
  108109. goog.exportProperty(
  108110. ol.interaction.Draw.prototype,
  108111. 'getKeys',
  108112. ol.interaction.Draw.prototype.getKeys);
  108113. goog.exportProperty(
  108114. ol.interaction.Draw.prototype,
  108115. 'getProperties',
  108116. ol.interaction.Draw.prototype.getProperties);
  108117. goog.exportProperty(
  108118. ol.interaction.Draw.prototype,
  108119. 'set',
  108120. ol.interaction.Draw.prototype.set);
  108121. goog.exportProperty(
  108122. ol.interaction.Draw.prototype,
  108123. 'setProperties',
  108124. ol.interaction.Draw.prototype.setProperties);
  108125. goog.exportProperty(
  108126. ol.interaction.Draw.prototype,
  108127. 'unset',
  108128. ol.interaction.Draw.prototype.unset);
  108129. goog.exportProperty(
  108130. ol.interaction.Draw.prototype,
  108131. 'changed',
  108132. ol.interaction.Draw.prototype.changed);
  108133. goog.exportProperty(
  108134. ol.interaction.Draw.prototype,
  108135. 'getRevision',
  108136. ol.interaction.Draw.prototype.getRevision);
  108137. goog.exportProperty(
  108138. ol.interaction.Draw.prototype,
  108139. 'on',
  108140. ol.interaction.Draw.prototype.on);
  108141. goog.exportProperty(
  108142. ol.interaction.Draw.prototype,
  108143. 'once',
  108144. ol.interaction.Draw.prototype.once);
  108145. goog.exportProperty(
  108146. ol.interaction.Draw.prototype,
  108147. 'un',
  108148. ol.interaction.Draw.prototype.un);
  108149. goog.exportProperty(
  108150. ol.interaction.Draw.prototype,
  108151. 'unByKey',
  108152. ol.interaction.Draw.prototype.unByKey);
  108153. goog.exportProperty(
  108154. ol.interaction.KeyboardPan.prototype,
  108155. 'getActive',
  108156. ol.interaction.KeyboardPan.prototype.getActive);
  108157. goog.exportProperty(
  108158. ol.interaction.KeyboardPan.prototype,
  108159. 'setActive',
  108160. ol.interaction.KeyboardPan.prototype.setActive);
  108161. goog.exportProperty(
  108162. ol.interaction.KeyboardPan.prototype,
  108163. 'get',
  108164. ol.interaction.KeyboardPan.prototype.get);
  108165. goog.exportProperty(
  108166. ol.interaction.KeyboardPan.prototype,
  108167. 'getKeys',
  108168. ol.interaction.KeyboardPan.prototype.getKeys);
  108169. goog.exportProperty(
  108170. ol.interaction.KeyboardPan.prototype,
  108171. 'getProperties',
  108172. ol.interaction.KeyboardPan.prototype.getProperties);
  108173. goog.exportProperty(
  108174. ol.interaction.KeyboardPan.prototype,
  108175. 'set',
  108176. ol.interaction.KeyboardPan.prototype.set);
  108177. goog.exportProperty(
  108178. ol.interaction.KeyboardPan.prototype,
  108179. 'setProperties',
  108180. ol.interaction.KeyboardPan.prototype.setProperties);
  108181. goog.exportProperty(
  108182. ol.interaction.KeyboardPan.prototype,
  108183. 'unset',
  108184. ol.interaction.KeyboardPan.prototype.unset);
  108185. goog.exportProperty(
  108186. ol.interaction.KeyboardPan.prototype,
  108187. 'changed',
  108188. ol.interaction.KeyboardPan.prototype.changed);
  108189. goog.exportProperty(
  108190. ol.interaction.KeyboardPan.prototype,
  108191. 'getRevision',
  108192. ol.interaction.KeyboardPan.prototype.getRevision);
  108193. goog.exportProperty(
  108194. ol.interaction.KeyboardPan.prototype,
  108195. 'on',
  108196. ol.interaction.KeyboardPan.prototype.on);
  108197. goog.exportProperty(
  108198. ol.interaction.KeyboardPan.prototype,
  108199. 'once',
  108200. ol.interaction.KeyboardPan.prototype.once);
  108201. goog.exportProperty(
  108202. ol.interaction.KeyboardPan.prototype,
  108203. 'un',
  108204. ol.interaction.KeyboardPan.prototype.un);
  108205. goog.exportProperty(
  108206. ol.interaction.KeyboardPan.prototype,
  108207. 'unByKey',
  108208. ol.interaction.KeyboardPan.prototype.unByKey);
  108209. goog.exportProperty(
  108210. ol.interaction.KeyboardZoom.prototype,
  108211. 'getActive',
  108212. ol.interaction.KeyboardZoom.prototype.getActive);
  108213. goog.exportProperty(
  108214. ol.interaction.KeyboardZoom.prototype,
  108215. 'setActive',
  108216. ol.interaction.KeyboardZoom.prototype.setActive);
  108217. goog.exportProperty(
  108218. ol.interaction.KeyboardZoom.prototype,
  108219. 'get',
  108220. ol.interaction.KeyboardZoom.prototype.get);
  108221. goog.exportProperty(
  108222. ol.interaction.KeyboardZoom.prototype,
  108223. 'getKeys',
  108224. ol.interaction.KeyboardZoom.prototype.getKeys);
  108225. goog.exportProperty(
  108226. ol.interaction.KeyboardZoom.prototype,
  108227. 'getProperties',
  108228. ol.interaction.KeyboardZoom.prototype.getProperties);
  108229. goog.exportProperty(
  108230. ol.interaction.KeyboardZoom.prototype,
  108231. 'set',
  108232. ol.interaction.KeyboardZoom.prototype.set);
  108233. goog.exportProperty(
  108234. ol.interaction.KeyboardZoom.prototype,
  108235. 'setProperties',
  108236. ol.interaction.KeyboardZoom.prototype.setProperties);
  108237. goog.exportProperty(
  108238. ol.interaction.KeyboardZoom.prototype,
  108239. 'unset',
  108240. ol.interaction.KeyboardZoom.prototype.unset);
  108241. goog.exportProperty(
  108242. ol.interaction.KeyboardZoom.prototype,
  108243. 'changed',
  108244. ol.interaction.KeyboardZoom.prototype.changed);
  108245. goog.exportProperty(
  108246. ol.interaction.KeyboardZoom.prototype,
  108247. 'getRevision',
  108248. ol.interaction.KeyboardZoom.prototype.getRevision);
  108249. goog.exportProperty(
  108250. ol.interaction.KeyboardZoom.prototype,
  108251. 'on',
  108252. ol.interaction.KeyboardZoom.prototype.on);
  108253. goog.exportProperty(
  108254. ol.interaction.KeyboardZoom.prototype,
  108255. 'once',
  108256. ol.interaction.KeyboardZoom.prototype.once);
  108257. goog.exportProperty(
  108258. ol.interaction.KeyboardZoom.prototype,
  108259. 'un',
  108260. ol.interaction.KeyboardZoom.prototype.un);
  108261. goog.exportProperty(
  108262. ol.interaction.KeyboardZoom.prototype,
  108263. 'unByKey',
  108264. ol.interaction.KeyboardZoom.prototype.unByKey);
  108265. goog.exportProperty(
  108266. ol.interaction.Modify.prototype,
  108267. 'getActive',
  108268. ol.interaction.Modify.prototype.getActive);
  108269. goog.exportProperty(
  108270. ol.interaction.Modify.prototype,
  108271. 'setActive',
  108272. ol.interaction.Modify.prototype.setActive);
  108273. goog.exportProperty(
  108274. ol.interaction.Modify.prototype,
  108275. 'get',
  108276. ol.interaction.Modify.prototype.get);
  108277. goog.exportProperty(
  108278. ol.interaction.Modify.prototype,
  108279. 'getKeys',
  108280. ol.interaction.Modify.prototype.getKeys);
  108281. goog.exportProperty(
  108282. ol.interaction.Modify.prototype,
  108283. 'getProperties',
  108284. ol.interaction.Modify.prototype.getProperties);
  108285. goog.exportProperty(
  108286. ol.interaction.Modify.prototype,
  108287. 'set',
  108288. ol.interaction.Modify.prototype.set);
  108289. goog.exportProperty(
  108290. ol.interaction.Modify.prototype,
  108291. 'setProperties',
  108292. ol.interaction.Modify.prototype.setProperties);
  108293. goog.exportProperty(
  108294. ol.interaction.Modify.prototype,
  108295. 'unset',
  108296. ol.interaction.Modify.prototype.unset);
  108297. goog.exportProperty(
  108298. ol.interaction.Modify.prototype,
  108299. 'changed',
  108300. ol.interaction.Modify.prototype.changed);
  108301. goog.exportProperty(
  108302. ol.interaction.Modify.prototype,
  108303. 'getRevision',
  108304. ol.interaction.Modify.prototype.getRevision);
  108305. goog.exportProperty(
  108306. ol.interaction.Modify.prototype,
  108307. 'on',
  108308. ol.interaction.Modify.prototype.on);
  108309. goog.exportProperty(
  108310. ol.interaction.Modify.prototype,
  108311. 'once',
  108312. ol.interaction.Modify.prototype.once);
  108313. goog.exportProperty(
  108314. ol.interaction.Modify.prototype,
  108315. 'un',
  108316. ol.interaction.Modify.prototype.un);
  108317. goog.exportProperty(
  108318. ol.interaction.Modify.prototype,
  108319. 'unByKey',
  108320. ol.interaction.Modify.prototype.unByKey);
  108321. goog.exportProperty(
  108322. ol.interaction.MouseWheelZoom.prototype,
  108323. 'getActive',
  108324. ol.interaction.MouseWheelZoom.prototype.getActive);
  108325. goog.exportProperty(
  108326. ol.interaction.MouseWheelZoom.prototype,
  108327. 'setActive',
  108328. ol.interaction.MouseWheelZoom.prototype.setActive);
  108329. goog.exportProperty(
  108330. ol.interaction.MouseWheelZoom.prototype,
  108331. 'get',
  108332. ol.interaction.MouseWheelZoom.prototype.get);
  108333. goog.exportProperty(
  108334. ol.interaction.MouseWheelZoom.prototype,
  108335. 'getKeys',
  108336. ol.interaction.MouseWheelZoom.prototype.getKeys);
  108337. goog.exportProperty(
  108338. ol.interaction.MouseWheelZoom.prototype,
  108339. 'getProperties',
  108340. ol.interaction.MouseWheelZoom.prototype.getProperties);
  108341. goog.exportProperty(
  108342. ol.interaction.MouseWheelZoom.prototype,
  108343. 'set',
  108344. ol.interaction.MouseWheelZoom.prototype.set);
  108345. goog.exportProperty(
  108346. ol.interaction.MouseWheelZoom.prototype,
  108347. 'setProperties',
  108348. ol.interaction.MouseWheelZoom.prototype.setProperties);
  108349. goog.exportProperty(
  108350. ol.interaction.MouseWheelZoom.prototype,
  108351. 'unset',
  108352. ol.interaction.MouseWheelZoom.prototype.unset);
  108353. goog.exportProperty(
  108354. ol.interaction.MouseWheelZoom.prototype,
  108355. 'changed',
  108356. ol.interaction.MouseWheelZoom.prototype.changed);
  108357. goog.exportProperty(
  108358. ol.interaction.MouseWheelZoom.prototype,
  108359. 'getRevision',
  108360. ol.interaction.MouseWheelZoom.prototype.getRevision);
  108361. goog.exportProperty(
  108362. ol.interaction.MouseWheelZoom.prototype,
  108363. 'on',
  108364. ol.interaction.MouseWheelZoom.prototype.on);
  108365. goog.exportProperty(
  108366. ol.interaction.MouseWheelZoom.prototype,
  108367. 'once',
  108368. ol.interaction.MouseWheelZoom.prototype.once);
  108369. goog.exportProperty(
  108370. ol.interaction.MouseWheelZoom.prototype,
  108371. 'un',
  108372. ol.interaction.MouseWheelZoom.prototype.un);
  108373. goog.exportProperty(
  108374. ol.interaction.MouseWheelZoom.prototype,
  108375. 'unByKey',
  108376. ol.interaction.MouseWheelZoom.prototype.unByKey);
  108377. goog.exportProperty(
  108378. ol.interaction.PinchRotate.prototype,
  108379. 'getActive',
  108380. ol.interaction.PinchRotate.prototype.getActive);
  108381. goog.exportProperty(
  108382. ol.interaction.PinchRotate.prototype,
  108383. 'setActive',
  108384. ol.interaction.PinchRotate.prototype.setActive);
  108385. goog.exportProperty(
  108386. ol.interaction.PinchRotate.prototype,
  108387. 'get',
  108388. ol.interaction.PinchRotate.prototype.get);
  108389. goog.exportProperty(
  108390. ol.interaction.PinchRotate.prototype,
  108391. 'getKeys',
  108392. ol.interaction.PinchRotate.prototype.getKeys);
  108393. goog.exportProperty(
  108394. ol.interaction.PinchRotate.prototype,
  108395. 'getProperties',
  108396. ol.interaction.PinchRotate.prototype.getProperties);
  108397. goog.exportProperty(
  108398. ol.interaction.PinchRotate.prototype,
  108399. 'set',
  108400. ol.interaction.PinchRotate.prototype.set);
  108401. goog.exportProperty(
  108402. ol.interaction.PinchRotate.prototype,
  108403. 'setProperties',
  108404. ol.interaction.PinchRotate.prototype.setProperties);
  108405. goog.exportProperty(
  108406. ol.interaction.PinchRotate.prototype,
  108407. 'unset',
  108408. ol.interaction.PinchRotate.prototype.unset);
  108409. goog.exportProperty(
  108410. ol.interaction.PinchRotate.prototype,
  108411. 'changed',
  108412. ol.interaction.PinchRotate.prototype.changed);
  108413. goog.exportProperty(
  108414. ol.interaction.PinchRotate.prototype,
  108415. 'getRevision',
  108416. ol.interaction.PinchRotate.prototype.getRevision);
  108417. goog.exportProperty(
  108418. ol.interaction.PinchRotate.prototype,
  108419. 'on',
  108420. ol.interaction.PinchRotate.prototype.on);
  108421. goog.exportProperty(
  108422. ol.interaction.PinchRotate.prototype,
  108423. 'once',
  108424. ol.interaction.PinchRotate.prototype.once);
  108425. goog.exportProperty(
  108426. ol.interaction.PinchRotate.prototype,
  108427. 'un',
  108428. ol.interaction.PinchRotate.prototype.un);
  108429. goog.exportProperty(
  108430. ol.interaction.PinchRotate.prototype,
  108431. 'unByKey',
  108432. ol.interaction.PinchRotate.prototype.unByKey);
  108433. goog.exportProperty(
  108434. ol.interaction.PinchZoom.prototype,
  108435. 'getActive',
  108436. ol.interaction.PinchZoom.prototype.getActive);
  108437. goog.exportProperty(
  108438. ol.interaction.PinchZoom.prototype,
  108439. 'setActive',
  108440. ol.interaction.PinchZoom.prototype.setActive);
  108441. goog.exportProperty(
  108442. ol.interaction.PinchZoom.prototype,
  108443. 'get',
  108444. ol.interaction.PinchZoom.prototype.get);
  108445. goog.exportProperty(
  108446. ol.interaction.PinchZoom.prototype,
  108447. 'getKeys',
  108448. ol.interaction.PinchZoom.prototype.getKeys);
  108449. goog.exportProperty(
  108450. ol.interaction.PinchZoom.prototype,
  108451. 'getProperties',
  108452. ol.interaction.PinchZoom.prototype.getProperties);
  108453. goog.exportProperty(
  108454. ol.interaction.PinchZoom.prototype,
  108455. 'set',
  108456. ol.interaction.PinchZoom.prototype.set);
  108457. goog.exportProperty(
  108458. ol.interaction.PinchZoom.prototype,
  108459. 'setProperties',
  108460. ol.interaction.PinchZoom.prototype.setProperties);
  108461. goog.exportProperty(
  108462. ol.interaction.PinchZoom.prototype,
  108463. 'unset',
  108464. ol.interaction.PinchZoom.prototype.unset);
  108465. goog.exportProperty(
  108466. ol.interaction.PinchZoom.prototype,
  108467. 'changed',
  108468. ol.interaction.PinchZoom.prototype.changed);
  108469. goog.exportProperty(
  108470. ol.interaction.PinchZoom.prototype,
  108471. 'getRevision',
  108472. ol.interaction.PinchZoom.prototype.getRevision);
  108473. goog.exportProperty(
  108474. ol.interaction.PinchZoom.prototype,
  108475. 'on',
  108476. ol.interaction.PinchZoom.prototype.on);
  108477. goog.exportProperty(
  108478. ol.interaction.PinchZoom.prototype,
  108479. 'once',
  108480. ol.interaction.PinchZoom.prototype.once);
  108481. goog.exportProperty(
  108482. ol.interaction.PinchZoom.prototype,
  108483. 'un',
  108484. ol.interaction.PinchZoom.prototype.un);
  108485. goog.exportProperty(
  108486. ol.interaction.PinchZoom.prototype,
  108487. 'unByKey',
  108488. ol.interaction.PinchZoom.prototype.unByKey);
  108489. goog.exportProperty(
  108490. ol.interaction.Select.prototype,
  108491. 'getActive',
  108492. ol.interaction.Select.prototype.getActive);
  108493. goog.exportProperty(
  108494. ol.interaction.Select.prototype,
  108495. 'setActive',
  108496. ol.interaction.Select.prototype.setActive);
  108497. goog.exportProperty(
  108498. ol.interaction.Select.prototype,
  108499. 'get',
  108500. ol.interaction.Select.prototype.get);
  108501. goog.exportProperty(
  108502. ol.interaction.Select.prototype,
  108503. 'getKeys',
  108504. ol.interaction.Select.prototype.getKeys);
  108505. goog.exportProperty(
  108506. ol.interaction.Select.prototype,
  108507. 'getProperties',
  108508. ol.interaction.Select.prototype.getProperties);
  108509. goog.exportProperty(
  108510. ol.interaction.Select.prototype,
  108511. 'set',
  108512. ol.interaction.Select.prototype.set);
  108513. goog.exportProperty(
  108514. ol.interaction.Select.prototype,
  108515. 'setProperties',
  108516. ol.interaction.Select.prototype.setProperties);
  108517. goog.exportProperty(
  108518. ol.interaction.Select.prototype,
  108519. 'unset',
  108520. ol.interaction.Select.prototype.unset);
  108521. goog.exportProperty(
  108522. ol.interaction.Select.prototype,
  108523. 'changed',
  108524. ol.interaction.Select.prototype.changed);
  108525. goog.exportProperty(
  108526. ol.interaction.Select.prototype,
  108527. 'getRevision',
  108528. ol.interaction.Select.prototype.getRevision);
  108529. goog.exportProperty(
  108530. ol.interaction.Select.prototype,
  108531. 'on',
  108532. ol.interaction.Select.prototype.on);
  108533. goog.exportProperty(
  108534. ol.interaction.Select.prototype,
  108535. 'once',
  108536. ol.interaction.Select.prototype.once);
  108537. goog.exportProperty(
  108538. ol.interaction.Select.prototype,
  108539. 'un',
  108540. ol.interaction.Select.prototype.un);
  108541. goog.exportProperty(
  108542. ol.interaction.Select.prototype,
  108543. 'unByKey',
  108544. ol.interaction.Select.prototype.unByKey);
  108545. goog.exportProperty(
  108546. ol.interaction.Snap.prototype,
  108547. 'getActive',
  108548. ol.interaction.Snap.prototype.getActive);
  108549. goog.exportProperty(
  108550. ol.interaction.Snap.prototype,
  108551. 'setActive',
  108552. ol.interaction.Snap.prototype.setActive);
  108553. goog.exportProperty(
  108554. ol.interaction.Snap.prototype,
  108555. 'get',
  108556. ol.interaction.Snap.prototype.get);
  108557. goog.exportProperty(
  108558. ol.interaction.Snap.prototype,
  108559. 'getKeys',
  108560. ol.interaction.Snap.prototype.getKeys);
  108561. goog.exportProperty(
  108562. ol.interaction.Snap.prototype,
  108563. 'getProperties',
  108564. ol.interaction.Snap.prototype.getProperties);
  108565. goog.exportProperty(
  108566. ol.interaction.Snap.prototype,
  108567. 'set',
  108568. ol.interaction.Snap.prototype.set);
  108569. goog.exportProperty(
  108570. ol.interaction.Snap.prototype,
  108571. 'setProperties',
  108572. ol.interaction.Snap.prototype.setProperties);
  108573. goog.exportProperty(
  108574. ol.interaction.Snap.prototype,
  108575. 'unset',
  108576. ol.interaction.Snap.prototype.unset);
  108577. goog.exportProperty(
  108578. ol.interaction.Snap.prototype,
  108579. 'changed',
  108580. ol.interaction.Snap.prototype.changed);
  108581. goog.exportProperty(
  108582. ol.interaction.Snap.prototype,
  108583. 'getRevision',
  108584. ol.interaction.Snap.prototype.getRevision);
  108585. goog.exportProperty(
  108586. ol.interaction.Snap.prototype,
  108587. 'on',
  108588. ol.interaction.Snap.prototype.on);
  108589. goog.exportProperty(
  108590. ol.interaction.Snap.prototype,
  108591. 'once',
  108592. ol.interaction.Snap.prototype.once);
  108593. goog.exportProperty(
  108594. ol.interaction.Snap.prototype,
  108595. 'un',
  108596. ol.interaction.Snap.prototype.un);
  108597. goog.exportProperty(
  108598. ol.interaction.Snap.prototype,
  108599. 'unByKey',
  108600. ol.interaction.Snap.prototype.unByKey);
  108601. goog.exportProperty(
  108602. ol.interaction.Translate.prototype,
  108603. 'getActive',
  108604. ol.interaction.Translate.prototype.getActive);
  108605. goog.exportProperty(
  108606. ol.interaction.Translate.prototype,
  108607. 'setActive',
  108608. ol.interaction.Translate.prototype.setActive);
  108609. goog.exportProperty(
  108610. ol.interaction.Translate.prototype,
  108611. 'get',
  108612. ol.interaction.Translate.prototype.get);
  108613. goog.exportProperty(
  108614. ol.interaction.Translate.prototype,
  108615. 'getKeys',
  108616. ol.interaction.Translate.prototype.getKeys);
  108617. goog.exportProperty(
  108618. ol.interaction.Translate.prototype,
  108619. 'getProperties',
  108620. ol.interaction.Translate.prototype.getProperties);
  108621. goog.exportProperty(
  108622. ol.interaction.Translate.prototype,
  108623. 'set',
  108624. ol.interaction.Translate.prototype.set);
  108625. goog.exportProperty(
  108626. ol.interaction.Translate.prototype,
  108627. 'setProperties',
  108628. ol.interaction.Translate.prototype.setProperties);
  108629. goog.exportProperty(
  108630. ol.interaction.Translate.prototype,
  108631. 'unset',
  108632. ol.interaction.Translate.prototype.unset);
  108633. goog.exportProperty(
  108634. ol.interaction.Translate.prototype,
  108635. 'changed',
  108636. ol.interaction.Translate.prototype.changed);
  108637. goog.exportProperty(
  108638. ol.interaction.Translate.prototype,
  108639. 'getRevision',
  108640. ol.interaction.Translate.prototype.getRevision);
  108641. goog.exportProperty(
  108642. ol.interaction.Translate.prototype,
  108643. 'on',
  108644. ol.interaction.Translate.prototype.on);
  108645. goog.exportProperty(
  108646. ol.interaction.Translate.prototype,
  108647. 'once',
  108648. ol.interaction.Translate.prototype.once);
  108649. goog.exportProperty(
  108650. ol.interaction.Translate.prototype,
  108651. 'un',
  108652. ol.interaction.Translate.prototype.un);
  108653. goog.exportProperty(
  108654. ol.interaction.Translate.prototype,
  108655. 'unByKey',
  108656. ol.interaction.Translate.prototype.unByKey);
  108657. goog.exportProperty(
  108658. ol.geom.Geometry.prototype,
  108659. 'get',
  108660. ol.geom.Geometry.prototype.get);
  108661. goog.exportProperty(
  108662. ol.geom.Geometry.prototype,
  108663. 'getKeys',
  108664. ol.geom.Geometry.prototype.getKeys);
  108665. goog.exportProperty(
  108666. ol.geom.Geometry.prototype,
  108667. 'getProperties',
  108668. ol.geom.Geometry.prototype.getProperties);
  108669. goog.exportProperty(
  108670. ol.geom.Geometry.prototype,
  108671. 'set',
  108672. ol.geom.Geometry.prototype.set);
  108673. goog.exportProperty(
  108674. ol.geom.Geometry.prototype,
  108675. 'setProperties',
  108676. ol.geom.Geometry.prototype.setProperties);
  108677. goog.exportProperty(
  108678. ol.geom.Geometry.prototype,
  108679. 'unset',
  108680. ol.geom.Geometry.prototype.unset);
  108681. goog.exportProperty(
  108682. ol.geom.Geometry.prototype,
  108683. 'changed',
  108684. ol.geom.Geometry.prototype.changed);
  108685. goog.exportProperty(
  108686. ol.geom.Geometry.prototype,
  108687. 'getRevision',
  108688. ol.geom.Geometry.prototype.getRevision);
  108689. goog.exportProperty(
  108690. ol.geom.Geometry.prototype,
  108691. 'on',
  108692. ol.geom.Geometry.prototype.on);
  108693. goog.exportProperty(
  108694. ol.geom.Geometry.prototype,
  108695. 'once',
  108696. ol.geom.Geometry.prototype.once);
  108697. goog.exportProperty(
  108698. ol.geom.Geometry.prototype,
  108699. 'un',
  108700. ol.geom.Geometry.prototype.un);
  108701. goog.exportProperty(
  108702. ol.geom.Geometry.prototype,
  108703. 'unByKey',
  108704. ol.geom.Geometry.prototype.unByKey);
  108705. goog.exportProperty(
  108706. ol.geom.SimpleGeometry.prototype,
  108707. 'getClosestPoint',
  108708. ol.geom.SimpleGeometry.prototype.getClosestPoint);
  108709. goog.exportProperty(
  108710. ol.geom.SimpleGeometry.prototype,
  108711. 'getExtent',
  108712. ol.geom.SimpleGeometry.prototype.getExtent);
  108713. goog.exportProperty(
  108714. ol.geom.SimpleGeometry.prototype,
  108715. 'simplify',
  108716. ol.geom.SimpleGeometry.prototype.simplify);
  108717. goog.exportProperty(
  108718. ol.geom.SimpleGeometry.prototype,
  108719. 'transform',
  108720. ol.geom.SimpleGeometry.prototype.transform);
  108721. goog.exportProperty(
  108722. ol.geom.SimpleGeometry.prototype,
  108723. 'get',
  108724. ol.geom.SimpleGeometry.prototype.get);
  108725. goog.exportProperty(
  108726. ol.geom.SimpleGeometry.prototype,
  108727. 'getKeys',
  108728. ol.geom.SimpleGeometry.prototype.getKeys);
  108729. goog.exportProperty(
  108730. ol.geom.SimpleGeometry.prototype,
  108731. 'getProperties',
  108732. ol.geom.SimpleGeometry.prototype.getProperties);
  108733. goog.exportProperty(
  108734. ol.geom.SimpleGeometry.prototype,
  108735. 'set',
  108736. ol.geom.SimpleGeometry.prototype.set);
  108737. goog.exportProperty(
  108738. ol.geom.SimpleGeometry.prototype,
  108739. 'setProperties',
  108740. ol.geom.SimpleGeometry.prototype.setProperties);
  108741. goog.exportProperty(
  108742. ol.geom.SimpleGeometry.prototype,
  108743. 'unset',
  108744. ol.geom.SimpleGeometry.prototype.unset);
  108745. goog.exportProperty(
  108746. ol.geom.SimpleGeometry.prototype,
  108747. 'changed',
  108748. ol.geom.SimpleGeometry.prototype.changed);
  108749. goog.exportProperty(
  108750. ol.geom.SimpleGeometry.prototype,
  108751. 'getRevision',
  108752. ol.geom.SimpleGeometry.prototype.getRevision);
  108753. goog.exportProperty(
  108754. ol.geom.SimpleGeometry.prototype,
  108755. 'on',
  108756. ol.geom.SimpleGeometry.prototype.on);
  108757. goog.exportProperty(
  108758. ol.geom.SimpleGeometry.prototype,
  108759. 'once',
  108760. ol.geom.SimpleGeometry.prototype.once);
  108761. goog.exportProperty(
  108762. ol.geom.SimpleGeometry.prototype,
  108763. 'un',
  108764. ol.geom.SimpleGeometry.prototype.un);
  108765. goog.exportProperty(
  108766. ol.geom.SimpleGeometry.prototype,
  108767. 'unByKey',
  108768. ol.geom.SimpleGeometry.prototype.unByKey);
  108769. goog.exportProperty(
  108770. ol.geom.Circle.prototype,
  108771. 'getFirstCoordinate',
  108772. ol.geom.Circle.prototype.getFirstCoordinate);
  108773. goog.exportProperty(
  108774. ol.geom.Circle.prototype,
  108775. 'getLastCoordinate',
  108776. ol.geom.Circle.prototype.getLastCoordinate);
  108777. goog.exportProperty(
  108778. ol.geom.Circle.prototype,
  108779. 'getLayout',
  108780. ol.geom.Circle.prototype.getLayout);
  108781. goog.exportProperty(
  108782. ol.geom.Circle.prototype,
  108783. 'getClosestPoint',
  108784. ol.geom.Circle.prototype.getClosestPoint);
  108785. goog.exportProperty(
  108786. ol.geom.Circle.prototype,
  108787. 'getExtent',
  108788. ol.geom.Circle.prototype.getExtent);
  108789. goog.exportProperty(
  108790. ol.geom.Circle.prototype,
  108791. 'simplify',
  108792. ol.geom.Circle.prototype.simplify);
  108793. goog.exportProperty(
  108794. ol.geom.Circle.prototype,
  108795. 'get',
  108796. ol.geom.Circle.prototype.get);
  108797. goog.exportProperty(
  108798. ol.geom.Circle.prototype,
  108799. 'getKeys',
  108800. ol.geom.Circle.prototype.getKeys);
  108801. goog.exportProperty(
  108802. ol.geom.Circle.prototype,
  108803. 'getProperties',
  108804. ol.geom.Circle.prototype.getProperties);
  108805. goog.exportProperty(
  108806. ol.geom.Circle.prototype,
  108807. 'set',
  108808. ol.geom.Circle.prototype.set);
  108809. goog.exportProperty(
  108810. ol.geom.Circle.prototype,
  108811. 'setProperties',
  108812. ol.geom.Circle.prototype.setProperties);
  108813. goog.exportProperty(
  108814. ol.geom.Circle.prototype,
  108815. 'unset',
  108816. ol.geom.Circle.prototype.unset);
  108817. goog.exportProperty(
  108818. ol.geom.Circle.prototype,
  108819. 'changed',
  108820. ol.geom.Circle.prototype.changed);
  108821. goog.exportProperty(
  108822. ol.geom.Circle.prototype,
  108823. 'getRevision',
  108824. ol.geom.Circle.prototype.getRevision);
  108825. goog.exportProperty(
  108826. ol.geom.Circle.prototype,
  108827. 'on',
  108828. ol.geom.Circle.prototype.on);
  108829. goog.exportProperty(
  108830. ol.geom.Circle.prototype,
  108831. 'once',
  108832. ol.geom.Circle.prototype.once);
  108833. goog.exportProperty(
  108834. ol.geom.Circle.prototype,
  108835. 'un',
  108836. ol.geom.Circle.prototype.un);
  108837. goog.exportProperty(
  108838. ol.geom.Circle.prototype,
  108839. 'unByKey',
  108840. ol.geom.Circle.prototype.unByKey);
  108841. goog.exportProperty(
  108842. ol.geom.GeometryCollection.prototype,
  108843. 'getClosestPoint',
  108844. ol.geom.GeometryCollection.prototype.getClosestPoint);
  108845. goog.exportProperty(
  108846. ol.geom.GeometryCollection.prototype,
  108847. 'getExtent',
  108848. ol.geom.GeometryCollection.prototype.getExtent);
  108849. goog.exportProperty(
  108850. ol.geom.GeometryCollection.prototype,
  108851. 'simplify',
  108852. ol.geom.GeometryCollection.prototype.simplify);
  108853. goog.exportProperty(
  108854. ol.geom.GeometryCollection.prototype,
  108855. 'transform',
  108856. ol.geom.GeometryCollection.prototype.transform);
  108857. goog.exportProperty(
  108858. ol.geom.GeometryCollection.prototype,
  108859. 'get',
  108860. ol.geom.GeometryCollection.prototype.get);
  108861. goog.exportProperty(
  108862. ol.geom.GeometryCollection.prototype,
  108863. 'getKeys',
  108864. ol.geom.GeometryCollection.prototype.getKeys);
  108865. goog.exportProperty(
  108866. ol.geom.GeometryCollection.prototype,
  108867. 'getProperties',
  108868. ol.geom.GeometryCollection.prototype.getProperties);
  108869. goog.exportProperty(
  108870. ol.geom.GeometryCollection.prototype,
  108871. 'set',
  108872. ol.geom.GeometryCollection.prototype.set);
  108873. goog.exportProperty(
  108874. ol.geom.GeometryCollection.prototype,
  108875. 'setProperties',
  108876. ol.geom.GeometryCollection.prototype.setProperties);
  108877. goog.exportProperty(
  108878. ol.geom.GeometryCollection.prototype,
  108879. 'unset',
  108880. ol.geom.GeometryCollection.prototype.unset);
  108881. goog.exportProperty(
  108882. ol.geom.GeometryCollection.prototype,
  108883. 'changed',
  108884. ol.geom.GeometryCollection.prototype.changed);
  108885. goog.exportProperty(
  108886. ol.geom.GeometryCollection.prototype,
  108887. 'getRevision',
  108888. ol.geom.GeometryCollection.prototype.getRevision);
  108889. goog.exportProperty(
  108890. ol.geom.GeometryCollection.prototype,
  108891. 'on',
  108892. ol.geom.GeometryCollection.prototype.on);
  108893. goog.exportProperty(
  108894. ol.geom.GeometryCollection.prototype,
  108895. 'once',
  108896. ol.geom.GeometryCollection.prototype.once);
  108897. goog.exportProperty(
  108898. ol.geom.GeometryCollection.prototype,
  108899. 'un',
  108900. ol.geom.GeometryCollection.prototype.un);
  108901. goog.exportProperty(
  108902. ol.geom.GeometryCollection.prototype,
  108903. 'unByKey',
  108904. ol.geom.GeometryCollection.prototype.unByKey);
  108905. goog.exportProperty(
  108906. ol.geom.LinearRing.prototype,
  108907. 'getFirstCoordinate',
  108908. ol.geom.LinearRing.prototype.getFirstCoordinate);
  108909. goog.exportProperty(
  108910. ol.geom.LinearRing.prototype,
  108911. 'getLastCoordinate',
  108912. ol.geom.LinearRing.prototype.getLastCoordinate);
  108913. goog.exportProperty(
  108914. ol.geom.LinearRing.prototype,
  108915. 'getLayout',
  108916. ol.geom.LinearRing.prototype.getLayout);
  108917. goog.exportProperty(
  108918. ol.geom.LinearRing.prototype,
  108919. 'getClosestPoint',
  108920. ol.geom.LinearRing.prototype.getClosestPoint);
  108921. goog.exportProperty(
  108922. ol.geom.LinearRing.prototype,
  108923. 'getExtent',
  108924. ol.geom.LinearRing.prototype.getExtent);
  108925. goog.exportProperty(
  108926. ol.geom.LinearRing.prototype,
  108927. 'simplify',
  108928. ol.geom.LinearRing.prototype.simplify);
  108929. goog.exportProperty(
  108930. ol.geom.LinearRing.prototype,
  108931. 'transform',
  108932. ol.geom.LinearRing.prototype.transform);
  108933. goog.exportProperty(
  108934. ol.geom.LinearRing.prototype,
  108935. 'get',
  108936. ol.geom.LinearRing.prototype.get);
  108937. goog.exportProperty(
  108938. ol.geom.LinearRing.prototype,
  108939. 'getKeys',
  108940. ol.geom.LinearRing.prototype.getKeys);
  108941. goog.exportProperty(
  108942. ol.geom.LinearRing.prototype,
  108943. 'getProperties',
  108944. ol.geom.LinearRing.prototype.getProperties);
  108945. goog.exportProperty(
  108946. ol.geom.LinearRing.prototype,
  108947. 'set',
  108948. ol.geom.LinearRing.prototype.set);
  108949. goog.exportProperty(
  108950. ol.geom.LinearRing.prototype,
  108951. 'setProperties',
  108952. ol.geom.LinearRing.prototype.setProperties);
  108953. goog.exportProperty(
  108954. ol.geom.LinearRing.prototype,
  108955. 'unset',
  108956. ol.geom.LinearRing.prototype.unset);
  108957. goog.exportProperty(
  108958. ol.geom.LinearRing.prototype,
  108959. 'changed',
  108960. ol.geom.LinearRing.prototype.changed);
  108961. goog.exportProperty(
  108962. ol.geom.LinearRing.prototype,
  108963. 'getRevision',
  108964. ol.geom.LinearRing.prototype.getRevision);
  108965. goog.exportProperty(
  108966. ol.geom.LinearRing.prototype,
  108967. 'on',
  108968. ol.geom.LinearRing.prototype.on);
  108969. goog.exportProperty(
  108970. ol.geom.LinearRing.prototype,
  108971. 'once',
  108972. ol.geom.LinearRing.prototype.once);
  108973. goog.exportProperty(
  108974. ol.geom.LinearRing.prototype,
  108975. 'un',
  108976. ol.geom.LinearRing.prototype.un);
  108977. goog.exportProperty(
  108978. ol.geom.LinearRing.prototype,
  108979. 'unByKey',
  108980. ol.geom.LinearRing.prototype.unByKey);
  108981. goog.exportProperty(
  108982. ol.geom.LineString.prototype,
  108983. 'getFirstCoordinate',
  108984. ol.geom.LineString.prototype.getFirstCoordinate);
  108985. goog.exportProperty(
  108986. ol.geom.LineString.prototype,
  108987. 'getLastCoordinate',
  108988. ol.geom.LineString.prototype.getLastCoordinate);
  108989. goog.exportProperty(
  108990. ol.geom.LineString.prototype,
  108991. 'getLayout',
  108992. ol.geom.LineString.prototype.getLayout);
  108993. goog.exportProperty(
  108994. ol.geom.LineString.prototype,
  108995. 'getClosestPoint',
  108996. ol.geom.LineString.prototype.getClosestPoint);
  108997. goog.exportProperty(
  108998. ol.geom.LineString.prototype,
  108999. 'getExtent',
  109000. ol.geom.LineString.prototype.getExtent);
  109001. goog.exportProperty(
  109002. ol.geom.LineString.prototype,
  109003. 'simplify',
  109004. ol.geom.LineString.prototype.simplify);
  109005. goog.exportProperty(
  109006. ol.geom.LineString.prototype,
  109007. 'transform',
  109008. ol.geom.LineString.prototype.transform);
  109009. goog.exportProperty(
  109010. ol.geom.LineString.prototype,
  109011. 'get',
  109012. ol.geom.LineString.prototype.get);
  109013. goog.exportProperty(
  109014. ol.geom.LineString.prototype,
  109015. 'getKeys',
  109016. ol.geom.LineString.prototype.getKeys);
  109017. goog.exportProperty(
  109018. ol.geom.LineString.prototype,
  109019. 'getProperties',
  109020. ol.geom.LineString.prototype.getProperties);
  109021. goog.exportProperty(
  109022. ol.geom.LineString.prototype,
  109023. 'set',
  109024. ol.geom.LineString.prototype.set);
  109025. goog.exportProperty(
  109026. ol.geom.LineString.prototype,
  109027. 'setProperties',
  109028. ol.geom.LineString.prototype.setProperties);
  109029. goog.exportProperty(
  109030. ol.geom.LineString.prototype,
  109031. 'unset',
  109032. ol.geom.LineString.prototype.unset);
  109033. goog.exportProperty(
  109034. ol.geom.LineString.prototype,
  109035. 'changed',
  109036. ol.geom.LineString.prototype.changed);
  109037. goog.exportProperty(
  109038. ol.geom.LineString.prototype,
  109039. 'getRevision',
  109040. ol.geom.LineString.prototype.getRevision);
  109041. goog.exportProperty(
  109042. ol.geom.LineString.prototype,
  109043. 'on',
  109044. ol.geom.LineString.prototype.on);
  109045. goog.exportProperty(
  109046. ol.geom.LineString.prototype,
  109047. 'once',
  109048. ol.geom.LineString.prototype.once);
  109049. goog.exportProperty(
  109050. ol.geom.LineString.prototype,
  109051. 'un',
  109052. ol.geom.LineString.prototype.un);
  109053. goog.exportProperty(
  109054. ol.geom.LineString.prototype,
  109055. 'unByKey',
  109056. ol.geom.LineString.prototype.unByKey);
  109057. goog.exportProperty(
  109058. ol.geom.MultiLineString.prototype,
  109059. 'getFirstCoordinate',
  109060. ol.geom.MultiLineString.prototype.getFirstCoordinate);
  109061. goog.exportProperty(
  109062. ol.geom.MultiLineString.prototype,
  109063. 'getLastCoordinate',
  109064. ol.geom.MultiLineString.prototype.getLastCoordinate);
  109065. goog.exportProperty(
  109066. ol.geom.MultiLineString.prototype,
  109067. 'getLayout',
  109068. ol.geom.MultiLineString.prototype.getLayout);
  109069. goog.exportProperty(
  109070. ol.geom.MultiLineString.prototype,
  109071. 'getClosestPoint',
  109072. ol.geom.MultiLineString.prototype.getClosestPoint);
  109073. goog.exportProperty(
  109074. ol.geom.MultiLineString.prototype,
  109075. 'getExtent',
  109076. ol.geom.MultiLineString.prototype.getExtent);
  109077. goog.exportProperty(
  109078. ol.geom.MultiLineString.prototype,
  109079. 'simplify',
  109080. ol.geom.MultiLineString.prototype.simplify);
  109081. goog.exportProperty(
  109082. ol.geom.MultiLineString.prototype,
  109083. 'transform',
  109084. ol.geom.MultiLineString.prototype.transform);
  109085. goog.exportProperty(
  109086. ol.geom.MultiLineString.prototype,
  109087. 'get',
  109088. ol.geom.MultiLineString.prototype.get);
  109089. goog.exportProperty(
  109090. ol.geom.MultiLineString.prototype,
  109091. 'getKeys',
  109092. ol.geom.MultiLineString.prototype.getKeys);
  109093. goog.exportProperty(
  109094. ol.geom.MultiLineString.prototype,
  109095. 'getProperties',
  109096. ol.geom.MultiLineString.prototype.getProperties);
  109097. goog.exportProperty(
  109098. ol.geom.MultiLineString.prototype,
  109099. 'set',
  109100. ol.geom.MultiLineString.prototype.set);
  109101. goog.exportProperty(
  109102. ol.geom.MultiLineString.prototype,
  109103. 'setProperties',
  109104. ol.geom.MultiLineString.prototype.setProperties);
  109105. goog.exportProperty(
  109106. ol.geom.MultiLineString.prototype,
  109107. 'unset',
  109108. ol.geom.MultiLineString.prototype.unset);
  109109. goog.exportProperty(
  109110. ol.geom.MultiLineString.prototype,
  109111. 'changed',
  109112. ol.geom.MultiLineString.prototype.changed);
  109113. goog.exportProperty(
  109114. ol.geom.MultiLineString.prototype,
  109115. 'getRevision',
  109116. ol.geom.MultiLineString.prototype.getRevision);
  109117. goog.exportProperty(
  109118. ol.geom.MultiLineString.prototype,
  109119. 'on',
  109120. ol.geom.MultiLineString.prototype.on);
  109121. goog.exportProperty(
  109122. ol.geom.MultiLineString.prototype,
  109123. 'once',
  109124. ol.geom.MultiLineString.prototype.once);
  109125. goog.exportProperty(
  109126. ol.geom.MultiLineString.prototype,
  109127. 'un',
  109128. ol.geom.MultiLineString.prototype.un);
  109129. goog.exportProperty(
  109130. ol.geom.MultiLineString.prototype,
  109131. 'unByKey',
  109132. ol.geom.MultiLineString.prototype.unByKey);
  109133. goog.exportProperty(
  109134. ol.geom.MultiPoint.prototype,
  109135. 'getFirstCoordinate',
  109136. ol.geom.MultiPoint.prototype.getFirstCoordinate);
  109137. goog.exportProperty(
  109138. ol.geom.MultiPoint.prototype,
  109139. 'getLastCoordinate',
  109140. ol.geom.MultiPoint.prototype.getLastCoordinate);
  109141. goog.exportProperty(
  109142. ol.geom.MultiPoint.prototype,
  109143. 'getLayout',
  109144. ol.geom.MultiPoint.prototype.getLayout);
  109145. goog.exportProperty(
  109146. ol.geom.MultiPoint.prototype,
  109147. 'getClosestPoint',
  109148. ol.geom.MultiPoint.prototype.getClosestPoint);
  109149. goog.exportProperty(
  109150. ol.geom.MultiPoint.prototype,
  109151. 'getExtent',
  109152. ol.geom.MultiPoint.prototype.getExtent);
  109153. goog.exportProperty(
  109154. ol.geom.MultiPoint.prototype,
  109155. 'simplify',
  109156. ol.geom.MultiPoint.prototype.simplify);
  109157. goog.exportProperty(
  109158. ol.geom.MultiPoint.prototype,
  109159. 'transform',
  109160. ol.geom.MultiPoint.prototype.transform);
  109161. goog.exportProperty(
  109162. ol.geom.MultiPoint.prototype,
  109163. 'get',
  109164. ol.geom.MultiPoint.prototype.get);
  109165. goog.exportProperty(
  109166. ol.geom.MultiPoint.prototype,
  109167. 'getKeys',
  109168. ol.geom.MultiPoint.prototype.getKeys);
  109169. goog.exportProperty(
  109170. ol.geom.MultiPoint.prototype,
  109171. 'getProperties',
  109172. ol.geom.MultiPoint.prototype.getProperties);
  109173. goog.exportProperty(
  109174. ol.geom.MultiPoint.prototype,
  109175. 'set',
  109176. ol.geom.MultiPoint.prototype.set);
  109177. goog.exportProperty(
  109178. ol.geom.MultiPoint.prototype,
  109179. 'setProperties',
  109180. ol.geom.MultiPoint.prototype.setProperties);
  109181. goog.exportProperty(
  109182. ol.geom.MultiPoint.prototype,
  109183. 'unset',
  109184. ol.geom.MultiPoint.prototype.unset);
  109185. goog.exportProperty(
  109186. ol.geom.MultiPoint.prototype,
  109187. 'changed',
  109188. ol.geom.MultiPoint.prototype.changed);
  109189. goog.exportProperty(
  109190. ol.geom.MultiPoint.prototype,
  109191. 'getRevision',
  109192. ol.geom.MultiPoint.prototype.getRevision);
  109193. goog.exportProperty(
  109194. ol.geom.MultiPoint.prototype,
  109195. 'on',
  109196. ol.geom.MultiPoint.prototype.on);
  109197. goog.exportProperty(
  109198. ol.geom.MultiPoint.prototype,
  109199. 'once',
  109200. ol.geom.MultiPoint.prototype.once);
  109201. goog.exportProperty(
  109202. ol.geom.MultiPoint.prototype,
  109203. 'un',
  109204. ol.geom.MultiPoint.prototype.un);
  109205. goog.exportProperty(
  109206. ol.geom.MultiPoint.prototype,
  109207. 'unByKey',
  109208. ol.geom.MultiPoint.prototype.unByKey);
  109209. goog.exportProperty(
  109210. ol.geom.MultiPolygon.prototype,
  109211. 'getFirstCoordinate',
  109212. ol.geom.MultiPolygon.prototype.getFirstCoordinate);
  109213. goog.exportProperty(
  109214. ol.geom.MultiPolygon.prototype,
  109215. 'getLastCoordinate',
  109216. ol.geom.MultiPolygon.prototype.getLastCoordinate);
  109217. goog.exportProperty(
  109218. ol.geom.MultiPolygon.prototype,
  109219. 'getLayout',
  109220. ol.geom.MultiPolygon.prototype.getLayout);
  109221. goog.exportProperty(
  109222. ol.geom.MultiPolygon.prototype,
  109223. 'getClosestPoint',
  109224. ol.geom.MultiPolygon.prototype.getClosestPoint);
  109225. goog.exportProperty(
  109226. ol.geom.MultiPolygon.prototype,
  109227. 'getExtent',
  109228. ol.geom.MultiPolygon.prototype.getExtent);
  109229. goog.exportProperty(
  109230. ol.geom.MultiPolygon.prototype,
  109231. 'simplify',
  109232. ol.geom.MultiPolygon.prototype.simplify);
  109233. goog.exportProperty(
  109234. ol.geom.MultiPolygon.prototype,
  109235. 'transform',
  109236. ol.geom.MultiPolygon.prototype.transform);
  109237. goog.exportProperty(
  109238. ol.geom.MultiPolygon.prototype,
  109239. 'get',
  109240. ol.geom.MultiPolygon.prototype.get);
  109241. goog.exportProperty(
  109242. ol.geom.MultiPolygon.prototype,
  109243. 'getKeys',
  109244. ol.geom.MultiPolygon.prototype.getKeys);
  109245. goog.exportProperty(
  109246. ol.geom.MultiPolygon.prototype,
  109247. 'getProperties',
  109248. ol.geom.MultiPolygon.prototype.getProperties);
  109249. goog.exportProperty(
  109250. ol.geom.MultiPolygon.prototype,
  109251. 'set',
  109252. ol.geom.MultiPolygon.prototype.set);
  109253. goog.exportProperty(
  109254. ol.geom.MultiPolygon.prototype,
  109255. 'setProperties',
  109256. ol.geom.MultiPolygon.prototype.setProperties);
  109257. goog.exportProperty(
  109258. ol.geom.MultiPolygon.prototype,
  109259. 'unset',
  109260. ol.geom.MultiPolygon.prototype.unset);
  109261. goog.exportProperty(
  109262. ol.geom.MultiPolygon.prototype,
  109263. 'changed',
  109264. ol.geom.MultiPolygon.prototype.changed);
  109265. goog.exportProperty(
  109266. ol.geom.MultiPolygon.prototype,
  109267. 'getRevision',
  109268. ol.geom.MultiPolygon.prototype.getRevision);
  109269. goog.exportProperty(
  109270. ol.geom.MultiPolygon.prototype,
  109271. 'on',
  109272. ol.geom.MultiPolygon.prototype.on);
  109273. goog.exportProperty(
  109274. ol.geom.MultiPolygon.prototype,
  109275. 'once',
  109276. ol.geom.MultiPolygon.prototype.once);
  109277. goog.exportProperty(
  109278. ol.geom.MultiPolygon.prototype,
  109279. 'un',
  109280. ol.geom.MultiPolygon.prototype.un);
  109281. goog.exportProperty(
  109282. ol.geom.MultiPolygon.prototype,
  109283. 'unByKey',
  109284. ol.geom.MultiPolygon.prototype.unByKey);
  109285. goog.exportProperty(
  109286. ol.geom.Point.prototype,
  109287. 'getFirstCoordinate',
  109288. ol.geom.Point.prototype.getFirstCoordinate);
  109289. goog.exportProperty(
  109290. ol.geom.Point.prototype,
  109291. 'getLastCoordinate',
  109292. ol.geom.Point.prototype.getLastCoordinate);
  109293. goog.exportProperty(
  109294. ol.geom.Point.prototype,
  109295. 'getLayout',
  109296. ol.geom.Point.prototype.getLayout);
  109297. goog.exportProperty(
  109298. ol.geom.Point.prototype,
  109299. 'getClosestPoint',
  109300. ol.geom.Point.prototype.getClosestPoint);
  109301. goog.exportProperty(
  109302. ol.geom.Point.prototype,
  109303. 'getExtent',
  109304. ol.geom.Point.prototype.getExtent);
  109305. goog.exportProperty(
  109306. ol.geom.Point.prototype,
  109307. 'simplify',
  109308. ol.geom.Point.prototype.simplify);
  109309. goog.exportProperty(
  109310. ol.geom.Point.prototype,
  109311. 'transform',
  109312. ol.geom.Point.prototype.transform);
  109313. goog.exportProperty(
  109314. ol.geom.Point.prototype,
  109315. 'get',
  109316. ol.geom.Point.prototype.get);
  109317. goog.exportProperty(
  109318. ol.geom.Point.prototype,
  109319. 'getKeys',
  109320. ol.geom.Point.prototype.getKeys);
  109321. goog.exportProperty(
  109322. ol.geom.Point.prototype,
  109323. 'getProperties',
  109324. ol.geom.Point.prototype.getProperties);
  109325. goog.exportProperty(
  109326. ol.geom.Point.prototype,
  109327. 'set',
  109328. ol.geom.Point.prototype.set);
  109329. goog.exportProperty(
  109330. ol.geom.Point.prototype,
  109331. 'setProperties',
  109332. ol.geom.Point.prototype.setProperties);
  109333. goog.exportProperty(
  109334. ol.geom.Point.prototype,
  109335. 'unset',
  109336. ol.geom.Point.prototype.unset);
  109337. goog.exportProperty(
  109338. ol.geom.Point.prototype,
  109339. 'changed',
  109340. ol.geom.Point.prototype.changed);
  109341. goog.exportProperty(
  109342. ol.geom.Point.prototype,
  109343. 'getRevision',
  109344. ol.geom.Point.prototype.getRevision);
  109345. goog.exportProperty(
  109346. ol.geom.Point.prototype,
  109347. 'on',
  109348. ol.geom.Point.prototype.on);
  109349. goog.exportProperty(
  109350. ol.geom.Point.prototype,
  109351. 'once',
  109352. ol.geom.Point.prototype.once);
  109353. goog.exportProperty(
  109354. ol.geom.Point.prototype,
  109355. 'un',
  109356. ol.geom.Point.prototype.un);
  109357. goog.exportProperty(
  109358. ol.geom.Point.prototype,
  109359. 'unByKey',
  109360. ol.geom.Point.prototype.unByKey);
  109361. goog.exportProperty(
  109362. ol.geom.Polygon.prototype,
  109363. 'getFirstCoordinate',
  109364. ol.geom.Polygon.prototype.getFirstCoordinate);
  109365. goog.exportProperty(
  109366. ol.geom.Polygon.prototype,
  109367. 'getLastCoordinate',
  109368. ol.geom.Polygon.prototype.getLastCoordinate);
  109369. goog.exportProperty(
  109370. ol.geom.Polygon.prototype,
  109371. 'getLayout',
  109372. ol.geom.Polygon.prototype.getLayout);
  109373. goog.exportProperty(
  109374. ol.geom.Polygon.prototype,
  109375. 'getClosestPoint',
  109376. ol.geom.Polygon.prototype.getClosestPoint);
  109377. goog.exportProperty(
  109378. ol.geom.Polygon.prototype,
  109379. 'getExtent',
  109380. ol.geom.Polygon.prototype.getExtent);
  109381. goog.exportProperty(
  109382. ol.geom.Polygon.prototype,
  109383. 'simplify',
  109384. ol.geom.Polygon.prototype.simplify);
  109385. goog.exportProperty(
  109386. ol.geom.Polygon.prototype,
  109387. 'transform',
  109388. ol.geom.Polygon.prototype.transform);
  109389. goog.exportProperty(
  109390. ol.geom.Polygon.prototype,
  109391. 'get',
  109392. ol.geom.Polygon.prototype.get);
  109393. goog.exportProperty(
  109394. ol.geom.Polygon.prototype,
  109395. 'getKeys',
  109396. ol.geom.Polygon.prototype.getKeys);
  109397. goog.exportProperty(
  109398. ol.geom.Polygon.prototype,
  109399. 'getProperties',
  109400. ol.geom.Polygon.prototype.getProperties);
  109401. goog.exportProperty(
  109402. ol.geom.Polygon.prototype,
  109403. 'set',
  109404. ol.geom.Polygon.prototype.set);
  109405. goog.exportProperty(
  109406. ol.geom.Polygon.prototype,
  109407. 'setProperties',
  109408. ol.geom.Polygon.prototype.setProperties);
  109409. goog.exportProperty(
  109410. ol.geom.Polygon.prototype,
  109411. 'unset',
  109412. ol.geom.Polygon.prototype.unset);
  109413. goog.exportProperty(
  109414. ol.geom.Polygon.prototype,
  109415. 'changed',
  109416. ol.geom.Polygon.prototype.changed);
  109417. goog.exportProperty(
  109418. ol.geom.Polygon.prototype,
  109419. 'getRevision',
  109420. ol.geom.Polygon.prototype.getRevision);
  109421. goog.exportProperty(
  109422. ol.geom.Polygon.prototype,
  109423. 'on',
  109424. ol.geom.Polygon.prototype.on);
  109425. goog.exportProperty(
  109426. ol.geom.Polygon.prototype,
  109427. 'once',
  109428. ol.geom.Polygon.prototype.once);
  109429. goog.exportProperty(
  109430. ol.geom.Polygon.prototype,
  109431. 'un',
  109432. ol.geom.Polygon.prototype.un);
  109433. goog.exportProperty(
  109434. ol.geom.Polygon.prototype,
  109435. 'unByKey',
  109436. ol.geom.Polygon.prototype.unByKey);
  109437. goog.exportProperty(
  109438. ol.format.GML2.prototype,
  109439. 'readFeatures',
  109440. ol.format.GML2.prototype.readFeatures);
  109441. goog.exportProperty(
  109442. ol.format.GML3.prototype,
  109443. 'readFeatures',
  109444. ol.format.GML3.prototype.readFeatures);
  109445. goog.exportProperty(
  109446. ol.format.GML.prototype,
  109447. 'readFeatures',
  109448. ol.format.GML.prototype.readFeatures);
  109449. goog.exportProperty(
  109450. ol.control.Control.prototype,
  109451. 'get',
  109452. ol.control.Control.prototype.get);
  109453. goog.exportProperty(
  109454. ol.control.Control.prototype,
  109455. 'getKeys',
  109456. ol.control.Control.prototype.getKeys);
  109457. goog.exportProperty(
  109458. ol.control.Control.prototype,
  109459. 'getProperties',
  109460. ol.control.Control.prototype.getProperties);
  109461. goog.exportProperty(
  109462. ol.control.Control.prototype,
  109463. 'set',
  109464. ol.control.Control.prototype.set);
  109465. goog.exportProperty(
  109466. ol.control.Control.prototype,
  109467. 'setProperties',
  109468. ol.control.Control.prototype.setProperties);
  109469. goog.exportProperty(
  109470. ol.control.Control.prototype,
  109471. 'unset',
  109472. ol.control.Control.prototype.unset);
  109473. goog.exportProperty(
  109474. ol.control.Control.prototype,
  109475. 'changed',
  109476. ol.control.Control.prototype.changed);
  109477. goog.exportProperty(
  109478. ol.control.Control.prototype,
  109479. 'getRevision',
  109480. ol.control.Control.prototype.getRevision);
  109481. goog.exportProperty(
  109482. ol.control.Control.prototype,
  109483. 'on',
  109484. ol.control.Control.prototype.on);
  109485. goog.exportProperty(
  109486. ol.control.Control.prototype,
  109487. 'once',
  109488. ol.control.Control.prototype.once);
  109489. goog.exportProperty(
  109490. ol.control.Control.prototype,
  109491. 'un',
  109492. ol.control.Control.prototype.un);
  109493. goog.exportProperty(
  109494. ol.control.Control.prototype,
  109495. 'unByKey',
  109496. ol.control.Control.prototype.unByKey);
  109497. goog.exportProperty(
  109498. ol.control.Attribution.prototype,
  109499. 'getMap',
  109500. ol.control.Attribution.prototype.getMap);
  109501. goog.exportProperty(
  109502. ol.control.Attribution.prototype,
  109503. 'setMap',
  109504. ol.control.Attribution.prototype.setMap);
  109505. goog.exportProperty(
  109506. ol.control.Attribution.prototype,
  109507. 'setTarget',
  109508. ol.control.Attribution.prototype.setTarget);
  109509. goog.exportProperty(
  109510. ol.control.Attribution.prototype,
  109511. 'get',
  109512. ol.control.Attribution.prototype.get);
  109513. goog.exportProperty(
  109514. ol.control.Attribution.prototype,
  109515. 'getKeys',
  109516. ol.control.Attribution.prototype.getKeys);
  109517. goog.exportProperty(
  109518. ol.control.Attribution.prototype,
  109519. 'getProperties',
  109520. ol.control.Attribution.prototype.getProperties);
  109521. goog.exportProperty(
  109522. ol.control.Attribution.prototype,
  109523. 'set',
  109524. ol.control.Attribution.prototype.set);
  109525. goog.exportProperty(
  109526. ol.control.Attribution.prototype,
  109527. 'setProperties',
  109528. ol.control.Attribution.prototype.setProperties);
  109529. goog.exportProperty(
  109530. ol.control.Attribution.prototype,
  109531. 'unset',
  109532. ol.control.Attribution.prototype.unset);
  109533. goog.exportProperty(
  109534. ol.control.Attribution.prototype,
  109535. 'changed',
  109536. ol.control.Attribution.prototype.changed);
  109537. goog.exportProperty(
  109538. ol.control.Attribution.prototype,
  109539. 'getRevision',
  109540. ol.control.Attribution.prototype.getRevision);
  109541. goog.exportProperty(
  109542. ol.control.Attribution.prototype,
  109543. 'on',
  109544. ol.control.Attribution.prototype.on);
  109545. goog.exportProperty(
  109546. ol.control.Attribution.prototype,
  109547. 'once',
  109548. ol.control.Attribution.prototype.once);
  109549. goog.exportProperty(
  109550. ol.control.Attribution.prototype,
  109551. 'un',
  109552. ol.control.Attribution.prototype.un);
  109553. goog.exportProperty(
  109554. ol.control.Attribution.prototype,
  109555. 'unByKey',
  109556. ol.control.Attribution.prototype.unByKey);
  109557. goog.exportProperty(
  109558. ol.control.FullScreen.prototype,
  109559. 'getMap',
  109560. ol.control.FullScreen.prototype.getMap);
  109561. goog.exportProperty(
  109562. ol.control.FullScreen.prototype,
  109563. 'setMap',
  109564. ol.control.FullScreen.prototype.setMap);
  109565. goog.exportProperty(
  109566. ol.control.FullScreen.prototype,
  109567. 'setTarget',
  109568. ol.control.FullScreen.prototype.setTarget);
  109569. goog.exportProperty(
  109570. ol.control.FullScreen.prototype,
  109571. 'get',
  109572. ol.control.FullScreen.prototype.get);
  109573. goog.exportProperty(
  109574. ol.control.FullScreen.prototype,
  109575. 'getKeys',
  109576. ol.control.FullScreen.prototype.getKeys);
  109577. goog.exportProperty(
  109578. ol.control.FullScreen.prototype,
  109579. 'getProperties',
  109580. ol.control.FullScreen.prototype.getProperties);
  109581. goog.exportProperty(
  109582. ol.control.FullScreen.prototype,
  109583. 'set',
  109584. ol.control.FullScreen.prototype.set);
  109585. goog.exportProperty(
  109586. ol.control.FullScreen.prototype,
  109587. 'setProperties',
  109588. ol.control.FullScreen.prototype.setProperties);
  109589. goog.exportProperty(
  109590. ol.control.FullScreen.prototype,
  109591. 'unset',
  109592. ol.control.FullScreen.prototype.unset);
  109593. goog.exportProperty(
  109594. ol.control.FullScreen.prototype,
  109595. 'changed',
  109596. ol.control.FullScreen.prototype.changed);
  109597. goog.exportProperty(
  109598. ol.control.FullScreen.prototype,
  109599. 'getRevision',
  109600. ol.control.FullScreen.prototype.getRevision);
  109601. goog.exportProperty(
  109602. ol.control.FullScreen.prototype,
  109603. 'on',
  109604. ol.control.FullScreen.prototype.on);
  109605. goog.exportProperty(
  109606. ol.control.FullScreen.prototype,
  109607. 'once',
  109608. ol.control.FullScreen.prototype.once);
  109609. goog.exportProperty(
  109610. ol.control.FullScreen.prototype,
  109611. 'un',
  109612. ol.control.FullScreen.prototype.un);
  109613. goog.exportProperty(
  109614. ol.control.FullScreen.prototype,
  109615. 'unByKey',
  109616. ol.control.FullScreen.prototype.unByKey);
  109617. goog.exportProperty(
  109618. ol.control.MousePosition.prototype,
  109619. 'getMap',
  109620. ol.control.MousePosition.prototype.getMap);
  109621. goog.exportProperty(
  109622. ol.control.MousePosition.prototype,
  109623. 'setMap',
  109624. ol.control.MousePosition.prototype.setMap);
  109625. goog.exportProperty(
  109626. ol.control.MousePosition.prototype,
  109627. 'setTarget',
  109628. ol.control.MousePosition.prototype.setTarget);
  109629. goog.exportProperty(
  109630. ol.control.MousePosition.prototype,
  109631. 'get',
  109632. ol.control.MousePosition.prototype.get);
  109633. goog.exportProperty(
  109634. ol.control.MousePosition.prototype,
  109635. 'getKeys',
  109636. ol.control.MousePosition.prototype.getKeys);
  109637. goog.exportProperty(
  109638. ol.control.MousePosition.prototype,
  109639. 'getProperties',
  109640. ol.control.MousePosition.prototype.getProperties);
  109641. goog.exportProperty(
  109642. ol.control.MousePosition.prototype,
  109643. 'set',
  109644. ol.control.MousePosition.prototype.set);
  109645. goog.exportProperty(
  109646. ol.control.MousePosition.prototype,
  109647. 'setProperties',
  109648. ol.control.MousePosition.prototype.setProperties);
  109649. goog.exportProperty(
  109650. ol.control.MousePosition.prototype,
  109651. 'unset',
  109652. ol.control.MousePosition.prototype.unset);
  109653. goog.exportProperty(
  109654. ol.control.MousePosition.prototype,
  109655. 'changed',
  109656. ol.control.MousePosition.prototype.changed);
  109657. goog.exportProperty(
  109658. ol.control.MousePosition.prototype,
  109659. 'getRevision',
  109660. ol.control.MousePosition.prototype.getRevision);
  109661. goog.exportProperty(
  109662. ol.control.MousePosition.prototype,
  109663. 'on',
  109664. ol.control.MousePosition.prototype.on);
  109665. goog.exportProperty(
  109666. ol.control.MousePosition.prototype,
  109667. 'once',
  109668. ol.control.MousePosition.prototype.once);
  109669. goog.exportProperty(
  109670. ol.control.MousePosition.prototype,
  109671. 'un',
  109672. ol.control.MousePosition.prototype.un);
  109673. goog.exportProperty(
  109674. ol.control.MousePosition.prototype,
  109675. 'unByKey',
  109676. ol.control.MousePosition.prototype.unByKey);
  109677. goog.exportProperty(
  109678. ol.control.OverviewMap.prototype,
  109679. 'getMap',
  109680. ol.control.OverviewMap.prototype.getMap);
  109681. goog.exportProperty(
  109682. ol.control.OverviewMap.prototype,
  109683. 'setMap',
  109684. ol.control.OverviewMap.prototype.setMap);
  109685. goog.exportProperty(
  109686. ol.control.OverviewMap.prototype,
  109687. 'setTarget',
  109688. ol.control.OverviewMap.prototype.setTarget);
  109689. goog.exportProperty(
  109690. ol.control.OverviewMap.prototype,
  109691. 'get',
  109692. ol.control.OverviewMap.prototype.get);
  109693. goog.exportProperty(
  109694. ol.control.OverviewMap.prototype,
  109695. 'getKeys',
  109696. ol.control.OverviewMap.prototype.getKeys);
  109697. goog.exportProperty(
  109698. ol.control.OverviewMap.prototype,
  109699. 'getProperties',
  109700. ol.control.OverviewMap.prototype.getProperties);
  109701. goog.exportProperty(
  109702. ol.control.OverviewMap.prototype,
  109703. 'set',
  109704. ol.control.OverviewMap.prototype.set);
  109705. goog.exportProperty(
  109706. ol.control.OverviewMap.prototype,
  109707. 'setProperties',
  109708. ol.control.OverviewMap.prototype.setProperties);
  109709. goog.exportProperty(
  109710. ol.control.OverviewMap.prototype,
  109711. 'unset',
  109712. ol.control.OverviewMap.prototype.unset);
  109713. goog.exportProperty(
  109714. ol.control.OverviewMap.prototype,
  109715. 'changed',
  109716. ol.control.OverviewMap.prototype.changed);
  109717. goog.exportProperty(
  109718. ol.control.OverviewMap.prototype,
  109719. 'getRevision',
  109720. ol.control.OverviewMap.prototype.getRevision);
  109721. goog.exportProperty(
  109722. ol.control.OverviewMap.prototype,
  109723. 'on',
  109724. ol.control.OverviewMap.prototype.on);
  109725. goog.exportProperty(
  109726. ol.control.OverviewMap.prototype,
  109727. 'once',
  109728. ol.control.OverviewMap.prototype.once);
  109729. goog.exportProperty(
  109730. ol.control.OverviewMap.prototype,
  109731. 'un',
  109732. ol.control.OverviewMap.prototype.un);
  109733. goog.exportProperty(
  109734. ol.control.OverviewMap.prototype,
  109735. 'unByKey',
  109736. ol.control.OverviewMap.prototype.unByKey);
  109737. goog.exportProperty(
  109738. ol.control.Rotate.prototype,
  109739. 'getMap',
  109740. ol.control.Rotate.prototype.getMap);
  109741. goog.exportProperty(
  109742. ol.control.Rotate.prototype,
  109743. 'setMap',
  109744. ol.control.Rotate.prototype.setMap);
  109745. goog.exportProperty(
  109746. ol.control.Rotate.prototype,
  109747. 'setTarget',
  109748. ol.control.Rotate.prototype.setTarget);
  109749. goog.exportProperty(
  109750. ol.control.Rotate.prototype,
  109751. 'get',
  109752. ol.control.Rotate.prototype.get);
  109753. goog.exportProperty(
  109754. ol.control.Rotate.prototype,
  109755. 'getKeys',
  109756. ol.control.Rotate.prototype.getKeys);
  109757. goog.exportProperty(
  109758. ol.control.Rotate.prototype,
  109759. 'getProperties',
  109760. ol.control.Rotate.prototype.getProperties);
  109761. goog.exportProperty(
  109762. ol.control.Rotate.prototype,
  109763. 'set',
  109764. ol.control.Rotate.prototype.set);
  109765. goog.exportProperty(
  109766. ol.control.Rotate.prototype,
  109767. 'setProperties',
  109768. ol.control.Rotate.prototype.setProperties);
  109769. goog.exportProperty(
  109770. ol.control.Rotate.prototype,
  109771. 'unset',
  109772. ol.control.Rotate.prototype.unset);
  109773. goog.exportProperty(
  109774. ol.control.Rotate.prototype,
  109775. 'changed',
  109776. ol.control.Rotate.prototype.changed);
  109777. goog.exportProperty(
  109778. ol.control.Rotate.prototype,
  109779. 'getRevision',
  109780. ol.control.Rotate.prototype.getRevision);
  109781. goog.exportProperty(
  109782. ol.control.Rotate.prototype,
  109783. 'on',
  109784. ol.control.Rotate.prototype.on);
  109785. goog.exportProperty(
  109786. ol.control.Rotate.prototype,
  109787. 'once',
  109788. ol.control.Rotate.prototype.once);
  109789. goog.exportProperty(
  109790. ol.control.Rotate.prototype,
  109791. 'un',
  109792. ol.control.Rotate.prototype.un);
  109793. goog.exportProperty(
  109794. ol.control.Rotate.prototype,
  109795. 'unByKey',
  109796. ol.control.Rotate.prototype.unByKey);
  109797. goog.exportProperty(
  109798. ol.control.ScaleLine.prototype,
  109799. 'getMap',
  109800. ol.control.ScaleLine.prototype.getMap);
  109801. goog.exportProperty(
  109802. ol.control.ScaleLine.prototype,
  109803. 'setMap',
  109804. ol.control.ScaleLine.prototype.setMap);
  109805. goog.exportProperty(
  109806. ol.control.ScaleLine.prototype,
  109807. 'setTarget',
  109808. ol.control.ScaleLine.prototype.setTarget);
  109809. goog.exportProperty(
  109810. ol.control.ScaleLine.prototype,
  109811. 'get',
  109812. ol.control.ScaleLine.prototype.get);
  109813. goog.exportProperty(
  109814. ol.control.ScaleLine.prototype,
  109815. 'getKeys',
  109816. ol.control.ScaleLine.prototype.getKeys);
  109817. goog.exportProperty(
  109818. ol.control.ScaleLine.prototype,
  109819. 'getProperties',
  109820. ol.control.ScaleLine.prototype.getProperties);
  109821. goog.exportProperty(
  109822. ol.control.ScaleLine.prototype,
  109823. 'set',
  109824. ol.control.ScaleLine.prototype.set);
  109825. goog.exportProperty(
  109826. ol.control.ScaleLine.prototype,
  109827. 'setProperties',
  109828. ol.control.ScaleLine.prototype.setProperties);
  109829. goog.exportProperty(
  109830. ol.control.ScaleLine.prototype,
  109831. 'unset',
  109832. ol.control.ScaleLine.prototype.unset);
  109833. goog.exportProperty(
  109834. ol.control.ScaleLine.prototype,
  109835. 'changed',
  109836. ol.control.ScaleLine.prototype.changed);
  109837. goog.exportProperty(
  109838. ol.control.ScaleLine.prototype,
  109839. 'getRevision',
  109840. ol.control.ScaleLine.prototype.getRevision);
  109841. goog.exportProperty(
  109842. ol.control.ScaleLine.prototype,
  109843. 'on',
  109844. ol.control.ScaleLine.prototype.on);
  109845. goog.exportProperty(
  109846. ol.control.ScaleLine.prototype,
  109847. 'once',
  109848. ol.control.ScaleLine.prototype.once);
  109849. goog.exportProperty(
  109850. ol.control.ScaleLine.prototype,
  109851. 'un',
  109852. ol.control.ScaleLine.prototype.un);
  109853. goog.exportProperty(
  109854. ol.control.ScaleLine.prototype,
  109855. 'unByKey',
  109856. ol.control.ScaleLine.prototype.unByKey);
  109857. goog.exportProperty(
  109858. ol.control.Zoom.prototype,
  109859. 'getMap',
  109860. ol.control.Zoom.prototype.getMap);
  109861. goog.exportProperty(
  109862. ol.control.Zoom.prototype,
  109863. 'setMap',
  109864. ol.control.Zoom.prototype.setMap);
  109865. goog.exportProperty(
  109866. ol.control.Zoom.prototype,
  109867. 'setTarget',
  109868. ol.control.Zoom.prototype.setTarget);
  109869. goog.exportProperty(
  109870. ol.control.Zoom.prototype,
  109871. 'get',
  109872. ol.control.Zoom.prototype.get);
  109873. goog.exportProperty(
  109874. ol.control.Zoom.prototype,
  109875. 'getKeys',
  109876. ol.control.Zoom.prototype.getKeys);
  109877. goog.exportProperty(
  109878. ol.control.Zoom.prototype,
  109879. 'getProperties',
  109880. ol.control.Zoom.prototype.getProperties);
  109881. goog.exportProperty(
  109882. ol.control.Zoom.prototype,
  109883. 'set',
  109884. ol.control.Zoom.prototype.set);
  109885. goog.exportProperty(
  109886. ol.control.Zoom.prototype,
  109887. 'setProperties',
  109888. ol.control.Zoom.prototype.setProperties);
  109889. goog.exportProperty(
  109890. ol.control.Zoom.prototype,
  109891. 'unset',
  109892. ol.control.Zoom.prototype.unset);
  109893. goog.exportProperty(
  109894. ol.control.Zoom.prototype,
  109895. 'changed',
  109896. ol.control.Zoom.prototype.changed);
  109897. goog.exportProperty(
  109898. ol.control.Zoom.prototype,
  109899. 'getRevision',
  109900. ol.control.Zoom.prototype.getRevision);
  109901. goog.exportProperty(
  109902. ol.control.Zoom.prototype,
  109903. 'on',
  109904. ol.control.Zoom.prototype.on);
  109905. goog.exportProperty(
  109906. ol.control.Zoom.prototype,
  109907. 'once',
  109908. ol.control.Zoom.prototype.once);
  109909. goog.exportProperty(
  109910. ol.control.Zoom.prototype,
  109911. 'un',
  109912. ol.control.Zoom.prototype.un);
  109913. goog.exportProperty(
  109914. ol.control.Zoom.prototype,
  109915. 'unByKey',
  109916. ol.control.Zoom.prototype.unByKey);
  109917. goog.exportProperty(
  109918. ol.control.ZoomSlider.prototype,
  109919. 'getMap',
  109920. ol.control.ZoomSlider.prototype.getMap);
  109921. goog.exportProperty(
  109922. ol.control.ZoomSlider.prototype,
  109923. 'setMap',
  109924. ol.control.ZoomSlider.prototype.setMap);
  109925. goog.exportProperty(
  109926. ol.control.ZoomSlider.prototype,
  109927. 'setTarget',
  109928. ol.control.ZoomSlider.prototype.setTarget);
  109929. goog.exportProperty(
  109930. ol.control.ZoomSlider.prototype,
  109931. 'get',
  109932. ol.control.ZoomSlider.prototype.get);
  109933. goog.exportProperty(
  109934. ol.control.ZoomSlider.prototype,
  109935. 'getKeys',
  109936. ol.control.ZoomSlider.prototype.getKeys);
  109937. goog.exportProperty(
  109938. ol.control.ZoomSlider.prototype,
  109939. 'getProperties',
  109940. ol.control.ZoomSlider.prototype.getProperties);
  109941. goog.exportProperty(
  109942. ol.control.ZoomSlider.prototype,
  109943. 'set',
  109944. ol.control.ZoomSlider.prototype.set);
  109945. goog.exportProperty(
  109946. ol.control.ZoomSlider.prototype,
  109947. 'setProperties',
  109948. ol.control.ZoomSlider.prototype.setProperties);
  109949. goog.exportProperty(
  109950. ol.control.ZoomSlider.prototype,
  109951. 'unset',
  109952. ol.control.ZoomSlider.prototype.unset);
  109953. goog.exportProperty(
  109954. ol.control.ZoomSlider.prototype,
  109955. 'changed',
  109956. ol.control.ZoomSlider.prototype.changed);
  109957. goog.exportProperty(
  109958. ol.control.ZoomSlider.prototype,
  109959. 'getRevision',
  109960. ol.control.ZoomSlider.prototype.getRevision);
  109961. goog.exportProperty(
  109962. ol.control.ZoomSlider.prototype,
  109963. 'on',
  109964. ol.control.ZoomSlider.prototype.on);
  109965. goog.exportProperty(
  109966. ol.control.ZoomSlider.prototype,
  109967. 'once',
  109968. ol.control.ZoomSlider.prototype.once);
  109969. goog.exportProperty(
  109970. ol.control.ZoomSlider.prototype,
  109971. 'un',
  109972. ol.control.ZoomSlider.prototype.un);
  109973. goog.exportProperty(
  109974. ol.control.ZoomSlider.prototype,
  109975. 'unByKey',
  109976. ol.control.ZoomSlider.prototype.unByKey);
  109977. goog.exportProperty(
  109978. ol.control.ZoomToExtent.prototype,
  109979. 'getMap',
  109980. ol.control.ZoomToExtent.prototype.getMap);
  109981. goog.exportProperty(
  109982. ol.control.ZoomToExtent.prototype,
  109983. 'setMap',
  109984. ol.control.ZoomToExtent.prototype.setMap);
  109985. goog.exportProperty(
  109986. ol.control.ZoomToExtent.prototype,
  109987. 'setTarget',
  109988. ol.control.ZoomToExtent.prototype.setTarget);
  109989. goog.exportProperty(
  109990. ol.control.ZoomToExtent.prototype,
  109991. 'get',
  109992. ol.control.ZoomToExtent.prototype.get);
  109993. goog.exportProperty(
  109994. ol.control.ZoomToExtent.prototype,
  109995. 'getKeys',
  109996. ol.control.ZoomToExtent.prototype.getKeys);
  109997. goog.exportProperty(
  109998. ol.control.ZoomToExtent.prototype,
  109999. 'getProperties',
  110000. ol.control.ZoomToExtent.prototype.getProperties);
  110001. goog.exportProperty(
  110002. ol.control.ZoomToExtent.prototype,
  110003. 'set',
  110004. ol.control.ZoomToExtent.prototype.set);
  110005. goog.exportProperty(
  110006. ol.control.ZoomToExtent.prototype,
  110007. 'setProperties',
  110008. ol.control.ZoomToExtent.prototype.setProperties);
  110009. goog.exportProperty(
  110010. ol.control.ZoomToExtent.prototype,
  110011. 'unset',
  110012. ol.control.ZoomToExtent.prototype.unset);
  110013. goog.exportProperty(
  110014. ol.control.ZoomToExtent.prototype,
  110015. 'changed',
  110016. ol.control.ZoomToExtent.prototype.changed);
  110017. goog.exportProperty(
  110018. ol.control.ZoomToExtent.prototype,
  110019. 'getRevision',
  110020. ol.control.ZoomToExtent.prototype.getRevision);
  110021. goog.exportProperty(
  110022. ol.control.ZoomToExtent.prototype,
  110023. 'on',
  110024. ol.control.ZoomToExtent.prototype.on);
  110025. goog.exportProperty(
  110026. ol.control.ZoomToExtent.prototype,
  110027. 'once',
  110028. ol.control.ZoomToExtent.prototype.once);
  110029. goog.exportProperty(
  110030. ol.control.ZoomToExtent.prototype,
  110031. 'un',
  110032. ol.control.ZoomToExtent.prototype.un);
  110033. goog.exportProperty(
  110034. ol.control.ZoomToExtent.prototype,
  110035. 'unByKey',
  110036. ol.control.ZoomToExtent.prototype.unByKey);
  110037. OPENLAYERS.ol = ol;
  110038. return OPENLAYERS.ol;
  110039. }));