| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180 |
- /**
- * Copyright (c) 2006-2017, JGraph Ltd
- * Copyright (c) 2006-2017, Gaudenz Alder
- */
- (function()
- {
- /**
- * Version
- */
- EditorUi.VERSION = '@DRAWIO-VERSION@';
-
- /**
- * Overrides compact UI setting.
- */
- EditorUi.compactUi = uiTheme != 'atlas';
- /**
- * Overrides default grid color for dark mode
- */
- if (Editor.isDarkMode())
- {
- mxGraphView.prototype.gridColor = mxGraphView.prototype.defaultDarkGridColor;
- }
-
- /**
- * Switch to disable logging for mode and search terms.
- */
- EditorUi.enableLogging = urlParams['stealth'] != '1' && urlParams['lockdown'] != '1' &&
- (/.*\.draw\.io$/.test(window.location.hostname) ||
- /.*\.diagrams\.net$/.test(window.location.hostname)) &&
- window.location.hostname != 'support.draw.io';
-
- /**
- * Protocol and hostname to use for embedded files. Default is https://www.draw.io
- */
- EditorUi.drawHost = window.DRAWIO_BASE_URL;
-
- /**
- * Protocol and hostname to use for embedded files. Default is https://www.draw.io
- */
- EditorUi.lightboxHost = window.DRAWIO_LIGHTBOX_URL;
-
- /**
- * Switch to disable logging for mode and search terms.
- */
- EditorUi.lastErrorMessage = null;
- /**
- * Switch to disable logging for mode and search terms.
- */
- EditorUi.ignoredAnonymizedChars = '\n\t`~!@#$%^&*()_+{}|:"<>?-=[]\;\'.\/,\n\t';
- /**
- * Specifies the URL for the templates index file.
- */
- EditorUi.templateFile = TEMPLATE_PATH + '/index.xml';
- /**
- * Specifies the URL for the diffsync cache.
- */
- EditorUi.cacheUrl = (urlParams['dev'] == '1') ? '/cache' : window.REALTIME_URL;
- if (EditorUi.cacheUrl == null && typeof DrawioFile !== 'undefined')
- {
- DrawioFile.SYNC = 'none'; //Disable real-time sync
- }
-
- /**
- * Cache timeout is 10 seconds.
- */
- Editor.cacheTimeout = 10000;
- /**
- * Switch to enable PlantUML in the insert from text dialog.
- * NOTE: This must also be enabled on the server-side.
- */
- EditorUi.enablePlantUml = EditorUi.enableLogging;
- /**
- * https://github.com/electron/electron/issues/2288
- */
- EditorUi.isElectronApp = window != null && window.process != null &&
- window.process.versions != null && window.process.versions['electron'] != null;
-
- /**
- * Specifies if drafts should be saved in IndexedDB.
- */
- EditorUi.enableDrafts = !mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp &&
- isLocalStorage && urlParams['drafts'] != '0';
-
- /**
- * Link for scratchpad help.
- */
- EditorUi.scratchpadHelpLink = 'https://www.diagrams.net/doc/faq/scratchpad';
- /**
- * Default Mermaid config without using foreign objects in flowcharts.
- */
- EditorUi.defaultMermaidConfig = {
- theme:'neutral',
- arrowMarkerAbsolute:false,
- flowchart:
- {
- htmlLabels:false
- },
- sequence:
- {
- diagramMarginX:50,
- diagramMarginY:10,
- actorMargin:50,
- width:150,
- height:65,
- boxMargin:10,
- boxTextMargin:5,
- noteMargin:10,
- messageMargin:35,
- mirrorActors:true,
- bottomMarginAdj:1,
- useMaxWidth:true,
- rightAngles:false,
- showSequenceNumbers:false
- },
- gantt:{
- titleTopMargin:25,
- barHeight:20,
- barGap:4,
- topPadding:50,
- leftPadding:75,
- gridLineStartPadding:35,
- fontSize:11,
- fontFamily:'"Open-Sans", "sans-serif"',
- numberSectionStyles:4,
- axisFormat:'%Y-%m-%d'
- }
- };
- /**
- * Updates action states depending on the selection.
- */
- EditorUi.logError = function(message, url, linenumber, colno, err, severity, quiet)
- {
- severity = ((severity != null) ? severity : (message.indexOf('NetworkError') >= 0 ||
- message.indexOf('SecurityError') >= 0 || message.indexOf('NS_ERROR_FAILURE') >= 0 ||
- message.indexOf('out of memory') >= 0) ? 'CONFIG' : 'SEVERE');
-
- if (EditorUi.enableLogging && urlParams['dev'] != '1')
- {
- try
- {
- if (message == EditorUi.lastErrorMessage || (message != null && url != null &&
- ((message.indexOf('Script error') != -1) || (message.indexOf('extension') != -1))))
- {
- // TODO log external domain script failure "Script error." is
- // reported when the error occurs in a script that is hosted
- // on a domain other than the domain of the current page
- }
- // DocumentClosedError seems to be an FF bug an can be ignored for now
- else if (message != null && message.indexOf('DocumentClosedError') < 0)
- {
- EditorUi.lastErrorMessage = message;
- var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
- err = (err != null) ? err : new Error(message);
- var img = new Image();
- img.src = logDomain + '/log?severity=' + severity + '&v=' + encodeURIComponent(EditorUi.VERSION) +
- '&msg=clientError:' + encodeURIComponent(message) + ':url:' + encodeURIComponent(window.location.href) +
- ':lnum:' + encodeURIComponent(linenumber) + ((colno != null) ? ':colno:' + encodeURIComponent(colno) : '') +
- ((err != null && err.stack != null) ? '&stack=' + encodeURIComponent(err.stack) : '');
- }
- }
- catch (e)
- {
- // do nothing
- }
- }
- try
- {
- if (!quiet && window.console != null)
- {
- console.error(severity, message, url, linenumber, colno, err);
- }
- }
- catch (e)
- {
- // ignore
- }
- };
-
- /**
- * Updates action states depending on the selection.
- */
- EditorUi.logEvent = function(data)
- {
- if (urlParams['dev'] == '1')
- {
- EditorUi.debug('logEvent', data);
- }
- else if (EditorUi.enableLogging)
- {
- try
- {
- var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
- var img = new Image();
- img.src = logDomain + '/images/1x1.png?' +
- 'v=' + encodeURIComponent(EditorUi.VERSION) +
- ((data != null) ? '&data=' + encodeURIComponent(JSON.stringify(data)) : '');
- }
- catch (e)
- {
- // ignore
- }
- }
- };
- /**
- * Sending error reports.
- */
- EditorUi.sendReport = function(data, maxLength)
- {
- if (urlParams['dev'] == '1')
- {
- EditorUi.debug('sendReport', data);
- }
- else if (EditorUi.enableLogging)
- {
- try
- {
- maxLength = (maxLength != null) ? maxLength : 50000;
- if (data.length > maxLength)
- {
- data = data.substring(0, maxLength) + '\n...[SHORTENED]'
- }
-
- mxUtils.post('/email', 'version=' + encodeURIComponent(EditorUi.VERSION) +
- '&url=' + encodeURIComponent(window.location.href) +
- '&data=' + encodeURIComponent(data));
- }
- catch (e)
- {
- // ignore
- }
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- EditorUi.debug = function()
- {
- try
- {
- if (window.console != null && urlParams['test'] == '1')
- {
- var args = [new Date().toISOString()];
-
- for (var i = 0; i < arguments.length; i++)
- {
- if (arguments[i] != null)
- {
- args.push(arguments[i]);
- }
- }
-
- console.log.apply(console, args);
- }
- }
- catch (e)
- {
- // ignore
- }
- };
- /**
- * Static method for pasing PNG files.
- */
- EditorUi.parsePng = function(f, fn, error)
- {
- var pos = 0;
-
- function fread(d, count)
- {
- var start = pos;
- pos += count;
-
- return d.substring(start, pos);
- };
-
- // Reads unsigned long 32 bit big endian
- function _freadint(d)
- {
- var bytes = fread(d, 4);
-
- return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
- (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
- };
-
- // Checks signature
- if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
- {
- if (error != null)
- {
- error();
- }
-
- return;
- }
-
- // Reads header chunk
- fread(f,4);
-
- if (fread(f,4) != 'IHDR')
- {
- if (error != null)
- {
- error();
- }
-
- return;
- }
-
- fread(f, 17);
-
- do
- {
- var n = _freadint(f);
- var type = fread(f,4);
-
- if (fn != null)
- {
- if (fn(pos - 8, type, n))
- {
- break;
- }
- }
-
- value = fread(f,n);
- fread(f,4);
-
- if (type == 'IEND')
- {
- break;
- }
- }
- while (n);
- };
-
- /**
- * Removes any values, styles and geometries from the given XML node.
- */
- EditorUi.removeChildNodes = function(node)
- {
- while (node.firstChild != null)
- {
- node.removeChild(node.firstChild);
- }
- };
-
- /**
- * Contains the default XML for an empty diagram.
- */
- EditorUi.prototype.emptyDiagramXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
- /**
- *
- */
- EditorUi.prototype.emptyLibraryXml = '<mxlibrary>[]</mxlibrary>';
- /**
- * Sets the delay for autosave in milliseconds. Default is 2000.
- */
- EditorUi.prototype.mode = null;
- /**
- * General timeout is 25 seconds.
- * LATER: Move to Editor
- */
- EditorUi.prototype.timeout = Editor.prototype.timeout;
- /**
- * Allows for two buttons in the sidebar footer.
- */
- EditorUi.prototype.sidebarFooterHeight = 38;
- /**
- * Specifies the default custom shape style.
- */
- EditorUi.prototype.defaultCustomShapeStyle = 'shape=stencil(tZRtTsQgEEBPw1+DJR7AoN6DbWftpAgE0Ortd/jYRGq72R+YNE2YgTePloEJGWblgA18ZuKFDcMj5/Sm8boZq+BgjCX4pTyqk6ZlKROitwusOMXKQDODx5iy4pXxZ5qTHiFHawxB0JrQZH7lCabQ0Fr+XWC1/E8zcsT/gAi+Subo2/3Mh6d/oJb5nU1b5tW7r2knautaa3T+U32o7f7vZwpJkaNDLORJjcu7t59m2jXxqX9un+tt022acsfmoKaQZ+vhhswZtS6Ne/ThQGt0IV0N3Yyv6P3CeT9/tHO0XFI5cAE=);whiteSpace=wrap;html=1;';
- /**
- * Defines the maximum size for images.
- */
- EditorUi.prototype.maxBackgroundSize = 1600;
- /**
- * Defines the maximum size for images.
- */
- EditorUi.prototype.maxImageSize = 520;
-
- /**
- * Defines the maximum width for pasted text.
- * Use 0 to disable check.
- */
- EditorUi.prototype.maxTextWidth = 520;
- /**
- * Images above 100K should be resampled.
- */
- EditorUi.prototype.resampleThreshold = 100000;
- /**
- * Maximum allowed size for images is 1 MB.
- */
- EditorUi.prototype.maxImageBytes = 1000000;
- /**
- * Maximum size for background images is 2.5 MB.
- */
- EditorUi.prototype.maxBackgroundBytes = 2500000;
- /**
- * Maximum size for text files in labels is 0.5 MB.
- */
- EditorUi.prototype.maxTextBytes = 500000;
- /**
- * Holds the current file.
- */
- EditorUi.prototype.currentFile = null;
- /**
- * Specifies if PDF export should be done via print dialog. Default is
- * false which uses the PhantomJS backend to create the PDF.
- */
- EditorUi.prototype.printPdfExport = false;
-
- /**
- * Specifies if PDF export with pages is enabled.
- */
- EditorUi.prototype.pdfPageExport = true;
- /**
- * Restores app defaults for UI
- */
- EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
- /**
- * Whether template action should be shown in insert menu.
- */
- EditorUi.prototype.insertTemplateEnabled = true;
-
- /**
- * Restores app defaults for UI
- */
- EditorUi.prototype.closableScratchpad = true;
- /**
- * Capability check for canvas export
- */
- (function()
- {
- EditorUi.prototype.useCanvasForExport = false;
- EditorUi.prototype.jpgSupported = false;
-
- // Checks if canvas is supported
- try
- {
- var cnv = document.createElement('canvas');
- EditorUi.prototype.canvasSupported = !!(cnv.getContext && cnv.getContext('2d'));
- }
- catch (e)
- {
- // ignore
- }
-
- try
- {
- var canvas = document.createElement('canvas');
- var img = new Image();
-
- // LATER: Capability check should not be async
- img.onload = function()
- {
- try
- {
- var ctx = canvas.getContext('2d');
- ctx.drawImage(img, 0, 0);
- // Works in Chrome, Firefox, Edge, Safari and Opera
- var result = canvas.toDataURL('image/png');
- EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
- }
- catch (e)
- {
- // ignore
- }
- };
- // Checks if SVG with foreignObject can be exported
- var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1px" height="1px" version="1.1"><foreignObject pointer-events="all" width="1" height="1"><div xmlns="http://www.w3.org/1999/xhtml"></div></foreignObject></svg>';
- img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
- }
- catch (e)
- {
- // ignore
- }
-
- // Checks for client-side JPG support
- try
- {
- var canvas = document.createElement('canvas');
- canvas.width = canvas.height = 1;
- var uri = canvas.toDataURL('image/jpeg');
-
- EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
- }
- catch (e)
- {
- // ignore
- }
- })();
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.openLink = function(url, target, allowOpener)
- {
- // LATER: Replace this with direct calls to graph
- return this.editor.graph.openLink(url, target, allowOpener);
- };
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.showSplash = function(force) { };
- /**
- * Abstraction for local storage access.
- */
- EditorUi.prototype.getLocalData = function(key, fn)
- {
- fn(localStorage.getItem(key));
- };
-
- /**
- * Abstraction for local storage access.
- */
- EditorUi.prototype.setLocalData = function(key, data, fn)
- {
- localStorage.setItem(key, data);
-
- if (fn != null)
- {
- fn();
- }
- };
-
- /**
- * Abstraction for local storage access.
- */
- EditorUi.prototype.removeLocalData = function(key, fn)
- {
- localStorage.removeItem(key)
- fn();
- };
- EditorUi.prototype.setMathEnabled = function(value)
- {
- this.editor.graph.mathEnabled = value;
- this.editor.updateGraphComponents();
- this.editor.graph.refresh();
-
- this.fireEvent(new mxEventObject('mathEnabledChanged'));
- };
- EditorUi.prototype.isMathEnabled = function(value)
- {
- return this.editor.graph.mathEnabled;
- };
- /**
- * Returns true if offline app, which isn't a defined thing
- */
- EditorUi.prototype.isOfflineApp = function()
- {
- return urlParams['offline'] == '1';
- };
- /**
- * Returns true if no external comms allowed or possible
- */
- EditorUi.prototype.isOffline = function(ignoreStealth)
- {
- return this.isOfflineApp() || !navigator.onLine || (!ignoreStealth && (urlParams['stealth'] == '1' || urlParams['lockdown'] == '1'));
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.createSpinner = function(x, y, size)
- {
- var autoPosition = (x == null || y == null);
- size = (size != null) ? size : 24;
- var spinner = new Spinner({
- lines: 12, // The number of lines to draw
- length: size, // The length of each line
- width: Math.round(size / 3), // The line thickness
- radius: Math.round(size / 2), // The radius of the inner circle
- rotate: 0, // The rotation offset
- color: (Editor.isDarkMode()) ? '#c0c0c0' : '#000', // #rgb or #rrggbb
- speed: 1.5, // Rounds per second
- trail: 60, // Afterglow percentage
- shadow: false, // Whether to render a shadow
- hwaccel: false, // Whether to use hardware acceleration
- zIndex: 2e9 // The z-index (defaults to 2000000000)
- });
- // Extends spin method to include an optional label
- var oldSpin = spinner.spin;
-
- spinner.spin = function(container, label)
- {
- var result = false;
-
- if (!this.active)
- {
- oldSpin.call(this, container);
- this.active = true;
-
- if (label != null)
- {
- if (autoPosition)
- {
- y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
- x = document.body.clientWidth / 2 - 2;
- }
- var status = document.createElement('div');
- status.style.position = 'absolute';
- status.style.whiteSpace = 'nowrap';
- status.style.background = '#4B4243';
- status.style.color = 'white';
- status.style.fontFamily = 'Helvetica, Arial';
- status.style.fontSize = '9pt';
- status.style.padding = '6px';
- status.style.paddingLeft = '10px';
- status.style.paddingRight = '10px';
- status.style.zIndex = 2e9;
- status.style.left = Math.max(0, x) + 'px';
- status.style.top = Math.max(0, y + 70) + 'px';
-
- mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
- mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
- if (!Editor.isDarkMode())
- {
- mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
- }
-
- if (label.substring(label.length - 3, label.length) != '...' &&
- label.charAt(label.length - 1) != '!')
- {
- label = label + '...';
- }
-
- status.innerHTML = label;
- container.appendChild(status);
- spinner.status = status;
- }
-
- // Pause returns a function to resume the spinner
- this.pause = mxUtils.bind(this, function()
- {
- var fn = function() { };
-
- if (this.active)
- {
- fn = mxUtils.bind(this, function()
- {
- this.spin(container, label);
- });
- }
-
- this.stop();
-
- return fn;
- });
-
- result = true;
- }
-
- return result;
- };
-
- // Extends stop method to remove the optional label
- var oldStop = spinner.stop;
-
- spinner.stop = function()
- {
- oldStop.call(this);
- this.active = false;
-
- if (spinner.status != null && spinner.status.parentNode != null)
- {
- spinner.status.parentNode.removeChild(spinner.status);
- }
- spinner.status = null;
- };
-
- spinner.pause = function()
- {
- return function() {};
- };
-
- return spinner;
- };
- /**
- * Returns true if the given string contains a compatible graph model.
- */
- EditorUi.prototype.isCompatibleString = function(data)
- {
- try
- {
- var doc = mxUtils.parseXml(data);
- var node = this.editor.extractGraphModel(doc.documentElement, true);
-
- return node != null && node.getElementsByTagName('parsererror').length == 0;
- }
- catch (e)
- {
- // ignore
- }
-
- return false;
- };
- /**
- * Returns true if the given binary data is a Visio file.
- */
- EditorUi.prototype.isVisioData = function(data)
- {
- return data.length > 8 && ((data.charCodeAt(0) == 0xD0 && data.charCodeAt(1) == 0xCF &&
- data.charCodeAt(2) == 0x11 && data.charCodeAt(3) == 0xE0 && data.charCodeAt(4) == 0xA1 && data.charCodeAt(5) == 0xB1 &&
- data.charCodeAt(6) == 0x1A && data.charCodeAt(7) == 0xE1) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
- data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x04) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
- data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x06));
- };
- /**
- * Returns true if the given binary data is a Visio file that requires remote conversion.
- * This code returns true for vss, vsd and vdx files.
- */
- EditorUi.prototype.isRemoteVisioData = function(data)
- {
- return data.length > 8 && ((data.charCodeAt(0) == 0xD0 && data.charCodeAt(1) == 0xCF &&
- data.charCodeAt(2) == 0x11 && data.charCodeAt(3) == 0xE0 && data.charCodeAt(4) == 0xA1 && data.charCodeAt(5) == 0xB1 &&
- data.charCodeAt(6) == 0x1A && data.charCodeAt(7) == 0xE1) || (data.charCodeAt(0) == 0x3C && data.charCodeAt(1) == 0x3F &&
- data.charCodeAt(2) == 0x78 && data.charCodeAt(3) == 0x6D && data.charCodeAt(3) == 0x6C));
- };
-
- /**
- * Returns true if the given binary data is a PNG file.
- */
- EditorUi.prototype.isPngData = function(data)
- {
- return data.length > 8 && data.charCodeAt(0) == 137 && data.charCodeAt(1) == 80 &&
- data.charCodeAt(2) == 78 && data.charCodeAt(3) == 71 && data.charCodeAt(4) == 13 &&
- data.charCodeAt(5) == 10 && data.charCodeAt(6) == 26 && data.charCodeAt(7) == 10;
- };
- /**
- * Adds keyboard shortcuts for page handling.
- */
- var editorUiCreateKeyHandler = EditorUi.prototype.createKeyHandler;
- EditorUi.prototype.createKeyHandler = function(editor)
- {
- var keyHandler = editorUiCreateKeyHandler.apply(this, arguments);
-
- if (!this.editor.chromeless || this.editor.editable)
- {
- var keyHandlerGetFunction = keyHandler.getFunction;
- var graph = this.editor.graph;
- var ui = this;
-
- keyHandler.getFunction = function(evt)
- {
- if (graph.isSelectionEmpty() && ui.pages != null && ui.pages.length > 0)
- {
- var idx = ui.getSelectedPageIndex();
- if (mxEvent.isShiftDown(evt))
- {
- if (evt.keyCode == 37)
- {
- return function()
- {
- if (idx > 0)
- {
- ui.movePage(idx, idx - 1);
- }
- };
- }
- else if (evt.keyCode == 38)
- {
- return function()
- {
- if (idx > 0)
- {
- ui.movePage(idx, 0);
- }
- };
- }
- else if (evt.keyCode == 39)
- {
- return function()
- {
- if (idx < ui.pages.length - 1)
- {
- ui.movePage(idx, idx + 1);
- }
- };
- }
- else if (evt.keyCode == 40)
- {
- return function()
- {
- if (idx < ui.pages.length - 1)
- {
- ui.movePage(idx, ui.pages.length - 1);
- }
- };
- }
- }
- else if (mxEvent.isControlDown(evt) || (mxClient.IS_MAC && mxEvent.isMetaDown(evt)))
- {
- if (evt.keyCode == 37)
- {
- return function()
- {
- if (idx > 0)
- {
- ui.selectNextPage(false);
- }
- };
- }
- else if (evt.keyCode == 38)
- {
- return function()
- {
- if (idx > 0)
- {
- ui.selectPage(ui.pages[0]);
- }
- };
- }
- else if (evt.keyCode == 39)
- {
- return function()
- {
- if (idx < ui.pages.length - 1)
- {
- ui.selectNextPage(true);
- }
- };
- }
- else if (evt.keyCode == 40)
- {
- return function()
- {
- if (idx < ui.pages.length - 1)
- {
- ui.selectPage(ui.pages[ui.pages.length - 1]);
- }
- };
- }
-
- }
- }
-
- return keyHandlerGetFunction.apply(this, arguments);
- };
- }
-
- return keyHandler;
- };
- /**
- * Extracts the mxfile from the given HTML data from a data transfer event.
- */
- var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
- EditorUi.prototype.extractGraphModelFromHtml = function(data)
- {
- var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
-
- if (result == null)
- {
- try
- {
- var idx = data.indexOf('<mxfile ');
-
- if (idx >= 0)
- {
- var idx2 = data.lastIndexOf('</mxfile>');
-
- if (idx2 > idx)
- {
- result = data.substring(idx, idx2 + 15).replace(/>/g, '>').
- replace(/</g, '<').replace(/\\"/g, '"').replace(/\n/g, '');
- }
- }
- else
- {
- // Gets compressed data from mxgraph element in HTML document
- var doc = mxUtils.parseXml(data);
- var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null ||
- this.diagramContainer.style.visibility == 'hidden');
- result = (node != null) ? mxUtils.getXml(node) : '';
- }
- }
- catch (e)
- {
- // ignore
- }
- }
-
- return result;
- };
-
- /**
- * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
- * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
- */
- EditorUi.prototype.validateFileData = function(data)
- {
- if (data != null && data.length > 0)
- {
- var index = data.indexOf('<meta charset="utf-8">');
-
- if (index >= 0)
- {
- var replaceString = '<meta charset="utf-8"/>';
- var replaceStrLen = replaceString.length;
- data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
- }
-
- data = Graph.zapGremlins(data);
- }
-
- return data;
- };
-
- /**
- *
- */
- EditorUi.prototype.replaceFileData = function(data)
- {
- data = this.validateFileData(data);
- var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
- // Some nodes must be extracted here to find the mxfile node
- // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
- var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
-
- if (tmp != null)
- {
- node = tmp;
- }
- if (node != null)
- {
- var graph = this.editor.graph;
-
- graph.model.beginUpdate();
- try
- {
- var oldPages = (this.pages != null) ? this.pages.slice() : null;
- var nodes = node.getElementsByTagName('diagram');
- if (urlParams['pages'] != '0' || nodes.length > 1 ||
- (nodes.length == 1 && nodes[0].hasAttribute('name')))
- {
- this.fileNode = node;
- this.pages = (this.pages != null) ? this.pages : [];
-
- // Wraps page nodes
- for (var i = nodes.length - 1; i >= 0; i--)
- {
- var page = this.updatePageRoot(new DiagramPage(nodes[i]));
-
- // Checks for invalid page names
- if (page.getName() == null)
- {
- page.setName(mxResources.get('pageWithNumber', [i + 1]));
- }
- graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
- }
- }
- else
- {
- // Creates tabbed file structure if enforced by URL
- if (urlParams['pages'] != '0' && this.fileNode == null)
- {
- this.fileNode = node.ownerDocument.createElement('mxfile');
- this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
- this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
- graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
- }
-
- // Avoids scroll offset when switching page
- this.editor.setGraphXml(node);
-
- // Avoids duplicate parsing of the XML stored in the node
- if (this.currentPage != null)
- {
- this.currentPage.root = this.editor.graph.model.root;
- }
- }
-
- if (oldPages != null)
- {
- for (var i = 0; i < oldPages.length; i++)
- {
- graph.model.execute(new ChangePage(this, oldPages[i], null));
- }
- }
- }
- finally
- {
- graph.model.endUpdate();
- }
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml,
- embeddedCallback, ignoreSelection, compact, uncompressed)
- {
- graph = (graph != null) ? graph : this.editor.graph;
- forceXml = (forceXml != null) ? forceXml : false;
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
-
- var editLink = null;
- var redirect = null;
-
- if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
- {
- editLink = '_blank';
- }
- else
- {
- editLink = url;
- redirect = editLink;
- }
- if (node == null)
- {
- return '';
- }
- else
- {
- var fileNode = node;
-
- // Ignores case for possible HTML or XML nodes
- if (fileNode.nodeName.toLowerCase() != 'mxfile')
- {
- if (uncompressed)
- {
- var diagramNode = node.ownerDocument.createElement('diagram');
- diagramNode.setAttribute('id', Editor.guid());
- diagramNode.appendChild(node);
-
- fileNode = node.ownerDocument.createElement('mxfile');
- fileNode.appendChild(diagramNode);
- }
- else
- {
- // Removes control chars in input for correct roundtrip check
- var text = Graph.zapGremlins(mxUtils.getXml(node));
- var data = Graph.compress(text);
-
- // Fallback to plain XML for invalid compression
- // TODO: Remove this fallback with active pages
- if (Graph.decompress(data) != text)
- {
- return text;
- }
- else
- {
- var diagramNode = node.ownerDocument.createElement('diagram');
- diagramNode.setAttribute('id', Editor.guid());
- mxUtils.setTextContent(diagramNode, data);
-
- fileNode = node.ownerDocument.createElement('mxfile');
- fileNode.appendChild(diagramNode);
- }
- }
- }
-
- if (!compact)
- {
- // Removes old metadata
- fileNode.removeAttribute('userAgent');
- fileNode.removeAttribute('version');
- fileNode.removeAttribute('editor');
- fileNode.removeAttribute('pages');
- fileNode.removeAttribute('type');
-
- if (mxClient.IS_CHROMEAPP)
- {
- fileNode.setAttribute('host', 'Chrome');
- }
- else if (EditorUi.isElectronApp)
- {
- fileNode.setAttribute('host', 'Electron');
- }
- else
- {
- fileNode.setAttribute('host', window.location.hostname);
- }
-
- // Adds new metadata
- fileNode.setAttribute('modified', new Date().toISOString());
- fileNode.setAttribute('agent', navigator.appVersion);
- fileNode.setAttribute('version', EditorUi.VERSION);
- fileNode.setAttribute('etag', Editor.guid());
-
- var md = (file != null) ? file.getMode() : this.mode;
-
- if (md != null)
- {
- fileNode.setAttribute('type', md);
- }
-
- if (fileNode.getElementsByTagName('diagram').length > 1 && this.pages != null)
- {
- fileNode.setAttribute('pages', this.pages.length);
- }
- }
- else
- {
- fileNode = fileNode.cloneNode(true);
- fileNode.removeAttribute('modified');
- fileNode.removeAttribute('host');
- fileNode.removeAttribute('agent');
- fileNode.removeAttribute('etag');
- fileNode.removeAttribute('userAgent');
- fileNode.removeAttribute('version');
- fileNode.removeAttribute('editor');
- fileNode.removeAttribute('type');
- }
- var xml = (uncompressed) ? mxUtils.getPrettyXml(fileNode) : mxUtils.getXml(fileNode);
-
- // Writes the file as an embedded HTML file
- if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
- {
- xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
- }
- // Maps the XML data to the content attribute in the SVG node
- else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
- {
- if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
- {
- url = null;
- }
-
- xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
- }
-
- return xml;
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage, uncompressed)
- {
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
- currentPage = (currentPage != null) ? currentPage : false;
- uncompressed = (uncompressed != null) ? uncompressed : !Editor.compressXml;
-
- // Generats graph model XML node for single page export
- var node = this.editor.getGraphXml(ignoreSelection);
-
- if (ignoreSelection && this.fileNode != null && this.currentPage != null)
- {
- // Updates current page XML if selection is ignored
- EditorUi.removeChildNodes(this.currentPage.node);
- mxUtils.setTextContent(this.currentPage.node, Graph.compressNode(node));
- // Creates a clone of the file node for processing
- node = this.fileNode.cloneNode(false);
- // Appends the node of the page and applies compression
- function appendPage(pageNode)
- {
- var models = pageNode.getElementsByTagName('mxGraphModel');
- var modelNode = (models.length > 0) ? models[0] : null;
- var clone = pageNode;
-
- if (modelNode == null && uncompressed)
- {
- var text = mxUtils.trim(mxUtils.getTextContent(pageNode));
- clone = pageNode.cloneNode(false);
-
- if (text.length > 0)
- {
- var tmp = Graph.decompress(text);
-
- if (tmp != null && tmp.length > 0)
- {
- clone.appendChild(mxUtils.parseXml(tmp).documentElement);
- }
- }
- }
- else if (modelNode != null && !uncompressed)
- {
- clone = pageNode.cloneNode(false);
- mxUtils.setTextContent(clone, Graph.compressNode(modelNode));
- }
- else
- {
- clone = pageNode.cloneNode(true);
- }
-
- node.appendChild(clone);
- };
- if (currentPage)
- {
- appendPage(this.currentPage.node);
- }
- else
- {
- // Restores order of pages
- for (var i = 0; i < this.pages.length; i++)
- {
- if (this.currentPage != this.pages[i])
- {
- if (this.pages[i].needsUpdate)
- {
- var enc = new mxCodec(mxUtils.createXmlDocument());
- var temp = enc.encode(new mxGraphModel(this.pages[i].root));
- this.editor.graph.saveViewState(this.pages[i].viewState, temp);
- EditorUi.removeChildNodes(this.pages[i].node);
- mxUtils.setTextContent(this.pages[i].node, Graph.compressNode(temp));
- // Marks the page as up-to-date
- delete this.pages[i].needsUpdate;
- }
- }
-
- appendPage(this.pages[i].node);
- }
- }
- }
-
- return node;
- };
-
- /**
- * Removes any values, styles and geometries from the given XML node.
- */
- EditorUi.prototype.anonymizeString = function(text, zeros)
- {
- var result = [];
-
- for (var i = 0; i < text.length; i++)
- {
- var c = text.charAt(i);
-
- if (EditorUi.ignoredAnonymizedChars.indexOf(c) >= 0)
- {
- result.push(c);
- }
- else if (!isNaN(parseInt(c)))
- {
- result.push((zeros) ? '0' : Math.round(Math.random() * 9));
- }
- else if (c.toLowerCase() != c)
- {
- result.push(String.fromCharCode(65 + Math.round(Math.random() * 25)));
- }
- else if (c.toUpperCase() != c)
- {
- result.push(String.fromCharCode(97 + Math.round(Math.random() * 25)));
- }
- else if (/\s/.test(c))
- {
- /* any whitespace */
- result.push(' ');
- }
- else
- {
- result.push('?');
- }
- }
-
- return result.join('');
- };
-
- /**
- * Removes any values, styles and geometries from the given XML node.
- */
- EditorUi.prototype.anonymizePatch = function(patch)
- {
- if (patch[EditorUi.DIFF_INSERT] != null)
- {
- for (var i = 0; i < patch[EditorUi.DIFF_INSERT].length; i++)
- {
- try
- {
- var data = patch[EditorUi.DIFF_INSERT][i].data;
- var doc = mxUtils.parseXml(data);
- var clone = doc.documentElement.cloneNode(false);
-
- if (clone.getAttribute('name') != null)
- {
- clone.setAttribute('name', this.anonymizeString(clone.getAttribute('name')));
- }
-
- patch[EditorUi.DIFF_INSERT][i].data = mxUtils.getXml(clone);
- }
- catch (e)
- {
- patch[EditorUi.DIFF_INSERT][i].data = e.message;
- }
- }
- }
-
- if (patch[EditorUi.DIFF_UPDATE] != null)
- {
- for (var pageId in patch[EditorUi.DIFF_UPDATE])
- {
- var diff = patch[EditorUi.DIFF_UPDATE][pageId];
-
- if (diff.name != null)
- {
- diff.name = this.anonymizeString(diff.name);
- }
-
- if (diff.cells != null)
- {
- var anonymizeCellDiffs = mxUtils.bind(this, function(key)
- {
- var cellDiffs = diff.cells[key];
-
- if (cellDiffs != null)
- {
- for (var cellId in cellDiffs)
- {
- if (cellDiffs[cellId].value != null)
- {
- cellDiffs[cellId].value = '[' +
- cellDiffs[cellId].value.length + ']';
- }
- if (cellDiffs[cellId].xmlValue != null)
- {
- cellDiffs[cellId].xmlValue = '[' +
- cellDiffs[cellId].xmlValue.length + ']';
- }
-
- if (cellDiffs[cellId].style != null)
- {
- cellDiffs[cellId].style = '[' +
- cellDiffs[cellId].style.length + ']';
- }
-
- if (Object.keys(cellDiffs[cellId]).length == 0)
- {
- delete cellDiffs[cellId];
- }
- }
-
- if (Object.keys(cellDiffs).length == 0)
- {
- delete diff.cells[key];
- }
- }
- });
-
- anonymizeCellDiffs(EditorUi.DIFF_INSERT);
- anonymizeCellDiffs(EditorUi.DIFF_UPDATE);
-
- if (Object.keys(diff.cells).length == 0)
- {
- delete diff.cells;
- }
- }
-
- if (Object.keys(diff).length == 0)
- {
- delete patch[EditorUi.DIFF_UPDATE][pageId];
- }
- }
-
- if (Object.keys(patch[EditorUi.DIFF_UPDATE]).length == 0)
- {
- delete patch[EditorUi.DIFF_UPDATE];
- }
- }
-
- return patch;
- };
- /**
- * Removes any values, styles and geometries from the given XML node.
- */
- EditorUi.prototype.anonymizeAttributes = function(node, zeros)
- {
- if (node.attributes != null)
- {
- for (var i = 0; i < node.attributes.length; i++)
- {
- if (node.attributes[i].name != 'as')
- {
- node.setAttribute(node.attributes[i].name,
- this.anonymizeString(node.attributes[i].value, zeros));
- }
- }
- }
-
- if (node.childNodes != null)
- {
- for (var i = 0; i < node.childNodes.length; i++)
- {
- this.anonymizeAttributes(node.childNodes[i], zeros);
- }
- }
- };
-
- /**
- * Removes any values, styles and geometries from the given XML node.
- */
- EditorUi.prototype.anonymizeNode = function(node, zeros)
- {
- var nodes = node.getElementsByTagName('mxCell');
-
- for (var i = 0; i < nodes.length; i++)
- {
- if (nodes[i].getAttribute('value') != null)
- {
- nodes[i].setAttribute('value', '[' + nodes[i].getAttribute('value').length + ']');
- }
- if (nodes[i].getAttribute('xmlValue') != null)
- {
- nodes[i].setAttribute('xmlValue', '[' + nodes[i].getAttribute('xmlValue').length + ']');
- }
-
- if (nodes[i].getAttribute('style') != null)
- {
- nodes[i].setAttribute('style', '[' + nodes[i].getAttribute('style').length + ']');
- }
-
- if (nodes[i].parentNode != null && nodes[i].parentNode.nodeName != 'root' &&
- nodes[i].parentNode.parentNode != null)
- {
- nodes[i].setAttribute('id', nodes[i].parentNode.getAttribute('id'));
- nodes[i].parentNode.parentNode.replaceChild(nodes[i], nodes[i].parentNode);
- }
- }
-
- return node;
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.synchronizeCurrentFile = function(forceReload)
- {
- var currentFile = this.getCurrentFile();
-
- if (currentFile != null)
- {
- if (currentFile.savingFile)
- {
- this.handleError({message: mxResources.get('busy')});
- }
- else if (!forceReload && currentFile.invalidChecksum)
- {
- currentFile.handleFileError(null, true);
- }
- else if (this.spinner.spin(document.body, mxResources.get('updatingDocument')))
- {
- currentFile.clearAutosave();
- this.editor.setStatus('');
-
- if (forceReload)
- {
- currentFile.reloadFile(mxUtils.bind(this, function()
- {
- currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
- }), mxUtils.bind(this, function(err)
- {
- currentFile.handleFileError(err, true);
- }));
- }
- else
- {
- currentFile.synchronizeFile(mxUtils.bind(this, function()
- {
- currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
- }), mxUtils.bind(this, function(err)
- {
- currentFile.handleFileError(err, true);
- }));
- }
- }
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection,
- currentPage, node, compact, file, uncompressed)
- {
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
- currentPage = (currentPage != null) ? currentPage : false;
- var graph = this.editor.graph;
-
- // Forces compression of embedded XML
- if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
- {
- uncompressed = false;
- var darkTheme = graph.themes != null && graph.defaultThemeName == 'darkTheme';
-
- // Exports SVG for first page while other page is visible by creating a graph
- // LATER: Add caching for the graph or SVG while not on first page
- // Dark mode requires a refresh that would destroy all handlers
- // LATER: Use dark theme here to bypass refresh
- if (darkTheme || (this.pages != null && this.currentPage != this.pages[0]))
- {
- var graphGetGlobalVariable = graph.getGlobalVariable;
- graph = this.createTemporaryGraph(graph.getStylesheet());
- var page = this.pages[0];
-
- graph.getGlobalVariable = function(name)
- {
- if (name == 'page')
- {
- return page.getName();
- }
- else if (name == 'pagenumber')
- {
- return 1;
- }
-
- return graphGetGlobalVariable.apply(this, arguments);
- };
-
- document.body.appendChild(graph.container);
- graph.model.setRoot(page.root);
- }
- }
-
- node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage, uncompressed);
- file = (file != null) ? file : this.getCurrentFile();
- var result = this.createFileData(node, graph, file, window.location.href,
- forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact,
- uncompressed);
-
- // Removes temporary graph from DOM
- if (graph != this.editor.graph)
- {
- graph.container.parentNode.removeChild(graph.container);
- }
-
- return result;
- };
-
- /**
- *
- */
- EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
- {
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
- var bg = null;
- var js = EditorUi.drawHost + '/js/embed-static.min.js';
-
- // LATER: Merge common code with EmbedDialog
- if (graph != null)
- {
- var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
- var scale = graph.view.scale;
- var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
- var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
- bg = graph.background;
-
- // Embed script only used if no redirect
- if (redirect == null)
- {
- var s = this.getBasenames().join(';');
-
- if (s.length > 0)
- {
- js = EditorUi.drawHost + '/embed.js?s=' + s;
- }
- }
-
- // Adds embed attributes
- node.setAttribute('x0', x0);
- node.setAttribute('y0', y0);
- }
-
- if (node != null)
- {
- node.setAttribute('pan', '1');
- node.setAttribute('zoom', '1');
- node.setAttribute('resize', '0');
- node.setAttribute('fit', '0');
- node.setAttribute('border', '20');
-
- // Hidden attributes
- node.setAttribute('links', '1');
-
- if (editLink != null)
- {
- node.setAttribute('edit', editLink);
- }
- }
-
- // Makes XHTML compatible
- if (redirect != null)
- {
- redirect = redirect.replace(/&/g, '&');
- }
-
- // Removes control chars in input for correct roundtrip check
- var text = (node != null) ? Graph.zapGremlins(mxUtils.getXml(node)) : '';
-
- // Double compression for mxfile not fixed since it may cause imcompatibilites with
- // embed clients that rely on this format. HTML files and export use getHtml2.
- var data = Graph.compress(text);
-
- // Fallback to URI encoded XML for invalid compression
- if (Graph.decompress(data) != text)
- {
- data = encodeURIComponent(text);
- }
-
- var style = 'position:relative;overflow:auto;width:100%;';
-
- return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
- '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
- '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
- '</title>\n' : '') : '<title>diagrams.net</title>\n') +
- ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
- '</head>\n<body' +
- (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
- '\n<div class="mxgraph" style="' + style + '">\n' +
- '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
- ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
- '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
- 'href="' + redirect + '" target="_blank"><img border="0" ' +
- 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
- '\n</body>\n</html>\n';
- };
-
- /**
- * Same as above but using the new embed code.
- */
- EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
- {
- var js = window.DRAWIO_VIEWER_URL || EditorUi.drawHost + '/js/viewer-static.min.js';
-
- // Makes XHTML compatible
- if (redirect != null)
- {
- redirect = redirect.replace(/&/g, '&');
- }
-
- var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
- xml: Graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
-
- if (this.pages != null && this.currentPage != null)
- {
- data.page = mxUtils.indexOf(this.pages, this.currentPage);
- }
-
- var style = 'max-width:100%;border:1px solid transparent;';
-
- return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
- '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
- '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
- '</title>\n' : '') : '<title>diagrams.net</title>\n') +
- ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
- '<meta charset="utf-8"/>\n</head>\n<body>' +
- '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
- ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
- '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
- 'href="' + redirect + '" target="_blank"><img border="0" ' +
- 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
- '\n</body>\n</html>\n';
- };
- /**
- *
- */
- EditorUi.prototype.setFileData = function(data)
- {
- data = this.validateFileData(data);
- this.currentPage = null;
- this.fileNode = null;
- this.pages = null;
- var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
-
- // Checks for parser errors
- var cause = Editor.extractParserError(node, mxResources.get('invalidOrMissingFile'));
-
- if (cause)
- {
- throw new Error(mxResources.get('notADiagramFile') + ' (' + cause + ')');
- }
- else
- {
- // Some nodes must be extracted here to find the mxfile node
- // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
- var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
-
- if (tmp != null)
- {
- node = tmp;
- }
- if (node != null && node.nodeName == 'mxfile')
- {
- var nodes = node.getElementsByTagName('diagram');
-
- if (urlParams['pages'] != '0' || nodes.length > 1 ||
- (nodes.length == 1 && nodes[0].hasAttribute('name')))
- {
- var selectedPage = null;
- this.fileNode = node;
- this.pages = [];
-
- // Wraps page nodes
- for (var i = 0; i < nodes.length; i++)
- {
- // Adds page ID based on page order to match
- // remote IDs given if IDs are missing here
- if (nodes[i].getAttribute('id') == null)
- {
- nodes[i].setAttribute('id', i);
- }
-
- var page = new DiagramPage(nodes[i]);
-
- // Checks for invalid page names
- if (page.getName() == null)
- {
- page.setName(mxResources.get('pageWithNumber', [i + 1]));
- }
-
- this.pages.push(page);
-
- if (urlParams['page-id'] != null && page.getId() == urlParams['page-id'])
- {
- selectedPage = page;
- }
- }
-
- this.currentPage = (selectedPage != null) ? selectedPage :
- this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
- node = this.currentPage.node;
- }
- }
-
- // Creates tabbed file structure if enforced by URL
- if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
- {
- this.fileNode = node.ownerDocument.createElement('mxfile');
- this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
- this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
- this.pages = [this.currentPage];
- }
-
- // Avoids scroll offset when switching page
- this.editor.setGraphXml(node);
-
- // Avoids duplicate parsing of the XML stored in the node
- if (this.currentPage != null)
- {
- this.currentPage.root = this.editor.graph.model.root;
- }
-
- if (urlParams['layer-ids'] != null)
- {
- try
- {
- var layerIds = urlParams['layer-ids'].split(' ');
- var layerIdsMap = {};
-
- for (var i = 0; i < layerIds.length; i++)
- {
- layerIdsMap[layerIds[i]] = true;
- }
-
- var model = this.editor.graph.getModel();
- var children = model.getChildren(model.root);
-
- // handle layers visibility
- for (var i = 0; i < children.length; i++)
- {
- var child = children[i];
- model.setVisible(child, layerIdsMap[child.id] || false);
- }
- }
- catch(e){} //ignore
- }
- }
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getBaseFilename = function(ignorePageName)
- {
- var file = this.getCurrentFile();
- var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
-
- if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
- /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename) ||
- /(\.drawio)$/i.test(basename))
- {
- basename = basename.substring(0, basename.lastIndexOf('.'));
- }
- if (!ignorePageName && this.pages != null && this.pages.length > 1 &&
- this.currentPage != null && this.currentPage.node.getAttribute('name') != null &&
- this.currentPage.getName().length > 0)
- {
- basename = basename + '-' + this.currentPage.getName();
- }
-
- return basename;
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.downloadFile = function(format, uncompressed, addShadow, ignoreSelection, currentPage,
- pageVisible, transparent, scale, border, grid, includeXml)
- {
- try
- {
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
- var basename = this.getBaseFilename(!currentPage);
- var filename = basename + '.' + format;
-
- if (format == 'xml')
- {
- var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
- this.getFileData(true, null, null, null, ignoreSelection, currentPage,
- null, null, null, uncompressed);
-
- this.saveData(filename, format, data, 'text/xml');
- }
- else if (format == 'html')
- {
- var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
- this.saveData(filename, format, data, 'text/html');
- }
- else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
- {
- var svg = null;
-
- var saveSvg = mxUtils.bind(this, function(data)
- {
- if (data.length <= MAX_REQUEST_SIZE)
- {
- this.saveData(filename, 'svg', data, 'image/svg+xml');
- }
- else
- {
- this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
- {
- mxUtils.popup(svg);
- }));
- }
- });
-
- if (format == 'svg')
- {
- var bg = this.editor.graph.background;
-
- if (transparent || bg == mxConstants.NONE)
- {
- bg = null;
- }
-
- // Sets or disables alternate text for foreignObjects. Disabling is needed
- // because PhantomJS seems to ignore switch statements and paint all text.
- var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
-
- if (addShadow)
- {
- this.editor.graph.addSvgShadow(svgRoot);
- }
-
- // Embeds the images in the SVG output (async)
- this.editor.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
- {
- this.spinner.stop();
-
- saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
- mxUtils.getXml(svgRoot2));
- })));
- }
- else
- {
- filename = basename + '.svg';
-
- svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
- {
- this.spinner.stop();
- saveSvg(svg);
- }), ignoreSelection);
- }
- }
- else
- {
- if (format == 'xmlpng')
- {
- filename = basename + '.png';
- }
- else if (format == 'jpeg')
- {
- filename = basename + '.jpg';
- }
-
- this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
- {
- try
- {
- var prev = this.editor.graph.pageVisible;
-
- if (pageVisible != null)
- {
- this.editor.graph.pageVisible = pageVisible;
- }
-
- var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64,
- transparent, currentPage, scale, border, grid, includeXml);
- this.editor.graph.pageVisible = prev;
-
- return req;
- }
- catch (e)
- {
- this.handleError(e);
- }
- }));
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64, transparent,
- currentPage, scale, border, grid, includeXml)
- {
- var graph = this.editor.graph;
- var bounds = graph.getGraphBounds();
-
- // Exports only current page for images that does not contain file data, but for
- // the other formats with XML included or pdf with all pages, we need to send the complete data and use
- // the from/to URL parameters to specify the page to be exported.
- var data = this.getFileData(true, null, null, null, ignoreSelection, currentPage == false? false : format != 'xmlpng');
- var range = '';
- var allPages = '';
-
- if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
- {
- throw {message: mxResources.get('drawingTooLarge')};
- }
-
- var embed = (includeXml) ? '1' : '0';
-
- if (format == 'pdf' && currentPage == false)
- {
- allPages = '&allPages=1';
- }
-
- if (format == 'xmlpng')
- {
- embed = '1';
- format = 'png';
-
- // Finds the current page number
- if (this.pages != null && this.currentPage != null)
- {
- for (var i = 0; i < this.pages.length; i++)
- {
- if (this.pages[i] == this.currentPage)
- {
- range = '&from=' + i;
- break;
- }
- }
- }
- }
-
- var bg = graph.background;
-
- if ((format == 'png' || format == 'pdf') && transparent)
- {
- bg = mxConstants.NONE;
- }
- else if (!transparent && (bg == null || bg == mxConstants.NONE))
- {
- bg = '#ffffff';
- }
-
- var extras = {globalVars: graph.getExportVariables()};
-
- if (grid)
- {
- extras.grid = {
- size: graph.gridSize,
- steps: graph.view.gridSteps,
- color: graph.view.gridColor
- };
- }
-
- if (Graph.translateDiagram)
- {
- extras.diagramLanguage = Graph.diagramLanguage;
- }
-
- return new mxXmlRequest(EXPORT_URL, 'format=' + format + range + allPages +
- '&bg=' + ((bg != null) ? bg : mxConstants.NONE) +
- '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
- encodeURIComponent(data) + ((filename != null) ?
- '&filename=' + encodeURIComponent(filename) : '') +
- '&extras=' + encodeURIComponent(JSON.stringify(extras)) +
- (scale != null? '&scale=' + scale : '') +
- (border != null? '&border=' + border : ''));
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.setMode = function(mode, remember)
- {
- this.mode = mode;
- };
- /**
- * Loads the given file descriptor. The descriptor may define the following properties:
- *
- * - url: The url to load the data from (proxy is used if CORS is not enabled)
- * - data: The data to be inserted. If both, data and url are defined, then the data
- * is preprendended to the data returned from the given URL.
- * - format: Currently, only 'csv' is supported as an optional value. Default is XML.
- * - update: Optional URL to fetch updates from (POST request with the page XML).
- * - interval: Optional interval for fetching updates. Default is 60000 (60 seconds).
- */
- EditorUi.prototype.loadDescriptor = function(desc, success, error)
- {
- var hash = window.location.hash;
-
- var loadData = mxUtils.bind(this, function(data)
- {
- var realData = (desc.data != null) ? desc.data : '';
-
- if (data != null && data.length > 0)
- {
- if (realData.length > 0)
- {
- realData += '\n';
- }
-
- realData += data;
- }
- var xml = (desc.format != 'csv' && realData.length > 0) ? realData : this.emptyDiagramXml;
- var tempFile = new LocalFile(this, xml, (urlParams['title'] != null) ?
- decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
- tempFile.getHash = function()
- {
- return hash;
- };
- this.fileLoaded(tempFile);
-
- if (desc.format == 'csv')
- {
- this.importCsv(realData, mxUtils.bind(this, function(cells)
- {
- this.editor.undoManager.clear();
- this.editor.setModified(false);
- this.editor.setStatus('');
- }));
- }
-
- // Installs updates
- if (desc.update != null)
- {
- var interval = (desc.interval != null) ? parseInt(desc.interval) : 60000;
- var currentThread = null;
-
- var doUpdate = mxUtils.bind(this, function()
- {
- var page = this.currentPage;
-
- mxUtils.post(desc.update, 'xml=' + encodeURIComponent(
- mxUtils.getXml(this.editor.getGraphXml())),
- mxUtils.bind(this, function(req)
- {
- if (page === this.currentPage)
- {
- if (req.getStatus() >= 200 && req.getStatus() <= 300)
- {
- var doc = this.updateDiagram(req.getText());
- schedule();
- }
- else
- {
- this.handleError({message: mxResources.get('error') + ' ' + req.getStatus()});
- }
- }
- }), mxUtils.bind(this, function(err)
- {
- this.handleError(err);
- }));
- });
-
- var schedule = mxUtils.bind(this, function()
- {
- window.clearTimeout(currentThread);
- currentThread = window.setTimeout(doUpdate, interval);
- });
-
- this.editor.addListener('pageSelected', mxUtils.bind(this, function()
- {
- schedule();
- doUpdate();
- }));
-
- schedule();
- doUpdate();
- }
-
- if (success != null)
- {
- success();
- }
- });
-
- if (desc.url != null && desc.url.length > 0)
- {
- // Cannot use proxy here as it will block unknown text content
- // LATER: Remove cache-control header
- this.editor.loadUrl(desc.url, mxUtils.bind(this, function(data)
- {
- loadData(data);
- }), mxUtils.bind(this, function(err)
- {
- if (error != null)
- {
- error(err)
- }
- }));
- }
- else
- {
- loadData('');
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.updateDiagram = function(xml)
- {
- var doc = null;
- var ui = this;
-
- function createOverlay(desc)
- {
- var overlay = new mxCellOverlay(desc.image || graph.warningImage,
- desc.tooltip, desc.align, desc.valign, desc.offset);
- // Installs a handler for clicks on the overlay
- overlay.addListener(mxEvent.CLICK, function(sender, evt)
- {
- ui.alert(desc.tooltip);
- });
-
- return overlay;
- };
-
- if (xml != null && xml.length > 0)
- {
- doc = mxUtils.parseXml(xml);
- var node = (doc != null) ? doc.documentElement : null;
-
- if (node != null && node.nodeName == 'updates')
- {
- var graph = this.editor.graph;
- var model = graph.getModel();
- model.beginUpdate();
- var fit = null;
- try
- {
- node = node.firstChild;
-
- while (node != null)
- {
- if (node.nodeName == 'update')
- {
- // Resolves the cell ID
- var cell = model.getCell(node.getAttribute('id'));
-
- if (cell != null)
- {
- // Changes the value
- try
- {
- var value = node.getAttribute('value');
-
- if (value != null)
- {
- var valueNode = mxUtils.parseXml(value).documentElement;
- if (valueNode != null)
- {
- if (valueNode.getAttribute('replace-value') == '1')
- {
- model.setValue(cell, valueNode);
- }
- else
- {
- var attrs = valueNode.attributes;
-
- for (var j = 0; j < attrs.length; j++)
- {
- graph.setAttributeForCell(cell, attrs[j].nodeName,
- (attrs[j].nodeValue.length > 0) ? attrs[j].nodeValue : null);
- }
- }
- }
- }
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.log('Error in value for ' + cell.id + ': ' + e);
- }
- }
-
- // Changes the style
- try
- {
- var style = node.getAttribute('style');
-
- if (style != null)
- {
- graph.model.setStyle(cell, style);
- }
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.log('Error in style for ' + cell.id + ': ' + e);
- }
- }
-
- // Adds or removes an overlay icon
- try
- {
- var icon = node.getAttribute('icon');
-
- if (icon != null)
- {
- var desc = (icon.length > 0) ? JSON.parse(icon) : null;
-
- if (desc == null || !desc.append)
- {
- graph.removeCellOverlays(cell);
- }
-
- if (desc != null)
- {
- graph.addCellOverlay(cell, createOverlay(desc));
- }
- }
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.log('Error in icon for ' + cell.id + ': ' + e);
- }
- }
-
- // Replaces the geometry
- try
- {
- var geo = node.getAttribute('geometry');
-
- if (geo != null)
- {
- geo = JSON.parse(geo);
- var curr = graph.getCellGeometry(cell);
-
- if (curr != null)
- {
- curr = curr.clone();
-
- // Partially overwrites geometry
- for (key in geo)
- {
- var val = parseFloat(geo[key]);
-
- if (key == 'dx')
- {
- curr.x += val;
- }
- else if (key == 'dy')
- {
- curr.y += val;
- }
- else if (key == 'dw')
- {
- curr.width += val;
- }
- else if (key == 'dh')
- {
- curr.height += val;
- }
- else
- {
- curr[key] = parseFloat(geo[key]);
- }
- }
-
- graph.model.setGeometry(cell, curr);
- }
- }
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.log('Error in icon for ' + cell.id + ': ' + e);
- }
- }
- } // if cell != null
- } // if node.nodeName == 'update
- else if (node.nodeName == 'model')
- {
- // Finds first child element
- var dataNode = node.firstChild;
-
- while (dataNode != null && dataNode.nodeType != mxConstants.NODETYPE_ELEMENT)
- {
- dataNode = dataNode.nextSibling;
- }
-
- if (dataNode != null)
- {
- var dec = new mxCodec(node.firstChild);
- dec.decode(dataNode, model);
- }
- }
- else if (node.nodeName == 'view')
- {
- if (node.hasAttribute('scale'))
- {
- graph.view.scale = parseFloat(node.getAttribute('scale'));
- }
-
- if (node.hasAttribute('dx') || node.hasAttribute('dy'))
- {
- graph.view.translate = new mxPoint(parseFloat(node.getAttribute('dx') || 0),
- parseFloat(node.getAttribute('dy') || 0));
- }
- }
- else if (node.nodeName == 'fit')
- {
- if (node.hasAttribute('max-scale'))
- {
- fit = parseFloat(node.getAttribute('max-scale'));
- }
- else
- {
- fit = 1;
- }
- }
-
- node = node.nextSibling;
- } // end of while
- }
- finally
- {
- model.endUpdate();
- }
-
- if (fit != null && this.chromelessResize)
- {
- this.chromelessResize(true, fit);
- }
- }
- }
-
- return doc;
- };
-
- /**
- * Constructs a filename for a copy of the given file.
- */
- EditorUi.prototype.getCopyFilename = function(file, timestamp)
- {
- var title = (file != null && file.getTitle() != null) ?
- file.getTitle() : this.defaultFilename;
-
- // Handles extension
- var extension = '';
- var dot = title.lastIndexOf('.');
-
- if (dot >= 0)
- {
- extension = title.substring(dot);
- title = title.substring(0, dot);
- }
-
- if (timestamp)
- {
- function getFormattedTime()
- {
- var today = new Date();
- var y = today.getFullYear();
- // JavaScript months are 0-based.
- var m = today.getMonth() + 1;
- var d = today.getDate();
- var h = today.getHours();
- var mi = today.getMinutes();
- var s = today.getSeconds();
-
- return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
- }
-
- var ts = new Date();
- title += ' ' + getFormattedTime();
- }
-
- title = mxResources.get('copyOf', [title]) + extension;
-
- return title;
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.fileLoaded = function(file, noDialogs)
- {
- var oldFile = this.getCurrentFile();
- this.fileLoadedError = null;
- this.fileEditable = null;
- this.setCurrentFile(null);
- var result = false;
- this.hideDialog();
-
- if (oldFile != null)
- {
- EditorUi.debug('File.closed', [oldFile]);
- oldFile.removeListener(this.descriptorChangedListener);
- oldFile.close();
- }
-
- this.editor.graph.model.clear();
- this.editor.undoManager.clear();
-
- var noFile = mxUtils.bind(this, function()
- {
- this.setGraphEnabled(false);
- this.setCurrentFile(null);
-
- // Keeps initial title if no file existed before
- if (oldFile != null)
- {
- this.updateDocumentTitle();
- }
-
- // File might have been loaded halfway
- this.editor.graph.model.clear();
- this.editor.undoManager.clear();
- this.setBackgroundImage(null);
-
- // Avoids empty hash with no value
- if (!noDialogs && window.location.hash != null && window.location.hash.length > 0)
- {
- window.location.hash = '';
- }
-
- if (this.fname != null)
- {
- this.fnameWrapper.style.display = 'none';
- this.fname.innerHTML = '';
- this.fname.setAttribute('title', mxResources.get('rename'));
- }
- this.editor.setStatus('');
- this.updateUi();
-
- if (!noDialogs)
- {
- this.showSplash();
- }
- });
-
- if (file != null)
- {
- try
- {
- // Workaround for delayed scroll repaint with min UI in Safari
- if (mxClient.IS_SF && uiTheme == 'min')
- {
- this.diagramContainer.style.visibility = '';
- }
-
- // Order is significant, current file needed for correct
- // file format for initial save after starting realtime
- this.openingFile = true;
- this.setCurrentFile(file);
- file.addListener('descriptorChanged', this.descriptorChangedListener);
- file.addListener('contentChanged', this.descriptorChangedListener);
- file.open();
- delete this.openingFile;
-
- // DescriptorChanged updates the enabled state of the graph
- this.setGraphEnabled(true);
- this.setMode(file.getMode());
- this.editor.graph.model.prefix = Editor.guid() + '-';
- this.editor.undoManager.clear();
- this.descriptorChanged();
- this.updateUi();
-
- // Realtime files have a valid status message
- if (!file.isEditable())
- {
- this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
- mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
- }
- // Handles modified state after error of loading new file
- else if (file.isModified())
- {
- file.addUnsavedStatus();
-
- // Restores unsaved data
- if (file.backupPatch != null)
- {
- file.patch([file.backupPatch]);
- }
- }
- else
- {
- this.editor.setStatus('');
- }
-
- if (!this.editor.isChromelessView() || this.editor.editable)
- {
- this.editor.graph.selectUnlockedLayer();
- this.showLayersDialog();
- this.restoreLibraries();
-
- // Workaround for no initial focus in FF
- if (window.self !== window.top)
- {
- window.focus();
- }
- }
- else if (this.editor.graph.isLightboxView())
- {
- this.lightboxFit();
- }
-
- if (this.chromelessResize)
- {
- this.chromelessResize();
- }
-
- this.editor.fireEvent(new mxEventObject('fileLoaded'));
- result = true;
- if (!this.isOffline() && file.getMode() != null)
- {
- EditorUi.logEvent({category: file.getMode().toUpperCase() + '-OPEN-FILE-' + file.getHash(),
- action: 'size_' + file.getSize(),
- label: 'autosave_' + ((this.editor.autosave) ? 'on' : 'off')});
- }
-
- EditorUi.debug('File.opened', [file]);
-
- if (this.editor.editable && this.mode == file.getMode() &&
- file.getMode() != App.MODE_DEVICE && file.getMode() != null)
- {
- try
- {
- this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
- }
- catch (e)
- {
- // ignore
- }
- }
-
- try
- {
- mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
- mxSettings.save();
- }
- catch (e)
- {
- // ignore
- }
- }
- catch (e)
- {
- this.fileLoadedError = e;
-
- if (EditorUi.enableLogging && !this.isOffline())
- {
- try
- {
- EditorUi.logEvent({category: 'ERROR-LOAD-FILE-' +
- ((file != null) ? file.getHash() : 'none'),
- action: 'message_' + e.message,
- label: 'stack_' + e.stack});
- }
- catch (e)
- {
- // ignore
- }
- }
-
- // Asynchronous handling of errors
- var fn = mxUtils.bind(this, function()
- {
- // Removes URL parameter and reloads the page
- if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
- {
- window.location.search = this.getSearch(['url']);
- }
- else if (oldFile != null)
- {
- this.fileLoaded(oldFile);
- }
- else
- {
- noFile();
- }
- });
-
- if (!noDialogs)
- {
- this.handleError(e, mxResources.get('errorLoadingFile'), fn, true, null, null, true);
- }
- else
- {
- fn();
- }
- }
- }
- else
- {
- noFile();
- }
-
- return result;
- };
- /**
- * Creates a hash value for the current file.
- */
- EditorUi.prototype.getHashValueForPages = function(pages, details)
- {
- // TODO: Avoid encoding to XML to make it faster
- var hash = 0;
- var model = new mxGraphModel();
- var codec = new mxCodec();
- if (details != null)
- {
- details.byteCount = 0;
- details.attrCount = 0;
- details.eltCount = 0;
- details.nodeCount = 0;
- }
-
- for (var i = 0; i < pages.length; i++)
- {
- this.updatePageRoot(pages[i]);
- var diagram = pages[i].node.cloneNode(false);
-
- // FIXME: Check why names can be null in newer files
- // ignore in hash and do not diff null names for now
- diagram.removeAttribute('name');
-
- // Model is only a holder for the root
- model.root = pages[i].root;
- var xmlNode = codec.encode(model);
- this.editor.graph.saveViewState(pages[i].viewState, xmlNode, true);
-
- // Local defaults may be different in files so ignore
- xmlNode.removeAttribute('pageWidth');
- xmlNode.removeAttribute('pageHeight');
-
- diagram.appendChild(xmlNode);
-
- if (details != null)
- {
- details.eltCount += diagram.getElementsByTagName('*').length;
- details.nodeCount += diagram.getElementsByTagName('mxCell').length;
- }
-
- hash = ((hash << 5) - hash + this.hashValue(diagram, function(obj, key, value, isXml)
- {
- // Ignores JS machine rounding errors in known numeric attributes
- // eg. 412.33333333333326 (Webkit/FF) == 412.33333333333325 (Edge/IE11)
- if (isXml && (obj.nodeName == 'mxGeometry' || obj.nodeName == 'mxPoint') &&
- (key == 'x' || key == 'y' || key == 'width' || key == 'height'))
- {
- return Math.round(value);
- }
- // Workaround for previous in patch written to mxCell in 10.0.23
- else if (isXml && obj.nodeName == 'mxCell' && key == 'previous')
- {
- return null;
- }
- else
- {
- return value;
- }
- }, details)) << 0;
- }
-
- return hash;
- };
-
- /**
- * Creates a hash value for the given object. Replacer returns the value of the
- * property or attribute for the given object or XML node.
- */
- EditorUi.prototype.hashValue = function(obj, replacer, details)
- {
- var hash = 0;
-
- // Checks for XML nodes
- if (obj != null && typeof obj === 'object' && typeof obj.nodeType === 'number' &&
- typeof obj.nodeName === 'string' && typeof obj.getAttribute === 'function')
- {
- if (obj.nodeName != null)
- {
- hash = hash ^ this.hashValue(obj.nodeName, replacer, details);
- }
-
- if (obj.attributes != null)
- {
- if (details != null)
- {
- details.attrCount += obj.attributes.length;
- }
-
- for (var i = 0; i < obj.attributes.length; i++)
- {
- var key = obj.attributes[i].name;
- var value = (replacer != null) ? replacer(obj, key, obj.attributes[i].value, true) : obj.attributes[i].value;
-
- if (value != null)
- {
- hash = hash ^ (this.hashValue(key, replacer, details) +
- this.hashValue(value, replacer, details));
- }
- }
- }
-
- if (obj.childNodes != null)
- {
- for (var i = 0; i < obj.childNodes.length; i++)
- {
- hash = ((hash << 5) - hash + this.hashValue(
- obj.childNodes[i], replacer, details)) << 0;
- }
- }
- }
- else if (obj != null && typeof obj !== 'function')
- {
- var str = String(obj);
- var temp = 0;
- if (details != null)
- {
- details.byteCount += str.length;
- }
-
- for (var i = 0; i < str.length; i++)
- {
- temp = ((temp << 5) - temp + str.charCodeAt(i)) << 0;
- }
-
- hash = hash ^ temp;
- }
-
- return hash;
- };
- /**
- * Adds empty implementation
- */
- EditorUi.prototype.descriptorChanged = function()
- {
- // empty
- };
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.restoreLibraries = function() { };
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn) { };
-
- /**
- *
- */
- EditorUi.prototype.isScratchpadEnabled = function()
- {
- return isLocalStorage || mxClient.IS_CHROMEAPP;
- };
- /**
- * Shows or hides the scratchpad library.
- */
- EditorUi.prototype.toggleScratchpad = function()
- {
- if (this.isScratchpadEnabled())
- {
- if (this.scratchpad == null)
- {
- StorageFile.getFileContent(this, '.scratchpad', mxUtils.bind(this, function(xml)
- {
- if (xml == null)
- {
- xml = this.emptyLibraryXml;
- }
-
- this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
- }));
- }
- else
- {
- this.closeLibrary(this.scratchpad);
- }
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.createLibraryDataFromImages = function(images)
- {
- var doc = mxUtils.createXmlDocument();
- var library = doc.createElement('mxlibrary');
- mxUtils.setTextContent(library, JSON.stringify(images));
- doc.appendChild(library);
-
- return mxUtils.getXml(doc);
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.closeLibrary = function(file)
- {
- if (file != null)
- {
- this.removeLibrarySidebar(file.getHash());
-
- if (file.constructor != LocalLibrary)
- {
- mxSettings.removeCustomLibrary(file.getHash());
- }
-
- if (file.title == '.scratchpad')
- {
- this.scratchpad = null;
- }
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.removeLibrarySidebar = function(id)
- {
- var elts = this.sidebar.palettes[id];
-
- if (elts != null)
- {
- for (var i = 0; i < elts.length; i++)
- {
- elts[i].parentNode.removeChild(elts[i]);
- }
-
- delete this.sidebar.palettes[id];
- }
- };
-
- /**
- * Changes the position of the library in the sidebar
- */
- EditorUi.prototype.repositionLibrary = function(nextChild)
- {
- var c = this.sidebar.container;
-
- if (nextChild == null)
- {
- var elts = this.sidebar.palettes['L.scratchpad'];
-
- if (elts == null)
- {
- elts = this.sidebar.palettes['search'];
- }
-
- if (elts != null)
- {
- nextChild = elts[elts.length - 1].nextSibling;
- }
- }
-
- nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
-
- var content = c.lastChild;
- var title = content.previousSibling;
-
- c.insertBefore(content, nextChild);
- c.insertBefore(title, content);
- }
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.loadLibrary = function(file, expand)
- {
- var doc = mxUtils.parseXml(file.getData());
-
- if (doc.documentElement.nodeName == 'mxlibrary')
- {
- var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
- this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'), expand);
- }
- else
- {
- throw {message: mxResources.get('notALibraryFile')};
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getLibraryStorageHint = function(file)
- {
- return '';
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle, expand)
- {
- if (this.sidebar == null)
- {
- return;
- }
-
- if (file.constructor != LocalLibrary)
- {
- mxSettings.addCustomLibrary(file.getHash());
- }
-
- if (file.title == '.scratchpad')
- {
- this.scratchpad = file;
- }
-
- var elts = this.sidebar.palettes[file.getHash()];
- var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
-
- // Removes existing sidebar entry for this library
- this.removeLibrarySidebar(file.getHash());
- var dropTarget = null;
-
- var addImages = mxUtils.bind(this, function(imgs, content)
- {
- if (imgs.length == 0 && file.isEditable())
- {
- if (dropTarget == null)
- {
- dropTarget = document.createElement('div');
- dropTarget.className = 'geDropTarget';
- mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
- }
-
- content.appendChild(dropTarget);
- }
- else
- {
- this.addLibraryEntries(imgs, content);
- }
- });
- // Adds entries to search index
- // KNOWN: Existing entries are not replaced after edit of custom library
- if (this.sidebar != null && images != null)
- {
- this.sidebar.addEntries(images);
- }
-
- // Adds new sidebar entry for this library
- var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
- var contentDiv = this.sidebar.addPalette(file.getHash(), tmp,
- (expand != null) ? expand : true, mxUtils.bind(this, function(content)
- {
- addImages(images, content);
- }));
-
- this.repositionLibrary(nextSibling);
-
- // Adds tooltip for backend
- var title = contentDiv.parentNode.previousSibling;
- var tip = title.getAttribute('title');
-
- if (tip != null && tip.length > 0 && file.title != '.scratchpad')
- {
- title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
- }
-
- var buttons = document.createElement('div');
- buttons.style.position = 'absolute';
- buttons.style.right = '0px';
- buttons.style.top = '0px';
- buttons.style.padding = '8px'
- buttons.style.backgroundColor = 'inherit';
-
- title.style.position = 'relative';
-
- var btnWidth = 18;
- var btn = document.createElement('img');
- btn.setAttribute('src', Dialog.prototype.closeImage);
- btn.setAttribute('title', mxResources.get('close'));
- btn.setAttribute('valign', 'absmiddle');
- btn.setAttribute('border', '0');
- btn.style.cursor = 'pointer';
- btn.style.margin = '0 3px';
-
- var saveBtn = null;
-
- if (file.title != '.scratchpad' || this.closableScratchpad)
- {
- buttons.appendChild(btn);
-
- mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
- {
- // Workaround for close after any button click in IE8
- if (!mxEvent.isConsumed(evt))
- {
- var fn = mxUtils.bind(this, function()
- {
- this.closeLibrary(file);
- });
-
- if (saveBtn != null)
- {
- this.confirm(mxResources.get('allChangesLost'), null, fn,
- mxResources.get('cancel'), mxResources.get('discardChanges'));
- }
- else
- {
- fn();
- }
-
- mxEvent.consume(evt);
- }
- }));
- }
-
- if (file.isEditable())
- {
- var graph = this.editor.graph;
- var spinBtn = null;
-
- var editLibrary = mxUtils.bind(this, function(evt)
- {
- this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
- mxEvent.consume(evt);
- });
-
- var saveLibrary = mxUtils.bind(this, function(evt)
- {
- file.setModified(true);
-
- if (file.isAutosave())
- {
- if (spinBtn != null && spinBtn.parentNode != null)
- {
- spinBtn.parentNode.removeChild(spinBtn);
- }
-
- spinBtn = btn.cloneNode(false);
- spinBtn.setAttribute('src', Editor.spinImage);
- spinBtn.setAttribute('title', mxResources.get('saving'));
- spinBtn.style.cursor = 'default';
- spinBtn.style.marginRight = '2px';
- spinBtn.style.marginTop = '-2px';
- buttons.insertBefore(spinBtn, buttons.firstChild);
- title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
-
- this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
- {
- if (spinBtn != null && spinBtn.parentNode != null)
- {
- spinBtn.parentNode.removeChild(spinBtn);
- title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
- }
- });
- }
- else if (saveBtn == null)
- {
- saveBtn = btn.cloneNode(false);
- saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
- saveBtn.setAttribute('title', mxResources.get('save'));
- buttons.insertBefore(saveBtn, buttons.firstChild);
-
- mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
- {
- this.saveLibrary(file.getTitle(), images, file, file.getMode(),
- file.constructor == LocalLibrary, true, function()
- {
- if (saveBtn != null && !file.isModified())
- {
- title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
- saveBtn.parentNode.removeChild(saveBtn);
- saveBtn = null;
- }
- });
-
- mxEvent.consume(evt);
- }));
-
- title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
- }
- });
-
- var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
- {
- cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
-
- // Translates cells to origin
- for (var i = 0; i < cells.length; i++)
- {
- var geo = graph.getCellGeometry(cells[i]);
-
- if (geo != null)
- {
- geo.translate(-bounds.x, -bounds.y);
- }
- }
-
- contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
- cells, bounds.width, bounds.height, title || '', true, false, false));
-
- var xml = Graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
- var entry = {xml: xml, w: bounds.width, h: bounds.height};
-
- if (title != null)
- {
- entry.title = title;
- }
-
- images.push(entry);
- saveLibrary(evt);
-
- if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
- {
- dropTarget.parentNode.removeChild(dropTarget);
- dropTarget = null;
- }
- });
-
- var addSelection = mxUtils.bind(this, function(evt)
- {
- if (!graph.isSelectionEmpty())
- {
- var cells = graph.getSelectionCells();
- var bounds = graph.view.getBounds(cells);
-
- var s = graph.view.scale;
-
- bounds.x /= s;
- bounds.y /= s;
- bounds.width /= s;
- bounds.height /= s;
-
- bounds.x -= graph.view.translate.x;
- bounds.y -= graph.view.translate.y;
-
- addCells(cells, bounds);
- }
- else if (graph.getRubberband().isActive())
- {
- graph.getRubberband().execute(evt);
- graph.getRubberband().reset();
- }
- else
- {
- this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
- }
-
- mxEvent.consume(evt);
- });
-
- // Adds drop handler from graph
- mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
- {
- if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.first != null)
- {
- graph.graphHandler.suspend();
-
- if (graph.graphHandler.hint != null)
- {
- graph.graphHandler.hint.style.visibility = 'hidden';
- }
-
- contentDiv.style.backgroundColor = '#f1f3f4';
- contentDiv.style.cursor = 'copy';
- graph.panningManager.stop();
- graph.autoScroll = false;
-
- mxEvent.consume(evt);
- }
- }), mxUtils.bind(this, function(evt)
- {
- if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
- {
- contentDiv.style.backgroundColor = '';
- contentDiv.style.cursor = 'default';
- this.sidebar.showTooltips = true;
- graph.panningManager.stop();
-
- graph.graphHandler.reset();
- graph.isMouseDown = false;
- graph.autoScroll = true;
-
- addSelection(evt);
- mxEvent.consume(evt);
- }
- }));
-
- // Handles mouse leaving the library and restoring move
- mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
- {
- if (graph.isMouseDown && graph.graphHandler.first != null)
- {
- graph.graphHandler.resume();
- if (graph.graphHandler.hint != null)
- {
- graph.graphHandler.hint.style.visibility = 'visible';
- }
-
- contentDiv.style.backgroundColor = '';
- contentDiv.style.cursor = '';
- graph.autoScroll = true;
- }
- }));
-
- // Adds drop handler from filesystem
- if (Graph.fileSupport)
- {
- mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
- {
- contentDiv.style.backgroundColor = '#f1f3f4';
- evt.dataTransfer.dropEffect = 'copy';
- contentDiv.style.cursor = 'copy';
- this.sidebar.hideTooltip();
- evt.stopPropagation();
- evt.preventDefault();
- }));
-
- mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
- {
- contentDiv.style.cursor = '';
- contentDiv.style.backgroundColor = '';
-
- if (evt.dataTransfer.files.length > 0)
- {
- this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
- {
- if (data != null && mimeType.substring(0, 6) == 'image/')
- {
- var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;aspect=fixed;image=' +
- this.convertDataUri(data);
- var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
- cells[0].vertex = true;
-
- addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
- if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
- {
- dropTarget.parentNode.removeChild(dropTarget);
- dropTarget = null;
- }
- }
- else
- {
- var done = false;
-
- var doImport = mxUtils.bind(this, function(theData, theMimeType)
- {
- if (theData != null && theMimeType == 'application/pdf')
- {
- var xml = Editor.extractGraphModelFromPdf(theData);
-
- if (xml != null && xml.length > 0)
- {
- theMimeType = 'text/xml';
- theData = xml;
- }
- }
-
- if (theData != null) //Try to parse the file as xml (can be a library or mxfile). Otherwise, an error will be shown
- {
- var doc = mxUtils.parseXml(theData);
-
- if (doc.documentElement.nodeName == 'mxlibrary')
- {
- try
- {
- var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
- addImages(temp, contentDiv);
- images = images.concat(temp);
- saveLibrary(evt);
- this.spinner.stop();
- done = true;
- }
- catch (e)
- {
- // ignore
- }
- }
- else if (doc.documentElement.nodeName == 'mxfile')
- {
- try
- {
- var pages = doc.documentElement.getElementsByTagName('diagram');
-
- for (var i = 0; i < pages.length; i++)
- {
- var cells = this.stringToCells(Editor.getDiagramNodeXml(pages[i]));
- var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
- addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
- }
-
- done = true;
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.log('error in drop handler:', e);
- }
- }
- }
- }
-
- if (!done)
- {
- this.spinner.stop();
- this.handleError({message: mxResources.get('errorLoadingFile')})
- }
- if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
- {
- dropTarget.parentNode.removeChild(dropTarget);
- dropTarget = null;
- }
- });
-
- if (file != null && img != null && ((/(\.v(dx|sdx?))($|\?)/i.test(img)) || /(\.vs(x|sx?))($|\?)/i.test(img)))
- {
- this.importVisio(file, function(xml)
- {
- doImport(xml, 'text/xml');
- }, null, img);
- }
- else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
- {
- this.parseFile(file, mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4)
- {
- this.spinner.stop();
-
- if (xhr.status >= 200 && xhr.status <= 299)
- {
- doImport(xhr.responseText, 'text/xml');
- }
- else
- {
- this.handleError({message: mxResources.get((xhr.status == 413) ?
- 'drawingTooLarge' : 'invalidOrMissingFile')},
- mxResources.get('errorLoadingFile'));
- }
- }
- }));
- }
- else
- {
- doImport(data, mimeType);
- }
- }
- }));
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- }));
-
- mxEvent.addListener(contentDiv, 'dragleave', function(evt)
- {
- contentDiv.style.cursor = '';
- contentDiv.style.backgroundColor = '';
- evt.stopPropagation();
- evt.preventDefault();
- });
- }
-
- btn = btn.cloneNode(false);
- btn.setAttribute('src', Editor.editImage);
- btn.setAttribute('title', mxResources.get('edit'));
- buttons.insertBefore(btn, buttons.firstChild);
-
- mxEvent.addListener(btn, 'click', editLibrary);
- mxEvent.addListener(contentDiv, 'dblclick', function(evt)
- {
- if (mxEvent.getSource(evt) == contentDiv)
- {
- editLibrary(evt);
- }
- });
-
- var btn2 = btn.cloneNode(false);
- btn2.setAttribute('src', Editor.plusImage);
- btn2.setAttribute('title', mxResources.get('add'));
- buttons.insertBefore(btn2, buttons.firstChild);
- mxEvent.addListener(btn2, 'click', addSelection);
-
- if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
- {
- var link = document.createElement('span');
- link.setAttribute('title', mxResources.get('help'));
- link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
- mxUtils.write(link, '?');
-
- mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
- {
- this.openLink(EditorUi.scratchpadHelpLink);
- mxEvent.consume(evt);
- }));
-
- buttons.insertBefore(link, buttons.firstChild);
- }
- }
-
- title.appendChild(buttons);
- title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
- };
- /**
- * Adds the library entries to the given DOM node.
- */
- EditorUi.prototype.addLibraryEntries = function(imgs, content)
- {
- for (var i = 0; i < imgs.length; i++)
- {
- var img = imgs[i];
- var data = img.data;
- if (data != null)
- {
- data = this.convertDataUri(data);
- var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
-
- if (img.aspect == 'fixed')
- {
- s += 'aspect=fixed;'
- }
-
- content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
- data, img.w, img.h, '', img.title || '', false, false, true));
- }
- else if (img.xml != null)
- {
- var cells = this.stringToCells(Graph.decompress(img.xml));
-
- if (cells.length > 0)
- {
- content.appendChild(this.sidebar.createVertexTemplateFromCells(
- cells, img.w, img.h, img.title || '', true, false, true));
- }
- }
- }
- };
- /**
- * Extracts the resource for the current language from the given multi language
- * resource object of the form {es: "...", de: "...", main: "..."} where the keys
- * are country codes and main defines the fallback if no resource for the current
- * country code exists.
- */
- EditorUi.prototype.getResource = function(obj)
- {
- return (obj != null) ? (obj[mxLanguage] || obj.main) : null;
- };
-
- /**
- * EditorUi Overrides
- */
- EditorUi.prototype.footerHeight = 0;
-
- if (urlParams['savesidebar'] == '1')
- {
- Sidebar.prototype.thumbWidth = 64;
- Sidebar.prototype.thumbHeight = 64;
- }
- /**
- * Programmatic settings for theme.
- */
- EditorUi.initTheme = function()
- {
- if (uiTheme == 'atlas')
- {
- mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
- if (typeof Toolbar !== 'undefined')
- {
- Toolbar.prototype.unselectedBackground = 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
- Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
- }
-
- Editor.prototype.initialTopSpacing = 3;
- EditorUi.prototype.menubarHeight = 41;
- EditorUi.prototype.toolbarHeight = 38;
- }
- else if (Editor.isDarkMode())
- {
- mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
- Dialog.backdropColor = '#2a2a2a';
- Format.inactiveTabBackgroundColor = 'black';
- Graph.prototype.defaultThemeName = 'darkTheme';
- Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
- Graph.prototype.defaultPageBorderColor = '#505759';
- BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
- mxGraphHandler.prototype.previewColor = '#cccccc';
- StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
- mxConstants.DROP_TARGET_COLOR = '#00ff00';
- }
- Editor.sketchFontFamily = 'Architects Daughter';
- Editor.sketchFontSource = 'https%3A%2F%2Ffonts.googleapis.com%2Fcss%3Ffamily%3DArchitects%2BDaughter';
- // Implements the sketch-min UI
- if (urlParams['sketch'] == '1')
- {
- Menus.prototype.defaultFonts = [{'fontFamily': Editor.sketchFontFamily,
- 'fontUrl': decodeURIComponent(Editor.sketchFontSource)},
- {'fontFamily': 'Rock Salt', 'fontUrl': 'https://fonts.googleapis.com/css?family=Rock+Salt'},
- {'fontFamily': 'Permanent Marker', 'fontUrl': 'https://fonts.googleapis.com/css?family=Permanent+Marker'}].
- concat(Menus.prototype.defaultFonts);
- Graph.prototype.defaultVertexStyle = {'fontFamily': Editor.sketchFontFamily , 'fontSize': '20',
- 'fontSource': Editor.sketchFontSource, 'pointerEvents': '0', 'sketch':
- urlParams['rough'] == '0' ? '0' : '1', 'hachureGap': '4'};
-
- Graph.prototype.defaultEdgeStyle = {'edgeStyle': 'none', 'rounded': '0', 'curved': '1',
- 'jettySize': 'auto', 'orthogonalLoop': '1', 'endArrow': 'open', 'startSize': '14', 'endSize': '14',
- 'fontFamily': Editor.sketchFontFamily, 'fontSize': '20','fontSource': Editor.sketchFontSource,
- 'sourcePerimeterSpacing': '8', 'targetPerimeterSpacing': '8', 'sketch':
- urlParams['rough'] == '0' ? '0' : '1'};
-
- Editor.configurationKey = '.sketch-configuration';
- Editor.settingsKey = '.sketch-config';
- Graph.prototype.defaultGridEnabled = false;
- Graph.prototype.defaultPageVisible = false;
- Graph.prototype.defaultEdgeLength = 120;
- Editor.fitWindowBorders = new mxRectangle(60, 30, 30, 30);
- }
- };
-
- EditorUi.initTheme();
- /**
- * Overrides image dialog to add image search and Google+.
- */
- EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
- {
- // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
- var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
- this.showDialog(dlg.container, (Graph.fileSupport) ? 480 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
- dlg.init();
- };
- /**
- * Hides the current menu.
- */
- EditorUi.prototype.showBackgroundImageDialog = function(apply, img)
- {
- apply = (apply != null) ? apply : mxUtils.bind(this, function(image, failed)
- {
- if (!failed)
- {
- var change = new ChangePageSetup(this, null, image);
- change.ignoreColor = true;
-
- this.editor.graph.model.execute(change);
- }
- });
- var dlg = new BackgroundImageDialog(this, apply, img);
- this.showDialog(dlg.container, 360, 200, true, true);
- dlg.init();
- };
- /**
- * Hides the current menu.
- */
- EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
- {
- var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
-
- this.showDialog(dlg.container, 640, 440, true, false, mxUtils.bind(this, function(cancel)
- {
- if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
- {
- this.showSplash();
- }
- }));
-
- dlg.init();
- };
- /**
- * Overridden to update after view state changes.
- */
- var editorUiCreateFormat = EditorUi.prototype.createFormat;
-
- EditorUi.prototype.createFormat = function(container)
- {
- var format = editorUiCreateFormat.apply(this, arguments);
-
- this.editor.graph.addListener('viewStateChanged', mxUtils.bind(this, function(evt)
- {
- if (this.editor.graph.isSelectionEmpty())
- {
- format.refresh();
- }
- }));
-
- return format;
- };
-
- /**
- * Hook for sidebar footer container.
- */
- EditorUi.prototype.createSidebarFooterContainer = function()
- {
- var div = this.createDiv('geSidebarContainer geSidebarFooter');
- div.style.position = 'absolute';
- div.style.overflow = 'hidden';
-
- var elt2 = document.createElement('a');
- elt2.className = 'geTitle';
- elt2.style.color = '#DF6C0C';
- elt2.style.fontWeight = 'bold';
- elt2.style.height = '100%';
- elt2.style.paddingTop = '9px';
- elt2.innerHTML = '<span style="font-size:18px;margin-right:5px;">+</span>';
- mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
- // Prevents focus
- mxEvent.addListener(elt2, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
- mxUtils.bind(this, function(evt)
- {
- evt.preventDefault();
- }));
-
- mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
- {
- this.actions.get('shapes').funct();
- mxEvent.consume(evt);
- }));
-
- div.appendChild(elt2);
-
- return div;
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose, notFoundMessage, fileHash, disableLogging)
- {
- var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
- var e = (resp != null && resp.error != null) ? resp.error : resp;
- // Logs errors and writes stack to console
- if (resp != null && resp.stack != null && resp.message != null)
- {
- try
- {
- if (!disableLogging)
- {
- EditorUi.logError('Caught: ' +
- (resp.message == '' && resp.name != null) ? resp.name : resp.message,
- resp.filename, resp.lineNumber, resp.columnNumber, resp, 'INFO');
- }
- else
- {
- if (window.console != null)
- {
- console.error('EditorUi.handleError:', resp);
- }
- }
- }
- catch (e)
- {
- // ignore
- }
- }
-
- if (e != null || title != null)
- {
- var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
- var btn = mxResources.get('ok');
- var retry = null;
- title = (title != null) ? title : mxResources.get('error');
-
- if (e != null)
- {
- if (e.retry != null)
- {
- btn = mxResources.get('cancel');
- retry = function()
- {
- resume();
- e.retry();
- };
- }
-
- if (e.code == 404 || e.status == 404 || e.code == 403)
- {
- if (e.code == 403)
- {
- if (e.message != null)
- {
- msg = mxUtils.htmlEntities(e.message);
- }
- else
- {
- msg = mxUtils.htmlEntities(mxResources.get('accessDenied'));
- }
- }
- else
- {
- msg = (notFoundMessage != null) ? notFoundMessage :
- mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied') +
- ((this.drive != null && this.drive.user != null) ? ' (' + this.drive.user.displayName +
- ', ' + this.drive.user.email+ ')' : ''));
- }
-
- var id = (notFoundMessage != null) ? null : ((fileHash != null) ? fileHash : window.location.hash);
-
- // #U handles case where we tried to fallback to Google File and
- // hash property still shows the public URL we tried to load
- if (id != null && (id.substring(0, 2) == '#G' ||
- id.substring(0, 45) == '#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D') &&
- ((resp != null && resp.error != null && ((resp.error.errors != null &&
- resp.error.errors.length > 0 && resp.error.errors[0].reason == 'fileAccess') ||
- (resp.error.data != null && resp.error.data.length > 0 &&
- resp.error.data[0].reason == 'fileAccess'))) ||
- e.code == 404 || e.status == 404))
- {
- id = (id.substring(0, 2) == '#U') ? id.substring(45, id.lastIndexOf('%26ex')) : id.substring(2);
-
- // Special case where the button must have a different label and function
- this.showError(title, msg, mxResources.get('openInNewWindow'), mxUtils.bind(this, function()
- {
- this.editor.graph.openLink('https://drive.google.com/open?id=' + id);
- this.handleError(resp, title, fn, invokeFnOnClose, notFoundMessage)
- }), retry, mxResources.get('changeUser'), mxUtils.bind(this, function()
- {
- var driveUsers = this.drive.getUsersList();
-
- var div = document.createElement('div');
-
- var title = document.createElement('span');
- title.style.marginTop = '6px';
- mxUtils.write(title, mxResources.get('changeUser') + ': ');
-
- div.appendChild(title);
-
- var usersSelect = document.createElement('select');
- usersSelect.style.width = '200px';
-
- //TODO This code is similar to Dialogs.js change user part in SplashDialog
- function fillUsersSelect()
- {
- usersSelect.innerHTML = '';
-
- for (var i = 0; i < driveUsers.length; i++)
- {
- var option = document.createElement('option');
- mxUtils.write(option, driveUsers[i].displayName);
- option.value = i;
- usersSelect.appendChild(option);
- //More info (email) about the user in a disabled option
- option = document.createElement('option');
- option.innerHTML = ' ';
- mxUtils.write(option, '<' + driveUsers[i].email + '>');
- option.setAttribute('disabled', 'disabled');
- usersSelect.appendChild(option);
- }
-
- //Add account option
- var option = document.createElement('option');
- mxUtils.write(option, mxResources.get('addAccount'));
- option.value = driveUsers.length;
- usersSelect.appendChild(option);
- }
-
- fillUsersSelect();
-
- mxEvent.addListener(usersSelect, 'change', mxUtils.bind(this, function()
- {
- var userIndex = usersSelect.value;
- var existingAccount = driveUsers.length != userIndex;
-
- if (existingAccount)
- {
- this.drive.setUser(driveUsers[userIndex]);
- }
-
- this.drive.authorize(existingAccount, mxUtils.bind(this, function()
- {
- if (!existingAccount)
- {
- driveUsers = this.drive.getUsersList();
- fillUsersSelect();
- }
- }), mxUtils.bind(this, function(resp)
- {
- this.handleError(resp);
- }), true);
- }));
-
- div.appendChild(usersSelect);
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- this.loadFile(window.location.hash.substr(1), true);
- }));
- this.showDialog(dlg.container, 300, 75, true, true);
- }), mxResources.get('cancel'), mxUtils.bind(this, function()
- {
- this.hideDialog();
-
- if (fn != null)
- {
- fn();
- }
- }), 480, 150);
- return;
- }
- }
-
- if (e.message != null)
- {
- if (e.message == '' && e.name != null)
- {
- msg = mxUtils.htmlEntities(e.name);
- }
- else
- {
- msg = mxUtils.htmlEntities(e.message);
- }
- }
- else if (e.response != null && e.response.error != null)
- {
- msg = mxUtils.htmlEntities(e.response.error);
- }
- else if (typeof window.App !== 'undefined')
- {
- if (e.code == App.ERROR_TIMEOUT)
- {
- msg = mxUtils.htmlEntities(mxResources.get('timeout'));
- }
- else if (e.code == App.ERROR_BUSY)
- {
- msg = mxUtils.htmlEntities(mxResources.get('busy'));
- }
- else if (typeof e === 'string' && e.length > 0)
- {
- msg = mxUtils.htmlEntities(e);
- }
- }
- }
-
- var btn3 = null;
- var fn3 = null;
-
- if (e != null && e.helpLink != null)
- {
- btn3 = mxResources.get('help');
-
- fn3 = mxUtils.bind(this, function()
- {
- return this.editor.graph.openLink(e.helpLink);
- });
- }
-
- this.showError(title, msg, btn, fn, retry, null, null, btn3, fn3,
- null, null, null, (invokeFnOnClose) ? fn : null);
- }
- else if (fn != null)
- {
- fn();
- }
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.alert = function(msg, fn, optionalWidth)
- {
- var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
- this.showDialog(dlg.container, optionalWidth || 340, 100, true, false);
- dlg.init();
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel, closable)
- {
- var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
- var height = Math.min(200, Math.ceil(msg.length / 50) * 28);
-
- var dlg = new ConfirmDialog(this, msg, function()
- {
- resume();
-
- if (okFn != null)
- {
- okFn();
- }
- }, function()
- {
- resume();
-
- if (cancelFn != null)
- {
- cancelFn();
- }
- }, okLabel, cancelLabel, null, null, null, null, height);
-
- this.showDialog(dlg.container, 340, 46 + height, true, closable);
- dlg.init();
- };
-
- /**
- * Creates a popup banner.
- */
- EditorUi.prototype.showBanner = function(id, text, onclick, doNotShowAgainOnClose)
- {
- var result = false;
-
- if (!this.bannerShowing && !this['hideBanner' + id] &&
- (!isLocalStorage || mxSettings.settings == null ||
- mxSettings.settings['close' + id] == null))
- {
- var banner = document.createElement('div');
- banner.style.cssText = 'position:absolute;bottom:10px;left:50%;max-width:90%;padding:18px 34px 12px 20px;' +
- 'font-size:16px;font-weight:bold;white-space:nowrap;cursor:pointer;z-index:' + mxPopupMenu.prototype.zIndex + ';';
- mxUtils.setPrefixedStyle(banner.style, 'box-shadow', '1px 1px 2px 0px #ddd');
- mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,120%)');
- mxUtils.setPrefixedStyle(banner.style, 'transition', 'all 1s ease');
- banner.className = 'geBtn gePrimaryBtn';
-
- var logo = document.createElement('img');
- logo.setAttribute('src', IMAGE_PATH + '/logo.png');
- logo.setAttribute('border', '0');
- logo.setAttribute('align', 'absmiddle');
- logo.style.cssText = 'margin-top:-4px;margin-left:8px;margin-right:12px;width:26px;height:26px;';
- banner.appendChild(logo);
-
- var img = document.createElement('img');
- img.setAttribute('src', Dialog.prototype.closeImage);
- img.setAttribute('title', mxResources.get((doNotShowAgainOnClose) ? 'doNotShowAgain' : 'close'));
- img.setAttribute('border', '0');
- img.style.cssText = 'position:absolute;right:10px;top:12px;filter:invert(1);padding:6px;margin:-6px;cursor:default;';
- banner.appendChild(img);
-
- mxUtils.write(banner, text);
- document.body.appendChild(banner);
- this.bannerShowing = true;
-
- var div = document.createElement('div');
- div.style.cssText = 'font-size:11px;text-align:center;font-weight:normal;';
- var chk = document.createElement('input');
- chk.setAttribute('type', 'checkbox');
- chk.setAttribute('id', 'geDoNotShowAgainCheckbox');
- chk.style.marginRight = '6px';
-
- if (!doNotShowAgainOnClose)
- {
- div.appendChild(chk);
-
- var label = document.createElement('label');
- label.setAttribute('for', 'geDoNotShowAgainCheckbox');
- mxUtils.write(label, mxResources.get('doNotShowAgain'));
- div.appendChild(label);
- banner.style.paddingBottom = '30px';
- banner.appendChild(div);
- }
-
- var onclose = mxUtils.bind(this, function()
- {
- if (banner.parentNode != null)
- {
- banner.parentNode.removeChild(banner);
- this.bannerShowing = false;
-
- if (chk.checked || doNotShowAgainOnClose)
- {
- this['hideBanner' + id] = true;
-
- if (isLocalStorage && mxSettings.settings != null)
- {
- mxSettings.settings['close' + id] = Date.now();
- mxSettings.save();
- }
- }
- }
- });
-
- mxEvent.addListener(img, 'click', mxUtils.bind(this, function(e)
- {
- mxEvent.consume(e);
- onclose();
- }));
-
- var hide = mxUtils.bind(this, function()
- {
- mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,120%)');
-
- window.setTimeout(mxUtils.bind(this, function()
- {
- onclose();
- }), 1000);
- });
-
- mxEvent.addListener(banner, 'click', mxUtils.bind(this, function(e)
- {
- var source = mxEvent.getSource(e);
-
- if (source != chk && source != label)
- {
- if (onclick != null)
- {
- onclick();
- }
-
- onclose();
- mxEvent.consume(e);
- }
- else
- {
- hide();
- }
- }));
-
- window.setTimeout(mxUtils.bind(this, function()
- {
- mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,0%)');
- }), 500);
-
- window.setTimeout(hide, 30000);
- result = true;
- }
-
- return result;
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.setCurrentFile = function(file)
- {
- if (file != null)
- {
- file.opened = new Date();
- }
-
- this.currentFile = file;
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getCurrentFile = function()
- {
- return this.currentFile;
- };
-
- /**
- * Handling for canvas export.
- */
- EditorUi.prototype.isExportToCanvas = function()
- {
- return this.editor.isExportToCanvas();
- };
- /**
- *
- */
- EditorUi.prototype.createImageDataUri = function(canvas, xml, format, dpi)
- {
- var data = canvas.toDataURL('image/' + format);
-
- // Checks for valid output
- if (data != null && data.length > 6)
- {
- if (xml != null)
- {
- data = Editor.writeGraphModelToPng(data, 'tEXt', 'mxfile', encodeURIComponent(xml));
- }
-
- if (dpi > 0)
- {
- data = Editor.writeGraphModelToPng(data, 'pHYs', 'dpi', dpi);
- }
- }
- else
- {
- throw {message: mxResources.get('unknownError')};
- }
-
- return data;
- };
-
- /**
- *
- */
- EditorUi.prototype.saveCanvas = function(canvas, xml, format, ignorePageName, dpi)
- {
- var ext = ((format == 'jpeg') ? 'jpg' : format);
- var filename = this.getBaseFilename(ignorePageName) + '.' + ext;
- var data = this.createImageDataUri(canvas, xml, format, dpi);
- this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
- };
-
- /**
- * Returns true if files should be saved using <saveLocalFile>.
- */
- EditorUi.prototype.isLocalFileSave = function()
- {
- return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
- (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
- document.documentMode != 9 && document.documentMode != 8 &&
- document.documentMode != 7) ||
- this.isOfflineApp() || mxClient.IS_IOS);
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.showTextDialog = function(title, text)
- {
- var dlg = new TextareaDialog(this, title, text, null, null, mxResources.get('close'));
- dlg.textarea.style.width = '600px';
- dlg.textarea.style.height = '380px';
- this.showDialog(dlg.container, 620, 460, true, true, null, null, null, null, true);
- dlg.init();
- document.execCommand('selectall', false, null);
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format, defaultExtension)
- {
- // Appends .drawio extension for XML files with no extension
- // to avoid the browser to automatically append .xml instead
- if (mimeType == 'text/xml' &&
- !/(\.drawio)$/i.test(filename) &&
- !/(\.xml)$/i.test(filename) &&
- !/(\.svg)$/i.test(filename) &&
- !/(\.html)$/i.test(filename))
- {
- defaultExtension = (defaultExtension != null) ? defaultExtension : 'drawio';
- filename = filename + '.' + defaultExtension;
- }
-
- // Newer versions of IE
- if (window.Blob && navigator.msSaveOrOpenBlob)
- {
- var blob = (base64Encoded) ?
- this.base64ToBlob(data, mimeType) :
- new Blob([data], {type: mimeType})
- navigator.msSaveOrOpenBlob(blob, filename);
- }
- // Older versions of IE (binary not supported)
- else if (mxClient.IS_IE)
- {
- var win = window.open('about:blank', '_blank');
-
- if (win == null)
- {
- mxUtils.popup(data, true);
- }
- else
- {
- win.document.write(data);
- win.document.close();
- win.document.execCommand('SaveAs', true, filename);
- win.close();
- }
- }
- else if (mxClient.IS_IOS && this.isOffline())
- {
- // Workaround for "WebKitBlobResource error 1" in mobile Safari
- if (!navigator.standalone && mimeType != null && mimeType.substring(0, 6) == 'image/')
- {
- this.openInNewWindow(data, mimeType, base64Encoded);
- }
- else
- {
- this.showTextDialog(filename + ':', data);
- }
- }
- else
- {
- var a = document.createElement('a');
-
- // Workaround for mxXmlRequest.simulate no longer working in PaleMoon
- // if this is used (ie PNG export broken after XML export in PaleMoon)
- // and for "WebKitBlobResource error 1" for all browsers on iOS.
- var useDownload = (navigator.userAgent == null ||
- navigator.userAgent.indexOf("PaleMoon/") < 0) &&
- typeof a.download !== 'undefined';
-
- // Workaround for Chromium 65 cross-domain anchor download issue
- if (mxClient.IS_GC && navigator.userAgent != null)
- {
- var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
- var vers = raw ? parseInt(raw[2], 10) : false;
- useDownload = vers == 65 ? false : useDownload;
- }
-
- if (useDownload || this.isOffline())
- {
- a.href = URL.createObjectURL((base64Encoded) ?
- this.base64ToBlob(data, mimeType) :
- new Blob([data], {type: mimeType}));
-
- if (useDownload)
- {
- a.download = filename;
- }
- else
- {
- // Workaround for same window in Safari
- a.setAttribute('target', '_blank');
- }
- document.body.appendChild(a);
-
- try
- {
- window.setTimeout(function()
- {
- URL.revokeObjectURL(a.href);
- }, 20000);
- a.click();
- a.parentNode.removeChild(a);
- }
- catch (e)
- {
- // ignore
- }
- }
- else
- {
- var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
-
- req.simulate(document, '_blank');
- }
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
- {
- var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
- 'data=' + encodeURIComponent(Graph.compress(data));
-
- return new mxXmlRequest(SAVE_URL, param +
- ((mimeType != null) ? '&mime=' + mimeType : '') +
- ((format != null) ? '&format=' + format : '') +
- ((base64Response != null) ? '&base64=' + base64Response : '') +
- ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
- ((base64Encoded) ? '&binary=1' : ''));
- };
-
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
- {
- contentType = contentType || '';
- var sliceSize = 1024;
- var byteCharacters = atob(base64Data);
- var bytesLength = byteCharacters.length;
- var slicesCount = Math.ceil(bytesLength / sliceSize);
- var byteArrays = new Array(slicesCount);
-
- for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
- {
- var begin = sliceIndex * sliceSize;
- var end = Math.min(begin + sliceSize, bytesLength);
-
- var bytes = new Array(end - begin);
-
- for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
- {
- bytes[i] = byteCharacters[offset].charCodeAt(0);
- }
-
- byteArrays[sliceIndex] = new Uint8Array(bytes);
- }
-
- return new Blob(byteArrays, {type: contentType});
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab, defaultExtension)
- {
- allowBrowser = (allowBrowser != null) ? allowBrowser : false;
- allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
- var count = this.getServiceCount(allowBrowser);
-
- if (isLocalStorage)
- {
- count++;
- }
-
- var rowLimit = (count <= 4) ? 2 : (count > 6 ? 4 : 3);
-
- var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
- {
- try
- {
- // Opens a new window
- if (mode == '_blank')
- {
- if (mimeType != null && mimeType.substring(0, 6) == 'image/')
- {
- this.openInNewWindow(data, mimeType, base64Encoded);
- }
- else if (mimeType != null && mimeType.substring(0, 9) == 'text/html')
- {
- var dlg = new EmbedDialog(this, data);
- this.showDialog(dlg.container, 440, 240, true, true);
- dlg.init();
- }
- else
- {
- var win = window.open('about:blank');
-
- if (win == null)
- {
- mxUtils.popup(data, true);
- }
- else
- {
- win.document.write('<pre>' + mxUtils.htmlEntities(data, false) + '</pre>');
- win.document.close();
- }
- }
- }
- else if (mode == App.MODE_DEVICE || mode == 'download')
- {
- this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded, null, defaultExtension);
- }
- else if (newTitle != null && newTitle.length > 0)
- {
- this.pickFolder(mode, mxUtils.bind(this, function(folderId)
- {
- try
- {
- this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
- }
- catch (e)
- {
- this.handleError(e);
- }
- }));
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- }), mxUtils.bind(this, function()
- {
- this.hideDialog();
- }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
- null, count > 1, rowLimit, data, mimeType, base64Encoded);
- var height = (this.isServices(count)) ? ((count > rowLimit) ? 390 : 270) : 160;
- this.showDialog(dlg.container, 400, height, true, true);
- dlg.init();
- };
-
- /**
- *
- */
- EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
- {
- var win = window.open('about:blank');
-
- if (win == null || win.document == null)
- {
- mxUtils.popup(data, true);
- }
- else
- {
- if (mimeType == 'image/svg+xml' && !mxClient.IS_SVG)
- {
- // KNOWN: Output is scaled in Chrome on macOS
- win.document.write('<html><pre>' + mxUtils.htmlEntities(data, false) + '</pre></html>');
- win.document.close();
- }
- else
- {
- if (mimeType == 'image/svg+xml')
- {
- win.document.write('<html>'+ data + '</html>');
- }
- else
- {
- var temp = (base64Encoded) ? data : btoa(unescape(encodeURIComponent(data)));
-
- win.document.write('<html><img style="max-width:100%;" src="data:' +
- mimeType + ';base64,' + temp + '"/></html>');
- }
-
- win.document.close();
- }
- }
- };
-
- var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
- /**
- * Creates a temporary graph instance for rendering off-screen content.
- */
- EditorUi.prototype.addChromelessToolbarItems = function(addButton)
- {
- if (this.isExportToCanvas())
- {
- this.exportDialog = null;
-
- var exportButton = addButton(mxUtils.bind(this, function(evt)
- {
- var clickHandler = mxUtils.bind(this, function()
- {
- mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
-
- if (this.exportDialog != null)
- {
- this.exportDialog.parentNode.removeChild(this.exportDialog);
- this.exportDialog = null;
- }
- });
-
- if (this.exportDialog != null)
- {
- clickHandler.apply(this);
- }
- else
- {
- this.exportDialog = document.createElement('div');
- var r = exportButton.getBoundingClientRect();
-
- mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
- this.exportDialog.style.position = 'fixed';
- this.exportDialog.style.textAlign = 'center';
- this.exportDialog.style.fontFamily = 'Helvetica,Arial';
- this.exportDialog.style.backgroundColor = '#000000';
- this.exportDialog.style.width = '50px';
- this.exportDialog.style.height = '50px';
- this.exportDialog.style.padding = '4px 2px 4px 2px';
- this.exportDialog.style.color = '#ffffff';
- mxUtils.setOpacity(this.exportDialog, 70);
- this.exportDialog.style.left = r.left + 'px';
- this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
- this.chromelessToolbar.offsetHeight + 4 + 'px';
-
- // Puts the dialog on top of the container z-index
- var style = mxUtils.getCurrentStyle(this.editor.graph.container);
- this.exportDialog.style.zIndex = style.zIndex;
-
- var spinner = new Spinner({
- lines: 8, // The number of lines to draw
- length: 6, // The length of each line
- width: 5, // The line thickness
- radius: 6, // The radius of the inner circle
- rotate: 0, // The rotation offset
- color: '#fff', // #rgb or #rrggbb
- speed: 1.5, // Rounds per second
- trail: 60, // Afterglow percentage
- shadow: false, // Whether to render a shadow
- hwaccel: false, // Whether to use hardware acceleration
- top: '28px',
- zIndex: 2e9 // The z-index (defaults to 2000000000)
- });
- spinner.spin(this.exportDialog);
-
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
- {
- spinner.stop();
-
- this.exportDialog.style.width = 'auto';
- this.exportDialog.style.height = 'auto';
- this.exportDialog.style.padding = '10px';
-
- var data = this.createImageDataUri(canvas, null, 'png');
- var img = document.createElement('img');
-
- img.style.maxWidth = '140px';
- img.style.maxHeight = '140px';
- img.style.cursor = 'pointer';
- img.style.backgroundColor = 'white';
-
- img.setAttribute('title', mxResources.get('openInNewWindow'));
- img.setAttribute('border', '0');
- img.setAttribute('src', data);
-
- this.exportDialog.appendChild(img);
- mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
- {
- this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
- clickHandler.apply(this, arguments);
- }));
- }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
- {
- this.spinner.stop();
- this.handleError(e);
- }), null, null, null, null, null, null, null, Editor.defaultBorder);
-
- mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
- document.body.appendChild(this.exportDialog);
- }
-
- mxEvent.consume(evt);
- }), Editor.cameraLargeImage, mxResources.get('export'));
- }
- editoUiAddChromelessToolbarItems.apply(this, arguments);
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
- {
- if (this.isLocalFileSave())
- {
- this.saveLocalFile(data, filename, mime, base64Encoded, format);
- }
- else
- {
- this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
- {
- return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
- }), data, base64Encoded, mime);
- }
- };
-
- /**
- * Translates this point by the given vector.
- *
- * Last 3 argument are optional and must only be used if the data can be stored as is on the client
- * side without requiring a server roundtrip.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
- {
- allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
- var count = this.getServiceCount(false);
-
- if (isLocalStorage)
- {
- count++;
- }
-
- var rowLimit = (count <= 4) ? 2 : (count > 6 ? 4 : 3);
-
- var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
- {
- if (mode == '_blank' || newTitle != null && newTitle.length > 0)
- {
- var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
- var xhr = fn((mode == '_blank') ? null : newTitle, base64);
-
- if (xhr != null)
- {
- if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
- {
- xhr.simulate(document, '_blank');
- }
- else
- {
- this.pickFolder(mode, mxUtils.bind(this, function(folderId)
- {
- mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
- 'application/pdf' : 'image/' + format);
-
- // Workaround for no roundtrip required if data is available on client-side
- // TODO: Refactor the saveData/saveRequest call chain for local data
- if (data != null)
- {
- try
- {
- this.exportFile(data, newTitle, mimeType, true, mode, folderId);
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- else if (this.spinner.spin(document.body, mxResources.get('saving')))
- {
- // LATER: Catch possible mixed content error
- // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
- xhr.send(mxUtils.bind(this, function()
- {
- this.spinner.stop();
-
- if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
- {
- try
- {
- this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- else
- {
- this.handleError({message: mxResources.get('errorSavingFile')});
- }
- }), function(resp)
- {
- this.spinner.stop();
- this.handleError(resp);
- });
- }
- }));
- }
- }
- }
- }), mxUtils.bind(this, function()
- {
- this.hideDialog();
- }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
- null, count > 1, rowLimit, data, mimeType, base64Encoded);
-
- var height = (this.isServices(count)) ? ((count > 4) ? 390 : 270) : 160;
- this.showDialog(dlg.container, 380, height, true, true);
- dlg.init();
- };
- /**
- * Returns whether or not any services should be shown in dialogs
- */
- EditorUi.prototype.isServices = function(count)
- {
- var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
- return count != noServices;
- };
- /**
- *
- */
- EditorUi.prototype.getEditBlankXml = function()
- {
- return this.getFileData(true);
- };
-
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
- {
- // do nothing
- };
-
- /**
- * Hook for subclassers.
- */
- EditorUi.prototype.pickFolder = function(mode, fn, enabled)
- {
- fn(null);
- };
- /**
- *
- */
- EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow,
- editable, embedImages, border, noCrop, currentPage, linkTarget, keepTheme, exportType)
- {
- if (this.spinner.spin(document.body, mxResources.get('export')))
- {
- try
- {
- var selectionEmpty = this.editor.graph.isSelectionEmpty();
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
- var bg = (transparentBackground) ? null : this.editor.graph.background;
-
- if (bg == mxConstants.NONE)
- {
- bg = null;
- }
-
- // Handles special case where background is null but transparent is false
- if (bg == null && transparentBackground == false)
- {
- bg = (keepTheme) ? this.editor.graph.defaultPageBackgroundColor : '#ffffff';
- }
-
- // Sets or disables alternate text for foreignObjects. Disabling is needed
- // because PhantomJS seems to ignore switch statements and paint all text.
- var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop,
- null, ignoreSelection, null, null, (linkTarget == 'blank') ? '_blank' :
- ((linkTarget == 'self') ? '_top' : null), null, true, keepTheme,
- exportType);
-
- if (addShadow)
- {
- this.editor.graph.addSvgShadow(svgRoot);
- }
-
- var filename = this.getBaseFilename() + '.svg';
-
- var doSave = mxUtils.bind(this, function(svgRoot)
- {
- this.spinner.stop();
-
- if (editable)
- {
- svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection,
- currentPage, null, null, null, false));
- }
-
- var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
- mxUtils.getXml(svgRoot);
-
- if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
- {
- this.saveData(filename, 'svg', svg, 'image/svg+xml');
- }
- else
- {
- this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
- {
- mxUtils.popup(svg);
- }));
- }
- });
- // Adds CSS
- this.editor.addFontCss(svgRoot);
-
- if (this.editor.graph.mathEnabled)
- {
- this.editor.addMathCss(svgRoot);
- }
-
- if (embedImages)
- {
- // Caches images
- if (this.thumbImageCache == null)
- {
- this.thumbImageCache = new Object();
- }
-
- this.editor.convertImages(svgRoot, doSave, this.thumbImageCache);
- }
- else
- {
- doSave(svgRoot);
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- };
-
- EditorUi.prototype.addRadiobox = function(div, radioGroupName, label, checked, disabled, disableNewline, visible)
- {
- return this.addCheckbox(div, label, checked, disabled, disableNewline, visible, true, radioGroupName);
- }
-
- /**
- *
- */
- EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible, asRadio, radioGroupName)
- {
- visible = (visible != null) ? visible : true;
-
- var cb = document.createElement('input');
- cb.style.marginRight = '8px';
- cb.style.marginTop = '16px';
- cb.setAttribute('type', asRadio? 'radio' : 'checkbox');
- var id = 'geCheckbox-' + Editor.guid();
- cb.id = id;
-
- if (radioGroupName != null)
- {
- cb.setAttribute('name', radioGroupName);
- }
-
- if (checked)
- {
- cb.setAttribute('checked', 'checked');
- cb.defaultChecked = true;
- }
-
- if (disabled)
- {
- cb.setAttribute('disabled', 'disabled');
- }
-
- if (visible)
- {
- div.appendChild(cb);
-
- var lbl = document.createElement('label');
- mxUtils.write(lbl, label);
- lbl.setAttribute('for', id);
- div.appendChild(lbl);
- if (!disableNewline)
- {
- mxUtils.br(div);
- }
- }
-
- return cb;
- };
-
- /**
- *
- */
- EditorUi.prototype.addEditButton = function(div, lightbox)
- {
- var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
- edit.style.marginLeft = '24px';
-
- var file = this.getCurrentFile();
- var editUrl = '';
-
- if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
- {
- editUrl = window.location.href;
- }
-
- var editSelect = document.createElement('select');
- editSelect.style.width = '120px';
- editSelect.style.marginLeft = '8px';
- editSelect.style.marginRight = '10px';
- editSelect.className = 'geBtn';
- var blankOption = document.createElement('option');
- blankOption.setAttribute('value', 'blank');
- mxUtils.write(blankOption, mxResources.get('makeCopy'));
- editSelect.appendChild(blankOption);
- var customOption = document.createElement('option');
- customOption.setAttribute('value', 'custom');
- mxUtils.write(customOption, mxResources.get('custom') + '...');
- editSelect.appendChild(customOption);
-
- div.appendChild(editSelect);
-
- mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
- {
- if (editSelect.value == 'custom')
- {
- var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
- {
- if (value != null)
- {
- editUrl = value;
- }
- else
- {
- editSelect.value = 'blank';
- }
- }, mxResources.get('url'), null, null, null, null, function()
- {
- editSelect.value = 'blank';
- });
- this.showDialog(dlg2.container, 300, 80, true, false);
- dlg2.init();
- }
- }));
-
- mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
- {
- if (edit.checked && (lightbox == null || lightbox.checked))
- {
- editSelect.removeAttribute('disabled');
- }
- else
- {
- editSelect.setAttribute('disabled', 'disabled');
- }
- }));
- mxUtils.br(div);
-
- return {
- getLink: function()
- {
- return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
- },
- getEditInput: function()
- {
- return edit;
- },
- getEditSelect: function()
- {
- return editSelect;
- }
- };
- }
-
- /**
- *
- */
- EditorUi.prototype.addLinkSection = function(div, showFrameOption)
- {
- mxUtils.write(div, mxResources.get('links') + ':');
- var linkSelect = document.createElement('select');
- linkSelect.style.width = '100px';
- linkSelect.style.marginLeft = '8px';
- linkSelect.style.marginRight = '10px';
- linkSelect.className = 'geBtn';
- var autoOption = document.createElement('option');
- autoOption.setAttribute('value', 'auto');
- mxUtils.write(autoOption, mxResources.get('automatic'));
- linkSelect.appendChild(autoOption);
- var blankOption = document.createElement('option');
- blankOption.setAttribute('value', 'blank');
- mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
- linkSelect.appendChild(blankOption);
- var selfOption = document.createElement('option');
- selfOption.setAttribute('value', 'self');
- mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
- linkSelect.appendChild(selfOption);
- if (showFrameOption)
- {
- var frameOption = document.createElement('option');
- frameOption.setAttribute('value', 'frame');
- mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
- ' (' + mxResources.get('iframe') + ')');
- linkSelect.appendChild(frameOption);
- }
-
- div.appendChild(linkSelect);
-
- mxUtils.write(div, mxResources.get('borderColor') + ':');
- var linkColor = '#0000ff';
- var linkButton = null;
-
- function updateLinkColor()
- {
- linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
- ((linkColor != null && linkColor != mxConstants.NONE) ?
- 'border:1px solid black;background-color:' + linkColor :
- 'background-position:center center;background-repeat:no-repeat;' +
- 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
- };
-
- linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
- {
- this.pickColor(linkColor || 'none', function(color)
- {
- linkColor = color;
- updateLinkColor();
- });
-
- mxEvent.consume(evt);
- }));
- updateLinkColor();
- linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
- linkButton.style.marginLeft = '4px';
- linkButton.style.height = '22px';
- linkButton.style.width = '22px';
- linkButton.style.position = 'relative';
- linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
- linkButton.className = 'geColorBtn';
- div.appendChild(linkButton);
- mxUtils.br(div);
-
- return {
- getColor: function()
- {
- return linkColor;
- },
- getTarget: function()
- {
- return linkSelect.value;
- },
- focus: function()
- {
- linkSelect.focus();
- }
- };
- }
- /**
- *
- */
- EditorUi.prototype.createUrlParameters = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, params)
- {
- params = (params != null) ? params : [];
-
- if (lightbox)
- {
- if (EditorUi.lightboxHost != 'https://viewer.diagrams.net' || urlParams['dev'] == '1')
- {
- params.push('lightbox=1');
- }
- if (linkTarget != 'auto')
- {
- params.push('target=' + linkTarget);
- }
-
- if (linkColor != null && linkColor != mxConstants.NONE)
- {
- params.push('highlight=' + ((linkColor.charAt(0) == '#') ?
- linkColor.substring(1) : linkColor));
- }
-
- if (editLink != null && editLink.length > 0)
- {
- params.push('edit=' + encodeURIComponent(editLink));
- }
-
- if (layers)
- {
- params.push('layers=1');
- }
-
- if (this.editor.graph.foldingEnabled)
- {
- params.push('nav=1');
- }
- }
-
- if (allPages && this.currentPage != null && this.pages != null &&
- this.currentPage != this.pages[0])
- {
- params.push('page-id=' + this.currentPage.getId());
- }
-
- return params;
- };
-
- /**
- *
- */
- EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile, params, useOpenParameter)
- {
- params = this.createUrlParameters(linkTarget, linkColor, allPages, lightbox, editLink, layers, params);
- var file = this.getCurrentFile();
- var addTitle = true;
- var data = '';
-
- if (url != null)
- {
- data = '#U' + encodeURIComponent(url);
- }
- else
- {
- var file = this.getCurrentFile();
- // Fallback to non-public URL for Drive files
- if (!ignoreFile && file != null && file.constructor == window.DriveFile)
- {
- data = '#' + file.getHash();
- addTitle = false;
- }
- else
- {
- data = '#R' + encodeURIComponent((allPages) ?
- this.getFileData(true, null, null, null, null, null, null, true, null, false) :
- Graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
- }
- }
- if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
- {
- params.push('title=' + encodeURIComponent(file.getTitle()));
- }
- if (useOpenParameter && data.length > 1)
- {
- params.push('open=' + data.substring(1));
- data = '';
- }
-
- return ((lightbox && urlParams['dev'] != '1') ? EditorUi.lightboxHost :
- (((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp ||
- !(/.*\.draw\.io$/.test(window.location.hostname))) ?
- EditorUi.drawHost : 'https://' + window.location.host))) + '/' +
- ((params.length > 0) ? '?' + params.join('&') : '') + data;
- };
-
- /**
- *
- */
- EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
- linkColor, fit, allPages, layers, lightbox, editLink, fn)
- {
- var s = this.getBasenames();
- var data = {};
-
- if (linkColor != '' && linkColor != mxConstants.NONE)
- {
- data.highlight = linkColor;
- }
-
- if (linkTarget !== 'auto')
- {
- data.target = linkTarget;
- }
-
- if (!lightbox)
- {
- data.lightbox = false;
- }
-
- data.nav = this.editor.graph.foldingEnabled;
- var zoom = parseInt(initialZoom);
-
- if (!isNaN(zoom) && zoom != 100)
- {
- data.zoom = zoom / 100;
- }
-
- var tb = [];
-
- if (allPages)
- {
- tb.push('pages');
- data.resize = true;
-
- if (this.pages != null && this.currentPage != null)
- {
- data.page = mxUtils.indexOf(this.pages, this.currentPage);
- }
- }
-
- if (zoomEnabled)
- {
- tb.push('zoom');
- data.resize = true;
- }
-
- if (layers)
- {
- tb.push('layers');
- }
-
- if (tb.length > 0)
- {
- if (lightbox)
- {
- tb.push('lightbox');
- }
-
- data.toolbar = tb.join(' ');
- }
- if (editLink != null && editLink.length > 0)
- {
- data.edit = editLink;
- }
-
- if (publicUrl != null)
- {
- data.url = publicUrl;
- }
- else
- {
- data.xml = this.getFileData(true, null, null, null, null, !allPages);
- }
-
- var value = '<div class="mxgraph" style="' +
- ((fit) ? 'max-width:100%;' : '') +
- ((tb != '') ? 'border:1px solid transparent;' : '') +
- '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
-
- var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
- var s2 = (fetchParam.length > 0) ? (((urlParams['dev'] == '1') ?
- 'https://test.draw.io/embed2.js?dev=1' : EditorUi.lightboxHost + '/embed2.js?')) + fetchParam :
- (((urlParams['dev'] == '1') ? 'https://test.draw.io/js/viewer-static.min.js' :
- window.VIEWER_URL ? window.VIEWER_URL : EditorUi.lightboxHost + '/js/viewer-static.min.js'));
- var src = '<script type="text/javascript" src="' + s2 + '"></script>';
-
- fn(value, src);
- };
- /**
- *
- */
- EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
- {
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
- var graph = this.editor.graph;
-
- var hd = document.createElement('h3');
- mxUtils.write(hd, mxResources.get('html'));
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
- div.appendChild(hd);
- var radioSection = document.createElement('div');
- radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
- var publicUrlRadio = document.createElement('input');
- publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
- publicUrlRadio.setAttribute('value', 'url');
- publicUrlRadio.setAttribute('type', 'radio');
- publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
- var copyRadio = publicUrlRadio.cloneNode(true);
- copyRadio.setAttribute('value', 'copy');
- radioSection.appendChild(copyRadio);
-
- var span = document.createElement('span');
- mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
- radioSection.appendChild(span);
-
- mxUtils.br(radioSection);
- radioSection.appendChild(publicUrlRadio);
- var span = document.createElement('span');
- mxUtils.write(span, mxResources.get('publicDiagramUrl'));
- radioSection.appendChild(span);
- var file = this.getCurrentFile();
-
- if (publicUrl == null && file != null && file.constructor == window.DriveFile)
- {
- var testLink = document.createElement('a');
- testLink.style.paddingLeft = '12px';
- testLink.style.color = 'gray';
- testLink.style.cursor = 'pointer';
- mxUtils.write(testLink, mxResources.get('share'));
- radioSection.appendChild(testLink);
-
- mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
- {
- this.hideDialog();
- this.drive.showPermissions(file.getId());
- }));
- }
- copyRadio.setAttribute('checked', 'checked');
-
- if (publicUrl == null)
- {
- publicUrlRadio.setAttribute('disabled', 'disabled');
- }
- div.appendChild(radioSection);
- var linkSection = this.addLinkSection(div);
- var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
- mxUtils.write(div, ':');
-
- var zoomInput = document.createElement('input');
- zoomInput.setAttribute('type', 'text');
- zoomInput.style.marginRight = '16px';
- zoomInput.style.width = '60px';
- zoomInput.style.marginLeft = '4px';
- zoomInput.style.marginRight = '12px';
- zoomInput.value = '100%';
-
- div.appendChild(zoomInput);
- var fit = this.addCheckbox(div, mxResources.get('fit'), true);
- var hasPages = this.pages != null && this.pages.length > 1;
- var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
- var layers = this.addCheckbox(div, mxResources.get('layers'), true);
- var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
-
- var editSection = this.addEditButton(div, lightbox);
- var edit = editSection.getEditInput();
- edit.style.marginBottom = '16px';
-
- mxEvent.addListener(lightbox, 'change', function()
- {
- if (lightbox.checked)
- {
- edit.removeAttribute('disabled');
- }
- else
- {
- edit.setAttribute('disabled', 'disabled');
- }
-
- if (edit.checked && lightbox.checked)
- {
- editSection.getEditSelect().removeAttribute('disabled');
- }
- else
- {
- editSection.getEditSelect().setAttribute('disabled', 'disabled');
- }
- });
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
- linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
- editSection.getLink());
- }), null, btnLabel, helpLink);
- this.showDialog(dlg.container, 340, 384, true, true);
- copyRadio.focus();
- };
-
- /**
- *
- */
- EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
- {
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
- var graph = this.editor.graph;
-
- var hd = document.createElement('h3');
- mxUtils.write(hd, title || mxResources.get('link'));
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
- div.appendChild(hd);
-
- var file = this.getCurrentFile();
- var helpLink = 'https://www.diagrams.net/doc/faq/publish-diagram-as-link';
- var dy = 0;
-
- if (file != null && file.constructor == window.DriveFile && !hideShare)
- {
- dy = 80;
- helpLink = 'https://www.diagrams.net/doc/faq/google-drive-publicly-publish-diagram';
- var hintSection = document.createElement('div');
- hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
-
- var text = document.createElement('div');
- text.style.whiteSpace = 'normal';
- mxUtils.write(text, mxResources.get('linkAccountRequired'));
- hintSection.appendChild(text);
-
- var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
- {
- this.drive.showPermissions(file.getId());
- }));
- shareBtn.style.marginTop = '12px';
- shareBtn.className = 'geBtn';
- hintSection.appendChild(shareBtn);
- div.appendChild(hintSection);
-
- var testLink = document.createElement('a');
- testLink.style.paddingLeft = '12px';
- testLink.style.color = 'gray';
- testLink.style.fontSize = '11px';
- testLink.style.cursor = 'pointer';
- mxUtils.write(testLink, mxResources.get('check'));
- hintSection.appendChild(testLink);
-
- mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
- {
- if (this.spinner.spin(document.body, mxResources.get('loading')))
- {
- this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
- {
- this.spinner.stop();
-
- var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
- 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
- this.showDialog(dlg.container, 300, 80, true, false);
- dlg.init();
- }));
- }
- }));
- }
-
- var widthInput = null;
- var heightInput = null;
-
- if (width != null || height != null)
- {
- dy += 30;
- mxUtils.write(div, mxResources.get('width') + ':');
- widthInput = document.createElement('input');
- widthInput.setAttribute('type', 'text');
- widthInput.style.marginRight = '16px';
- widthInput.style.width = '50px';
- widthInput.style.marginLeft = '6px';
- widthInput.style.marginRight = '16px';
- widthInput.style.marginBottom = '10px';
- widthInput.value = '100%';
-
- div.appendChild(widthInput);
- mxUtils.write(div, mxResources.get('height') + ':');
-
- heightInput = document.createElement('input');
- heightInput.setAttribute('type', 'text');
- heightInput.style.width = '50px';
- heightInput.style.marginLeft = '6px';
- heightInput.style.marginBottom = '10px';
- heightInput.value = height + 'px';
-
- div.appendChild(heightInput);
- mxUtils.br(div);
- }
-
- var linkSection = this.addLinkSection(div, showFrameOption);
- var hasPages = this.pages != null && this.pages.length > 1;
- var allPages = null;
-
- if (file == null || file.constructor != window.DriveFile || hideShare)
- {
- allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
- }
-
- var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true, null, null, !showFrameOption);
- var editSection = this.addEditButton(div, lightbox);
- var edit = editSection.getEditInput();
- // Cannot disable lightbox in iframes
- if (showFrameOption)
- {
- edit.style.marginLeft = lightbox.style.marginLeft;
- lightbox.style.display = 'none';
- dy -= 30;
- }
-
- var layers = this.addCheckbox(div, mxResources.get('layers'), true);
- layers.style.marginLeft = edit.style.marginLeft;
- layers.style.marginBottom = '16px';
- layers.style.marginTop = '8px';
-
- mxEvent.addListener(lightbox, 'change', function()
- {
- if (lightbox.checked)
- {
- layers.removeAttribute('disabled');
- edit.removeAttribute('disabled');
- }
- else
- {
- layers.setAttribute('disabled', 'disabled');
- edit.setAttribute('disabled', 'disabled');
- }
-
- if (edit.checked && lightbox.checked)
- {
- editSection.getEditSelect().removeAttribute('disabled');
- }
- else
- {
- editSection.getEditSelect().setAttribute('disabled', 'disabled');
- }
- });
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- fn(linkSection.getTarget(), linkSection.getColor(),
- (allPages == null) ? true : allPages.checked,
- lightbox.checked, editSection.getLink(),
- layers.checked, (widthInput != null) ? widthInput.value : null,
- (heightInput != null) ? heightInput.value : null);
- }), null, mxResources.get('create'), helpLink);
- this.showDialog(dlg.container, 340, 254 + dy, true, true);
-
- if (widthInput != null)
- {
- widthInput.focus();
-
- if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5)
- {
- widthInput.select();
- }
- else
- {
- document.execCommand('selectAll', false, null);
- }
- }
- else
- {
- linkSection.focus();
- }
- };
- /**
- *
- */
- EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude, showZoomBorder)
- {
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
-
- var hd = document.createElement('h3');
- mxUtils.write(hd, mxResources.get('image'));
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:' + (showZoomBorder? '10' : '4') +'px';
- div.appendChild(hd);
- if (showZoomBorder)
- {
- mxUtils.write(div, mxResources.get('zoom') + ':');
- var zoomInput = document.createElement('input');
- zoomInput.setAttribute('type', 'text');
- zoomInput.style.marginRight = '16px';
- zoomInput.style.width = '60px';
- zoomInput.style.marginLeft = '4px';
- zoomInput.style.marginRight = '12px';
- zoomInput.value = this.lastExportZoom || '100%';
- div.appendChild(zoomInput);
-
- mxUtils.write(div, mxResources.get('borderWidth') + ':');
- var borderInput = document.createElement('input');
- borderInput.setAttribute('type', 'text');
- borderInput.style.marginRight = '16px';
- borderInput.style.width = '60px';
- borderInput.style.marginLeft = '4px';
- borderInput.value = this.lastExportBorder || '0';
- div.appendChild(borderInput);
- mxUtils.br(div);
- }
-
- var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
- this.editor.graph.isSelectionEmpty());
- var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
-
- var graph = this.editor.graph;
- var transparent = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('transparentBackground'),
- graph.background == mxConstants.NONE || graph.background == null);
- if (transparent != null)
- {
- transparent.style.marginBottom = '16px';
- }
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- var scale = parseInt(zoomInput.value) / 100 || 1;
- var border = parseInt(borderInput.value) || 0;
-
- callback(!selection.checked, (include != null) ? include.checked : false,
- (transparent != null) ? transparent.checked : false, scale, border);
- }), null, btnLabel, helpLink);
- this.showDialog(dlg.container, 300, (showZoomBorder? 25 : 0) + (hideInclude ? 125 : 210), true, true);
- };
-
- /**
- *
- */
- EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
- cropOption, defaultInclude, format, exportOption)
- {
- defaultInclude = (defaultInclude != null) ? defaultInclude : true;
-
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
- var graph = this.editor.graph;
- var height = (format == 'jpeg') ? 196 : 300;
-
- var hd = document.createElement('h3');
- mxUtils.write(hd, title);
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
- div.appendChild(hd);
- mxUtils.write(div, mxResources.get('zoom') + ':');
- var zoomInput = document.createElement('input');
- zoomInput.setAttribute('type', 'text');
- zoomInput.style.marginRight = '16px';
- zoomInput.style.width = '60px';
- zoomInput.style.marginLeft = '4px';
- zoomInput.style.marginRight = '12px';
- zoomInput.value = this.lastExportZoom || '100%';
- div.appendChild(zoomInput);
-
- mxUtils.write(div, mxResources.get('borderWidth') + ':');
- var borderInput = document.createElement('input');
- borderInput.setAttribute('type', 'text');
- borderInput.style.marginRight = '16px';
- borderInput.style.width = '60px';
- borderInput.style.marginLeft = '4px';
- borderInput.value = this.lastExportBorder || '0';
- div.appendChild(borderInput);
- mxUtils.br(div);
- var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
- false, graph.isSelectionEmpty());
- var cb6 = document.createElement('input');
- cb6.style.marginTop = '16px';
- cb6.style.marginRight = '8px';
- cb6.style.marginLeft = '24px';
- cb6.setAttribute('disabled', 'disabled');
- cb6.setAttribute('type', 'checkbox');
- var exportSelect = document.createElement('select');
- exportSelect.style.marginTop = '16px';
- exportSelect.style.marginLeft = '8px';
- var sizes = ['selectionOnly', 'diagram', 'page'];
-
- for (var i = 0; i < sizes.length; i++)
- {
- if (!graph.isSelectionEmpty() || sizes[i] != 'selectionOnly')
- {
- var opt = document.createElement('option');
- mxUtils.write(opt, mxResources.get(sizes[i]));
- opt.setAttribute('value', sizes[i]);
- exportSelect.appendChild(opt);
- }
- }
- if (exportOption)
- {
- mxUtils.write(div, mxResources.get('size') + ':');
- div.appendChild(exportSelect);
- mxUtils.br(div);
- height += 26;
- mxEvent.addListener(exportSelect, 'change', function()
- {
- if (exportSelect.value == 'selectionOnly')
- {
- selection.checked = true;
- }
- });
- }
- else if (cropOption)
- {
- div.appendChild(cb6);
- mxUtils.write(div, mxResources.get('crop'));
- mxUtils.br(div);
-
- height += 26;
-
- mxEvent.addListener(selection, 'change', function()
- {
- if (selection.checked)
- {
- cb6.removeAttribute('disabled');
- }
- else
- {
- cb6.setAttribute('disabled', 'disabled');
- }
- });
- }
- if (graph.isSelectionEmpty())
- {
- if (exportOption)
- {
- selection.style.display = 'none';
- selection.nextSibling.style.display = 'none';
- selection.nextSibling.nextSibling.style.display = 'none';
- height -= 26;
- }
- }
- else
- {
- exportSelect.value = 'diagram';
- cb6.setAttribute('checked', 'checked');
- cb6.defaultChecked = true;
- mxEvent.addListener(selection, 'change', function()
- {
- if (selection.checked)
- {
- exportSelect.value = 'selectionOnly';
- }
- else
- {
- exportSelect.value = 'diagram';
- }
- });
- }
-
- var defaultTransparent = false; /*graph.background == mxConstants.NONE || graph.background == null*/;
- var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
- defaultTransparent, null, null, format != 'jpeg');
- var keepTheme = null;
-
- if (Editor.isDarkMode())
- {
- keepTheme = this.addCheckbox(div, mxResources.get('dark'), true);
- height += 26;
- }
-
- var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
-
- var cb5 = document.createElement('input');
- cb5.style.marginTop = '16px';
- cb5.style.marginRight = '8px';
- cb5.setAttribute('type', 'checkbox');
-
- if (this.isOffline() || !this.canvasSupported)
- {
- cb5.setAttribute('disabled', 'disabled');
- }
-
- if (embedOption)
- {
- div.appendChild(cb5);
- mxUtils.write(div, mxResources.get('embedImages'));
- mxUtils.br(div);
-
- height += 26;
- }
-
- var grid = null;
-
- if (format == 'png' || format == 'jpeg')
- {
- grid = this.addCheckbox(div, mxResources.get('grid'), false, this.isOffline() || !this.canvasSupported, false, true);
- height += 26;
- }
-
- var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
- include.style.marginBottom = '16px';
-
- var linkSelect = document.createElement('select');
- linkSelect.style.maxWidth = '260px';
- linkSelect.style.marginLeft = '8px';
- linkSelect.style.marginRight = '10px';
- linkSelect.className = 'geBtn';
- var autoOption = document.createElement('option');
- autoOption.setAttribute('value', 'auto');
- mxUtils.write(autoOption, mxResources.get('automatic'));
- linkSelect.appendChild(autoOption);
- var blankOption = document.createElement('option');
- blankOption.setAttribute('value', 'blank');
- mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
- linkSelect.appendChild(blankOption);
- var selfOption = document.createElement('option');
- selfOption.setAttribute('value', 'self');
- mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
- linkSelect.appendChild(selfOption);
- if (format == 'svg')
- {
- mxUtils.write(div, mxResources.get('links') + ':');
- div.appendChild(linkSelect);
- mxUtils.br(div);
- mxUtils.br(div);
- height += 26;
- }
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- this.lastExportBorder = borderInput.value;
- this.lastExportZoom = zoomInput.value;
-
- callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
- include.checked, cb5.checked, borderInput.value, cb6.checked, false,
- linkSelect.value, (grid != null) ? grid.checked : null, (keepTheme != null) ?
- keepTheme.checked : null, exportSelect.value);
- }), null, btnLabel, helpLink);
- this.showDialog(dlg.container, 340, height, true, true, null, null, null, null, true);
- zoomInput.focus();
-
- if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5)
- {
- zoomInput.select();
- }
- else
- {
- document.execCommand('selectAll', false, null);
- }
- };
-
- /**
- *
- */
- EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
- {
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
- var graph = this.editor.graph;
-
- if (title != null)
- {
- var hd = document.createElement('h3');
- mxUtils.write(hd, title);
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
- div.appendChild(hd);
- }
-
- var fit = this.addCheckbox(div, mxResources.get('fit'), true);
- var shadow = this.addCheckbox(div, mxResources.get('shadow'),
- graph.shadowVisible && shadowEnabled, !shadowEnabled);
- var image = this.addCheckbox(div, imageLabel);
- var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
- var editSection = this.addEditButton(div, lightbox);
- var edit = editSection.getEditInput();
-
- var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
- var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
- layers.style.marginLeft = edit.style.marginLeft;
- layers.style.marginBottom = '12px';
- layers.style.marginTop = '8px';
-
- mxEvent.addListener(lightbox, 'change', function()
- {
- if (lightbox.checked)
- {
- if (hasLayers)
- {
- layers.removeAttribute('disabled');
- }
-
- edit.removeAttribute('disabled');
- }
- else
- {
- layers.setAttribute('disabled', 'disabled');
- edit.setAttribute('disabled', 'disabled');
- }
-
- if (edit.checked && lightbox.checked)
- {
- editSection.getEditSelect().removeAttribute('disabled');
- }
- else
- {
- editSection.getEditSelect().setAttribute('disabled', 'disabled');
- }
- });
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
- editSection.getLink(), layers.checked);
- }), null, mxResources.get('embed'), helpLink);
- this.showDialog(dlg.container, 280, 280, true, true);
- };
- /**
- *
- */
- EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
- {
- var bounds = this.editor.graph.getGraphBounds();
- var page = this.getSelectedPageIndex();
-
- function doUpdate(dataUri)
- {
- var onclick = ' ';
- var css = '';
-
- // Adds double click handling
- if (lightbox)
- {
- // KNOWN: Message passing does not seem to work in IE11
- onclick = " onclick=\"(function(img){if(img.wnd!=null&&!img.wnd.closed){img.wnd.focus();}else{var r=function(evt){if(evt.data=='ready'&&evt.source==img.wnd){img.wnd.postMessage(decodeURIComponent(" +
- "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.lightboxHost + "/?client=1" +
- ((page != null) ? ("&page=" + page) : "") +
- ((edit) ? "&edit=_blank" : "") +
- ((layers) ? '&layers=1' : '') + "');}})(this);\"";
- css += 'cursor:pointer;';
- }
-
- if (fit)
- {
- css += 'max-width:100%;';
- }
-
- var atts = '';
-
- if (retina)
- {
- atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
- }
-
- fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
- };
-
- if (this.isExportToCanvas())
- {
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
- {
- var xml = (lightbox) ? this.getFileData(true) : null;
- var data = this.createImageDataUri(canvas, xml, 'png');
- doUpdate(data);
- }), null, null, null, mxUtils.bind(this, function(e)
- {
- err({message: mxResources.get('unknownError')});
- }), null, true, (retina) ? 2 : 1, null, shadow, null, null, Editor.defaultBorder);
- }
- else
- {
- var data = this.getFileData(true);
-
- if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
- {
- var size = '';
-
- if (retina)
- {
- size = '&w=' + Math.round(2 * bounds.width) +
- '&h=' + Math.round(2 * bounds.height);
- }
-
- var embed = (lightbox) ? '1' : '0';
- var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
- '&base64=1&embedXml=' + embed + size + '&xml=' +
- encodeURIComponent(data));
-
- // LATER: Updates on each change, add a delay
- req.send(mxUtils.bind(this, function()
- {
- if (req.getStatus() >= 200 && req.getStatus() <= 299)
- {
- // Fixes possible "incorrect function" for select() on
- // DOM node which is no longer in document with IE11
- doUpdate('data:image/png;base64,' + req.getText());
- }
- else
- {
- err({message: mxResources.get('unknownError')});
- }
- }));
- }
- else
- {
- err({message: mxResources.get('drawingTooLarge')});
- }
- }
- };
-
- /**
- *
- */
- EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
- {
- var svgRoot = this.editor.graph.getSvg(null, null, null, null, null,
- null, null, null, null, null, !image);
-
- // Keeps hashtag links on same page
- var links = svgRoot.getElementsByTagName('a');
-
- if (links != null)
- {
- for (var i = 0; i < links.length; i++)
- {
- var href = links[i].getAttribute('href');
-
- if (href != null && href.charAt(0) == '#' &&
- links[i].getAttribute('target') == '_blank')
- {
- links[i].removeAttribute('target');
- }
- }
- }
-
- if (lightbox)
- {
- svgRoot.setAttribute('content', this.getFileData(true));
- }
-
- // Adds shadow filter
- if (shadow)
- {
- this.editor.graph.addSvgShadow(svgRoot);
- }
-
- // SVG inside image tag
- if (image)
- {
- var onclick = ' ';
- var css = '';
- // Adds double click handling
- if (lightbox)
- {
- // KNOWN: Message passing does not seem to work in IE11
- onclick = "onclick=\"(function(img){if(img.wnd!=null&&!img.wnd.closed){img.wnd.focus();}else{var r=function(evt){if(evt.data=='ready'&&evt.source==img.wnd){img.wnd.postMessage(decodeURIComponent(" +
- "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.lightboxHost + "/?client=1" +
- ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
- css += 'cursor:pointer;';
- }
-
- if (fit)
- {
- css += 'max-width:100%;';
- }
-
- // Images inside IMG don't seem to work so embed them all
- this.editor.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
- {
- fn('<img src="' + Editor.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
- ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
- }));
- }
- else
- {
- var css = '';
-
- // Adds double click handling
- if (lightbox)
- {
- var page = this.getSelectedPageIndex();
-
- // KNOWN: Message passing does not seem to work in IE11
- var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
- // Ignores link events
- "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
- // Focus existing lightbox
- "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
- // Message handling
- "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
- "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
- "window.addEventListener('message',r);" +
- // Opens lightbox window
- "svg.wnd=window.open('" + EditorUi.lightboxHost + "/?client=1" +
- ((page != null) ? ("&page=" + page) : "") +
- ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
- svgRoot.setAttribute('onclick', js);
- css += 'cursor:pointer;';
- }
-
- // Adds responsive size
- if (fit)
- {
- var w = parseInt(svgRoot.getAttribute('width'));
- var h = parseInt(svgRoot.getAttribute('height'));
- svgRoot.setAttribute('viewBox', '-0.5 -0.5 ' + w + ' ' + h);
- css += 'max-width:100%;max-height:' + h + 'px;';
- svgRoot.removeAttribute('height');
- }
-
- if (css != '')
- {
- svgRoot.setAttribute('style', css);
- }
-
- // Adds CSS
- this.editor.addFontCss(svgRoot);
-
- if (this.editor.graph.mathEnabled)
- {
- this.editor.addMathCss(svgRoot);
- }
-
- fn(mxUtils.getXml(svgRoot));
- }
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.timeSince = function(date)
- {
- var seconds = Math.floor((new Date() - date) / 1000);
- var interval = Math.floor(seconds / 31536000);
- if (interval > 1)
- {
- return interval + ' ' + mxResources.get('years');
- }
-
- interval = Math.floor(seconds / 2592000);
-
- if (interval > 1)
- {
- return interval + ' ' + mxResources.get('months');
- }
-
- interval = Math.floor(seconds / 86400);
-
- if (interval > 1)
- {
- return interval + ' ' + mxResources.get('days');
- }
-
- interval = Math.floor(seconds / 3600);
-
- if (interval > 1)
- {
- return interval + ' ' + mxResources.get('hours');
- }
-
- interval = Math.floor(seconds / 60);
-
- if (interval > 1)
- {
- return interval + ' ' + mxResources.get('minutes');
- }
-
- if (interval == 1)
- {
- return interval + ' ' + mxResources.get('minute');
- }
-
- return null;
- };
- /**
- *
- */
- EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
- {
- if (node != null)
- {
- var diagramNode = null;
-
- if (node.nodeName == 'diagram')
- {
- diagramNode = node;
- }
- else if (node.nodeName == 'mxfile')
- {
- var diagrams = node.getElementsByTagName('diagram');
- if (diagrams.length > 0)
- {
- diagramNode = diagrams[0];
- var graphGetGlobalVariable = graph.getGlobalVariable;
-
- graph.getGlobalVariable = function(name)
- {
- if (name == 'page')
- {
- return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
- }
- else if (name == 'pagenumber')
- {
- return 1;
- }
-
- return graphGetGlobalVariable.apply(this, arguments);
- };
- }
- }
-
- if (diagramNode != null)
- {
- node = Editor.parseDiagramNode(diagramNode);
- }
- }
-
- // Hack to decode XML into temp graph via editor
- var prev = this.editor.graph;
-
- try
- {
- this.editor.graph = graph;
- this.editor.setGraphXml(node);
- }
- catch (e)
- {
- // ignore
- }
- finally
- {
- this.editor.graph = prev;
- }
-
- return node;
- };
-
-
- /**
- *
- */
- EditorUi.prototype.getPngFileProperties = function(node)
- {
- var scale = 1;
- var border = 0;
-
- if (node != null)
- {
- if (node.hasAttribute('scale'))
- {
- var temp = parseFloat(node.getAttribute('scale'));
-
- if (!isNaN(temp) && temp > 0)
- {
- scale = temp;
- }
- }
-
- if (node.hasAttribute('border'))
- {
- var temp = parseInt(node.getAttribute('border'));
-
- if (!isNaN(temp) && temp > 0)
- {
- border = temp;
- }
- }
- }
-
- return {scale: scale, border: border};
- };
-
- /**
- *
- */
- EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData, scale, border)
- {
- try
- {
- var graph = this.editor.graph;
- var darkTheme = graph.themes != null && graph.defaultThemeName == 'darkTheme';
- var diagramData = null;
-
- // Exports PNG for given optional data
- if (optionalData != null && optionalData.length > 0)
- {
- graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
- document.body.appendChild(graph.container);
- this.decodeNodeIntoGraph(this.editor.extractGraphModel(
- mxUtils.parseXml(optionalData).documentElement, true), graph);
- diagramData = optionalData;
- }
- // Exports PNG for first page while other page is showing
- else if (darkTheme || (this.pages != null && this.currentPage != this.pages[0]))
- {
- graph = this.createTemporaryGraph(graph.getStylesheet());
- var graphGetGlobalVariable = graph.getGlobalVariable;
- var page = this.pages[0];
-
- graph.getGlobalVariable = function(name)
- {
- if (name == 'page')
- {
- return page.getName();
- }
- else if (name == 'pagenumber')
- {
- return 1;
- }
-
- return graphGetGlobalVariable.apply(this, arguments);
- };
-
- document.body.appendChild(graph.container);
- graph.model.setRoot(page.root);
- }
-
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
- {
- try
- {
- if (diagramData == null)
- {
- diagramData = this.getFileData(true, null, null, null, null,
- null, null, null, null, false);
- }
-
- var data = canvas.toDataURL('image/png');
- data = Editor.writeGraphModelToPng(data,
- 'tEXt', 'mxfile', encodeURIComponent(diagramData));
- success(data.substring(data.lastIndexOf(',') + 1));
-
- // Removes temporary graph from DOM
- if (graph != this.editor.graph)
- {
- graph.container.parentNode.removeChild(graph.container);
- }
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }), null, null, null, mxUtils.bind(this, function(e)
- {
- if (error != null)
- {
- error(e);
- }
- }), null, null, scale, null, graph.shadowVisible, null, graph, border);
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }
- /**
- * Returns the SVG of the diagram with embedded XML. If a callback function is
- * used, the images are converted to data URIs.
- */
- EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection,
- redirect, embedImages, background, scale, border, shadow, keepTheme)
- {
- embedImages = (embedImages != null) ? embedImages : true;
- var bg = (background != null) ? background : graph.background;
-
- if (bg == mxConstants.NONE)
- {
- bg = null;
- }
- // Sets or disables alternate text for foreignObjects. Disabling is needed
- // because PhantomJS seems to ignore switch statements and paint all text.
- var svgRoot = graph.getSvg(bg, scale, border, null, null, ignoreSelection,
- null, null, null, graph.shadowVisible || shadow, null, keepTheme);
-
- if (graph.shadowVisible || shadow)
- {
- graph.addSvgShadow(svgRoot);
- }
- if (xml != null)
- {
- svgRoot.setAttribute('content', xml);
- }
-
- if (url != null)
- {
- svgRoot.setAttribute('resource', url);
- }
-
- // LATER: Click on SVG content to start editing
- // if (redirect != null)
- // {
- // // TODO: Ignore anchor tag source for click event
- // svgRoot.setAttribute('style', 'cursor:pointer;');
- // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
- // }
- if (callback != null)
- {
- this.embedFonts(svgRoot, mxUtils.bind(this, function(svgRoot)
- {
- if (embedImages)
- {
- this.editor.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
- {
- callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
- mxUtils.getXml(svgRoot));
- }));
- }
- else
- {
- callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
- mxUtils.getXml(svgRoot));
- }
- }));
- }
- else
- {
- return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
- mxUtils.getXml(svgRoot);
- }
- };
-
- /**
- * Embeds font CSS as data URIs into the given svgRoot.
- */
- EditorUi.prototype.embedFonts = function(svgRoot, callback)
- {
- this.editor.loadFonts(mxUtils.bind(this, function()
- {
- try
- {
- if (this.editor.resolvedFontCss != null)
- {
- this.editor.addFontCss(svgRoot, this.editor.resolvedFontCss);
- }
-
- this.editor.embedExtFonts(mxUtils.bind(this, function(extFontsEmbeddedCss)
- {
- try
- {
- if (extFontsEmbeddedCss != null)
- {
- this.editor.addFontCss(svgRoot, extFontsEmbeddedCss);
- }
-
- callback(svgRoot);
- }
- catch (e)
- {
- callback(svgRoot);
- }
- }));
- }
- catch (e)
- {
- callback(svgRoot);
- }
- }));
- };
-
- /**
- *
- */
- EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow,
- editable, border, noCrop, currentPage, format, grid, dpi, keepTheme, exportType)
- {
- format = (format != null) ? format : 'png';
-
- if (this.spinner.spin(document.body, mxResources.get('exporting')))
- {
- var selectionEmpty = this.editor.graph.isSelectionEmpty();
- ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
-
- // Caches images
- if (this.thumbImageCache == null)
- {
- this.thumbImageCache = new Object();
- }
-
- try
- {
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
- {
- this.spinner.stop();
-
- try
- {
- this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
- null, null, ignoreSelection, currentPage) : null,
- format, (this.pages == null || this.pages.length == 0), dpi);
- }
- catch (e)
- {
- this.handleError(e);
- }
- }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
- {
- this.spinner.stop();
- this.handleError(e);
- }), null, ignoreSelection, scale || 1, transparentBackground, addShadow,
- null, null, border, noCrop, grid, keepTheme, exportType);
- }
- catch (e)
- {
- this.spinner.stop();
- this.handleError(e);
- }
- }
- };
- /**
- /**
- * Returns true if the given URL is known to have CORS headers.
- */
- EditorUi.prototype.isCorsEnabledForUrl = function(url)
- {
- return this.editor.isCorsEnabledForUrl(url);
- };
- /**
- * Handling drag and drop and import.
- */
- /**
- * Imports the given XML into the existing diagram.
- */
- EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling, addNewPage)
- {
- dx = (dx != null) ? dx : 0;
- dy = (dy != null) ? dy : 0;
- var cells = []
-
- try
- {
- var graph = this.editor.graph;
-
- if (xml != null && xml.length > 0)
- {
- // Adds pages
- graph.model.beginUpdate();
- try
- {
- var doc = mxUtils.parseXml(xml);
- var mapping = {};
-
- // Checks for mxfile with multiple pages
- var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
- if (node != null && node.nodeName == 'mxfile' && this.pages != null)
- {
- var diagrams = node.getElementsByTagName('diagram');
- if (diagrams.length == 1 && !addNewPage)
- {
- node = Editor.parseDiagramNode(diagrams[0]);
-
- if (this.currentPage != null)
- {
- mapping[diagrams[0].getAttribute('id')] = this.currentPage.getId();
-
- // Renames page if diagram has one blank page with default name
- if (this.pages != null && this.pages.length == 1 &&
- this.isDiagramEmpty() && this.currentPage.getName() ==
- mxResources.get('pageWithNumber', [1]))
- {
- var name = diagrams[0].getAttribute('name');
-
- if (name != null && name != '')
- {
- this.editor.graph.model.execute(new RenamePage(
- this, this.currentPage, name));
- }
- }
- }
- }
- else if (diagrams.length > 0)
- {
- var pages = [];
- var i0 = 0;
-
- // Adds first page to current page if current page is only page and empty
- if (this.pages != null && this.pages.length == 1 && this.isDiagramEmpty())
- {
- mapping[diagrams[0].getAttribute('id')] = this.pages[0].getId();
- node = Editor.parseDiagramNode(diagrams[0]);
- crop = false;
- i0 = 1;
- }
- for (var i = i0; i < diagrams.length; i++)
- {
- // Imported pages must obtain a new ID and
- // all links to pages must be updated below
- var oldId = diagrams[i].getAttribute('id')
- diagrams[i].removeAttribute('id');
-
- var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
- mapping[oldId] = diagrams[i].getAttribute('id');
- var index = this.pages.length;
-
- // Checks for invalid page names
- if (page.getName() == null)
- {
- page.setName(mxResources.get('pageWithNumber', [index + 1]));
- }
-
- graph.model.execute(new ChangePage(this, page, page, index, true));
- pages.push(page);
- }
-
- this.updatePageLinks(mapping, pages);
- }
- }
-
- if (node != null && node.nodeName === 'mxGraphModel')
- {
- cells = graph.importGraphModel(node, dx, dy, crop);
-
- if (cells != null)
- {
- for (var i = 0; i < cells.length; i++)
- {
- this.updatePageLinksForCell(mapping, cells[i]);
- }
- }
- }
- }
- finally
- {
- graph.model.endUpdate();
- }
- }
- }
- catch (e)
- {
- if (!noErrorHandling)
- {
- this.handleError(e);
- }
- else
- {
- throw e;
- }
- }
-
- return cells;
- };
-
- /**
- * Updates links to pages in shapes and labels.
- */
- EditorUi.prototype.updatePageLinks = function(mapping, pages)
- {
- for (var i = 0; i < pages.length; i++)
- {
- this.updatePageLinksForCell(mapping, pages[i].root);
- }
- };
-
- /**
- * Updates links to pages in shapes and labels.
- */
- EditorUi.prototype.updatePageLinksForCell = function(mapping, cell)
- {
- var temp = document.createElement('div');
- var graph = this.editor.graph;
- var href = graph.getLinkForCell(cell);
- if (href != null)
- {
- graph.setLinkForCell(cell, this.updatePageLink(mapping, href));
- }
-
- if (graph.isHtmlLabel(cell))
- {
- temp.innerHTML = graph.sanitizeHtml(graph.getLabel(cell));
- var links = temp.getElementsByTagName('a');
- var changed = false;
-
- for (var i = 0; i < links.length; i++)
- {
- href = links[i].getAttribute('href');
-
- if (href != null)
- {
- links[i].setAttribute('href', this.updatePageLink(mapping, href));
- changed = true;
- }
- }
-
- if (changed)
- {
- graph.labelChanged(cell, temp.innerHTML);
- }
- }
-
- for (var i = 0; i < graph.model.getChildCount(cell); i++)
- {
- this.updatePageLinksForCell(mapping, graph.model.getChildAt(cell, i));
- }
- };
- /**
- * Updates links to pages in shapes and labels.
- */
- EditorUi.prototype.updatePageLink = function(mapping, href)
- {
- if (href.substring(0, 13) == 'data:page/id,')
- {
- var newId = mapping[href.substring(href.indexOf(',') + 1)];
- href = (newId != null) ? 'data:page/id,' + newId : null;
- }
- else if (href.substring(0, 17) == 'data:action/json,')
- {
- try
- {
- var link = JSON.parse(href.substring(17));
- if (link.actions != null)
- {
- for (var i = 0; i < link.actions.length; i++)
- {
- var action = link.actions[i];
-
- if (action.open != null && action.open.substring(0, 13) == 'data:page/id,')
- {
- var oldId = action.open.substring(action.open.indexOf(',') + 1);
- var newId = mapping[oldId];
-
- if (newId != null)
- {
- action.open = 'data:page/id,' + newId;
- }
- else if (this.getPageById(oldId) == null)
- {
- delete action.open;
- }
- }
- }
-
- href = 'data:action/json,' + JSON.stringify(link);
- }
- }
- catch (e)
- {
- // Ignore
- }
- }
-
- return href;
- };
-
- /**
- * Returns true for VSD, VDX and VSS, VSX files.
- */
- EditorUi.prototype.isRemoteVisioFormat = function(filename)
- {
- return /(\.v(sd|dx))($|\?)/i.test(filename) || /(\.vs(s|x))($|\?)/i.test(filename);
- };
-
- /**
- * Imports the given Visio file
- */
- EditorUi.prototype.importVisio = function(file, done, onerror, filename)
- {
- //A reduced version of this code is used in conf/jira plugins, review that code whenever this function is changed
- filename = (filename != null) ? filename : file.name;
- onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- });
-
- var delayed = mxUtils.bind(this, function()
- {
- this.loadingExtensions = false;
-
- if (this.doImportVisio)
- {
- var remote = this.isRemoteVisioFormat(filename);
-
- try
- {
- var ext = 'UNKNOWN-VISIO';
- var dot = filename.lastIndexOf('.');
-
- if (dot >= 0 && dot < filename.length)
- {
- ext = filename.substring(dot + 1).toUpperCase();
- }
- else
- {
- var slash = filename.lastIndexOf('/');
-
- if (slash >= 0 && slash < filename.length)
- {
- filename = filename.substring(slash + 1);
- }
- }
-
- EditorUi.logEvent({category: ext + '-MS-IMPORT-FILE',
- action: 'filename_' + filename,
- label: (remote) ? 'remote' : 'local'});
- }
- catch (e)
- {
- // ignore
- }
-
- if (remote)
- {
- if (VSD_CONVERT_URL != null && !this.isOffline())
- {
- var formData = new FormData();
- formData.append('file1', file, filename);
-
- var xhr = new XMLHttpRequest();
- xhr.open('POST', VSD_CONVERT_URL + (/(\.vss|\.vsx)$/.test(filename)? '?stencil=1' : ''));
- xhr.responseType = 'blob';
- this.addRemoteServiceSecurityCheck(xhr);
-
- xhr.onreadystatechange = mxUtils.bind(this, function()
- {
- if (xhr.readyState == 4)
- {
- if (xhr.status >= 200 && xhr.status <= 299)
- {
- try
- {
- var resp = xhr.response;
- if (resp.type == 'text/xml')
- {
- var reader = new FileReader();
-
- reader.onload = mxUtils.bind(this, function(e)
- {
- try
- {
- done(e.target.result);
- }
- catch (e)
- {
- onerror({message: mxResources.get('errorLoadingFile')});
- }
- });
-
- reader.readAsText(resp);
- }
- else
- {
- this.doImportVisio(resp, done, onerror, filename);
- }
- }
- catch (e)
- {
- onerror(e);
- }
- }
- else
- {
- try
- {
- if (xhr.responseType == '' || xhr.responseType == 'text')
- {
- onerror({message: xhr.responseText});
- }
- else
- {
- var reader = new FileReader();
- reader.onload = function()
- {
- onerror({message: JSON.parse(reader.result).Message});
- }
- reader.readAsText(xhr.response);
- }
- }
- catch(e)
- {
- onerror({});
- }
- }
- }
- });
-
- xhr.send(formData);
- }
- else
- {
- onerror({message: this.getServiceName() == 'conf'? mxResources.get('vsdNoConfig') : mxResources.get('serviceUnavailableOrBlocked')});
- }
- }
- else
- {
- try
- {
- this.doImportVisio(file, done, onerror, filename);
- }
- catch (e)
- {
- onerror(e);
- }
- }
- }
- else
- {
- this.spinner.stop();
- this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
- }
- });
-
- if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline(true))
- {
- this.loadingExtensions = true;
- mxscript('js/extensions.min.js', delayed);
- }
- else
- {
- delayed();
- }
- };
- /**
- * Imports the given GraphML (yEd) file
- */
- EditorUi.prototype.importGraphML = function(xmlData, done, onerror)
- {
- onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- });
-
- var delayed = mxUtils.bind(this, function()
- {
- this.loadingExtensions = false;
-
- if (this.doImportGraphML)
- {
-
- try
- {
- this.doImportGraphML(xmlData, done, onerror);
- }
- catch (e)
- {
- onerror(e);
- }
- }
- else
- {
- this.spinner.stop();
- this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
- }
- });
-
- if (!this.doImportGraphML && !this.loadingExtensions && !this.isOffline(true))
- {
- this.loadingExtensions = true;
- mxscript('js/extensions.min.js', delayed);
- }
- else
- {
- delayed();
- }
- };
-
- /**
- * Export the diagram to VSDX
- */
- EditorUi.prototype.exportVisio = function(currentPage)
- {
- var delayed = mxUtils.bind(this, function()
- {
- this.loadingExtensions = false;
-
- if (typeof VsdxExport !== 'undefined')
- {
- try
- {
- var expSuccess = new VsdxExport(this).exportCurrentDiagrams(currentPage);
-
- if (!expSuccess)
- {
- this.handleError({message: mxResources.get('unknownError')});
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- else
- {
- this.spinner.stop();
- this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
- }
- });
-
- if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline(true))
- {
- this.loadingExtensions = true;
- mxscript('js/extensions.min.js', delayed);
- }
- else
- {
- delayed();
- }
- };
-
- /**
- * Imports the given Lucidchart data.
- */
- EditorUi.prototype.convertLucidChart = function(data, success, error)
- {
- var delayed = mxUtils.bind(this, function()
- {
- this.loadingExtensions = false;
-
- // Checks for signature method
- if (typeof window.LucidImporter !== 'undefined')
- {
- try
- {
- EditorUi.logEvent({category: 'LUCIDCHART-IMPORT-FILE',
- action: 'size_' + data.length});
- EditorUi.debug('convertLucidChart', data);
- }
- catch (e)
- {
- // ignore
- }
-
- try
- {
- success(LucidImporter.importState(JSON.parse(data)));
- }
- catch (e)
- {
- if (window.console != null)
- {
- console.error(e);
- }
-
- error(e);
- }
- }
- else
- {
- error({message: mxResources.get('serviceUnavailableOrBlocked')});
- }
- });
-
- if (typeof window.LucidImporter === 'undefined' &&
- !this.loadingExtensions && !this.isOffline(true))
- {
- this.loadingExtensions = true;
-
- if (urlParams['dev'] == '1')
- {
- //Lucid org chart requires orgChart layout, in production, it is part of the extemsions.min.js
- mxscript('js/diagramly/Extensions.js', function()
- {
- mxscript('js/orgchart/bridge.min.js', function()
- {
- mxscript('js/orgchart/bridge.collections.min.js', function()
- {
- mxscript('js/orgchart/OrgChart.Layout.min.js', function()
- {
- mxscript('js/orgchart/mxOrgChartLayout.js', delayed);
- });
- });
- });
- });
- }
- else
- {
- mxscript('js/extensions.min.js', delayed);
- }
- }
- else
- {
- // Async needed for selection
- window.setTimeout(delayed, 0);
- }
- };
- /**
- * Generates a Mermaid image.
- */
- EditorUi.prototype.generateMermaidImage = function(data, config, success, error)
- {
- var ui = this;
-
- var delayed = function()
- {
- try
- {
- this.loadingMermaid = false;
-
- config = (config != null) ? config : EditorUi.defaultMermaidConfig;
- config.securityLevel = 'strict';
- config.startOnLoad = false;
-
- mermaid.mermaidAPI.initialize(config);
-
- mermaid.mermaidAPI.render('geMermaidOutput-' + new Date().getTime(), data, function(svg)
- {
- try
- {
- // Workaround for namespace errors in SVG output for IE
- if (mxClient.IS_IE || mxClient.IS_IE11)
- {
- svg = svg.replace(/ xmlns:\S*="http:\/\/www.w3.org\/XML\/1998\/namespace"/g, '').
- replace(/ (NS xml|\S*):space="preserve"/g, ' xml:space="preserve"');
- }
-
- var doc = mxUtils.parseXml(svg);
- var svgs = doc.getElementsByTagName('svg');
- if (svgs.length > 0)
- {
- var w = parseFloat(svgs[0].getAttribute('width'));
- var h = parseFloat(svgs[0].getAttribute('height'));
-
- if (isNaN(w) || isNaN(h))
- {
- try
- {
- var viewBox = svgs[0].getAttribute('viewBox').split(/\s+/);
- w = parseFloat(viewBox[2]);
- h = parseFloat(viewBox[3]);
- }
- catch(e)
- {
- //Any size such that it shows up
- w = w || 100;
- h = h || 100;
- }
- }
-
- success(ui.convertDataUri(Editor.createSvgDataUri(svg)), w, h);
- }
- else
- {
- error({message: mxResources.get('invalidInput')});
- }
- }
- catch (e)
- {
- error(e);
- }
- });
- }
- catch (e)
- {
- error(e);
- }
- };
- if (typeof mermaid === 'undefined' && !this.loadingMermaid && !this.isOffline(true))
- {
- this.loadingMermaid = true;
-
- if (urlParams['dev'] == '1')
- {
- mxscript('js/mermaid/mermaid.min.js', delayed);
- }
- else
- {
- mxscript('js/extensions.min.js', delayed);
- }
- }
- else
- {
- delayed();
- }
- };
-
- /**
- * Generates a plant UML image. Possible types are svg, png and txt.
- */
- EditorUi.prototype.generatePlantUmlImage = function(data, type, success, error)
- {
- function encode64(data)
- {
- r = "";
-
- for (i = 0; i < data.length; i += 3)
- {
- if (i + 2 == data.length)
- {
- r += append3bytes(data.charCodeAt(i), data.charCodeAt(i + 1), 0);
- }
- else if (i + 1 == data.length)
- {
- r += append3bytes(data.charCodeAt(i), 0, 0);
- }
- else
- {
- r += append3bytes(data.charCodeAt(i), data.charCodeAt(i + 1),
- data.charCodeAt(i + 2));
- }
- }
-
- return r;
- }
- function append3bytes(b1, b2, b3)
- {
- c1 = b1 >> 2;
- c2 = ((b1 & 0x3) << 4) | (b2 >> 4);
- c3 = ((b2 & 0xF) << 2) | (b3 >> 6);
- c4 = b3 & 0x3F;
- r = "";
- r += encode6bit(c1 & 0x3F);
- r += encode6bit(c2 & 0x3F);
- r += encode6bit(c3 & 0x3F);
- r += encode6bit(c4 & 0x3F);
-
- return r;
- }
- function encode6bit(b)
- {
- if (b < 10)
- {
- return String.fromCharCode(48 + b);
- }
-
- b -= 10;
-
- if (b < 26)
- {
- return String.fromCharCode(65 + b);
- }
-
- b -= 26;
-
- if (b < 26)
- {
- return String.fromCharCode(97 + b);
- }
-
- b -= 26;
-
- if (b == 0)
- {
- return '-';
- }
-
- if (b == 1)
- {
- return '_';
- }
-
- return '?';
- }
- // TODO: Remove unescape, use btoa for compatibility with graph.compress
- function compress(s)
- {
- return encode64(Graph.arrayBufferToString(pako.deflateRaw(s)));
- };
- var plantUmlServerUrl = (type == 'txt') ? PLANT_URL + '/txt/' :
- ((type == 'png') ? PLANT_URL + '/png/' : PLANT_URL + '/svg/');
-
- var xhr = new XMLHttpRequest();
- xhr.open('GET', plantUmlServerUrl + compress(data), true);
- if (type != 'txt')
- {
- xhr.responseType = 'blob';
- }
- xhr.onload = function(e)
- {
- if (this.status >= 200 && this.status < 300)
- {
- if (type == 'txt')
- {
- success(this.response);
- }
- else
- {
- var reader = new FileReader();
- reader.readAsDataURL(this.response);
- reader.onloadend = function(e)
- {
- var img = new Image();
- img.onload = function()
- {
- try
- {
- var w = img.width;
- var h = img.height;
-
- // Workaround for 0 image size in IE11
- if (w == 0 && h == 0)
- {
- var data = reader.result;
- var comma = data.indexOf(',');
- var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
- var root = mxUtils.parseXml(svgText);
- var svgs = root.getElementsByTagName('svg');
-
- if (svgs.length > 0)
- {
- w = parseFloat(svgs[0].getAttribute('width'));
- h = parseFloat(svgs[0].getAttribute('height'));
- }
- }
-
- success(reader.result, w, h);
- }
- catch (e)
- {
- error(e);
- }
- };
- img.src = reader.result;
- };
- reader.onerror = function(e)
- {
- error(e);
- };
- }
- }
- else
- {
- error(e);
- }
- };
- xhr.onerror = function(e)
- {
- error(e);
- };
- xhr.send();
- };
- /**
- * Inserts the given text as a preformatted HTML text.
- */
- EditorUi.prototype.insertAsPreText = function(text, x, y)
- {
- var graph = this.editor.graph;
- var cell = null;
-
- graph.getModel().beginUpdate();
- try
- {
- cell = graph.insertVertex(null, null, '<pre>' + text + '</pre>',
- x, y, 1, 1, 'text;html=1;align=left;verticalAlign=top;');
- graph.updateCellSize(cell, true);
- }
- finally
- {
- graph.getModel().endUpdate();
- }
- return cell;
- };
- /**
- * Imports the given XML into the existing diagram.
- * TODO: Make this function asynchronous
- */
- EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages, addNewPage)
- {
- crop = (crop != null) ? crop : true;
- resizeImages = (resizeImages != null) ? resizeImages : true;
-
- // Handles special case for Gliffy data which requires async server-side for parsing
- if (text != null)
- {
- if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
- {
- // Fixes possible parsing problems with ASCII 160 (non-breaking space)
- this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
- {
- this.editor.graph.setSelectionCells(this.insertTextAt(
- xhr.responseText, dx, dy, true));
- }
- }));
-
- // Returns empty cells array as it is aysynchronous
- return [];
- }
- // Handles special case of data URI which requires async loading for finding size
- else if (text.substring(0, 5) == 'data:' || (!this.isOffline() &&
- (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
- {
- var graph = this.editor.graph;
-
- // Checks for embedded XML in PDF
- if (text.substring(0, 28) == 'data:application/pdf;base64,')
- {
- var xml = Editor.extractGraphModelFromPdf(text);
-
- if (xml != null && xml.length > 0)
- {
- return this.importXml(xml, dx, dy, crop, true, addNewPage);
- }
- }
-
- // Checks for embedded XML in PNG
- if (text.substring(0, 22) == 'data:image/png;base64,')
- {
- var xml = this.extractGraphModelFromPng(text);
-
- if (xml != null && xml.length > 0)
- {
- return this.importXml(xml, dx, dy, crop, true, addNewPage);
- }
- }
-
- // Tries to extract embedded XML from SVG data URI
- if (text.substring(0, 19) == 'data:image/svg+xml;')
- {
- try
- {
- var xml = null;
-
- if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
- {
- xml = text.substring(text.indexOf(',') + 1);
- xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
- }
- else
- {
- xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
- }
-
- var result = this.importXml(xml, dx, dy, crop, true, addNewPage);
-
- if (result.length > 0)
- {
- return result;
- }
- }
- catch (e)
- {
- // Ignore
- }
- }
-
- this.loadImage(text, mxUtils.bind(this, function(img)
- {
- if (text.substring(0, 5) == 'data:')
- {
- this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
- {
- graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
- w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
- 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
- }), resizeImages, this.maxImageSize);
- }
- else
- {
- var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
- var w = Math.round(img.width * s);
- var h = Math.round(img.height * s);
-
- graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
- w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
- 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
- }
- }), mxUtils.bind(this, function()
- {
- var cell = null;
-
- // Inserts invalid data URIs as text
- graph.getModel().beginUpdate();
- try
- {
- cell = graph.insertVertex(graph.getDefaultParent(), null, text,
- graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
- graph.updateCellSize(cell);
- graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
- }
- finally
- {
- graph.getModel().endUpdate();
- }
-
- graph.setSelectionCell(cell);
- }));
-
- return [];
- }
- else
- {
- text = Graph.zapGremlins(mxUtils.trim(text));
-
- if (this.isCompatibleString(text))
- {
- return this.importXml(text, dx, dy, crop, null, addNewPage);
- }
- else if (text.length > 0)
- {
- if (this.isLucidChartData(text))
- {
- this.convertLucidChart(text, mxUtils.bind(this, function(xml)
- {
- this.editor.graph.setSelectionCells(
- this.importXml(xml, dx, dy, crop,
- null, addNewPage));
- }), mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- }));
- }
- else
- {
- var graph = this.editor.graph;
- var cell = null;
-
- graph.getModel().beginUpdate();
- try
- {
- // Fires cellsInserted to apply the current style to the inserted text.
- // This requires the value to be empty when the event is fired.
- cell = graph.insertVertex(graph.getDefaultParent(), null, '',
- graph.snap(dx), graph.snap(dy), 1, 1, 'text;whiteSpace=wrap;' + ((html) ? 'html=1;' : ''));
- graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
-
- // Single tag is converted
- if (text.charAt(0) == '<' && text.indexOf('>') == text.length - 1)
- {
- text = mxUtils.htmlEntities(text);
- }
- //TODO Refuse unsupported file types early as at this stage a lot of processing has beed done and time is wasted.
- // For example, 5 MB PDF files is processed and then only 0.5 MB of meaningless text is added!
- //Limit labels to maxTextBytes
- if (text.length > this.maxTextBytes)
- {
- text = text.substring(0, this.maxTextBytes) + '...';
- }
-
- // Apply value and updates the cell size to fit the text block
- cell.value = text;
- graph.updateCellSize(cell);
-
- // Adds wrapping for large text blocks
- if (this.maxTextWidth > 0 && cell.geometry.width > this.maxTextWidth)
- {
- var size = graph.getPreferredSizeForCell(cell, this.maxTextWidth);
- cell.geometry.width = size.width;
- cell.geometry.height = size.height;
- }
-
- // See https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url
- if (Graph.isLink(cell.value))
- {
- graph.setLinkForCell(cell, cell.value);
- }
-
- // Adds spacing
- cell.geometry.width += graph.gridSize;
- cell.geometry.height += graph.gridSize;
- }
- finally
- {
- graph.getModel().endUpdate();
- }
-
- return [cell];
- }
- }
- }
- }
-
- return [];
- };
- /**
- * Formats the given file size.
- */
- EditorUi.prototype.formatFileSize = function(size)
- {
- var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
- var i = -1;
-
- do
- {
- size = size / 1024;
- i++;
- } while (size > 1024);
- return Math.max(size, 0.1).toFixed(1) + units[i];
- };
- /**
- * Imports the given XML into the existing diagram.
- */
- EditorUi.prototype.convertDataUri = function(uri)
- {
- // Handles special case of data URI which needs to be rewritten
- // to be used in a cell style to remove the semicolon
- if (uri.substring(0, 5) == 'data:')
- {
- var semi = uri.indexOf(';');
-
- if (semi > 0)
- {
- uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
- }
- }
-
- return uri;
- };
-
- /**
- * Returns true for Gliffy data.
- */
- EditorUi.prototype.isRemoteFileFormat = function(data, filename)
- {
- return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
- };
-
- /**
- * Returns true for Gliffy
- */
- EditorUi.prototype.isLucidChartData = function(data)
- {
- return data != null && (data.substring(0, 26) ==
- '{"state":"{\\"Properties\\":' ||
- data.substring(0, 14) == '{"Properties":');
- };
- /**
- * Imports a local file from the device or local storage.
- */
- EditorUi.prototype.importLocalFile = function(device, noSplash)
- {
- if (device && Graph.fileSupport)
- {
- if (this.importFileInputElt == null)
- {
- var input = document.createElement('input');
- input.setAttribute('type', 'file');
-
- mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
- {
- if (input.files != null)
- {
- // Using null for position will disable crop of input file
- this.importFiles(input.files, null, null, this.maxImageSize);
-
- // Resets input to force change event for same file (type reset required for IE)
- input.type = '';
- input.type = 'file';
- input.value = '';
- }
- }));
-
- input.style.display = 'none';
- document.body.appendChild(input);
- this.importFileInputElt = input;
- }
-
- this.importFileInputElt.click();
- }
- else
- {
- window.openNew = false;
- window.openKey = 'import';
-
- window.listBrowserFiles = mxUtils.bind(this, function(success, error)
- {
- StorageFile.listFiles(this, 'F', success, error);
- });
-
- window.openBrowserFile = mxUtils.bind(this, function(title, success, error)
- {
- StorageFile.getFileContent(this, title, success, error);
- });
-
- window.deleteBrowserFile = mxUtils.bind(this, function(title, success, error)
- {
- StorageFile.deleteFile(this, title, success, error);
- });
- if (!noSplash)
- {
- var prevValue = Editor.useLocalStorage;
- Editor.useLocalStorage = !device;
- }
- // Closes dialog after open
- window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
- {
- this.hideDialog(cancel);
- }));
-
- window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
- {
- if (filename != null && Graph.fileSupport && /(\.v(dx|sdx?))($|\?)/i.test(filename))
- {
- // "Not a UTF 8 file" when opening VSDX in IE so this is never called
- var file = new Blob([xml], {type: 'application/octet-stream'})
-
- this.importVisio(file, mxUtils.bind(this, function(xml)
- {
- this.importXml(xml, 0, 0, true);
- }), null, filename);
- }
- else
- {
- this.editor.graph.setSelectionCells(this.importXml(xml, 0, 0, true));
- }
- }));
- // Removes openFile if dialog is closed
- this.showDialog(new OpenDialog(this).container, (Editor.useLocalStorage) ? 640 : 360,
- (Editor.useLocalStorage) ? 480 : 220, true, true, function()
- {
- window.openFile = null;
- });
-
- // Extends dialog close to show splash screen
- if (!noSplash)
- {
- var dlg = this.dialog;
- var dlgClose = dlg.close;
-
- this.dialog.close = mxUtils.bind(this, function(cancel)
- {
- Editor.useLocalStorage = prevValue;
- dlgClose.apply(dlg, arguments);
-
- if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
- {
- this.showSplash();
- }
- });
- }
- }
- };
- /**
- * Imports the given zip file.
- */
- EditorUi.prototype.importZipFile = function(file, success, onerror)
- {
- var ui = this;
-
- var delayed = mxUtils.bind(this, function()
- {
- this.loadingExtensions = false;
-
- if (typeof JSZip !== 'undefined')
- {
- JSZip.loadAsync(file)
- .then(function(zip)
- {
- if (Object.keys(zip.files).length == 0)
- {
- onerror();
- }
- else
- {
- var gliffyLatestVer = {version: 0};
- var drawioFound = false;
-
- zip.forEach(function (relativePath, zipEntry)
- {
- var name = zipEntry.name.toLowerCase();
-
- if (name == 'diagram/diagram.xml') //draw.io zip format has the latest diagram version at diagram/diagram.xml
- {
- drawioFound = true;
-
- zipEntry.async("string").then(function(str){
- if (str.indexOf('<mxfile ') == 0)
- {
- success(str);
- }
- else
- {
- onerror();
- }
- });
- }
- else if (name.indexOf('versions/') == 0) //Gliffy zip format has the versions inside versions folder
- {
- var version = parseInt(name.substr(9)); //9 is the length of versions/
-
- if (version > gliffyLatestVer.version)
- {
- gliffyLatestVer = {version: version, zipEntry: zipEntry}
- }
- }
- });
-
- if (gliffyLatestVer.version > 0)
- {
- gliffyLatestVer.zipEntry.async("string").then(function(data)
- {
- if (!ui.isOffline() && new XMLHttpRequest().upload && ui.isRemoteFileFormat(data, file.name))
- {
- ui.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4)
- {
- if (xhr.status >= 200 && xhr.status <= 299)
- {
- success(xhr.responseText);
- }
- else
- {
- onerror();
- }
- }
- }), file.name);
- }
- else
- {
- onerror();
- }
- });
- }
- else if (!drawioFound)
- {
- onerror();
- }
- }
- }, function (e) {
- onerror(e);
- });
- }
- else
- {
- onerror();
- }
- });
-
- if (typeof JSZip === 'undefined' && !this.loadingExtensions && !this.isOffline(true))
- {
- this.loadingExtensions = true;
- mxscript('js/extensions.min.js', delayed);
- }
- else
- {
- delayed();
- }
- };
-
- /**
- * Imports the given XML into the existing diagram.
- */
- EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename,
- done, file, crop, ignoreEmbeddedXml, evt)
- {
- crop = (crop != null) ? crop : true;
- var async = false;
- var cells = null;
- var handleResult = mxUtils.bind(this, function(xml)
- {
- var importedCells = null;
-
- if (xml != null && xml.substring(0, 10) == '<mxlibrary')
- {
- this.loadLibrary(new LocalLibrary(this, xml, filename));
- }
- else
- {
- importedCells = this.importXml(xml, dx, dy, crop, null,
- (evt != null) ? mxEvent.isControlDown(evt) : null);
- }
-
- if (done != null)
- {
- done(importedCells);
- }
- });
-
- if (mimeType.substring(0, 5) == 'image')
- {
- var containsModel = false;
- if (mimeType.substring(0, 9) == 'image/png')
- {
- var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
-
- if (xml != null && xml.length > 0)
- {
- cells = this.importXml(xml, dx, dy, crop, null, (evt != null) ?
- mxEvent.isControlDown(evt) : null);
- containsModel = true;
- }
- }
-
- if (!containsModel)
- {
- var graph = this.editor.graph;
-
- // Strips encoding bit (eg. ;base64,) for cell style
- var semi = data.indexOf(';');
-
- if (semi > 0)
- {
- data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
- }
-
- if (crop && graph.isGridEnabled())
- {
- dx = graph.snap(dx);
- dy = graph.snap(dy);
- }
- cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
- 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
- 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
- }
- }
- else if (/(\.*<graphml )/.test(data))
- {
- async = true;
- this.importGraphML(data, handleResult);
- }
- else if (file != null && filename != null && ((/(\.v(dx|sdx?))($|\?)/i.test(filename)) || /(\.vs(x|sx?))($|\?)/i.test(filename)))
- {
- // LATER: done and async are a hack before making this asynchronous
- async = true;
- this.importVisio(file, handleResult);
- }
- else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
- {
- // LATER: done and async are a hack before making this asynchronous
- async = true;
- // Returns empty cells array as it is aysynchronous
- this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4)
- {
- if (xhr.status >= 200 && xhr.status <= 299)
- {
- handleResult(xhr.responseText);
- }
- else if (done != null)
- {
- done(null);
- }
- }
- }), filename);
- }
- else if (data.indexOf('PK') == 0 && file != null)
- {
- async = true;
-
- this.importZipFile(file, handleResult, mxUtils.bind(this, function()
- {
- //If importing as a zip file failed, just insert as text
- cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
- done(cells);
- }));
- }
- else if (!/(\.v(sd|dx))($|\?)/i.test(filename) && !/(\.vs(s|x))($|\?)/i.test(filename))
- {
- cells = this.insertTextAt(this.validateFileData(data), dx, dy, true,
- null, crop, null, (evt != null) ? mxEvent.isControlDown(evt) : null);
- }
-
- if (!async && done != null)
- {
- done(cells);
- }
-
- return cells;
- };
- /**
- *
- */
- EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn,
- resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml, evt)
- {
- maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
- maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
-
- var crop = x != null && y != null;
- var resizeImages = true;
- x = (x != null) ? x : 0;
- y = (y != null) ? y : 0;
-
- // Checks if large images are imported
- var largeImages = false;
-
- if (!mxClient.IS_CHROMEAPP && files != null)
- {
- var thresh = resampleThreshold || this.resampleThreshold;
-
- for (var i = 0; i < files.length; i++)
- {
- if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
- {
- largeImages = true;
-
- break;
- }
- }
- }
- var doImportFiles = mxUtils.bind(this, function()
- {
- var graph = this.editor.graph;
- var gs = graph.gridSize;
-
- fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
- {
- try
- {
- if (data != null && data.substring(0, 10) == '<mxlibrary')
- {
- this.spinner.stop();
- this.loadLibrary(new LocalLibrary(this, data, filename));
-
- return null;
- }
- else
- {
- return this.importFile(data, mimeType, x, y, w, h, filename,
- done, file, crop, ignoreEmbeddedXml, evt);
- }
- }
- catch (e)
- {
- this.handleError(e);
-
- return null;
- }
- });
-
- resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
- {
- graph.setSelectionCells(cells);
- });
-
- if (this.spinner.spin(document.body, mxResources.get('loading')))
- {
- var count = files.length;
- var remain = count;
- var queue = [];
-
- // Barrier waits for all files to be loaded asynchronously
- var barrier = mxUtils.bind(this, function(index, fnc)
- {
- queue[index] = fnc;
-
- if (--remain == 0)
- {
- this.spinner.stop();
-
- if (barrierFn != null)
- {
- barrierFn(queue);
- }
- else
- {
- var cells = [];
-
- graph.getModel().beginUpdate();
- try
- {
- for (var j = 0; j < queue.length; j++)
- {
- var tmp = queue[j]();
-
- if (tmp != null)
- {
- cells = cells.concat(tmp);
- }
- }
- }
- finally
- {
- graph.getModel().endUpdate();
- }
- }
-
- resultFn(cells);
- }
- });
-
- for (var i = 0; i < count; i++)
- {
- (mxUtils.bind(this, function(index)
- {
- var file = files[index];
-
- if (file != null)
- {
- var reader = new FileReader();
-
- reader.onload = mxUtils.bind(this, function(e)
- {
- if (filterFn == null || filterFn(file))
- {
- if (file.type.substring(0, 6) == 'image/')
- {
- if (file.type.substring(0, 9) == 'image/svg')
- {
- // Checks if SVG contains content attribute
- var data = Graph.clipSvgDataUri(e.target.result);
- var comma = data.indexOf(',');
- var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
- var root = mxUtils.parseXml(svgText);
- var svgs = root.getElementsByTagName('svg');
-
- if (svgs.length > 0)
- {
- var svgRoot = svgs[0];
- var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
-
- if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
- {
- cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
- }
-
- if (cont != null && cont.charAt(0) == '%')
- {
- cont = decodeURIComponent(cont);
- }
-
- if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
- cont.substring(0, 14) === '<mxGraphModel '))
- {
- barrier(index, mxUtils.bind(this, function()
- {
- return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
- }));
- }
- else
- {
- // SVG needs special handling to add viewbox if missing and
- // find initial size from SVG attributes (only for IE11)
- barrier(index, mxUtils.bind(this, function()
- {
- try
- {
- var prefix = data.substring(0, comma + 1);
-
- // Parses SVG and find width and height
- if (root != null)
- {
- var svgs = root.getElementsByTagName('svg');
-
- if (svgs.length > 0)
- {
- var svgRoot = svgs[0];
- var w = svgRoot.getAttribute('width');
- var h = svgRoot.getAttribute('height');
-
- if (w != null && w.charAt(w.length - 1) != '%')
- {
- w = parseFloat(w);
- }
- else
- {
- w = NaN;
- }
-
- if (h != null && h.charAt(h.length - 1) != '%')
- {
- h = parseFloat(h);
- }
- else
- {
- h = NaN;
- }
-
- // Check if viewBox attribute already exists
- var vb = svgRoot.getAttribute('viewBox');
-
- if (vb == null || vb.length == 0)
- {
- svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
- }
- // Uses width and height from viewbox for
- // missing width and height attributes
- else if (isNaN(w) || isNaN(h))
- {
- var tokens = vb.split(' ');
-
- if (tokens.length > 3)
- {
- w = parseFloat(tokens[2]);
- h = parseFloat(tokens[3]);
- }
- }
-
- data = Editor.createSvgDataUri(mxUtils.getXml(svgRoot));
- var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
- var cells = fn(data, file.type, x + index * gs, y + index * gs, Math.max(
- 1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
-
- // Hack to fix width and height asynchronously
- if (isNaN(w) || isNaN(h))
- {
- var img = new Image();
-
- img.onload = mxUtils.bind(this, function()
- {
- w = Math.max(1, img.width);
- h = Math.max(1, img.height);
-
- cells[0].geometry.width = w;
- cells[0].geometry.height = h;
-
- svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
- data = Editor.createSvgDataUri(mxUtils.getXml(svgRoot));
-
- var semi = data.indexOf(';');
-
- if (semi > 0)
- {
- data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
- }
-
- graph.setCellStyles('image', data, [cells[0]]);
- });
-
- img.src = Editor.createSvgDataUri(mxUtils.getXml(svgRoot));
- }
-
- return cells;
- }
- }
- }
- catch (e)
- {
- // ignores any SVG parsing errors
- }
-
- return null;
- }));
- }
- }
- else
- {
- barrier(index, mxUtils.bind(this, function()
- {
- return null;
- }));
- }
- }
- else
- {
- // Checks if PNG+XML is available to bypass code below
- var containsModel = false;
-
- if (file.type == 'image/png')
- {
- var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
-
- if (xml != null && xml.length > 0)
- {
- var img = new Image();
- img.src = e.target.result;
-
- barrier(index, mxUtils.bind(this, function()
- {
- return fn(xml, 'text/xml', x + index * gs, y + index * gs,
- img.width, img.height, file.name);
- }));
-
- containsModel = true;
- }
- }
-
- // Additional asynchronous step for finding image size
- if (!containsModel)
- {
- // Cannot load local files in Chrome App
- if (mxClient.IS_CHROMEAPP)
- {
- this.spinner.stop();
- this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
- mxResources.get('cancel'), mxUtils.bind(this, function()
- {
- // Hides the dialog
- }), null, mxResources.get('ok'), mxUtils.bind(this, function()
- {
- // Redirects to import function
- this.actions.get('import').funct();
- })
- );
- }
- else
- {
- this.loadImage(e.target.result, mxUtils.bind(this, function(img)
- {
- this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
- {
- barrier(index, mxUtils.bind(this, function()
- {
- // Refuses to insert images above a certain size as they kill the app
- if (data2 != null && data2.length < maxBytes)
- {
- var s = (!resizeImages || !this.isResampleImageSize(file.size, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
-
- return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
- }
- else
- {
- this.handleError({message: mxResources.get('imageTooBig')});
-
- return null;
- }
- }));
- }), resizeImages, maxSize, resampleThreshold, file.size);
- }), mxUtils.bind(this, function()
- {
- this.handleError({message: mxResources.get('invalidOrMissingFile')});
- }));
- }
- }
- }
- }
- else
- {
- var data = e.target.result;
-
- fn(data, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
- {
- barrier(index, function()
- {
- return cells;
- });
- }, file);
- }
- }
- });
-
- // Handles special cases
- if (/(\.v(dx|sdx?))($|\?)/i.test(file.name) || /(\.vs(x|sx?))($|\?)/i.test(file.name))
- {
- fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
- {
- barrier(index, function()
- {
- return cells;
- });
- }, file);
- }
- else if (file.type.substring(0, 5) == 'image' || file.type == 'application/pdf')
- {
- reader.readAsDataURL(file);
- }
- else
- {
- reader.readAsText(file);
- }
- }
- }))(i);
- }
- }
- });
-
- if (largeImages)
- {
- // Workaround for lost files array in async code
- var tmp = [];
-
- for (var i = 0; i < files.length; i++)
- {
- tmp.push(files[i]);
- }
-
- files = tmp;
-
- this.confirmImageResize(function(doResize)
- {
- resizeImages = doResize;
- doImportFiles();
- }, resizeDialog);
- }
- else
- {
- doImportFiles();
- }
- };
- /**
- * Parses the file using XHR2 via the server. File can be a blob or file object.
- * Filename is an optional parameter for blobs (that do not have a filename).
- */
- EditorUi.prototype.confirmImageResize = function(fn, force)
- {
- force = (force != null) ? force : false;
- var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
- var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
-
- var wrapper = function(remember, resize)
- {
- if (remember || force)
- {
- mxSettings.setResizeImages((remember) ? resize : null);
- mxSettings.save();
- }
-
- resume();
- fn(resize);
- };
- if (resizeImages != null && !force)
- {
- wrapper(false, resizeImages);
- }
- else
- {
- this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
- function(remember)
- {
- wrapper(remember, true);
- },
- function(remember)
- {
- wrapper(remember, false);
- }, mxResources.get('resize'), mxResources.get('actualSize'),
- '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
- '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
- isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
- (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
- }
- };
-
- /**
- * Parses the file using XHR2 via the server. File can be a blob or file object.
- * Filename is an optional parameter for blobs (that do not have a filename).
- */
- EditorUi.prototype.parseFile = function(file, fn, filename)
- {
- filename = (filename != null) ? filename : file.name;
-
- var formData = new FormData();
- formData.append('format', 'xml');
- formData.append('upfile', file, filename);
- var xhr = new XMLHttpRequest();
- xhr.open('POST', OPEN_URL);
-
- xhr.onreadystatechange = function()
- {
- fn(xhr);
- };
-
- xhr.send(formData);
-
- try
- {
- EditorUi.logEvent({category: 'GLIFFY-IMPORT-FILE',
- action: 'size_' + file.size});
- }
- catch (e)
- {
- // ignore
- }
- };
-
- /**
- *
- */
- EditorUi.prototype.isResampleImageSize = function(size, thresh)
- {
- thresh = (thresh != null) ? thresh : this.resampleThreshold;
- return size > thresh;
- };
-
- /**
- * Resizes the given image if <maxImageBytes> is not null.
- */
- EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh, fileSize)
- {
- maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
- var w = Math.max(1, img.width);
- var h = Math.max(1, img.height);
-
- if (enabled && this.isResampleImageSize((fileSize != null) ? fileSize : data.length, thresh))
- {
- try
- {
- var factor = Math.max(w / maxSize, h / maxSize);
-
- if (factor > 1)
- {
- var w2 = Math.round(w / factor);
- var h2 = Math.round(h / factor);
-
- var canvas = document.createElement('canvas');
- canvas.width = w2;
- canvas.height = h2;
-
- var ctx = canvas.getContext('2d');
- ctx.drawImage(img, 0, 0, w2, h2);
-
- var tmp = canvas.toDataURL();
- // Uses new image if smaller
- if (tmp.length < data.length)
- {
- // Checks if the image is empty by comparing
- // with an empty image of the same size
- var canvas2 = document.createElement('canvas');
- canvas2.width = w2;
- canvas2.height = h2;
- var tmp2 = canvas2.toDataURL();
-
- if (tmp !== tmp2)
- {
- data = tmp;
- w = w2;
- h = h2;
- }
- }
- }
- }
- catch (e)
- {
- // ignores image scaling errors
- }
- }
- fn(data, w, h);
- };
-
- /**
- * Extracts the XML from the compressed or non-compressed text chunk.
- */
- EditorUi.prototype.extractGraphModelFromPng = function(data)
- {
- return Editor.extractGraphModelFromPng(data);
- };
- /**
- * Loads the image from the given URI.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.loadImage = function(uri, onload, onerror)
- {
- try
- {
- var img = new Image();
-
- img.onload = function()
- {
- img.width = (img.width > 0) ? img.width : 120;
- img.height = (img.height > 0) ? img.height : 120;
-
- onload(img);
- };
-
- if (onerror != null)
- {
- img.onerror = onerror;
- };
-
- img.src = uri;
- }
- catch (e)
- {
- if (onerror != null)
- {
- onerror(e);
- }
- else
- {
- throw e;
- }
- }
- };
- // Initializes the user interface
- var editorUiInit = EditorUi.prototype.init;
- EditorUi.prototype.init = function()
- {
- mxStencilRegistry.allowEval = mxStencilRegistry.allowEval && !this.isOfflineApp();
-
- // Must be set before UI is created in superclass
- if (typeof window.mxSettings !== 'undefined')
- {
- this.formatWidth = mxSettings.getFormatWidth();
- }
-
- var ui = this;
- var graph = this.editor.graph;
-
- if (Editor.isDarkMode())
- {
- graph.view.defaultGridColor = mxGraphView.prototype.defaultDarkGridColor;
- }
-
- // Starts editing PlantUML data
- graph.cellEditor.editPlantUmlData = function(cell, trigger, data)
- {
- var obj = JSON.parse(data);
-
- var dlg = new TextareaDialog(ui, mxResources.get('plantUml') + ':',
- obj.data, function(text)
- {
- if (text != null)
- {
- if (ui.spinner.spin(document.body, mxResources.get('inserting')))
- {
- ui.generatePlantUmlImage(text, obj.format, function(data, w, h)
- {
- ui.spinner.stop();
- graph.getModel().beginUpdate();
- try
- {
- if (obj.format == 'txt')
- {
- graph.labelChanged(cell, '<pre>' + data + '</pre>');
- graph.updateCellSize(cell, true);
- }
- else
- {
- graph.setCellStyles('image', ui.convertDataUri(data), [cell]);
- var geo = graph.model.getGeometry(cell);
-
- if (geo != null)
- {
- geo = geo.clone();
- geo.width = w;
- geo.height = h;
- graph.cellsResized([cell], [geo], false);
- }
- }
-
- graph.setAttributeForCell(cell, 'plantUmlData',
- JSON.stringify({data: text, format: obj.format}));
- }
- finally
- {
- graph.getModel().endUpdate();
- }
- }, function(e)
- {
- ui.handleError(e);
- });
- }
- }
- }, null, null, 400, 220);
- ui.showDialog(dlg.container, 420, 300, true, true);
- dlg.init();
- };
-
- // Starts editing Mermaid data
- graph.cellEditor.editMermaidData = function(cell, trigger, data)
- {
- var obj = JSON.parse(data);
-
- var dlg = new TextareaDialog(ui, mxResources.get('mermaid') + ':',
- obj.data, function(text)
- {
- if (text != null)
- {
- if (ui.spinner.spin(document.body, mxResources.get('inserting')))
- {
- ui.generateMermaidImage(text, obj.config, function(data, w, h)
- {
- ui.spinner.stop();
- graph.getModel().beginUpdate();
- try
- {
- graph.setCellStyles('image', data, [cell]);
- var geo = graph.model.getGeometry(cell);
-
- if (geo != null)
- {
- geo = geo.clone();
- geo.width = Math.max(geo.width, w);
- geo.height = Math.max(geo.height, h);
- graph.cellsResized([cell], [geo], false);
- }
-
- graph.setAttributeForCell(cell, 'mermaidData',
- JSON.stringify({data: text, config:
- obj.config}, null, 2));
- }
- finally
- {
- graph.getModel().endUpdate();
- }
- }, function(e)
- {
- ui.handleError(e);
- });
- }
- }
- }, null, null, 400, 220);
- ui.showDialog(dlg.container, 420, 300, true, true);
- dlg.init();
- };
-
- // Overrides function to add editing for Plant UML.
- var cellEditorStartEditing = graph.cellEditor.startEditing;
- graph.cellEditor.startEditing = function(cell, trigger)
- {
- try
- {
- var data = this.graph.getAttributeForCell(cell, 'plantUmlData');
-
- if (data != null)
- {
- this.editPlantUmlData(cell, trigger, data);
- }
- else
- {
- data = this.graph.getAttributeForCell(cell, 'mermaidData');
-
- if (data != null)
- {
- this.editMermaidData(cell, trigger, data);
- }
- else
- {
- var style = graph.getCellStyle(cell);
-
- if (mxUtils.getValue(style, 'metaEdit', '0') == '1')
- {
- ui.showDataDialog(cell);
- }
- else
- {
- cellEditorStartEditing.apply(this, arguments);
- }
- }
- }
- }
- catch (e)
- {
- ui.handleError(e);
- }
- };
- // Redirects custom link title via UI for page links
- graph.getLinkTitle = function(href)
- {
- return ui.getLinkTitle(href);
- };
-
- // Redirects custom link via UI for page link handling
- graph.customLinkClicked = function(link)
- {
- var done = false;
-
- try
- {
- ui.handleCustomLink(link);
- done = true;
- }
- catch (e)
- {
- ui.handleError(e);
- }
-
- return done;
- };
- // Extends clear default style to clear persisted settings
- var clearDefaultStyle = this.clearDefaultStyle;
-
- this.clearDefaultStyle = function()
- {
- clearDefaultStyle.apply(this, arguments);
- };
-
- // Sets help link for placeholders
- if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
- {
- EditDataDialog.placeholderHelpLink = 'https://www.diagrams.net/doc/faq/predefined-placeholders';
- }
-
- if (/viewer\.diagrams\.net$/.test(window.location.hostname) ||
- /embed\.diagrams\.net$/.test(window.location.hostname))
- {
- this.editor.editBlankUrl = 'https://app.diagrams.net/';
- }
-
- // Passes dev mode to new window
- var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
-
- this.editor.getEditBlankUrl = function(params)
- {
- params = (params != null) ? params : '';
- if (urlParams['dev'] == '1')
- {
- params += ((params.length > 0) ? '&' : '?') + 'dev=1';
- }
-
- return editorGetEditBlankUrl.apply(this, arguments);
- };
- // For chromeless mode and lightbox mode in viewer
- // Must be overridden before supercall to be applied
- // in case of chromeless initialization
- var graphAddClickHandler = graph.addClickHandler;
- graph.addClickHandler = function(highlight, beforeClick, onClick)
- {
- var tmp = beforeClick;
- beforeClick = function(evt, href)
- {
- if (href == null)
- {
- var source = mxEvent.getSource(evt);
-
- if (source.nodeName.toLowerCase() == 'a')
- {
- href = source.getAttribute('href');
- }
- }
- if (href != null && graph.isCustomLink(href) &&
- (mxEvent.isTouchEvent(evt) ||
- !mxEvent.isPopupTrigger(evt)) &&
- graph.customLinkClicked(href))
- {
- mxEvent.consume(evt);
- }
-
- if (tmp != null)
- {
- tmp(evt, href);
- }
- };
-
- // For some reason, local argument override is not enough in this case...
- graphAddClickHandler.call(this, highlight, beforeClick, onClick);
- };
- editorUiInit.apply(this, arguments);
-
- if (mxClient.IS_SVG)
- {
- // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
- this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
- }
- if (this.menus != null)
- {
- var menusAddPopupMenuEditItems = Menus.prototype.addPopupMenuEditItems;
-
- // Inserts copyAsImage into popup menu
- this.menus.addPopupMenuEditItems = function(menu, cell, evt)
- {
- if (ui.editor.graph.isSelectionEmpty())
- {
- menusAddPopupMenuEditItems.apply(this, arguments);
- }
- else
- {
- ui.menus.addMenuItems(menu, ['delete', '-', 'cut', 'copy',
- 'copyAsImage', '-', 'duplicate'], null, evt);
- }
- };
- }
- // Overrides print dialog size
- ui.actions.get('print').funct = function()
- {
- ui.showDialog(new PrintDialog(ui).container, 360,
- (ui.pages != null && ui.pages.length > 1) ?
- 450 : 370, true, true);
- };
- // Specifies the default filename
- this.defaultFilename = mxResources.get('untitledDiagram');
- // Adds export for %page%, %pagenumber% and %pagecount% placeholders
- var graphGetExportVariables = graph.getExportVariables;
-
- graph.getExportVariables = function()
- {
- var vars = graphGetExportVariables.apply(this, arguments);
- var file = ui.getCurrentFile();
-
- if (file != null)
- {
- vars['filename'] = file.getTitle();
- }
-
- vars['pagecount'] = (ui.pages != null) ? ui.pages.length : 1;
- vars['page'] = (ui.currentPage != null) ? ui.currentPage.getName() : '';
- vars['pagenumber'] = (ui.pages != null && ui.currentPage != null) ?
- mxUtils.indexOf(ui.pages, ui.currentPage) + 1 : 1;
-
- return vars;
- };
- // Adds %page%, %pagenumber% and %pagecount% placeholders
- var graphGetGlobalVariable = graph.getGlobalVariable;
-
- graph.getGlobalVariable = function(name)
- {
- var file = ui.getCurrentFile();
-
- if (name == 'filename' && file != null)
- {
- return file.getTitle();
- }
- else if (name == 'page' && ui.currentPage != null)
- {
- return ui.currentPage.getName();
- }
- else if (name == 'pagenumber')
- {
- if (ui.currentPage != null && ui.pages != null)
- {
- return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
- }
- else
- {
- return 1;
- }
- }
- else if (name == 'pagecount')
- {
- return (ui.pages != null) ? ui.pages.length : 1;
- }
-
- return graphGetGlobalVariable.apply(this, arguments);
- };
- var graphLabelLinkClicked = graph.labelLinkClicked;
-
- graph.labelLinkClicked = function(state, elt, evt)
- {
- var href = elt.getAttribute('href');
-
- if (href != null && graph.isCustomLink(href) &&
- (mxEvent.isTouchEvent(evt) ||
- !mxEvent.isPopupTrigger(evt)))
- {
- // Active links are moved to the hint
- if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
- {
- graph.customLinkClicked(href);
-
- // Resets rubberband after click on locked cell
- graph.getRubberband().reset();
- }
-
- mxEvent.consume(evt);
- }
- else
- {
- graphLabelLinkClicked.apply(this, arguments);
- }
- };
- // Overrides editor filename
- this.editor.getOrCreateFilename = function()
- {
- var filename = ui.defaultFilename;
- var file = ui.getCurrentFile();
-
- if (file != null)
- {
- filename = (file.getTitle() != null) ? file.getTitle() : filename;
- }
-
- return filename;
- };
- // Disables print action for standalone apps on iOS
- // because there is no way to close the new window
- // LATER: Use iframe for print, disable preview
- var printAction = this.actions.get('print');
- printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
- printAction.visible = printAction.isEnabled();
-
- // Installs additional keyboard shortcuts for editor
- if (!this.editor.chromeless || this.editor.editable)
- {
- // Defines additional hotkeys
- this.keyHandler.bindAction(70, true, 'findReplace'); // Ctrl+F
- this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
- this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
- this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
- this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
- this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
- this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
- this.altShiftActions[83] = 'synchronize'; // Alt+Shift+S
- this.installImagePasteHandler();
- this.installNativeClipboardHandler();
- };
- // Creates the spinner
- this.spinner = this.createSpinner(null, null, 24);
-
- // Installs drag and drop handler for rich text editor
- if (Graph.fileSupport)
- {
- graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
- {
- // Setup the dnd listeners
- var textElt = graph.cellEditor.text2;
- var dropElt = null;
-
- if (textElt != null)
- {
- mxEvent.addListener(textElt, 'dragleave', function(evt)
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- });
-
- mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
- {
- // IE 10 does not implement pointer-events so it can't have a drop highlight
- if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
- {
- dropElt = this.highlightElement(textElt);
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- }));
-
- mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
- if (evt.dataTransfer.files.length > 0)
- {
- this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
- {
- // Inserts image into current text box
- graph.insertImage(data, w, h);
- }, function()
- {
- // No post processing
- }, function(file)
- {
- // Handles only images
- return file.type.substring(0, 6) == 'image/';
- }, function(queue)
- {
- // Invokes elements of queue in order
- for (var i = 0; i < queue.length; i++)
- {
- queue[i]();
- }
- }, mxEvent.isControlDown(evt));
- }
- else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
- {
- var uri = evt.dataTransfer.getData('text/uri-list');
-
- if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
- {
- this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
- {
- var w = Math.max(1, img.width);
- var h = Math.max(1, img.height);
- var maxSize = this.maxImageSize;
- var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
- graph.insertImage(decodeURIComponent(uri), w * s, h * s);
- }));
- }
- else
- {
- document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
- }
- }
- else
- {
- if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
- {
- document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
- }
- else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
- {
- document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
- }
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- }));
- }
- }));
- }
-
- // Adding mxRuler to editor
- if (typeof window.mxSettings !== 'undefined')
- {
- var view = this.editor.graph.view;
- view.setUnit(mxSettings.getUnit());
-
- view.addListener('unitChanged', function(sender, evt)
- {
- mxSettings.setUnit(evt.getProperty('unit'));
- mxSettings.save();
- });
- var showRuler = this.canvasSupported && document.documentMode != 9 &&
- (urlParams['ruler'] == '1' || mxSettings.isRulerOn()) &&
- (!this.editor.isChromelessView() || this.editor.editable);
-
- this.ruler = (showRuler) ? new mxDualRuler(this, view.unit) : null;
- this.refresh();
- }
-
- // Adds an element to edit the style in the footer in test mode
- if (urlParams['styledev'] == '1')
- {
- var footer = document.getElementById('geFooter');
- if (footer != null)
- {
- this.styleInput = document.createElement('input');
- this.styleInput.setAttribute('type', 'text');
- this.styleInput.style.position = 'absolute';
- this.styleInput.style.top = '14px';
- this.styleInput.style.left = '2px';
- // Workaround for ignore right CSS property in FF
- this.styleInput.style.width = '98%';
- this.styleInput.style.visibility = 'hidden';
- this.styleInput.style.opacity = '0.9';
- mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
- {
- this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
- }));
- footer.appendChild(this.styleInput);
- this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
- {
- if (this.editor.graph.getSelectionCount() > 0)
- {
- var cell = this.editor.graph.getSelectionCell();
- var style = this.editor.graph.getModel().getStyle(cell);
- this.styleInput.value = style || '';
- this.styleInput.style.visibility = 'visible';
- }
- else
- {
- this.styleInput.style.visibility = 'hidden';
- }
- }));
- }
- var isSelectionAllowed = this.isSelectionAllowed;
- this.isSelectionAllowed = function(evt)
- {
- if (mxEvent.getSource(evt) == this.styleInput)
- {
- return true;
- }
- return isSelectionAllowed.apply(this, arguments);
- };
- }
- // Removes info text in page
- var info = document.getElementById('geInfo');
- if (info != null)
- {
- info.parentNode.removeChild(info);
- }
- // Installs drag and drop handler for files
- // Enables dropping files
- if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
- {
- // Setup the dnd listeners
- var dropElt = null;
- mxEvent.addListener(graph.container, 'dragleave', function(evt)
- {
- if (graph.isEnabled())
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- }
- });
-
- mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
- {
- // IE 10 does not implement pointer-events so it can't have a drop highlight
- if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
- {
- dropElt = this.highlightElement(graph.container);
- }
-
- if (this.sidebar != null)
- {
- this.sidebar.hideTooltip();
- }
- evt.stopPropagation();
- evt.preventDefault();
- }));
-
- mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
-
- if (graph.isEnabled())
- {
- var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
- var tr = graph.view.translate;
- var scale = graph.view.scale;
- var x = pt.x / scale - tr.x;
- var y = pt.y / scale - tr.y;
-
- if (evt.dataTransfer.files.length > 0)
- {
- if (mxEvent.isShiftDown(evt))
- {
- this.openFiles(evt.dataTransfer.files, true);
- }
- else
- {
- if (mxEvent.isAltDown(evt))
- {
- x = null;
- y = null;
- }
-
- this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null,
- null, mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt), evt);
- }
- }
- else
- {
- if (mxEvent.isAltDown(evt))
- {
- x = 0;
- y = 0;
- }
-
- var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
- evt.dataTransfer.getData('text/uri-list') : null;
- var data = this.extractGraphModelFromEvent(evt, this.pages != null);
-
- if (data != null)
- {
- graph.setSelectionCells(this.importXml(data, x, y, true));
- }
- else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
- {
- var html = evt.dataTransfer.getData('text/html');
- var div = document.createElement('div');
- div.innerHTML = graph.sanitizeHtml(html);
-
- // The default is based on the extension
- var asImage = null;
-
- // Extracts single image
- var imgs = div.getElementsByTagName('img');
- if (imgs != null && imgs.length == 1)
- {
- html = imgs[0].getAttribute('src');
-
- if (html == null)
- {
- html = imgs[0].getAttribute('srcset');
- }
-
- // Handles special case where the src attribute has no valid extension
- // in which case the text would be inserted as text with a link
- if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
- {
- asImage = true;
- }
- }
- else
- {
- // Extracts single link
- var a = div.getElementsByTagName('a');
- if (a != null && a.length == 1)
- {
- html = a[0].getAttribute('href');
- }
- else
- {
- // Extracts preformatted text
- var pre = div.getElementsByTagName('pre');
-
- if (pre != null && pre.length == 1)
- {
- html = mxUtils.getTextContent(pre[0]);
- }
- }
- }
-
- var resizeImages = true;
-
- var doInsert = mxUtils.bind(this, function()
- {
- graph.setSelectionCells(this.insertTextAt(html, x, y, true,
- asImage, null, resizeImages, mxEvent.isControlDown(evt)));
- });
-
- if (asImage && html != null && html.length > this.resampleThreshold)
- {
- this.confirmImageResize(function(doResize)
- {
- resizeImages = doResize;
- doInsert();
- }, mxEvent.isControlDown(evt));
- }
- else
- {
- doInsert();
- }
- }
- else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
- {
- this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
- {
- var w = Math.max(1, img.width);
- var h = Math.max(1, img.height);
- var maxSize = this.maxImageSize;
- var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
- graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
- 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
- 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
- }), mxUtils.bind(this, function(img)
- {
- graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
- }));
- }
- else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
- {
- graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
- }
- }
- }
- evt.stopPropagation();
- evt.preventDefault();
- }), false);
- }
- graph.enableFlowAnimation = true;
- this.initPages();
- // Embedded mode
- if (urlParams['embed'] == '1')
- {
- this.initializeEmbedMode();
- }
-
- this.installSettings();
- };
-
- /**
- * Installs handler for pasting image from clipboard.
- */
- EditorUi.prototype.installImagePasteHandler = function()
- {
- if (!mxClient.IS_IE)
- {
- var graph = this.editor.graph;
-
- graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
- {
- if (!mxEvent.isConsumed(evt))
- {
- try
- {
- var data = (evt.clipboardData || evt.originalEvent.clipboardData);
- var containsText = false;
-
- // Workaround for asynchronous paste event processing in textInput
- // is to ignore this event if it contains text/html/rtf (see below).
- // NOTE: Image is not pasted into textInput so can't listen there.
- for (var i = 0; i < data.types.length; i++)
- {
- if (data.types[i].substring(0, 5) === 'text/')
- {
- containsText = true;
- break;
- }
- }
-
- if (!containsText)
- {
- var items = data.items;
-
- for (index in items)
- {
- var item = items[index];
-
- if (item.kind === 'file')
- {
- if (graph.isEditing())
- {
- this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
- {
- // Inserts image into current text box
- graph.insertImage(data, w, h);
- }, function()
- {
- // No post processing
- }, function(file)
- {
- // Handles only images
- return file.type.substring(0, 6) == 'image/';
- }, function(queue)
- {
- // Invokes elements of queue in order
- for (var i = 0; i < queue.length; i++)
- {
- queue[i]();
- }
- });
- }
- else
- {
- var pt = this.editor.graph.getInsertPoint();
- this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
- mxEvent.consume(evt);
- }
-
- break;
- }
- }
- }
- }
- catch (e)
- {
- // ignore
- }
- }
- }), false);
- }
- };
-
- /**
- * Installs the native clipboard support.
- */
- EditorUi.prototype.installNativeClipboardHandler = function()
- {
- var graph = this.editor.graph;
- // Focused but invisible textarea during control or meta key events
- // LATER: Disable text rendering to avoid delay while keeping focus
- var textInput = document.createElement('div');
- textInput.setAttribute('autocomplete', 'off');
- textInput.setAttribute('autocorrect', 'off');
- textInput.setAttribute('autocapitalize', 'off');
- textInput.setAttribute('spellcheck', 'false');
- textInput.style.textRendering = 'optimizeSpeed';
- textInput.style.fontFamily = 'monospace';
- textInput.style.wordBreak = 'break-all';
- textInput.style.background = 'transparent';
- textInput.style.color = 'transparent';
- textInput.style.position = 'absolute';
- textInput.style.whiteSpace = 'nowrap';
- textInput.style.overflow = 'hidden';
- textInput.style.display = 'block';
- textInput.style.fontSize = '1';
- textInput.style.zIndex = '-1';
- textInput.style.resize = 'none';
- textInput.style.outline = 'none';
- textInput.style.width = '1px';
- textInput.style.height = '1px';
- mxUtils.setOpacity(textInput, 0);
- textInput.contentEditable = true;
- textInput.innerHTML = ' ';
- var restoreFocus = false;
-
- // Disables built-in cut, copy and paste shortcuts
- this.keyHandler.bindControlKey(88, null);
- this.keyHandler.bindControlKey(67, null);
- this.keyHandler.bindControlKey(86, null);
- // Shows a textare when control/cmd is pressed to handle native clipboard actions
- mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
- {
- // No dialog visible
- var source = mxEvent.getSource(evt);
-
- if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
- this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
- {
- if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
- (mxClient.IS_MAC && (evt.keyCode == 91 || evt.keyCode == 93) /* Left/Right Meta */))
- {
- // Cannot use parentNode for check in IE
- if (!restoreFocus)
- {
- // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
- textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
- textInput.style.top = (graph.container.scrollTop + 10) + 'px';
-
- graph.container.appendChild(textInput);
- restoreFocus = true;
-
- textInput.focus();
- document.execCommand('selectAll', false, null);
- }
- }
- }
- }));
- // Clears input and restores focus and selection
- function clearInput()
- {
- window.setTimeout(function()
- {
- textInput.innerHTML = ' ';
- textInput.focus();
- document.execCommand('selectAll', false, null);
- }, 0);
- };
-
- mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
- {
- // Workaround for asynchronous event read invalid in IE quirks mode
- var keyCode = evt.keyCode;
-
- // Asynchronous workaround for scroll to origin after paste if the
- // Ctrl-key is not pressed for long enough in FF on Windows
- window.setTimeout(mxUtils.bind(this, function()
- {
- if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
- keyCode == 91 /* MetaLeft */ || keyCode == 93 /* MetaRight */))
- {
- restoreFocus = false;
-
- if (!graph.isEditing() && this.dialog == null && graph.container != null)
- {
- graph.container.focus();
- }
-
- textInput.parentNode.removeChild(textInput);
-
- // Workaround for lost cursor in focused element
- if (this.dialog == null)
- {
- mxUtils.clearSelection();
- }
- }
- }), 0);
- }));
-
- mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
- {
- if (graph.isEnabled())
- {
- try
- {
- mxClipboard.copy(graph);
- this.copyCells(textInput);
- clearInput();
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- }));
-
- mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
- {
- if (graph.isEnabled())
- {
- try
- {
- mxClipboard.copy(graph);
- this.copyCells(textInput, true);
- clearInput();
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- }));
-
- mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
- {
- if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
- {
- textInput.innerHTML = ' ';
- textInput.focus();
-
- if (evt.clipboardData != null)
- {
- this.pasteCells(evt, textInput, true, true);
- }
- if (!mxEvent.isConsumed(evt))
- {
- window.setTimeout(mxUtils.bind(this, function()
- {
- this.pasteCells(evt, textInput, false, true);
- }), 0);
- }
- }
- }), true);
-
- // Needed for IE11
- var isSelectionAllowed2 = this.isSelectionAllowed;
- this.isSelectionAllowed = function(evt)
- {
- if (mxEvent.getSource(evt) == textInput)
- {
- return true;
- }
- return isSelectionAllowed2.apply(this, arguments);
- };
- };
- /**
- *
- */
- EditorUi.prototype.getLinkTitle = function(href)
- {
- var title = Graph.prototype.getLinkTitle.apply(this, arguments);
- if (href.substring(0, 13) == 'data:page/id,')
- {
- var comma = href.indexOf(',');
-
- if (comma > 0)
- {
- var page = this.getPageById(href.substring(comma + 1));
-
- if (page != null)
- {
- title = page.getName();
- }
- else
- {
- title = mxResources.get('pageNotFound');
- }
- }
- }
- else if (href.substring(0, 5) == 'data:')
- {
- title = mxResources.get('action');
- }
-
- return title;
- };
-
- /**
- *
- */
- EditorUi.prototype.handleCustomLink = function(href)
- {
- if (href.substring(0, 13) == 'data:page/id,')
- {
- var comma = href.indexOf(',');
- var page = this.getPageById(href.substring(comma + 1));
-
- if (page)
- {
- this.selectPage(page)
- }
- else
- {
- // Needs fallback for missing resource in case of viewer lightbox
- throw new Error(mxResources.get('pageNotFound') || 'Page not found');
- }
- }
- else
- {
- this.editor.graph.handleCustomLink(href);
- }
- };
-
- /**
- *
- */
- EditorUi.prototype.isSettingsEnabled = function()
- {
- return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
- };
- /**
- * Creates the format panel and adds overrides.
- */
- EditorUi.prototype.installSettings = function()
- {
- if (this.isSettingsEnabled())
- {
- // Gets recent colors from settings
- ColorDialog.recentColors = mxSettings.getRecentColors();
- // Avoids overridden values for changes in
- // multiple windows and updates shared values
- if (isLocalStorage)
- {
- try
- {
- window.addEventListener('storage', mxUtils.bind(this, function(evt)
- {
- if (evt.key == mxSettings.key)
- {
- mxSettings.load();
-
- // Updates values
- ColorDialog.recentColors = mxSettings.getRecentColors();
- this.menus.customFonts = mxSettings.getCustomFonts();
- }
- }), false);
- }
- catch (e)
- {
- // ignore
- }
- }
- // Updates UI to reflect current edge style
- this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
-
- /**
- * Persists custom fonts.
- */
- this.menus.customFonts = mxSettings.getCustomFonts();
-
- this.addListener('customFontsChanged', mxUtils.bind(this, function(sender, evt)
- {
- if (urlParams['ext-fonts'] != '1')
- {
- mxSettings.setCustomFonts(this.menus.customFonts);
- }
- else
- {
- var customFonts = evt.getProperty('customFonts');
- this.menus.customFonts = customFonts;
- mxSettings.setCustomFonts(customFonts);
- }
-
- mxSettings.save();
- }));
-
- /**
- * Persists copy on connect switch.
- */
- this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
- this.fireEvent(new mxEventObject('copyConnectChanged'));
-
- this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
- {
- mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
- mxSettings.save();
- }));
-
- /**
- * Persists default page format.
- */
- this.editor.graph.pageFormat = mxSettings.getPageFormat();
-
- this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
- {
- mxSettings.setPageFormat(this.editor.graph.pageFormat);
- mxSettings.save();
- }));
-
- /**
- * Persists default grid color.
- */
- this.editor.graph.view.gridColor = mxSettings.getGridColor(Editor.isDarkMode());
-
- this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
- {
- mxSettings.setGridColor(this.editor.graph.view.gridColor, Editor.isDarkMode());
- mxSettings.save();
- }));
- /**
- * Persists autosave switch in Chrome app.
- */
- if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
- {
- this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
- {
- mxSettings.setAutosave(this.editor.autosave);
- mxSettings.save();
- }));
-
- this.editor.autosave = mxSettings.getAutosave();
- }
-
- if (this.sidebar != null)
- {
- if (urlParams['search-shapes'] != null && this.sidebar.searchShapes != null)
- {
- this.sidebar.searchShapes(decodeURIComponent(urlParams['search-shapes']));
- this.sidebar.showEntries('search');
- }
- else
- {
- this.sidebar.showPalette('search', mxSettings.settings.search);
-
- /**
- * Shows scratchpad if never shown.
- */
- if ((!this.editor.chromeless || this.editor.editable) && (mxSettings.settings.isNew ||
- parseInt(mxSettings.settings.version || 0) <= 8))
- {
- this.toggleScratchpad();
- mxSettings.save();
- }
- }
- }
- // Saves app defaults for UI
- this.addListener('formatWidthChanged', function()
- {
- mxSettings.setFormatWidth(this.formatWidth);
- mxSettings.save();
- });
- }
- };
-
- /**
- * Copies the given cells and XML to the clipboard as an embedded image.
- */
- EditorUi.prototype.copyImage = function(cells, xml, scale)
- {
- try
- {
- if (navigator.clipboard != null && this.spinner.spin(document.body, mxResources.get('exporting')))
- {
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas, svgRoot)
- {
- try
- {
- this.spinner.stop();
-
- // KNOWN: SVG and delayed content currently not supported
- var dataUrl = this.createImageDataUri(canvas, xml, 'png');
- var w = parseInt(svgRoot.getAttribute('width'));
- var h = parseInt(svgRoot.getAttribute('height'));
- this.writeImageToClipboard(dataUrl, w, h, mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- }));
- }
- catch (e)
- {
- this.handleError(e);
- }
- }), null, null, null, mxUtils.bind(this, function(e)
- {
- this.spinner.stop();
- this.handleError(e);
- }), null, null, (scale != null) ? scale : 4,
- this.editor.graph.background == null ||
- this.editor.graph.background == mxConstants.NONE,
- null, null, null, 10, null, null, true, null,
- (cells.length > 0) ? cells : null);
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- };
-
- /**
- * Copies the given cells and XML to the clipboard as an embedded image.
- */
- EditorUi.prototype.writeImageToClipboard = function(dataUrl, w, h, error)
- {
- var blob = this.base64ToBlob(dataUrl.substring(dataUrl.indexOf(',') + 1), 'image/png');
- var html = '<img src="' + dataUrl + '" width="' + w + '" height="' + h + '">';
- var cbi = new ClipboardItem({'image/png': blob,
- 'text/html': new Blob([html], {type: 'text/html'})});
- navigator.clipboard.write([cbi])['catch'](error);
- };
- /**
- * Creates the format panel and adds overrides.
- */
- EditorUi.prototype.copyCells = function(elt, removeCells)
- {
- var graph = this.editor.graph;
-
- if (!graph.isSelectionEmpty())
- {
- // Fixes cross-platform clipboard UTF8 issues by encoding as URI
- var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
- var xml = mxUtils.getXml(graph.encodeCells(cells));
- mxUtils.setTextContent(elt, encodeURIComponent(xml));
- if (removeCells)
- {
- graph.removeCells(cells, false);
- graph.lastPasteXml = null;
- }
- else
- {
- graph.lastPasteXml = xml;
- graph.pasteCounter = 0;
- }
- elt.focus();
- document.execCommand('selectAll', false, null);
- }
- else
- {
- // Disables copy on focused element
- elt.innerHTML = '';
- }
- };
- /**
- * Creates the format panel and adds overrides.
- */
- EditorUi.prototype.copyXml = function()
- {
- var cells = null;
-
- if (Editor.enableNativeCipboard)
- {
- var graph = this.editor.graph;
-
- if (!graph.isSelectionEmpty())
- {
- cells = mxUtils.sortCells(graph.getExportableCells(
- graph.model.getTopmostCells(graph.getSelectionCells())));
- var xml = mxUtils.getXml(graph.encodeCells(cells));
- navigator.clipboard.writeText(xml);
- }
- }
-
- return cells;
- };
-
- /**
- * Creates the format panel and adds overrides.
- */
- EditorUi.prototype.pasteXml = function(xml, pasteAsLabel, compat, evt)
- {
- var graph = this.editor.graph;
- var cells = null;
-
- if (graph.lastPasteXml == xml)
- {
- graph.pasteCounter++;
- }
- else
- {
- graph.lastPasteXml = xml;
- graph.pasteCounter = 0;
- }
-
- var dx = graph.pasteCounter * graph.gridSize;
-
- if (compat || this.isCompatibleString(xml))
- {
- cells = this.importXml(xml, dx, dx);
- graph.setSelectionCells(cells);
- }
- else if (pasteAsLabel && graph.getSelectionCount() == 1)
- {
- var cell = graph.getStartEditingCell(graph.getSelectionCell(), evt);
-
- if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(xml) &&
- graph.getCurrentCellStyle(cell)[mxConstants.STYLE_SHAPE] == 'image')
- {
- graph.setCellStyles(mxConstants.STYLE_IMAGE, xml, [cell]);
- }
- else
- {
- graph.model.beginUpdate();
- try
- {
- graph.labelChanged(cell, xml);
-
- if (Graph.isLink(xml))
- {
- graph.setLinkForCell(cell, xml);
- }
- }
- finally
- {
- graph.model.endUpdate();
- }
- }
-
- graph.setSelectionCell(cell);
- }
- else
- {
- var pt = graph.getInsertPoint();
-
- if (graph.isMouseInsertPoint())
- {
- dx = 0;
-
- // No offset for insert at mouse position
- if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
- {
- graph.pasteCounter--;
- }
- }
-
- cells = this.insertTextAt(xml, pt.x + dx, pt.y + dx, true);
- graph.setSelectionCells(cells);
- }
-
- if (!graph.isSelectionEmpty())
- {
- graph.scrollCellToVisible(graph.getSelectionCell());
-
- if (this.hoverIcons != null)
- {
- this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
- }
- }
-
- return cells;
- };
-
- /**
- * Creates the format panel and adds overrides.
- */
- EditorUi.prototype.pasteCells = function(evt, realElt, useEvent, pasteAsLabel)
- {
- if (!mxEvent.isConsumed(evt))
- {
- var elt = realElt;
- var asHtml = false;
-
- if (useEvent && evt.clipboardData != null && evt.clipboardData.getData)
- {
- // Workaround for paste from IE11 where the page is copied
- // as HTML while the data is only available via text/plain
- var plain = evt.clipboardData.getData('text/plain');
- var override = false;
-
- if (plain != null && plain.length > 0 && plain.substring(0, 18) == '%3CmxGraphModel%3E')
- {
- var tmp = decodeURIComponent(plain);
-
- if (this.isCompatibleString(tmp))
- {
- override = true;
- plain = tmp;
- }
- }
-
- var data = (!override) ? evt.clipboardData.getData('text/html') : null;
-
- if (data != null && data.length > 0)
- {
- elt = this.parseHtmlData(data);
- asHtml = elt.getAttribute('data-type') != 'text/plain';
- }
- else if (plain != null && plain.length > 0)
- {
- elt = document.createElement('div');
- mxUtils.setTextContent(elt, data);
- }
- }
-
- var spans = elt.getElementsByTagName('span');
-
- if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
- 'application/vnd.lucid.chart.objects')
- {
- var content = spans[0].getAttribute('data-lucid-content');
-
- if (content != null && content.length > 0)
- {
- this.convertLucidChart(content, mxUtils.bind(this, function(xml)
- {
- var graph = this.editor.graph;
-
- if (graph.lastPasteXml == xml)
- {
- graph.pasteCounter++;
- }
- else
- {
- graph.lastPasteXml = xml;
- graph.pasteCounter = 0;
- }
-
- var dx = graph.pasteCounter * graph.gridSize;
- graph.setSelectionCells(this.importXml(xml, dx, dx));
- graph.scrollCellToVisible(graph.getSelectionCell());
- }), mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- }));
-
- mxEvent.consume(evt);
- }
- }
- else
- {
- // KNOWN: Paste from IE11 to other browsers on Windows
- // seems to paste the contents of index.html
- var xml = (asHtml) ? elt.innerHTML :
- mxUtils.trim((elt.innerText == null) ?
- mxUtils.getTextContent(elt) : elt.innerText);
- var compat = false;
- // Workaround for junk after XML in VM
- try
- {
- var idx = xml.lastIndexOf('%3E');
-
- if (idx >= 0 && idx < xml.length - 3)
- {
- xml = xml.substring(0, idx + 3);
- }
- }
- catch (e)
- {
- // ignore
- }
-
- // Checks for embedded XML content
- try
- {
- var spans = elt.getElementsByTagName('span');
- var tmp = (spans != null && spans.length > 0) ?
- mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
- decodeURIComponent(xml);
-
- if (this.isCompatibleString(tmp))
- {
- compat = true;
- xml = tmp;
- }
- }
- catch (e)
- {
- // ignore
- }
- try
- {
- if (xml != null && xml.length > 0)
- {
- this.pasteXml(xml, pasteAsLabel, compat, evt);
- try
- {
- mxEvent.consume(evt);
- }
- catch (e)
- {
- // ignore event no longer exists in async handler in IE8-
- }
- }
- else if (!useEvent)
- {
- var graph = this.editor.graph;
-
- graph.lastPasteXml = null;
- graph.pasteCounter = 0;
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- }
- }
-
- realElt.innerHTML = ' ';
- };
- /**
- * Adds a file drop handler for opening local files.
- */
- EditorUi.prototype.addFileDropHandler = function(elts)
- {
- // Installs drag and drop handler for files
- if (Graph.fileSupport)
- {
- var dropElt = null;
-
- for (var i = 0; i < elts.length; i++)
- {
- // Setup the dnd listeners
- mxEvent.addListener(elts[i], 'dragleave', function(evt)
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
-
- evt.stopPropagation();
- evt.preventDefault();
- });
-
- mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
- {
- if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
- {
- // IE 10 does not implement pointer-events so it can't have a drop highlight
- if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
- {
- dropElt = this.highlightElement();
- }
- }
- evt.stopPropagation();
- evt.preventDefault();
- }));
-
- mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
- {
- if (dropElt != null)
- {
- dropElt.parentNode.removeChild(dropElt);
- dropElt = null;
- }
-
- if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
- {
- if (evt.dataTransfer.files.length > 0)
- {
- this.hideDialog();
-
- // Never open files in embed mode
- if (urlParams['embed'] == '1')
- {
- this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
- null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
- }
- else
- {
- this.openFiles(evt.dataTransfer.files, true);
- }
- }
- else
- {
- // Handles open special files via text drag and drop
- var data = this.extractGraphModelFromEvent(evt);
-
- // Tries additional and async parsing of text content such as HTML, Gliffy data
- if (data == null)
- {
- var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
-
- if (provider != null)
- {
- if (document.documentMode == 10 || document.documentMode == 11)
- {
- data = provider.getData('Text');
- }
- else
- {
- var data = null;
-
- if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
- {
- data = evt.dataTransfer.getData('text/uri-list');
- }
- else
- {
- data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
- }
-
- if (data != null && data.length > 0)
- {
- var div = document.createElement('div');
- div.innerHTML = this.editor.graph.sanitizeHtml(data);
-
- // Extracts single image
- var imgs = div.getElementsByTagName('img');
-
- if (imgs.length > 0)
- {
- data = imgs[0].getAttribute('src');
- }
- }
- else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
- {
- data = provider.getData('text/plain');
- }
- }
-
- if (data != null)
- {
- // Checks for embedded XML in PNG
- if (data.substring(0, 22) == 'data:image/png;base64,')
- {
- var xml = this.extractGraphModelFromPng(data);
-
- if (xml != null && xml.length > 0)
- {
- this.openLocalFile(xml, null, true);
- }
- }
- else if (!this.isOffline() && this.isRemoteFileFormat(data))
- {
- new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
- {
- if (req.getStatus() >= 200 && req.getStatus() <= 299)
- {
- this.openLocalFile(req.getText(), null, true);
- }
- }));
- }
- else if (/^https?:\/\//.test(data))
- {
- if (this.getCurrentFile() == null)
- {
- window.location.hash = '#U' + encodeURIComponent(data);
- }
- else
- {
- window.openWindow(((mxClient.IS_CHROMEAPP) ?
- (EditorUi.drawHost + '/') : 'https://' + location.host + '/') +
- window.location.search + '#U' + encodeURIComponent(data));
- }
- }
- }
- }
- }
- else
- {
- this.openLocalFile(data, null, true);
- }
- }
- }
- evt.stopPropagation();
- evt.preventDefault();
- }));
- }
- }
- };
-
- /**
- * Highlights the given element
- */
- EditorUi.prototype.highlightElement = function(elt)
- {
- var x = 0;
- var y = 0;
- var w = 0;
- var h = 0;
-
- if (elt == null)
- {
- var b = document.body;
- var d = document.documentElement;
-
- w = (b.clientWidth || d.clientWidth) - 3;
- h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
- }
- else
- {
- x = elt.offsetTop;
- y = elt.offsetLeft;
- w = elt.clientWidth;
- h = elt.clientHeight;
- }
-
- var hl = document.createElement('div');
- hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
- hl.style.border = '3px dotted rgb(254, 137, 12)';
- hl.style.pointerEvents = 'none';
- hl.style.position = 'absolute';
- hl.style.top = x + 'px';
- hl.style.left = y + 'px';
- hl.style.width = Math.max(0, w - 3) + 'px';
- hl.style.height = Math.max(0, h - 3) + 'px';
-
- if (elt != null && elt.parentNode == this.editor.graph.container)
- {
- this.editor.graph.container.appendChild(hl);
- }
- else
- {
- document.body.appendChild(hl);
- }
-
- return hl;
- };
-
- /**
- * Highlights the given element
- */
- EditorUi.prototype.stringToCells = function(xml)
- {
- var doc = mxUtils.parseXml(xml);
- var node = this.editor.extractGraphModel(doc.documentElement);
- var cells = [];
-
- if (node != null)
- {
- var codec = new mxCodec(node.ownerDocument);
- var model = new mxGraphModel();
- codec.decode(node, model);
-
- var parent = model.getChildAt(model.getRoot(), 0);
-
- for (var j = 0; j < model.getChildCount(parent); j++)
- {
- cells.push(model.getChildAt(parent, j));
- }
- }
-
- return cells;
- };
-
- /**
- * Opens the given files in the editor.
- */
- EditorUi.prototype.openFileHandle = function(data, name, file, temp, fileHandle)
- {
- if (name != null && name.length > 0)
- {
- if (!this.useCanvasForExport && /(\.png)$/i.test(name))
- {
- name = name.substring(0, name.length - 4) + '.drawio';
- }
- else if (/(\.pdf)$/i.test(name))
- {
- name = name.substring(0, name.length - 4) + '.drawio';
- }
-
- var handleResult = mxUtils.bind(this, function(xml)
- {
- var dot = name.lastIndexOf('.');
-
- if (dot >= 0)
- {
- name = name.substring(0, name.lastIndexOf('.')) + '.drawio';
- }
- else
- {
- name = name + '.drawio';
- }
-
- if (xml.substring(0, 10) == '<mxlibrary')
- {
- // Creates new temporary file if library is dropped in splash screen
- if (this.getCurrentFile() == null && urlParams['embed'] != '1')
- {
- this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
- }
-
- try
- {
- this.loadLibrary(new LocalLibrary(this, xml, name));
- }
- catch (e)
- {
- this.handleError(e, mxResources.get('errorLoadingFile'));
- }
- }
- else
- {
- this.openLocalFile(xml, name, temp);
- }
- });
-
- if (/(\.v(dx|sdx?))($|\?)/i.test(name) || /(\.vs(x|sx?))($|\?)/i.test(name))
- {
- this.importVisio(file, mxUtils.bind(this, function(xml)
- {
- this.spinner.stop();
- handleResult(xml);
- }));
- }
- else if (/(\.*<graphml )/.test(data))
- {
- this.importGraphML(data, mxUtils.bind(this, function(xml)
- {
- this.spinner.stop();
- handleResult(xml);
- }));
- }
- else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
- this.isRemoteFileFormat(data, name))
- {
- this.parseFile(file, mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4)
- {
- this.spinner.stop();
-
- if (xhr.status >= 200 && xhr.status <= 299)
- {
- handleResult(xhr.responseText);
- }
- else
- {
- this.handleError({message: mxResources.get((xhr.status == 413) ?
- 'drawingTooLarge' : 'invalidOrMissingFile')},
- mxResources.get('errorLoadingFile'));
- }
- }
- }));
- }
- else if (this.isLucidChartData(data))
- {
- if (/(\.json)$/i.test(name))
- {
- name = name.substring(0, name.length - 5) + '.drawio';
- }
- // LATER: Add import step that produces cells and use callback
- this.convertLucidChart(data, mxUtils.bind(this, function(xml)
- {
- this.spinner.stop();
- this.openLocalFile(xml, name, temp);
- }), mxUtils.bind(this, function(e)
- {
- this.spinner.stop();
- this.handleError(e);
- }));
- }
- else if (data.substring(0, 10) == '<mxlibrary')
- {
- this.spinner.stop();
-
- // Creates new temporary file if library is dropped in splash screen
- if (this.getCurrentFile() == null && urlParams['embed'] != '1')
- {
- this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
- }
-
- try
- {
- this.loadLibrary(new LocalLibrary(this, data, file.name));
- }
- catch (e)
- {
- this.handleError(e, mxResources.get('errorLoadingFile'));
- }
- }
- else if (data.indexOf('PK') == 0)
- {
- this.importZipFile(file, mxUtils.bind(this, function(xml)
- {
- this.spinner.stop();
- handleResult(xml);
- }), mxUtils.bind(this, function()
- {
- this.spinner.stop();
- this.openLocalFile(data, name, temp);
- }));
- }
- else
- {
- if (file.type.substring(0, 9) == 'image/png')
- {
- data = this.extractGraphModelFromPng(data);
- }
- else if (file.type == 'application/pdf')
- {
- var xml = Editor.extractGraphModelFromPdf(data);
-
- if (xml != null)
- {
- fileHandle = null;
- temp = true;
- data = xml;
- }
- }
-
- this.spinner.stop();
- this.openLocalFile(data, name, temp, fileHandle, (fileHandle != null) ? file : null);
- }
- }
- };
-
- /**
- * Opens the given files in the editor.
- */
- EditorUi.prototype.openFiles = function(files, temp)
- {
- if (this.spinner.spin(document.body, mxResources.get('loading')))
- {
- for (var i = 0; i < files.length; i++)
- {
- (mxUtils.bind(this, function(file)
- {
- var reader = new FileReader();
-
- reader.onload = mxUtils.bind(this, function(e)
- {
- try
- {
- this.openFileHandle(e.target.result, file.name, file, temp);
- }
- catch (e)
- {
- this.handleError(e);
- }
- });
-
- reader.onerror = mxUtils.bind(this, function(e)
- {
- this.spinner.stop();
- this.handleError(e);
- window.openFile = null;
- });
-
- if ((file.type.substring(0, 5) === 'image' ||
- file.type === 'application/pdf') &&
- file.type.substring(0, 9) !== 'image/svg')
- {
- reader.readAsDataURL(file);
- }
- else
- {
- reader.readAsText(file);
- }
- }))(files[i]);
- }
- }
- };
- /**
- * Shows the layers dialog if the graph has more than one layer.
- */
- EditorUi.prototype.openLocalFile = function(data, name, temp, fileHandle, desc)
- {
- var currentFile = this.getCurrentFile();
-
- var fn = mxUtils.bind(this, function()
- {
- window.openFile = null;
-
- if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
- {
- var doc = mxUtils.parseXml(data);
-
- if (doc != null)
- {
- this.editor.setGraphXml(doc.documentElement);
- this.editor.graph.selectAll();
- }
- }
- else
- {
- this.fileLoaded(new LocalFile(this, data, name ||
- this.defaultFilename, temp, fileHandle, desc));
- }
- });
- if (data != null && data.length > 0)
- {
- if (currentFile == null || (!currentFile.isModified() &&
- (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || fileHandle != null)))
- {
- fn();
- }
- else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || fileHandle != null) &&
- currentFile != null && currentFile.isModified())
- {
- this.confirm(mxResources.get('allChangesLost'), null, fn,
- mxResources.get('cancel'), mxResources.get('discardChanges'));
- }
- else
- {
- window.openFile = new OpenFile(function()
- {
- window.openFile = null;
- });
-
- window.openFile.setData(data, name);
- window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
- {
- if (currentFile != null && currentFile.isModified())
- {
- this.confirm(mxResources.get('allChangesLost'), null, fn,
- mxResources.get('cancel'), mxResources.get('discardChanges'));
- }
- else
- {
- fn();
- }
- }));
- }
- }
- else
- {
- throw new Error(mxResources.get('notADiagramFile'));
- }
- };
-
- /**
- * Returns a list of all shapes used in the current file.
- */
- EditorUi.prototype.getBasenames = function()
- {
- var basenames = {};
- if (this.pages != null)
- {
- for (var i = 0; i < this.pages.length; i++)
- {
- this.updatePageRoot(this.pages[i]);
- this.addBasenamesForCell(this.pages[i].root, basenames);
- }
- }
- else
- {
- this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
- }
-
- var result = [];
-
- for (var key in basenames)
- {
- result.push(key);
- }
-
- return result;
- };
-
- /**
- * Returns a list of all shapes used in the current file.
- */
- EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
- {
- function addName(name)
- {
- if (name != null)
- {
- // LATER: Check if this case exists
- var dot = name.lastIndexOf('.');
-
- if (dot > 0)
- {
- name = name.substring(dot + 1, name.length);
- }
-
- if (basenames[name] == null)
- {
- basenames[name] = true;
- }
- }
- };
-
- var graph = this.editor.graph;
- var style = graph.getCellStyle(cell);
- var shape = style[mxConstants.STYLE_SHAPE];
- addName(mxStencilRegistry.getBasenameForStencil(shape));
-
- // Adds package names for markers in edges
- if (graph.model.isEdge(cell))
- {
- addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
- addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
- }
- var childCount = graph.model.getChildCount(cell);
-
- for (var i = 0; i < childCount; i++)
- {
- this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
- }
- };
-
- /**
- * Shows the layers dialog if the graph has more than one layer.
- */
- EditorUi.prototype.setGraphEnabled = function(enabled)
- {
- this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
- this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
- this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
- this.sidebarContainer.style.display = (enabled) ? '' : 'none';
- this.hsplit.style.display = (enabled) ? '' : 'none';
- this.editor.graph.setEnabled(enabled);
-
- if (this.ruler != null)
- {
- this.ruler.hRuler.container.style.visibility = (enabled) ? '' : 'hidden';
- this.ruler.vRuler.container.style.visibility = (enabled) ? '' : 'hidden';
- }
-
- if (this.tabContainer != null)
- {
- this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
- }
-
- if (!enabled)
- {
- if (this.actions.outlineWindow != null)
- {
- this.actions.outlineWindow.window.setVisible(false);
- }
- if (this.actions.layersWindow != null)
- {
- this.actions.layersWindow.window.setVisible(false);
- }
- if (this.menus.tagsWindow != null)
- {
- this.menus.tagsWindow.window.setVisible(false);
- }
- if (this.menus.findWindow != null)
- {
- this.menus.findWindow.window.setVisible(false);
- }
- if (this.menus.findReplaceWindow != null)
- {
- this.menus.findReplaceWindow.window.setVisible(false);
- }
- }
- };
-
- /**
- * Shows the layers dialog if the graph has more than one layer.
- */
- EditorUi.prototype.initializeEmbedMode = function()
- {
- this.setGraphEnabled(false);
- var parent = window.opener || window.parent;
- if (parent != window)
- {
- if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
- {
- this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
- {
- this.spinner.stop();
- this.addEmbedButtons();
- this.setGraphEnabled(true);
-
- if (xml == null || xml.length == 0)
- {
- xml = this.emptyDiagramXml;
- }
-
- // Creates temporary file for diff sync in embed mode
- this.setCurrentFile(new EmbedFile(this, xml, {}));
- this.mode = App.MODE_EMBED;
- this.setFileData(xml);
-
- if (!this.editor.isChromelessView())
- {
- this.showLayersDialog();
- }
- else if (this.editor.graph.isLightboxView())
- {
- this.lightboxFit();
- }
-
- if (this.chromelessResize)
- {
- this.chromelessResize();
- }
-
- this.editor.undoManager.clear();
- this.editor.modified = (modified != null) ? modified : false;
- this.updateUi();
-
- // Workaround for no initial focus in FF
- // (does not work in Conf Cloud with FF)
- if (window.self !== window.top)
- {
- window.focus();
- }
-
- if (this.format != null)
- {
- this.format.refresh();
- }
- }));
- }
- }
- };
-
- /**
- * Shows the layers dialog if the graph has more than one layer.
- */
- EditorUi.prototype.showLayersDialog = function()
- {
- if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
- {
- if (this.actions.layersWindow == null)
- {
- this.actions.get('layers').funct();
- }
- else
- {
- this.actions.layersWindow.window.setVisible(true);
- }
- }
- };
- /**
- * Tries to find a public URL for the given file.
- */
- EditorUi.prototype.getPublicUrl = function(file, fn)
- {
- if (file != null)
- {
- file.getPublicUrl(fn);
- }
- else
- {
- fn(null);
- }
- };
- /**
- * Adds the buttons for embedded mode.
- */
- EditorUi.prototype.createLoadMessage = function(eventName)
- {
- var graph = this.editor.graph;
-
- return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
- bounds: graph.getGraphBounds(), currentPage: this.getSelectedPageIndex(),
- scale: graph.view.scale, page: graph.view.getBackgroundPageBounds()};
- };
-
- /**
- * Adds the buttons for embedded mode.
- */
- EditorUi.prototype.installMessageHandler = function(fn)
- {
- var changeListener = null;
- var ignoreChange = false;
- var autosave = false;
- var lastData = null;
-
- var updateStatus = mxUtils.bind(this, function(sender, eventObject)
- {
- if (!this.editor.modified || urlParams['modified'] == '0')
- {
- this.editor.setStatus('');
- }
- else if (urlParams['modified'] != null)
- {
- this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
- }
- });
-
- this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
-
- // Receives XML message from opener and puts it into the graph
- mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
- {
- var validSource = window.opener || window.parent;
-
- if (evt.source != validSource)
- {
- return;
- }
-
- var data = evt.data;
-
- var extractDiagramXml = mxUtils.bind(this, function(data)
- {
- if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
- {
- try
- {
- if (data.substring(0, 22) == 'data:image/png;base64,')
- {
- data = this.extractGraphModelFromPng(data);
- }
- else if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
- {
- data = atob(data.substring(26));
- }
- else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
- {
- data = data.substring(24);
- }
-
- if (data != null)
- {
- if (data.charAt(0) == '%')
- {
- data = decodeURIComponent(data);
- }
- else if (data.charAt(0) != '<')
- {
- data = Graph.decompress(data);
- }
- }
- }
- catch (e)
- {
- // ignore compression errors and use empty data
- }
- }
-
- return data;
- });
- if (urlParams['proto'] == 'json')
- {
- try
- {
- data = JSON.parse(data);
- }
- catch (e)
- {
- data = null;
- }
-
- try
- {
- if (data == null)
- {
- // Ignore
- return;
- }
- else if (data.action == 'dialog')
- {
- this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
- (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
- (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
-
- if (data.modified != null)
- {
- this.editor.modified = data.modified;
- }
-
- return;
- }
- else if (data.action == 'layout')
- {
- this.executeLayoutList(data.layouts)
- return;
- }
- else if (data.action == 'prompt')
- {
- this.spinner.stop();
-
- var dlg = new FilenameDialog(this, data.defaultValue || '',
- (data.okKey != null) ? mxResources.get(data.okKey) : data.ok, function(value)
- {
- if (value != null)
- {
- parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
- }
- else
- {
- parent.postMessage(JSON.stringify({event: 'prompt-cancel', message: data}), '*');
- }
- }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
- this.showDialog(dlg.container, 300, 80, true, false);
- dlg.init();
-
- return;
- }
- else if (data.action == 'draft')
- {
- var tmp = extractDiagramXml(data.xml);
- this.spinner.stop();
-
- var dlg = new DraftDialog(this, mxResources.get('draftFound',
- [data.name || this.defaultFilename]),
- tmp, mxUtils.bind(this, function()
- {
- this.hideDialog();
- parent.postMessage(JSON.stringify({event: 'draft',
- result: 'edit', message: data}), '*');
- }), mxUtils.bind(this, function()
- {
- this.hideDialog();
- parent.postMessage(JSON.stringify({event: 'draft',
- result: 'discard', message: data}), '*');
- }), (data.editKey) ? mxResources.get(data.editKey) : null,
- (data.discardKey) ? mxResources.get(data.discardKey) : null,
- (data.ignore) ? mxUtils.bind(this, function()
- {
- this.hideDialog();
- parent.postMessage(JSON.stringify({event: 'draft',
- result: 'ignore', message: data}), '*');
- }) : null);
- this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
- {
- if (cancel)
- {
- this.actions.get('exit').funct();
- }
- }));
-
- try
- {
- dlg.init();
- }
- catch (e)
- {
- parent.postMessage(JSON.stringify({event: 'draft',
- error: e.toString(), message: data}), '*');
- }
-
- return;
- }
- else if (data.action == 'template')
- {
- this.spinner.stop();
-
- var enableRecentDocs = data.enableRecent == 1;
- var enableSearchDocs = data.enableSearch == 1;
- var enableCustomTemp = data.enableCustomTemp == 1;
-
- var dlg = new NewDialog(this, false, data.templatesOnly? false : data.callback != null,
- mxUtils.bind(this, function(xml, name, url, libs)
- {
- xml = xml || this.emptyDiagramXml;
-
- // LATER: Add autosave option in template message
- if (data.callback != null)
- {
- parent.postMessage(JSON.stringify({event: 'template', xml: xml,
- blank: xml == this.emptyDiagramXml, name: name,
- tempUrl: url, libs: libs, builtIn: true,
- message: data}), '*');
- }
- else
- {
- fn(xml, evt, xml != this.emptyDiagramXml);
-
- // Workaround for status updated before modified applied
- if (!this.editor.modified)
- {
- this.editor.setStatus('');
- }
- }
- }), null, null, null, null, null, null, null,
- enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
- {
- this.remoteInvoke('getRecentDiagrams', null, null, recentReadyCallback, function()
- {
- recentReadyCallback(null, 'Network Error!');
- });
- }) : null,
- enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
- {
- this.remoteInvoke('searchDiagrams', [searchStr], null, searchReadyCallback, function()
- {
- searchReadyCallback(null, 'Network Error!');
- });
- }) : null,
- mxUtils.bind(this, function(url, info, name)
- {
- //If binary files are possible, we can get the file content using remote invokation, imported it, and send final mxFile back
- parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
- name: name}), '*');
- }), null, null,
- enableCustomTemp? mxUtils.bind(this, function(customTempCallback)
- {
- this.remoteInvoke('getCustomTemplates', null, null, customTempCallback, function()
- {
- customTempCallback({}, 0); //ignore error by sending empty templates
- });
- }) : null);
-
- this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
- {
- if (cancel)
- {
- this.actions.get('exit').funct();
- }
- }));
- dlg.init();
-
- return;
- }
- else if (data.action == 'textContent')
- {
- //TODO Remove this message and use remote invokation instead
- var allPagesTxt = this.getDiagramTextContent();
- parent.postMessage(JSON.stringify({event: 'textContent',
- data: allPagesTxt, message: data}), '*');
- return;
- }
- else if (data.action == 'status')
- {
- if (data.messageKey != null)
- {
- this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
- }
- else if (data.message != null)
- {
- this.editor.setStatus(mxUtils.htmlEntities(data.message));
- }
-
- if (data.modified != null)
- {
- this.editor.modified = data.modified;
- }
-
- return;
- }
- else if (data.action == 'spinner')
- {
- var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
-
- if (data.show != null && !data.show)
- {
- this.spinner.stop();
- }
- else
- {
- this.spinner.spin(document.body, msg)
- }
-
- return;
- }
- else if (data.action == 'export')
- {
- if (data.format == 'png' || data.format == 'xmlpng')
- {
- if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
- (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
- {
- var xml = (data.xml != null) ? data.xml : this.getFileData(true);
- this.editor.graph.setEnabled(false);
- var graph = this.editor.graph;
-
- var postDataBack = mxUtils.bind(this, function(uri)
- {
- this.editor.graph.setEnabled(true);
- this.spinner.stop();
-
- var msg = this.createLoadMessage('export');
- msg.format = data.format;
- msg.message = data;
- msg.data = uri;
- msg.xml = xml;
- parent.postMessage(JSON.stringify(msg), '*');
- });
-
- var processUri = mxUtils.bind(this, function(uri)
- {
- if (uri == null)
- {
- uri = Editor.blankImage;
- }
-
- if (data.format == 'xmlpng')
- {
- uri = Editor.writeGraphModelToPng(uri, 'tEXt', 'mxfile',
- encodeURIComponent(xml));
- }
-
- // Removes temporary graph from DOM
- if (graph != this.editor.graph)
- {
- graph.container.parentNode.removeChild(graph.container);
- }
-
- postDataBack(uri);
- });
-
- var pageId = data.pageId || (this.pages != null? ((data.currentPage) ?
- this.currentPage.getId() : this.pages[0].getId()) : null);
-
- if (this.isExportToCanvas())
- {
- // Uses optional XML from incoming message
- if (data.xml != null && data.xml.length > 0)
- {
- ignoreChange = true;
- this.setFileData(xml);
- ignoreChange = false;
- }
- // Exports PNG for first/specific page while other page is visible by creating a graph
- // LATER: Add caching for the graph or SVG while not on first page
- if (this.pages != null && this.currentPage.getId() != pageId)
- {
- var graphGetGlobalVariable = graph.getGlobalVariable;
- graph = this.createTemporaryGraph(graph.getStylesheet());
- var page;
-
- for (var i = 0; i < this.pages.length; i++)
- {
- if (this.pages[i].getId() == pageId)
- {
- page = this.updatePageRoot(this.pages[i]);
- break;
- }
- }
-
- //If pageId info is incorrect
- if (page == null)
- {
- page = this.currentPage;
- }
-
- graph.getGlobalVariable = function(name)
- {
- if (name == 'page')
- {
- return page.getName();
- }
- else if (name == 'pagenumber')
- {
- return 1;
- }
-
- return graphGetGlobalVariable.apply(this, arguments);
- };
-
- document.body.appendChild(graph.container);
- graph.model.setRoot(page.root);
- }
-
- // Set visible layers based on message setting
- if (data.layerIds != null)
- {
- var graphModel = graph.model;
- var layers = graphModel.getChildCells(graphModel.getRoot());
- var layerIdsMap = {};
-
- for (var i = 0; i < data.layerIds.length; i++)
- {
- layerIdsMap[data.layerIds[i]] = true;
- }
-
- for (var i = 0; i < layers.length; i++)
- {
- graphModel.setVisible(layers[i], layerIdsMap[layers[i].id] || false);
- }
- }
- this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
- {
- processUri(canvas.toDataURL('image/png'));
- }), data.width, null, data.background, mxUtils.bind(this, function()
- {
- processUri(null);
- }), null, null, data.scale, data.transparent, data.shadow, null,
- graph, data.border, null, data.grid, data.keepTheme);
- }
- else
- {
- // Data from server is base64 encoded to avoid binary XHR
- // Double encoding for XML arg is needed for UTF8 encoding
- var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
- ((data.format == 'xmlpng') ? '1' : '0') +
- (pageId != null? '&pageId=' + pageId : '') +
- (data.layerIds != null && data.layerIds.length > 0? '&extras=' + encodeURIComponent(JSON.stringify({layerIds: data.layerIds})) : '') +
- (data.scale != null? '&scale=' + data.scale : '') +'&base64=1&xml=' +
- encodeURIComponent(xml));
-
- req.send(mxUtils.bind(this, function(req)
- {
- // Temp graph was never created at this point so we can
- // skip processUri since it already contains the XML
- if (req.getStatus() >= 200 && req.getStatus() <= 299)
- {
- postDataBack('data:image/png;base64,' + req.getText());
- }
- else
- {
- processUri(null);
- }
- }), mxUtils.bind(this, function()
- {
- processUri(null);
- }));
- }
- }
- }
- else
- {
- // SVG is generated from graph so parse optional XML
- if (data.xml != null && data.xml.length > 0)
- {
- ignoreChange = true;
- this.setFileData(data.xml);
- ignoreChange = false;
- }
-
- var msg = this.createLoadMessage('export');
-
- // Attaches incoming message
- msg.message = data;
-
- // Forces new HTML format if pages exists
- if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
- (this.pages != null && this.pages.length > 1))))
- {
- var node = this.getXmlFileData();
- msg.xml = mxUtils.getXml(node);
- msg.data = this.getFileData(null, null, true, null, null, null, node);
- msg.format = data.format;
- }
- else if (data.format == 'html')
- {
- var xml = this.editor.getGraphXml();
- msg.data = this.getHtml(xml, this.editor.graph);
- msg.xml = mxUtils.getXml(xml);
- msg.format = data.format;
- }
- else
- {
- // Creates a preview with no alt text for unsupported browsers
- mxSvgCanvas2D.prototype.foAltText = null;
-
- var bg = (data.background != null) ? data.background : this.editor.graph.background;
-
- if (bg == mxConstants.NONE)
- {
- bg = null;
- }
-
- msg.xml = this.getFileData(true, null, null, null, null,
- null, null, null, null, false);
- msg.format = 'svg';
-
- var postResult = mxUtils.bind(this, function(svg)
- {
- this.editor.graph.setEnabled(true);
- this.spinner.stop();
-
- msg.data = Editor.createSvgDataUri(svg);
- parent.postMessage(JSON.stringify(msg), '*');
- });
-
- if (data.format == 'xmlsvg')
- {
- if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
- (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
- {
- this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, postResult, null, null,
- data.embedImages, bg, data.scale, data.border, data.shadow, data.keepTheme);
- }
- }
- else
- {
- if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
- (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
- {
- this.editor.graph.setEnabled(false);
- var svgRoot = this.editor.graph.getSvg(bg, data.scale, data.border, null, null,
- null, null, null, null, this.editor.graph.shadowVisible || data.shadow,
- null, data.keepTheme);
-
- if (this.editor.graph.shadowVisible || data.shadow)
- {
- this.editor.graph.addSvgShadow(svgRoot);
- }
- this.embedFonts(svgRoot, mxUtils.bind(this, function(svgRoot)
- {
- if (data.embedImages || data.embedImages == null)
- {
- this.editor.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
- {
- postResult(mxUtils.getXml(svgRoot));
- }));
- }
- else
- {
- postResult(mxUtils.getXml(svgRoot));
- }
- }));
- }
- }
-
- return;
- }
-
- parent.postMessage(JSON.stringify(msg), '*');
- }
-
- return;
- }
- else if (data.action == 'load')
- {
- autosave = data.autosave == 1;
- this.hideDialog();
-
- if (data.modified != null && urlParams['modified'] == null)
- {
- urlParams['modified'] = data.modified;
- }
-
- if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
- {
- urlParams['saveAndExit'] = data.saveAndExit;
- }
-
- if (data.noSaveBtn != null && urlParams['noSaveBtn'] == null)
- {
- urlParams['noSaveBtn'] = data.noSaveBtn;
- }
-
- if (data.noExitBtn != null && urlParams['noExitBtn'] == null)
- {
- urlParams['noExitBtn'] = data.noExitBtn;
- }
-
- if (data.title != null && this.buttonContainer != null)
- {
- var tmp = document.createElement('span');
- mxUtils.write(tmp, data.title);
-
- if (uiTheme == 'atlas')
- {
- this.buttonContainer.style.paddingRight = '12px';
- this.buttonContainer.style.paddingTop = '6px';
- this.buttonContainer.style.right = urlParams['noLangIcon'] == '1'? '0' : '25px';
- }
- else if (uiTheme != 'min')
- {
- this.buttonContainer.style.paddingRight = '38px';
- this.buttonContainer.style.paddingTop = '6px';
- }
-
- if (this.embedFilenameSpan != null)
- {
- this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
- }
-
- this.buttonContainer.appendChild(tmp);
- this.embedFilenameSpan = tmp;
- }
-
- try
- {
- if (data.libs)
- {
- this.sidebar.showEntries(data.libs);
- }
- }
- catch(e){}
- if (data.xmlpng != null)
- {
- data = this.extractGraphModelFromPng(data.xmlpng);
- }
- else if (data.descriptor != null)
- {
- data = data.descriptor;
- }
- else
- {
- data = data.xml;
- }
- }
- else if (data.action == 'merge')
- {
- var file = this.getCurrentFile();
-
- if (file != null)
- {
- var tmp = extractDiagramXml(data.xml);
- if (tmp != null && tmp != '')
- {
- file.mergeFile(new LocalFile(this, tmp), function()
- {
- parent.postMessage(JSON.stringify({event: 'merge', message: data}), '*');
- }, function(err)
- {
- parent.postMessage(JSON.stringify({event: 'merge', message: data, error: err}), '*');
- });
- }
- }
-
- return;
- }
- else if (data.action == 'remoteInvokeReady')
- {
- this.handleRemoteInvokeReady(parent);
- return;
- }
- else if (data.action == 'remoteInvoke')
- {
- this.handleRemoteInvoke(data, evt.origin);
- return;
- }
- else if (data.action == 'remoteInvokeResponse')
- {
- this.handleRemoteInvokeResponse(data);
- return;
- }
- else
- {
- // Unknown message must stop execution
- parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
-
- return;
- }
- }
- catch (e)
- {
- // TODO: Block handling of more messages when in error state
- this.handleError(e);
- }
- }
-
- var getData = mxUtils.bind(this, function()
- {
- return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
- this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
- });
-
- var doLoad = mxUtils.bind(this, function(data, evt)
- {
- ignoreChange = true;
- try
- {
- fn(data, evt);
- }
- catch (e)
- {
- this.handleError(e);
- }
- ignoreChange = false;
-
- if (urlParams['modified'] != null)
- {
- this.editor.setStatus('');
- }
- lastData = getData();
- if (autosave && changeListener == null)
- {
- changeListener = mxUtils.bind(this, function(sender, eventObject)
- {
- var data = getData();
-
- if (data != lastData && !ignoreChange)
- {
- var msg = this.createLoadMessage('autosave');
- msg.xml = data;
- var parent = window.opener || window.parent;
- parent.postMessage(JSON.stringify(msg), '*');
- }
-
- lastData = data;
- });
-
- this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
- // Some options trigger autosave
- this.editor.graph.addListener('gridSizeChanged', changeListener);
- this.editor.graph.addListener('shadowVisibleChanged', changeListener);
- this.addListener('pageFormatChanged', changeListener);
- this.addListener('pageScaleChanged', changeListener);
- this.addListener('backgroundColorChanged', changeListener);
- this.addListener('backgroundImageChanged', changeListener);
- this.addListener('foldingEnabledChanged', changeListener);
- this.addListener('mathEnabledChanged', changeListener);
- this.addListener('gridEnabledChanged', changeListener);
- this.addListener('guidesEnabledChanged', changeListener);
- this.addListener('pageViewChanged', changeListener);
- }
-
- // Sends the bounds of the graph to the host after parsing
- if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
- {
- var resp = this.createLoadMessage('load');
-
- // Attaches XML to response
- resp.xml = data;
-
- parent.postMessage(JSON.stringify(resp), '*');
- }
- });
-
- if (data != null && typeof data.substring === 'function' && data.substring(0, 34) == 'data:application/vnd.visio;base64,')
- {
- // Checks VND binary magic number in base64
- var filename = (data.substring(34, 45) == '0M8R4KGxGuE') ? 'raw.vsd' : 'raw.vsdx';
-
- this.importVisio(this.base64ToBlob(data.substring(data.indexOf(',') + 1)), function(xml)
- {
- doLoad(xml, evt);
- }, mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- }), filename);
- }
- else if (data != null && typeof data.substring === 'function' && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, ''))
- {
- // Asynchronous parsing via server
- this.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
- {
- if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299 &&
- xhr.responseText.substring(0, 13) == '<mxGraphModel')
- {
- doLoad(xhr.responseText, evt);
- }
- }), '');
- }
- else if (data != null && typeof data.substring === 'function' && this.isLucidChartData(data))
- {
- this.convertLucidChart(data, mxUtils.bind(this, function(xml)
- {
- doLoad(xml);
- }), mxUtils.bind(this, function(e)
- {
- this.handleError(e);
- }));
- }
- else if (data != null && typeof data === 'object' && data.format != null && (data.data != null || data.url != null))
- {
- this.loadDescriptor(data, mxUtils.bind(this, function(e)
- {
- doLoad(getData(), evt);
- }), mxUtils.bind(this, function(e)
- {
- this.handleError(e, mxResources.get('errorLoadingFile'));
- }));
- }
- else
- {
- data = extractDiagramXml(data);
- doLoad(data, evt);
- }
- }));
-
- // Requests data from the sender. This is a workaround for not allowing
- // the opener to listen for the onload event if not in the same origin.
- var parent = window.opener || window.parent;
- var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
- parent.postMessage(msg, '*');
-
- // Adds JSON event for opening links
- if (urlParams['proto'] == 'json')
- {
- var graphOpenLink = this.editor.graph.openLink;
-
- this.editor.graph.openLink = function(href, target, allowOpener)
- {
- graphOpenLink.apply(this, arguments);
-
- parent.postMessage(JSON.stringify({event: 'openLink', href: href, target: target, allowOpener: allowOpener}), '*');
- };
- }
- };
-
- /**
- * Adds the buttons for embedded mode.
- */
- EditorUi.prototype.addEmbedButtons = function()
- {
- if (this.menubar != null)
- {
- var div = document.createElement('div');
- div.style.display = 'inline-block';
- div.style.position = 'absolute';
- div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '0px';
- div.style.paddingLeft = '8px';
- div.style.paddingBottom = '2px';
- var button = document.createElement('button');
- button.className = 'geBigButton';
- var lastBtn = button;
-
- if (urlParams['noSaveBtn'] == '1')
- {
- if (urlParams['saveAndExit'] != '0')
- {
- var saveAndExitTitle = urlParams['publishClose'] == '1' ? mxResources.get('publish') : mxResources.get('saveAndExit');
- mxUtils.write(button, saveAndExitTitle);
- button.setAttribute('title', saveAndExitTitle);
-
- mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
- {
- this.actions.get('saveAndExit').funct();
- }));
-
- div.appendChild(button);
- }
- }
- else
- {
- mxUtils.write(button, mxResources.get('save'));
- button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
-
- mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
- {
- this.actions.get('save').funct();
- }));
-
- div.appendChild(button);
-
- if (urlParams['saveAndExit'] == '1')
- {
- button = document.createElement('a');
- mxUtils.write(button, mxResources.get('saveAndExit'));
- button.setAttribute('title', mxResources.get('saveAndExit'));
- button.className = 'geBigButton geBigStandardButton';
- button.style.marginLeft = '6px';
-
- mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
- {
- this.actions.get('saveAndExit').funct();
- }));
-
- div.appendChild(button);
- lastBtn = button;
- }
- }
- if (urlParams['noExitBtn'] != '1')
- {
- button = document.createElement('a');
- var exitTitle = urlParams['publishClose'] == '1' ? mxResources.get('close') : mxResources.get('exit');
- mxUtils.write(button, exitTitle);
- button.setAttribute('title', exitTitle);
- button.className = 'geBigButton geBigStandardButton';
- button.style.marginLeft = '6px';
-
- mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
- {
- this.actions.get('exit').funct();
- }));
-
- div.appendChild(button);
- lastBtn = button;
- }
-
- lastBtn.style.marginRight = '20px';
-
- this.toolbar.container.appendChild(div);
- this.toolbar.staticElements.push(div);
- div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
- }
- };
- /**
- *
- */
- EditorUi.prototype.showImportCsvDialog = function()
- {
- if (this.importCsvDialog == null)
- {
- this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
- Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
- {
- this.importCsv(newValue);
- }), null, null, 620, 430, null, true, true, mxResources.get('import'),
- !this.isOffline() ? 'https://drawio-app.com/import-from-csv-to-drawio/' : null);
- }
-
- this.showDialog(this.importCsvDialog.container, 640, 520, true, true, null, null, null, null, true);
- this.importCsvDialog.init();
- };
- /**
- * Runs the layout from the given JavaScript array which is of the form [{layout: name, config: obj}, ...]
- * where name is the layout constructor name and config contains the properties of the layout instance.
- */
- EditorUi.prototype.executeLayoutList = function(layoutList, done)
- {
- var graph = this.editor.graph;
- var cells = graph.getSelectionCells();
- for (var i = 0; i < layoutList.length; i++)
- {
- var layout = new window[layoutList[i].layout](graph);
-
- if (layoutList[i].config != null)
- {
- for (var key in layoutList[i].config)
- {
- layout[key] = layoutList[i].config[key];
- }
- }
-
- this.executeLayout(function()
- {
- layout.execute(graph.getDefaultParent(), cells.length == 0 ? null : cells);
- }, i == layoutList.length - 1, done);
- }
- };
-
- /**
- *
- */
- EditorUi.prototype.importCsv = function(text, done)
- {
- try
- {
- var lines = text.split('\n');
- var allCells = [];
- var cells = [];
- var dups = {};
-
- if (lines.length > 0)
- {
- // Internal lookup table
- var lookups = {};
-
- // Default values
- var vars = null;
- var style = null;
- var styles = null;
- var stylename = null;
- var labelname = null;
- var labels = null;
- var parentstyle = null;
- var identity = null;
- var parent = null;
- var namespace = '';
- var width = 'auto';
- var height = 'auto';
- var left = null;
- var top = null;
- var edgespacing = 40;
- var nodespacing = 40;
- var levelspacing = 100;
- var padding = 0;
-
- var graph = this.editor.graph;
- var view = graph.view;
- var bds = graph.getGraphBounds();
- // Delayed after optional layout
- var afterInsert = function()
- {
- if (done != null)
- {
- done(select);
- }
- else
- {
- graph.setSelectionCells(select);
- graph.scrollCellToVisible(graph.getSelectionCell());
- }
- };
-
- // Computes unscaled, untranslated graph bounds
- var pt = graph.getFreeInsertPoint();
- var x0 = pt.x;
- var y0 = pt.y;
- var y = y0;
- // Default label value depends on column names
- var label = null;
-
- // Default layout to run.
- var layout = 'auto';
-
- // Name of the attribute that contains the parent reference
- var parent = null;
-
- // Name of the attribute that contains the references for creating edges
- var edges = [];
- // Name of the column for hyperlinks
- var link = null;
-
- // String array of names to remove from metadata
- var ignore = null;
-
- // Read processing instructions first
- var index = 0;
-
- while (index < lines.length && lines[index].charAt(0) == '#')
- {
- var text = lines[index];
- index++;
-
- while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
- lines[index].charAt(0) == '#')
- {
- text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
- index++;
- }
-
- if (text.charAt(1) != '#')
- {
- // Processing instruction
- var idx = text.indexOf(':');
-
- if (idx > 0)
- {
- var key = mxUtils.trim(text.substring(1, idx));
- var value = mxUtils.trim(text.substring(idx + 1));
-
- if (key == 'label')
- {
- label = graph.sanitizeHtml(value);
- }
- else if (key == 'labelname' && value.length > 0 && value != '-')
- {
- labelname = value;
- }
- else if (key == 'labels' && value.length > 0 && value != '-')
- {
- labels = JSON.parse(value);
- }
- else if (key == 'style')
- {
- style = value;
- }
- else if (key == 'parentstyle')
- {
- parentstyle = value;
- }
- else if (key == 'stylename' && value.length > 0 && value != '-')
- {
- stylename = value;
- }
- else if (key == 'styles' && value.length > 0 && value != '-')
- {
- styles = JSON.parse(value);
- }
- else if (key == 'vars' && value.length > 0 && value != '-')
- {
- vars = JSON.parse(value);
- }
- else if (key == 'identity' && value.length > 0 && value != '-')
- {
- identity = value;
- }
- else if (key == 'parent' && value.length > 0 && value != '-')
- {
- parent = value;
- }
- else if (key == 'namespace' && value.length > 0 && value != '-')
- {
- namespace = value;
- }
- else if (key == 'width')
- {
- width = value;
- }
- else if (key == 'height')
- {
- height = value;
- }
- else if (key == 'left' && value.length > 0)
- {
- left = value;
- }
- else if (key == 'top' && value.length > 0)
- {
- top = value;
- }
- else if (key == 'ignore')
- {
- ignore = value.split(',');
- }
- else if (key == 'connect')
- {
- edges.push(JSON.parse(value));
- }
- else if (key == 'link')
- {
- link = value;
- }
- else if (key == 'padding')
- {
- padding = parseFloat(value);
- }
- else if (key == 'edgespacing')
- {
- edgespacing = parseFloat(value);
- }
- else if (key == 'nodespacing')
- {
- nodespacing = parseFloat(value);
- }
- else if (key == 'levelspacing')
- {
- levelspacing = parseFloat(value);
- }
- else if (key == 'layout')
- {
- layout = value;
- }
- }
- }
- }
-
- if (lines[index] == null)
- {
- throw new Error(mxResources.get('invalidOrMissingFile'));
- }
-
- // Converts identity and parent to index and validates XML attribute names
- var keys = this.editor.csvToArray(lines[index]);
- var identityIndex = null;
- var parentIndex = null;
- var attribs = [];
-
- for (var i = 0; i < keys.length; i++)
- {
- if (identity == keys[i])
- {
- identityIndex = i;
- }
-
- if (parent == keys[i])
- {
- parentIndex = i;
- }
-
- attribs.push(mxUtils.trim(keys[i]).replace(/[^a-z0-9]+/ig, '_').
- replace(/^\d+/, '').replace(/_+$/, ''));
- }
-
- if (label == null)
- {
- label = '%' + attribs[0] + '%';
- }
-
- if (edges != null)
- {
- for (var e = 0; e < edges.length; e++)
- {
- if (lookups[edges[e].to] == null)
- {
- lookups[edges[e].to] = {};
- }
- }
- }
-
- // Parse and validate input
- var arrays = [];
-
- for (var i = index + 1; i < lines.length; i++)
- {
- var values = this.editor.csvToArray(lines[i]);
-
- if (values == null)
- {
- var short = (lines[i].length > 40) ? lines[i].substring(0, 40) + '...' : lines[i];
-
- throw new Error(short + ' (' + i + '):\n' + mxResources.get('containsValidationErrors'));
- }
- else if (values.length > 0)
- {
- arrays.push(values);
- }
- }
-
- graph.model.beginUpdate();
- try
- {
- for (var i = 0; i < arrays.length; i++)
- {
- var values = arrays[i];
- var cell = null;
- var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
-
- if (id != null)
- {
- cell = graph.model.getCell(id);
- }
-
- var exists = cell != null;
- var newCell = new mxCell(label, new mxGeometry(x0, y,
- 0, 0), style || 'whiteSpace=wrap;html=1;');
- newCell.vertex = true;
- newCell.id = id;
-
- for (var j = 0; j < values.length; j++)
- {
- graph.setAttributeForCell(newCell, attribs[j], values[j]);
- }
-
- if (labelname != null && labels != null)
- {
- var tempLabel = labels[newCell.getAttribute(labelname)];
-
- if (tempLabel != null)
- {
- graph.labelChanged(newCell, tempLabel);
- }
- }
- if (stylename != null && styles != null)
- {
- var tempStyle = styles[newCell.getAttribute(stylename)];
-
- if (tempStyle != null)
- {
- newCell.style = tempStyle;
- }
- }
- graph.setAttributeForCell(newCell, 'placeholders', '1');
- newCell.style = graph.replacePlaceholders(newCell, newCell.style, vars);
- if (exists)
- {
- graph.model.setGeometry(cell, newCell.geometry);
- graph.model.setStyle(cell, newCell.style);
-
- if (mxUtils.indexOf(cells, cell) < 0)
- {
- cells.push(cell);
- }
- }
-
- cell = newCell;
-
- if (!exists)
- {
- for (var e = 0; e < edges.length; e++)
- {
- lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
- }
- }
-
- if (link != null && link != 'link')
- {
- graph.setLinkForCell(cell, cell.getAttribute(link));
-
- // Removes attribute
- graph.setAttributeForCell(cell, link, null);
- }
-
- // Sets the size
- graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
- var size = this.editor.graph.getPreferredSizeForCell(cell);
-
- if (cell.vertex)
- {
- if (left != null && cell.getAttribute(left) != null)
- {
- cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
- }
- if (top != null && cell.getAttribute(top) != null)
- {
- cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
- }
-
- if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
- {
- cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
- }
- else
- {
- cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
- }
- if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
- {
- cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
- }
- else
- {
- cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
- }
-
- y += cell.geometry.height + nodespacing;
- }
-
- if (!exists)
- {
- var parent = (parentIndex != null) ? graph.model.getCell(
- namespace + values[parentIndex]) : null;
- allCells.push(cell);
-
- if (parent != null)
- {
- parent.style = graph.replacePlaceholders(parent, parentstyle, vars);
- graph.addCell(cell, parent);
- }
- else
- {
- cells.push(graph.addCell(cell));
- }
- }
- else
- {
- if (dups[id] == null)
- {
- dups[id] = [];
- }
-
- dups[id].push(cell);
- }
- }
- var roots = cells.slice();
- var select = cells.slice();
-
- for (var e = 0; e < edges.length; e++)
- {
- var edge = edges[e];
-
- for (var i = 0; i < allCells.length; i++)
- {
- var cell = allCells[i];
-
- var insertEdge = mxUtils.bind(this, function(realCell, dataCell, edge)
- {
- var tmp = dataCell.getAttribute(edge.from);
-
- if (tmp != null)
- {
- // Removes attribute
- graph.setAttributeForCell(dataCell, edge.from, null);
-
- if (tmp != '')
- {
- var refs = tmp.split(',');
-
- for (var j = 0; j < refs.length; j++)
- {
- var ref = lookups[edge.to][refs[j]];
-
- if (ref != null)
- {
- var label = edge.label;
-
- if (edge.fromlabel != null)
- {
- label = (dataCell.getAttribute(edge.fromlabel) || '') + (label || '');
- }
-
- if (edge.sourcelabel != null)
- {
- label = graph.replacePlaceholders(dataCell,
- edge.sourcelabel, vars) + (label || '');
- }
-
- if (edge.tolabel != null)
- {
- label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
- }
-
- if (edge.targetlabel != null)
- {
- label = (label || '') + graph.replacePlaceholders(
- ref, edge.targetlabel, vars);
- }
-
- var placeholders = ((edge.placeholders == 'target') ==
- !edge.invert) ? ref : realCell;
- var style = (edge.style != null) ?
- graph.replacePlaceholders(placeholders, edge.style, vars) :
- graph.createCurrentEdgeStyle();
- var edgeCell = graph.insertEdge(null, null, label || '', (edge.invert) ?
- ref : realCell, (edge.invert) ? realCell : ref, style);
-
- // Adds additional edge labels
- if (edge.labels != null)
- {
- for (var k = 0; k < edge.labels.length; k++)
- {
- var def = edge.labels[k];
- var elx = (def.x != null) ? def.x : 0;
- var ely = (def.y != null) ? def.y : 0;
- var st = 'resizable=0;html=1;';
- var el = new mxCell(def.label || k,
- new mxGeometry(elx, ely, 0, 0), st);
- el.vertex = true;
- el.connectable = false;
- el.geometry.relative = true;
-
- if (def.placeholders != null)
- {
- el.value = graph.replacePlaceholders(
- ((def.placeholders == 'target') ==
- !edge.invert) ? ref : realCell,
- el.value, vars)
- }
-
- if (def.dx != null || def.dy != null)
- {
- el.geometry.offset = new mxPoint(
- (def.dx != null) ? def.dx : 0,
- (def.dy != null) ? def.dy : 0);
- }
-
- edgeCell.insert(el);
- }
- }
-
- select.push(edgeCell);
- mxUtils.remove((edge.invert) ? realCell : ref, roots);
- }
- }
- }
- }
- });
-
- insertEdge(cell, cell, edge);
- // Checks more entries
- if (dups[cell.id] != null)
- {
- for (var j = 0; j < dups[cell.id].length; j++)
- {
- insertEdge(cell, dups[cell.id][j], edge);
- }
- }
- }
- }
-
- // Removes ignored attributes after processing above
- if (ignore != null)
- {
- for (var i = 0; i < allCells.length; i++)
- {
- var cell = allCells[i];
-
- for (var j = 0; j < ignore.length; j++)
- {
- graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
- }
- }
- }
-
- if (cells.length > 0)
- {
- var edgeLayout = new mxParallelEdgeLayout(graph);
- edgeLayout.spacing = edgespacing;
- edgeLayout.checkOverlap = true;
-
- var postProcess = function()
- {
- if (edgeLayout.spacing > 0)
- {
- edgeLayout.execute(graph.getDefaultParent());
- }
-
- // Aligns cells to grid and/or rounds positions
- for (var i = 0; i < cells.length; i++)
- {
- var geo = graph.getCellGeometry(cells[i]);
- geo.x = Math.round(graph.snap(geo.x));
- geo.y = Math.round(graph.snap(geo.y));
-
- if (width == 'auto')
- {
- geo.width = Math.round(graph.snap(geo.width));
- }
-
- if (height == 'auto')
- {
- geo.height = Math.round(graph.snap(geo.height));
- }
- }
- };
-
- if (layout.charAt(0) == '[')
- {
- // Required for layouts to work with new cells
- var temp = afterInsert;
- graph.view.validate();
- this.executeLayoutList(JSON.parse(layout), function()
- {
- postProcess();
- temp();
- });
- afterInsert = null;
- }
- else if (layout == 'circle')
- {
- var circleLayout = new mxCircleLayout(graph);
- circleLayout.disableEdgeStyle = false;
- circleLayout.resetEdges = false;
-
- var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
-
- // Ignore other cells
- circleLayout.isVertexIgnored = function(vertex)
- {
- return circleLayoutIsVertexIgnored.apply(this, arguments) ||
- mxUtils.indexOf(cells, vertex) < 0;
- };
-
- this.executeLayout(function()
- {
- circleLayout.execute(graph.getDefaultParent());
- postProcess();
- }, true, afterInsert);
-
- afterInsert = null;
- }
- else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
- (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
- {
- // Required for layouts to work with new cells
- graph.view.validate();
-
- var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
- treeLayout.levelDistance = nodespacing;
- treeLayout.edgeRouting = false;
- treeLayout.resetEdges = false;
-
- this.executeLayout(function()
- {
- treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
- }, true, afterInsert);
-
- afterInsert = null;
- }
- else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
- (layout == 'auto' && roots.length == 1))
- {
- // Required for layouts to work with new cells
- graph.view.validate();
-
- var flowLayout = new mxHierarchicalLayout(graph,
- (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
- flowLayout.intraCellSpacing = nodespacing;
- flowLayout.parallelEdgeSpacing = edgespacing;
- flowLayout.interRankCellSpacing = levelspacing;
- flowLayout.disableEdgeStyle = false;
-
- this.executeLayout(function()
- {
- flowLayout.execute(graph.getDefaultParent(), select);
-
- // Workaround for flow layout moving cells to origin
- graph.moveCells(select, x0, y0);
- }, true, afterInsert);
-
- afterInsert = null;
- }
- else if (layout == 'organic' || (layout == 'auto' &&
- select.length > cells.length))
- {
- // Required for layouts to work with new cells
- graph.view.validate();
-
- var organicLayout = new mxFastOrganicLayout(graph);
- organicLayout.forceConstant = nodespacing * 3;
- organicLayout.disableEdgeStyle = false;
- organicLayout.resetEdges = false;
-
- var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
-
- // Ignore other cells
- organicLayout.isVertexIgnored = function(vertex)
- {
- return organicLayoutIsVertexIgnored.apply(this, arguments) ||
- mxUtils.indexOf(cells, vertex) < 0;
- };
-
- this.executeLayout(function()
- {
- organicLayout.execute(graph.getDefaultParent());
- postProcess();
- }, true, afterInsert);
-
- afterInsert = null;
- }
- }
-
- this.hideDialog();
- }
- finally
- {
- graph.model.endUpdate();
- }
-
- if (afterInsert != null)
- {
- afterInsert();
- }
- }
- }
- catch (e)
- {
- this.handleError(e);
- }
- };
- /**
- * Translates this point by the given vector.
- *
- * @param {number} dx X-coordinate of the translation.
- * @param {number} dy Y-coordinate of the translation.
- */
- EditorUi.prototype.getSearch = function(exclude)
- {
- var result = '';
-
- if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
- {
- var amp = '?';
-
- for (var key in urlParams)
- {
- if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
- {
- result += amp + key + '=' + urlParams[key];
- amp = '&';
- }
- }
- }
- else
- {
- result = window.location.search;
- }
-
- return result;
- };
- /**
- * Returns the URL for a copy of this editor with no state.
- */
- EditorUi.prototype.getUrl = function(pathname)
- {
- var href = (pathname != null) ? pathname : window.location.pathname;
- var parms = (href.indexOf('?') > 0) ? 1 : 0;
- if (urlParams['offline'] == '1')
- {
- href += window.location.search;
- }
- else
- {
- var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
- 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
-
- // Removes template URL parameter for new blank diagram
- for (var key in urlParams)
- {
- if (mxUtils.indexOf(ignored, key) < 0)
- {
- if (parms == 0)
- {
- href += '?';
- }
- else
- {
- href += '&';
- }
-
- if (urlParams[key] != null)
- {
- href += key + '=' + urlParams[key];
- parms++;
- }
- }
- }
- }
- return href;
- };
- /**
- * Overrides link dialog.
- */
- EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn, showNewWindowOption, linkTarget)
- {
- var dlg = new LinkDialog(this, value, btnLabel, fn, true, showNewWindowOption, linkTarget);
- this.showDialog(dlg.container, 560, 130, true, true);
- dlg.init();
- };
- /**
- * Overrides createOutline
- */
- var editorUiCreateOutline = EditorUi.prototype.createOutline;
- EditorUi.prototype.createOutline = function(wnd)
- {
- var outline = editorUiCreateOutline.apply(this, arguments);
- var graph = this.editor.graph;
- var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
- outline.getSourceGraphBounds = function()
- {
- if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
- {
- var pb = this.source.getPagePadding();
- var s = this.source.view.scale;
-
- var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
- Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
-
- return result;
- }
-
- return outlineGetSourceGraphBounds.apply(this, arguments);
- };
-
- var outlineGetSourceContainerSize = outline.getSourceContainerSize;
- outline.getSourceContainerSize = function()
- {
- if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
- {
- var pad = this.source.getPagePadding();
- var s = this.source.view.scale;
-
- return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
- Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
- }
- return outlineGetSourceContainerSize.apply(this, arguments);
- };
- outline.getOutlineOffset = function(scale)
- {
- if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
- {
- var pb = this.source.getPagePadding();
- var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
- var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
- // Why is vertical offset negative relative to dy
- return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
- }
-
- return new mxPoint(8 / scale, 8 / scale);
- };
-
- var outlineInit = outline.init;
- outline.init = function()
- {
- outlineInit.apply(this, arguments);
-
- // Problem: Need to override a function in the view but the view is created
- // with the graph so a refresh of the page is needed to see this change.
- outline.outline.view.getBackgroundPageBounds = function()
- {
- var layout = graph.getPageLayout();
- var page = graph.getPageSize();
-
- return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
- this.scale * (this.translate.y + layout.y * page.height),
- this.scale * layout.width * page.width,
- this.scale * layout.height * page.height);
- };
-
- outline.outline.view.validateBackgroundPage();
- };
-
- this.editor.addListener('pageSelected', function(sender, evt)
- {
- var change = evt.getProperty('change');
-
- var graph = outline.source;
- var g = outline.outline;
-
- g.pageScale = graph.pageScale;
- g.pageFormat = graph.pageFormat;
- g.background = graph.background;
- g.pageVisible = graph.pageVisible;
- g.background = graph.background;
-
- var current = mxUtils.getCurrentStyle(graph.container);
- g.container.style.backgroundColor = current.backgroundColor;
-
- if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
- {
- g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
- }
- outline.outline.view.clear(change.previousPage.root, true);
- outline.outline.view.validate();
- });
- return outline;
- };
-
- /**
- * Returns the number of storage options enabled
- */
- EditorUi.prototype.getServiceCount = function(allowBrowser)
- {
- var serviceCount = 1;
-
- if (this.drive != null || typeof window.DriveClient === 'function')
- {
- serviceCount++
- }
-
- if (this.dropbox != null || typeof window.DropboxClient === 'function')
- {
- serviceCount++
- }
- if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
- {
- serviceCount++
- }
-
- if (this.gitHub != null)
- {
- serviceCount++
- }
-
- if (this.gitLab != null)
- {
- serviceCount++
- }
-
- if (allowBrowser && isLocalStorage && urlParams['browser'] == '1')
- {
- serviceCount++
- }
-
- return serviceCount;
- }
- /**
- * Updates action and menu states depending on the file.
- */
- EditorUi.prototype.updateUi = function()
- {
- this.updateButtonContainer();
- this.updateActionStates();
-
- // Action states that only need update for new files
- var file = this.getCurrentFile();
- var active = file != null || (urlParams['embed'] == '1' &&
- this.editor.graph.isEnabled());
- this.menus.get('viewPanels').setEnabled(active);
- this.menus.get('viewZoom').setEnabled(active);
-
- var restricted = (urlParams['embed'] != '1' ||
- !this.editor.graph.isEnabled()) &&
- (file == null || file.isRestricted());
- this.actions.get('makeCopy').setEnabled(!restricted);
- this.actions.get('print').setEnabled(!restricted);
- this.menus.get('exportAs').setEnabled(!restricted);
- this.menus.get('embed').setEnabled(!restricted);
-
- // Disables libraries and extras menu in embed mode
- // while waiting for file data
- var libsEnabled = urlParams['embed'] != '1' ||
- this.editor.graph.isEnabled();
- this.menus.get('extras').setEnabled(libsEnabled);
-
- if (Editor.enableCustomLibraries)
- {
- this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
- this.menus.get('newLibrary').setEnabled(libsEnabled);
- }
-
- // Disables actions in the toolbar
- var editable = (urlParams['embed'] == '1' &&
- this.editor.graph.isEnabled()) ||
- (file != null && file.isEditable());
- this.actions.get('image').setEnabled(active);
- this.actions.get('zoomIn').setEnabled(active);
- this.actions.get('zoomOut').setEnabled(active);
- this.actions.get('resetView').setEnabled(active);
-
- // Updates undo history states
- this.actions.get('undo').setEnabled(this.canUndo() && editable);
- this.actions.get('redo').setEnabled(this.canRedo() && editable);
-
- // Disables menus
- this.menus.get('edit').setEnabled(active);
- this.menus.get('view').setEnabled(active);
- this.menus.get('importFrom').setEnabled(editable);
- this.menus.get('arrange').setEnabled(editable);
-
- // Disables connection drop downs in toolbar
- if (this.toolbar != null)
- {
- if (this.toolbar.edgeShapeMenu != null)
- {
- this.toolbar.edgeShapeMenu.setEnabled(editable);
- }
-
- if (this.toolbar.edgeStyleMenu != null)
- {
- this.toolbar.edgeStyleMenu.setEnabled(editable);
- }
- }
- this.updateUserElement();
- };
-
- /**
- * Hook for subclassers
- */
- EditorUi.prototype.updateButtonContainer = function()
- {
- // do nothing
- };
-
- /**
- * Hook for subclassers
- */
- EditorUi.prototype.updateUserElement = function()
- {
- // do nothing
- };
-
- /**
- * Hook for subclassers
- */
- EditorUi.prototype.scheduleSanityCheck = function()
- {
- // do nothing
- };
-
- /**
- * Hook for subclassers
- */
- EditorUi.prototype.stopSanityCheck = function()
- {
- // do nothing
- };
- /**
- * Returns true if a diagram is cative and editable.
- */
- EditorUi.prototype.isDiagramActive = function()
- {
- var file = this.getCurrentFile();
-
- return (file != null && file.isEditable()) ||
- (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
- };
-
- /**
- * Updates action states depending on the selection.
- */
- var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
- EditorUi.prototype.updateActionStates = function()
- {
- editorUiUpdateActionStates.apply(this, arguments);
- var graph = this.editor.graph;
- var active = this.isDiagramActive();
- var file = this.getCurrentFile();
- var enabled = file != null || urlParams['embed'] == '1';
- this.actions.get('pageSetup').setEnabled(active);
- this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
- this.actions.get('guides').setEnabled(active);
- this.actions.get('editData').setEnabled(active);
- this.actions.get('shadowVisible').setEnabled(active);
- this.actions.get('connectionArrows').setEnabled(active);
- this.actions.get('connectionPoints').setEnabled(active);
- this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
- this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
- this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
- this.actions.get('createShape').setEnabled(active);
- this.actions.get('createRevision').setEnabled(active);
- this.actions.get('moveToFolder').setEnabled(file != null);
- this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
- this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
- this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
- this.actions.get('tags').setEnabled(this.diagramContainer.style.visibility != 'hidden');
- this.actions.get('layers').setEnabled(this.diagramContainer.style.visibility != 'hidden');
- this.actions.get('outline').setEnabled(this.diagramContainer.style.visibility != 'hidden');
- this.actions.get('rename').setEnabled((file != null && file.isRenamable()) || urlParams['embed'] == '1');
- this.actions.get('close').setEnabled(file != null);
- this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
-
- var findReplace = this.actions.get('findReplace');
- findReplace.setEnabled(this.diagramContainer.style.visibility != 'hidden');
- findReplace.label = mxResources.get('find') + ((graph.isEnabled()) ?
- '/' + mxResources.get('replace') : '') + '...';
-
- var state = graph.view.getState(graph.getSelectionCell());
- this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
- };
- /**
- * Overridden to remove export dialog in chromeless lightbox.
- */
- var editoUiDestroy = EditorUi.prototype.destroy;
- EditorUi.prototype.destroy = function()
- {
- if (this.exportDialog != null)
- {
- this.exportDialog.parentNode.removeChild(this.exportDialog);
- this.exportDialog = null;
- }
-
- editoUiDestroy.apply(this, arguments);
- };
-
- /**
- * Overrides export dialog for using ui functions for save and setting global switches.
- */
- if (window.ExportDialog != null)
- {
- ExportDialog.showXmlOption = false;
- ExportDialog.showGifOption = false;
-
- ExportDialog.exportFile = function(editorUi, name, format, bg, s, b, dpi, grid)
- {
- var graph = editorUi.editor.graph;
-
- if (format == 'xml')
- {
- editorUi.hideDialog();
- editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
- }
- else if (format == 'svg')
- {
- editorUi.hideDialog();
- editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
- }
- else
- {
- var data = editorUi.getFileData(true, null, null, null, null, true);
- var bounds = graph.getGraphBounds();
- var w = Math.floor(bounds.width * s / graph.view.scale);
- var h = Math.floor(bounds.height * s / graph.view.scale);
-
- if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
- {
- editorUi.hideDialog();
-
- if ((format == 'png' || format == 'jpg' || format == 'jpeg') && editorUi.isExportToCanvas())
- {
- if (format == 'png')
- {
- editorUi.exportImage(s, bg == null || bg == 'none', true,
- false, false, b, true, false, null, grid, dpi);
- }
- else
- {
- editorUi.exportImage(s, false, true,
- false, false, b, true, false, 'jpeg', grid);
- }
- }
- else
- {
- var extras = {globalVars: graph.getExportVariables()};
-
- if (grid)
- {
- extras.grid = {
- size: graph.gridSize,
- steps: graph.view.gridSteps,
- color: graph.view.gridColor
- };
- }
-
- editorUi.saveRequest(name, format,
- function(newTitle, base64)
- {
- return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
- ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
- '&extras=' + encodeURIComponent(JSON.stringify(extras)) +
- (dpi > 0? '&dpi=' + dpi : '') +
- '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
- '&border=' + b + '&xml=' + encodeURIComponent(data));
- });
- }
- }
- else
- {
- mxUtils.alert(mxResources.get('drawingTooLarge'));
- }
- }
- };
- }
- EditorUi.prototype.getDiagramTextContent = function()
- {
- this.editor.graph.setEnabled(false);
- var graph = this.editor.graph;
-
- var allPagesTxt = '';
-
- if (this.pages != null)
- {
- for (var i = 0; i < this.pages.length; i++)
- {
- var pageGraph = graph;
-
- if (this.currentPage != this.pages[i])
- {
- pageGraph = this.createTemporaryGraph(graph.getStylesheet());
- this.updatePageRoot(this.pages[i]);
- pageGraph.model.setRoot(this.pages[i].root);
- }
- allPagesTxt += this.pages[i].getName() + ' ' + pageGraph.getIndexableText() + ' ';
- }
- }
- else
- {
- allPagesTxt = graph.getIndexableText();
- }
-
- this.editor.graph.setEnabled(true);
- return allPagesTxt;
- };
-
- EditorUi.prototype.showRemotelyStoredLibrary = function(title)
- {
- var selectedLibs = {};
- var div = document.createElement('div');
- div.style.whiteSpace = 'nowrap';
- var graph = this.editor.graph;
-
- var hd = document.createElement('h3');
- mxUtils.write(hd, mxUtils.htmlEntities(title));
- hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
- div.appendChild(hd);
- var libsSection = document.createElement('div');
- libsSection.style.cssText = 'border:1px solid lightGray;overflow: auto;height:300px';
- libsSection.innerHTML = '<div style="text-align:center;padding:8px;"><img src="' + IMAGE_PATH + '/spin.gif"></div>';
-
- var loadedLibs = {};
-
- try
- {
- var custLibs = mxSettings.getCustomLibraries();
-
- for (var j = 0; j < custLibs.length; j++)
- {
- var l = custLibs[j];
-
- if (l.substring(0, 1) == 'R')
- {
- var libDesc = JSON.parse(decodeURIComponent(l.substring(1)));
- loadedLibs[libDesc[0]] = {
- id: libDesc[0],
- title: libDesc[1],
- downloadUrl: libDesc[2]
- };
- }
- }
- }
- catch(e){}
- this.remoteInvoke('getCustomLibraries', null, null, function(libsList)
- {
- libsSection.innerHTML = '';
-
- if (libsList.length == 0)
- {
- libsSection.innerHTML = '<div style="text-align:center;padding-top:20px;color:gray;">' +
- mxUtils.htmlEntities(mxResources.get('noLibraries')) + '</div>';
- }
- else
- {
- for (var i = 0; i < libsList.length; i++)
- {
- var lib = libsList[i];
-
- if (loadedLibs[lib.id])
- {
- selectedLibs[lib.id] = lib;
- }
-
- var libCheck = this.addCheckbox(libsSection, lib.title, loadedLibs[lib.id]);
-
- (function(lib2, check)
- {
- mxEvent.addListener(check, 'change', function()
- {
- if (this.checked)
- {
- selectedLibs[lib2.id] = lib2;
- }
- else
- {
- delete selectedLibs[lib2.id];
- }
- });
- })(lib, libCheck)
- }
- }
- }, mxUtils.bind(this, function(e)
- {
- libsSection.innerHTML = '';
- var status = document.createElement('div');
- status.style.padding = '8px';
- status.style.textAlign = 'center';
- mxUtils.write(status, mxResources.get('error') + ': ');
- mxUtils.write(status, (e != null && e.message != null) ?
- e.message : mxResources.get('unknownError'));
- libsSection.appendChild(status);
- }));
- div.appendChild(libsSection);
-
- var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
- {
- this.spinner.spin(document.body, mxResources.get('loading'));
- var pendingLibs = 0;
-
- for (var id in selectedLibs)
- {
- if (loadedLibs[id] != null) continue; //already loaded!
-
- pendingLibs++;
-
- (mxUtils.bind(this, function(lib)
- {
- this.remoteInvoke('getFileContent', [lib.downloadUrl], null, mxUtils.bind(this, function(libContent)
- {
- pendingLibs--;
-
- if (pendingLibs == 0) this.spinner.stop();
-
- try
- {
- this.loadLibrary(new RemoteLibrary(this, libContent, lib));
- }
- catch (e)
- {
- this.handleError(e, mxResources.get('errorLoadingFile'));
- }
- }), mxUtils.bind(this, function()
- {
- pendingLibs--;
-
- if (pendingLibs == 0) this.spinner.stop();
-
- this.handleError(null, mxResources.get('errorLoadingFile'));
- }));
- }))(selectedLibs[id]);
- }
-
- for (var id in loadedLibs)
- {
- if (!selectedLibs[id]) //Removed
- {
- this.closeLibrary(new RemoteLibrary(this, null, loadedLibs[id])); //create a dummy library such that we can call closeLibrary
- }
- }
-
- if (pendingLibs == 0) this.spinner.stop();
- }), null, null, 'https://www.diagrams.net/doc/faq/custom-libraries-confluence-cloud');
- this.showDialog(dlg.container, 340, 375, true, true, null, null, null, null, true);
- };
-
- //Remote invokation, currently limited to functions in EditorUi (and its sub objects) for security reasons
- //White-listed functions and some info about it
- EditorUi.prototype.remoteInvokableFns = {
- getDiagramTextContent: {isAsync: false},
- getLocalStorageFile: {isAsync: false, allowedDomains: ['app.diagrams.net']},
- getLocalStorageFileNames: {isAsync: false, allowedDomains: ['app.diagrams.net']},
- setMigratedFlag: {isAsync: false, allowedDomains: ['app.diagrams.net']}
- };
-
- EditorUi.prototype.remoteInvokeCallbacks = [];
- EditorUi.prototype.remoteInvokeQueue = [];
- EditorUi.prototype.handleRemoteInvokeReady = function(remoteWin)
- {
- this.remoteWin = remoteWin;
-
- for (var i = 0; i < this.remoteInvokeQueue.length; i++)
- {
- remoteWin.postMessage(this.remoteInvokeQueue[i], '*');
- }
-
- this.remoteInvokeQueue = [];
- };
-
- EditorUi.prototype.handleRemoteInvokeResponse = function(msg)
- {
- var msgMarkers = msg.msgMarkers;
- var callback = this.remoteInvokeCallbacks[msgMarkers.callbackId];
-
- if (callback == null)
- {
- throw new Error('No callback for ' + ((msgMarkers != null) ? msgMarkers.callbackId : 'null'));
- }
- else if (msg.error)
- {
- if (callback.error) callback.error(msg.error.errResp);
- }
- else if (callback.callback)
- {
- callback.callback.apply(this, msg.resp);
- }
-
- this.remoteInvokeCallbacks[msgMarkers.callbackId] = null; //set it to null only to keep the index
- };
- EditorUi.prototype.remoteInvoke = function(remoteFn, remoteFnArgs, msgMarkers, callback, error)
- {
- var acceptResponse = true;
-
- var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
- {
- acceptResponse = false;
- error({code: App.ERROR_TIMEOUT, message: mxResources.get('timeout')});
- }), this.timeout);
- var wrapper = mxUtils.bind(this, function()
- {
- window.clearTimeout(timeoutThread);
-
- if (acceptResponse)
- {
- callback.apply(this, arguments);
- }
- });
-
- var errWrapper = mxUtils.bind(this, function()
- {
- window.clearTimeout(timeoutThread);
-
- if (acceptResponse)
- {
- error.apply(this, arguments);
- }
- });
-
- msgMarkers = msgMarkers || {};
- msgMarkers.callbackId = this.remoteInvokeCallbacks.length;
- this.remoteInvokeCallbacks.push({callback: wrapper, error: errWrapper});
- var msg = JSON.stringify({event: 'remoteInvoke', funtionName: remoteFn, functionArgs: remoteFnArgs, msgMarkers: msgMarkers});
-
- if (this.remoteWin != null) //remote invoke is ready
- {
- this.remoteWin.postMessage(msg, '*');
- }
- else
- {
- this.remoteInvokeQueue.push(msg);
- }
- };
- EditorUi.prototype.handleRemoteInvoke = function(msg, origin)
- {
- var sendResponse = mxUtils.bind(this, function(resp, error)
- {
- var respMsg = {event: 'remoteInvokeResponse', msgMarkers: msg.msgMarkers};
-
- if (error != null)
- {
- respMsg.error = {errResp: error};
- }
- else if (resp != null)
- {
- respMsg.resp = resp;
- }
-
- this.remoteWin.postMessage(JSON.stringify(respMsg), '*');
- });
-
- try
- {
- //Remote invoke are allowed to call functions in AC
- var funtionName = msg.funtionName;
- var functionInfo = this.remoteInvokableFns[funtionName];
-
- if (functionInfo != null && typeof this[funtionName] === 'function')
- {
- if (functionInfo.allowedDomains)
- {
- var allowed = false;
-
- for (var i = 0; i < functionInfo.allowedDomains.length; i++)
- {
- if (origin == 'https://' + functionInfo.allowedDomains[i])
- {
- allowed = true;
- break;
- }
- }
-
- if (!allowed)
- {
- sendResponse(null, 'Invalid Call: ' + funtionName + ' is not allowed.');
- return;
- }
- }
-
- var functionArgs = msg.functionArgs;
-
- //Confirm functionArgs are not null and is array, otherwise, discard it
- if (!Array.isArray(functionArgs))
- {
- functionArgs = [];
- }
-
- //for functions with callbacks (async) we assume last two arguments are success, error
- if (functionInfo.isAsync)
- {
- //success
- functionArgs.push(function()
- {
- sendResponse(Array.prototype.slice.apply(arguments));
- });
-
- //error
- functionArgs.push(function(err)
- {
- sendResponse(null, err || 'Unkown Error');
- });
-
- this[funtionName].apply(this, functionArgs);
- }
- else
- {
- var resp = this[funtionName].apply(this, functionArgs);
-
- sendResponse([resp]);
- }
- }
- else
- {
- sendResponse(null, 'Invalid Call: ' + funtionName + ' is not found.');
- }
- }
- catch(e)
- {
- sendResponse(null, 'Invalid Call: An error occured, ' + e.message);
- }
- };
-
- /**
- * Opens the application keystore.
- */
- EditorUi.prototype.openDatabase = function(success, error)
- {
- if (this.database == null)
- {
- var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB;
-
- if (indexedDB != null)
- {
- try
- {
- var req = indexedDB.open('database', 2);
-
- req.onupgradeneeded = function(e)
- {
- try
- {
- var db = req.result;
-
- if (e.oldVersion < 1)
- {
- // Version 1 is the first version of the database.
- db.createObjectStore('objects', {keyPath: 'key'});
- }
-
- if (e.oldVersion < 2)
- {
- // Version 2 introduces browser file storage.
- db.createObjectStore('files', {keyPath: 'title'});
- db.createObjectStore('filesInfo', {keyPath: 'title'});
- EditorUi.migrateStorageFiles = isLocalStorage;
- }
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }
-
- req.onsuccess = mxUtils.bind(this, function(e)
- {
- var db = req.result;
- this.database = db;
-
- if (EditorUi.migrateStorageFiles)
- {
- StorageFile.migrate(db);
- EditorUi.migrateStorageFiles = false;
- }
- if (location.host == 'app.diagrams.net' && !this.drawioMigrationStarted)
- {
- this.drawioMigrationStarted = true;
-
- this.getDatabaseItem('.drawioMigrated3', mxUtils.bind(this, function(value)
- {
- if (value && urlParams['forceMigration'] != '1') //Already migrated
- {
- return;
- }
-
- var drawioFrame = document.createElement('iframe');
- drawioFrame.style.display = 'none';
- drawioFrame.setAttribute('src', 'https://www.draw.io?embed=1&proto=json&forceMigration=' + urlParams['forceMigration']);
- document.body.appendChild(drawioFrame);
- var collectNames = true, allDone = false;
- var fileNames, index = 0;
-
- var markAsMigrated = mxUtils.bind(this, function()
- {
- allDone = true;
- this.setDatabaseItem('.drawioMigrated3', true);
- drawioFrame.contentWindow.postMessage(JSON.stringify({action: 'remoteInvoke', funtionName: 'setMigratedFlag'}), '*');
- });
-
- var next = mxUtils.bind(this, function()
- {
- index++;
- fetchOneFile();
- });
-
- var fetchOneFile = mxUtils.bind(this, function()
- {
- try
- {
- if (index >= fileNames.length)
- {
- markAsMigrated();
- return;
- }
-
- var fileTitle = fileNames[index];
-
- StorageFile.getFileContent(this, fileTitle, mxUtils.bind(this, function(data)
- {
- if (data == null || (fileTitle == '.scratchpad' && data == this.emptyLibraryXml)) //Don't overwrite
- {
- drawioFrame.contentWindow.postMessage(JSON.stringify({action: 'remoteInvoke', funtionName: 'getLocalStorageFile', functionArgs: [fileTitle]}), '*');
- }
- else
- {
- next();
- }
- }), next); //Ignore errors
- }
- catch(e)
- {
- //Log error
- console.log(e);
- }
- });
-
- var importOneFile = mxUtils.bind(this, function(file)
- {
- try
- {
- this.setDatabaseItem(null, [{
- title: file.title,
- size: file.data.length,
- lastModified: Date.now(),
- type: file.isLib? 'L' : 'F'
- }, {
- title: file.title,
- data: file.data
- }], next, next /* Ignore errors */, ['filesInfo', 'files']);
- }
- catch(e)
- {
- //Log error
- console.log(e);
- }
- });
-
- var messageListener = mxUtils.bind(this, function(evt)
- {
- try
- {
- //Only accept messages from migration iframe
- if (evt.source != drawioFrame.contentWindow)
- {
- return;
- }
-
- var drawMsg = {};
-
- try
- {
- drawMsg = JSON.parse(evt.data);
- }
- catch(e){} //Ignore
-
- if (drawMsg.event == 'init')
- {
- drawioFrame.contentWindow.postMessage(JSON.stringify({action: 'remoteInvokeReady'}), '*');
- drawioFrame.contentWindow.postMessage(JSON.stringify({action: 'remoteInvoke', funtionName: 'getLocalStorageFileNames'}), '*');
- }
- else if (drawMsg.event == 'remoteInvokeResponse' && !allDone)
- {
- if (collectNames)
- {
- if (drawMsg.resp != null && drawMsg.resp.length > 0 && drawMsg.resp[0] != null)
- {
- fileNames = drawMsg.resp[0];
- collectNames = false;
- fetchOneFile();
- }
- else
- {
- //Nothing in draw.io localStorage
- markAsMigrated();
- }
- }
- else
- {
- //Add the file, then move to the next
- if (drawMsg.resp != null && drawMsg.resp.length > 0 && drawMsg.resp[0] != null)
- {
- importOneFile(drawMsg.resp[0]);
- }
- else
- {
- next();
- }
- }
- }
- }
- catch(e)
- {
- console.log(e);
- }
- });
-
- window.addEventListener('message', messageListener);
- })); //Ignore errors
- }
-
- success(db);
-
- db.onversionchange = function()
- {
- //TODO Handle DB revision update while code is running
- // Save open file and request a page reload before closing the DB
- db.close();
- };
- });
-
- req.onerror = error;
-
- req.onblocked = function()
- {
- //TODO Use this when a new version is introduced
- // there's another open connection to same database
- // and it wasn't closed after db.onversionchange triggered for them
- };
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }
- else if (error != null)
- {
- error();
- }
- }
- else
- {
- success(this.database);
- }
- };
-
- /**
- * Add/Update item(s) in the database. It supports multiple stores transactions by sending an array of data, storeName
- * (key is optional, can be an array also if multiple stores are needed)
- */
- EditorUi.prototype.setDatabaseItem = function(key, data, success, error, storeName)
- {
- this.openDatabase(mxUtils.bind(this, function(db)
- {
- try
- {
- storeName = storeName || 'objects';
-
- if (!Array.isArray(storeName))
- {
- storeName = [storeName];
- key = [key];
- data = [data];
- }
-
- var trx = db.transaction(storeName, 'readwrite');
- trx.oncomplete = success;
- trx.onerror = error;
-
- for (var i = 0; i < storeName.length; i++)
- {
- trx.objectStore(storeName[i]).put(key != null && key[i] != null? {key: key[i], data: data[i]} : data[i]);
- }
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }), error);
- };
- /**
- * Removes the item for the given key from the database.
- */
- EditorUi.prototype.removeDatabaseItem = function(key, success, error, storeName)
- {
- this.openDatabase(mxUtils.bind(this, function(db)
- {
- storeName = storeName || 'objects';
-
- if (!Array.isArray(storeName))
- {
- storeName = [storeName];
- key = [key];
- }
-
- var trx = db.transaction(storeName, 'readwrite');
- trx.oncomplete = success;
- trx.onerror = error;
-
- for (var i = 0; i < storeName.length; i++)
- {
- trx.objectStore(storeName[i]).delete(key[i]);
- }
- }), error);
- };
-
- /**
- * Returns one item from the database.
- */
- EditorUi.prototype.getDatabaseItem = function(key, success, error, storeName)
- {
- this.openDatabase(mxUtils.bind(this, function(db)
- {
- try
- {
- storeName = storeName || 'objects';
- var trx = db.transaction([storeName], 'readonly');
- var req = trx.objectStore(storeName).get(key);
-
- req.onsuccess = function()
- {
- success(req.result);
- };
-
- req.onerror = error;
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }), error);
- };
-
- /**
- * Returns all items from the database.
- */
- EditorUi.prototype.getDatabaseItems = function(success, error, storeName)
- {
- this.openDatabase(mxUtils.bind(this, function(db)
- {
- try
- {
- storeName = storeName || 'objects';
- var trx = db.transaction([storeName], 'readonly');
- var req = trx.objectStore(storeName).openCursor(
- IDBKeyRange.lowerBound(0));
- var items = [];
-
- req.onsuccess = function(e)
- {
- if (e.target.result == null)
- {
- success(items);
- }
- else
- {
- items.push(e.target.result.value);
- e.target.result.continue();
- }
- };
-
- req.onerror = error;
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }), error);
- };
-
- /**
- * Returns all item keys from the database.
- */
- EditorUi.prototype.getDatabaseItemKeys = function(success, error, storeName)
- {
- this.openDatabase(mxUtils.bind(this, function(db)
- {
- try
- {
- storeName = storeName || 'objects';
- var trx = db.transaction([storeName], 'readonly');
- var req = trx.objectStore(storeName).getAllKeys();
-
- req.onsuccess = function()
- {
- success(req.result);
- };
-
- req.onerror = error;
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }), error);
- };
- /**
- * Comments: We need these functions as wrapper of File functions in order to facilitate
- * overriding them if comments are needed without having a file (e.g. Confluence Plugin)
- */
-
- /**
- * Are comments supported
- */
- EditorUi.prototype.commentsSupported = function()
- {
- var file = this.getCurrentFile();
-
- return file != null? file.commentsSupported() : false;
- };
- /**
- * Show refresh button?
- */
- EditorUi.prototype.commentsRefreshNeeded = function()
- {
- var file = this.getCurrentFile();
-
- return file != null? file.commentsRefreshNeeded() : true;
- };
-
- /**
- * Show save button?
- */
- EditorUi.prototype.commentsSaveNeeded = function()
- {
- var file = this.getCurrentFile();
- return file != null? file.commentsSaveNeeded() : false;
- };
-
- /**
- * Get comments
- */
- EditorUi.prototype.getComments = function(success, error)
- {
- var file = this.getCurrentFile();
-
- if (file != null)
- {
- file.getComments(success, error);
- }
- else
- {
- success([]); //placeholder
- }
- };
- /**
- * Add a comment
- */
- EditorUi.prototype.addComment = function(comment, success, error)
- {
- var file = this.getCurrentFile();
-
- if (file != null)
- {
- file.addComment(comment, success, error);
- }
- else
- {
- success(Date.now()); //placeholder
- }
- };
- /**
- * Can add a reply to a reply
- */
- EditorUi.prototype.canReplyToReplies = function()
- {
- var file = this.getCurrentFile();
-
- return file != null? file.canReplyToReplies() : true;
- };
- /**
- * Can add comments (The permission to comment)
- */
- EditorUi.prototype.canComment = function()
- {
- var file = this.getCurrentFile();
-
- return file != null? file.canComment() : true;
- };
- /**
- * Get a new comment object
- */
- EditorUi.prototype.newComment = function(content, user)
- {
- var file = this.getCurrentFile();
-
- if (file != null)
- {
- return file.newComment(content, user)
- }
- else
- {
- return new DrawioComment(this, null, content, Date.now(), Date.now(), false, user);
- }
- };
-
- //==================================================== End of comments =================================================================
-
- /**
- * Does revisions history available
- */
- EditorUi.prototype.isRevisionHistorySupported = function()
- {
- var file = this.getCurrentFile();
-
- return file != null && file.isRevisionHistorySupported();
- };
- /**
- * Get revisions of current file
- */
- EditorUi.prototype.getRevisions = function(success, error)
- {
- var file = this.getCurrentFile();
-
- if (file != null && file.getRevisions)
- {
- file.getRevisions(success, error);
- }
- else
- {
- error({message: mxResources.get('unknownError')});
- }
- };
-
- /**
- * Is revisions history enabled
- */
- EditorUi.prototype.isRevisionHistoryEnabled = function()
- {
- var file = this.getCurrentFile();
-
- return file != null &&
- ((file.constructor == DriveFile && file.isEditable()) ||
- file.constructor == DropboxFile);
- };
-
- //===========Adding methods to find the service running draw.io and allowing calling draw.io remote services
- EditorUi.prototype.getServiceName = function()
- {
- return 'draw.io';
- };
-
- EditorUi.prototype.addRemoteServiceSecurityCheck = function(xhr)
- {
- //Using a standard header with specific sequence
- xhr.setRequestHeader('Content-Language', 'da, mi, en, de-DE');
- };
-
- //===========To Be Removed Soon==========
- EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix, noBinary, headers)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: loadUrl');
- return this.editor.loadUrl(url, success, error, forceBinary, retry, dataUriPrefix, noBinary, headers);
- };
-
- EditorUi.prototype.loadFonts = function(then)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: loadFonts');
- return this.editor.loadFonts(then);
- };
-
- EditorUi.prototype.createSvgDataUri = function(svg)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: createSvgDataUri');
- return Editor.createSvgDataUri(svg);
- };
-
- EditorUi.prototype.embedCssFonts = function(fontCss, then)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: embedCssFonts');
- return this.editor.embedCssFonts(fontCss, then);
- };
-
- EditorUi.prototype.embedExtFonts = function(callback)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: embedExtFonts');
- return this.editor.embedExtFonts(callback);
- };
-
- EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
- ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop, grid, keepTheme)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: exportToCanvas');
- return this.editor.exportToCanvas(callback, width, imageCache, background, error, limitHeight,
- ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border,
- noCrop, grid, keepTheme);
- };
-
- EditorUi.prototype.createImageUrlConverter = function()
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: createImageUrlConverter');
- return this.editor.createImageUrlConverter();
- };
-
- EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: convertImages');
- return this.editor.convertImages(svgRoot, callback, imageCache, converter);
- };
-
- EditorUi.prototype.convertImageToDataUri = function(url, callback)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: convertImageToDataUri');
- return this.editor.convertImageToDataUri(url, callback);
- };
-
- EditorUi.prototype.base64Encode = function(str)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: base64Encode');
- return Editor.base64Encode(str);
- };
-
- EditorUi.prototype.updateCRC = function(crc, data, off, len)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: updateCRC');
- return Editor.updateCRC(crc, data, off, len);
- };
-
- EditorUi.prototype.crc32 = function(str)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: crc32');
- return Editor.crc32(str);
- };
-
- EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
- {
- EditorUi.logEvent('SHOULD NOT BE CALLED: writeGraphModelToPng');
- return Editor.writeGraphModelToPng(data, type, key, value, error);
- };
-
- //=======End of To Be Removed Soon==========
-
- EditorUi.prototype.getLocalStorageFileNames = function()
- {
- if (localStorage.getItem('.localStorageMigrated') == '1' && urlParams['forceMigration'] != '1')
- {
- return null;
- }
-
- var files = [];
-
- for (var i = 0; i < localStorage.length; i++)
- {
- var key = localStorage.key(i);
- var value = localStorage.getItem(key);
-
- if (key.length > 0 && (key == '.scratchpad' || key.charAt(0) != '.') && value.length > 0)
- {
- var isFile = (value.substring(0, 8) === '<mxfile ' ||
- value.substring(0, 5) === '<?xml' || value.substring(0, 12) === '<!--[if IE]>');
- var isLib = (value.substring(0, 11) === '<mxlibrary>');
- if (isFile || isLib)
- {
- files.push(key);
- }
- }
- }
-
- return files;
- };
-
- EditorUi.prototype.getLocalStorageFile = function(key)
- {
- if (localStorage.getItem('.localStorageMigrated') == '1' && urlParams['forceMigration'] != '1')
- {
- return null;
- }
-
- var value = localStorage.getItem(key);
- return {title: key, data: value, isLib: value.substring(0, 11) === '<mxlibrary>'};
- };
-
- EditorUi.prototype.setMigratedFlag = function()
- {
- localStorage.setItem('.localStorageMigrated', '1');
- };
- })();
- /**
- * Comments Window, It is used by both editor and viewer. So, it is here in a common place
- */
- var CommentsWindow = function(editorUi, x, y, w, h, saveCallback)
- {
- var readOnly = !editorUi.canComment();
- var canReplyToReplies = editorUi.canReplyToReplies();
- var curEdited = null;
-
- var div = document.createElement('div');
- div.className = 'geCommentsWin';
- div.style.background = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
- var tbarHeight = (!EditorUi.compactUi) ? '30px' : '26px';
-
- var listDiv = document.createElement('div');
- listDiv.className = 'geCommentsList';
- listDiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
- listDiv.style.bottom = (parseInt(tbarHeight) + 7) + 'px';
- div.appendChild(listDiv);
-
- var noComments = document.createElement('span');
- noComments.style.cssText = 'display:none;padding-top:10px;text-align:center;';
- mxUtils.write(noComments, mxResources.get('noCommentsFound'));
-
- var selectionComment = null;
-
- var ldiv = document.createElement('div');
-
- ldiv.className = 'geToolbarContainer geCommentsToolbar';
- ldiv.style.height = tbarHeight;
- ldiv.style.padding = (!EditorUi.compactUi) ? '1px' : '4px 0px 3px 0px';
- ldiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
-
- var link = document.createElement('a');
- link.className = 'geButton';
-
- function updateNoComments()
- {
- var divs = listDiv.getElementsByTagName('div');
- var visibleCount = 0;
-
- for (var i = 0; i < divs.length; i++)
- {
- if (divs[i].style.display != 'none' && divs[i].parentNode == listDiv)
- {
- visibleCount++;
- }
- }
-
- noComments.style.display = (visibleCount == 0) ? 'block' : 'none';
- };
-
- function editComment(comment, cdiv, saveCallback, deleteOnCancel)
- {
- curEdited = {div: cdiv, comment: comment, saveCallback: saveCallback, deleteOnCancel: deleteOnCancel};
-
- var commentTxt = cdiv.querySelector('.geCommentTxt');
- var actionsDiv = cdiv.querySelector('.geCommentActionsList');
-
- var textArea = document.createElement('textarea');
- textArea.className = 'geCommentEditTxtArea';
- textArea.style.minHeight = commentTxt.offsetHeight + 'px';
- textArea.value = comment.content;
- cdiv.insertBefore(textArea, commentTxt);
-
- var btnDiv = document.createElement('div');
- btnDiv.className = 'geCommentEditBtns';
-
- function reset()
- {
- cdiv.removeChild(textArea);
- cdiv.removeChild(btnDiv);
- actionsDiv.style.display = 'block';
- commentTxt.style.display = 'block';
- };
-
- var cancelBtn = mxUtils.button(mxResources.get('cancel'), function()
- {
- if (deleteOnCancel)
- {
- cdiv.parentNode.removeChild(cdiv);
- updateNoComments();
- }
- else
- {
- reset();
- }
-
- curEdited = null;
- });
-
- cancelBtn.className = 'geCommentEditBtn';
- btnDiv.appendChild(cancelBtn);
-
- var saveBtn = mxUtils.button(mxResources.get('save'), function()
- {
- commentTxt.innerHTML = '';
- comment.content = textArea.value;
- mxUtils.write(commentTxt, comment.content);
- reset();
- saveCallback(comment);
- curEdited = null;
- });
-
- // Updates modified state and handles placeholder text
- mxEvent.addListener(textArea, 'keydown', mxUtils.bind(this, function(evt)
- {
- if (!mxEvent.isConsumed(evt))
- {
- if ((mxEvent.isControlDown(evt) || (mxClient.IS_MAC &&
- mxEvent.isMetaDown(evt))) && evt.keyCode == 13 /* Ctrl+Enter */)
- {
- saveBtn.click();
- mxEvent.consume(evt);
- }
- else if (evt.keyCode == 27 /* Escape */)
- {
- cancelBtn.click();
- mxEvent.consume(evt);
- }
- }
- }));
-
- // Focused to include in viewport before focusin textbox
- saveBtn.focus();
- saveBtn.className = 'geCommentEditBtn gePrimaryBtn';
- btnDiv.appendChild(saveBtn);
- cdiv.insertBefore(btnDiv, commentTxt);
- actionsDiv.style.display = 'none';
- commentTxt.style.display = 'none';
- textArea.focus();
- };
-
- function writeCommentDate(comment, dateDiv)
- {
- dateDiv.innerHTML = '';
- var ts = new Date(comment.modifiedDate);
- var str = editorUi.timeSince(ts);
-
- if (str == null)
- {
- str = mxResources.get('lessThanAMinute');
- }
-
- mxUtils.write(dateDiv, mxResources.get('timeAgo', [str], '{1} ago'));
- dateDiv.setAttribute('title', ts.toLocaleDateString() + ' ' +
- ts.toLocaleTimeString());
- };
-
- function showBusy(commentDiv)
- {
- var busyImg = document.createElement('img');
- busyImg.className = 'geCommentBusyImg';
- busyImg.src= IMAGE_PATH + '/spin.gif';
- commentDiv.appendChild(busyImg);
- commentDiv.busyImg = busyImg;
- };
-
- function showError(commentDiv)
- {
- commentDiv.style.border = '1px solid red';
- commentDiv.removeChild(commentDiv.busyImg);
- };
-
- function showDone(commentDiv)
- {
- commentDiv.style.border = '';
- commentDiv.removeChild(commentDiv.busyImg);
- };
- function addComment(comment, parentArr, parent, level, showResolved)
- {
- //Skip resolved comments if showResolved is not set
- if (!showResolved && comment.isResolved)
- {
- return;
- }
- noComments.style.display = 'none';
-
- var cdiv = document.createElement('div');
- cdiv.className = 'geCommentContainer';
- cdiv.setAttribute('data-commentId', comment.id);
- cdiv.style.marginLeft = (level * 20 + 5) + 'px';
- if (comment.isResolved && !Editor.isDarkMode())
- {
- cdiv.style.backgroundColor = 'ghostWhite';
- }
-
- var headerDiv = document.createElement('div');
- headerDiv.className = 'geCommentHeader';
-
- var userImg = document.createElement('img');
- userImg.className = 'geCommentUserImg';
- userImg.src = comment.user.pictureUrl || Editor.userImage;
- headerDiv.appendChild(userImg);
-
- var headerTxt = document.createElement('div');
- headerTxt.className = 'geCommentHeaderTxt';
- headerDiv.appendChild(headerTxt);
-
- var usernameDiv = document.createElement('div');
- usernameDiv.className = 'geCommentUsername';
- mxUtils.write(usernameDiv, comment.user.displayName || '');
- headerTxt.appendChild(usernameDiv);
-
- var dateDiv = document.createElement('div');
- dateDiv.className = 'geCommentDate';
- dateDiv.setAttribute('data-commentId', comment.id);
- writeCommentDate(comment, dateDiv);
- headerTxt.appendChild(dateDiv);
- cdiv.appendChild(headerDiv);
-
- var commentTxtDiv = document.createElement('div');
- commentTxtDiv.className = 'geCommentTxt';
- mxUtils.write(commentTxtDiv, comment.content || '');
- cdiv.appendChild(commentTxtDiv);
-
- if (comment.isLocked)
- {
- cdiv.style.opacity = '0.5';
- }
-
- var actionsDiv = document.createElement('div');
- actionsDiv.className = 'geCommentActions';
- var actionsList = document.createElement('ul');
- actionsList.className = 'geCommentActionsList';
- actionsDiv.appendChild(actionsList);
-
- function addAction(name, evtHandler, hide)
- {
- var action = document.createElement('li');
- action.className = 'geCommentAction';
- var actionLnk = document.createElement('a');
- actionLnk.className = 'geCommentActionLnk';
- mxUtils.write(actionLnk, name);
- action.appendChild(actionLnk);
-
- mxEvent.addListener(actionLnk, 'click', function(evt)
- {
- evtHandler(evt, comment);
- evt.preventDefault();
- mxEvent.consume(evt);
- });
-
- actionsList.appendChild(action);
-
- if (hide) action.style.display = 'none';
- };
-
- function collectReplies()
- {
- var replies = [];
- var pdiv = cdiv;
-
- function collectReplies(comment)
- {
- replies.push(pdiv);
-
- if (comment.replies != null)
- {
- for (var i = 0; i < comment.replies.length; i++)
- {
- pdiv = pdiv.nextSibling;
- collectReplies(comment.replies[i]);
- }
- }
- }
-
- collectReplies(comment);
-
- return {pdiv: pdiv, replies: replies};
- };
-
- function addReply(initContent, editIt, saveCallback, doResolve, doReopen)
- {
- var pdiv = collectReplies().pdiv;
-
- var newReply = editorUi.newComment(initContent, editorUi.getCurrentUser());
- newReply.pCommentId = comment.id;
-
- if (comment.replies == null) comment.replies = [];
-
- var replyComment = addComment(newReply, comment.replies, pdiv, level + 1);
- function doAddReply()
- {
- showBusy(replyComment);
-
- comment.addReply(newReply, function(id)
- {
- newReply.id = id;
- comment.replies.push(newReply);
- showDone(replyComment);
-
- if (saveCallback) saveCallback();
-
- }, function(err)
- {
- doEdit();
- showError(replyComment);
- editorUi.handleError(err, null, null, null,
- mxUtils.htmlEntities(mxResources.get('objectNotFound')));
- }, doResolve, doReopen);
- };
-
- function doEdit()
- {
- editComment(newReply, replyComment, function(newReply)
- {
- doAddReply();
- }, true);
- };
- if (editIt)
- {
- doEdit();
- }
- else
- {
- doAddReply();
- }
- };
-
- if (!readOnly && !comment.isLocked && (level == 0 || canReplyToReplies))
- {
- addAction(mxResources.get('reply'), function()
- {
- addReply('', true);
- }, comment.isResolved);
- }
-
- var user = editorUi.getCurrentUser();
-
- if (user != null && user.id == comment.user.id && !readOnly && !comment.isLocked)
- {
- addAction(mxResources.get('edit'), function()
- {
- function doEditComment()
- {
- editComment(comment, cdiv, function()
- {
- showBusy(cdiv);
-
- comment.editComment(comment.content, function()
- {
- showDone(cdiv);
- }, function(err)
- {
- showError(cdiv);
- doEditComment();
- editorUi.handleError(err, null, null, null,
- mxUtils.htmlEntities(mxResources.get('objectNotFound')));
- });
- });
- };
-
- doEditComment();
- }, comment.isResolved);
-
- addAction(mxResources.get('delete'), function()
- {
- editorUi.confirm(mxResources.get('areYouSure'), function()
- {
- showBusy(cdiv);
-
- comment.deleteComment(function(markedOnly)
- {
- if (markedOnly === true)
- {
- var commentTxt = cdiv.querySelector('.geCommentTxt');
- commentTxt.innerHTML = '';
- mxUtils.write(commentTxt, mxResources.get('msgDeleted'));
-
- var actions = cdiv.querySelectorAll('.geCommentAction');
-
- for (var i = 0; i < actions.length; i++)
- {
- actions[i].parentNode.removeChild(actions[i]);
- }
-
- showDone(cdiv);
- cdiv.style.opacity = '0.5';
- }
- else
- {
- var replies = collectReplies(comment).replies;
-
- for (var i = 0; i < replies.length; i++)
- {
- listDiv.removeChild(replies[i]);
- }
-
- for (var i = 0; i < parentArr.length; i++)
- {
- if (parentArr[i] == comment)
- {
- parentArr.splice(i, 1);
- break;
- }
- }
-
- noComments.style.display = (listDiv.getElementsByTagName('div').length == 0) ? 'block' : 'none';
- }
- }, function(err)
- {
- showError(cdiv);
- editorUi.handleError(err, null, null, null,
- mxUtils.htmlEntities(mxResources.get('objectNotFound')));
- });
- });
- }, comment.isResolved);
- }
-
- if (!readOnly && !comment.isLocked && level == 0) //Resolve is a top-level action only
- {
- function toggleResolve(evt)
- {
- function doToggle()
- {
- var resolveActionLnk = evt.target;
- resolveActionLnk.innerHTML = '';
- comment.isResolved = !comment.isResolved;
- mxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));
- var actionsDisplay = comment.isResolved? 'none' : '';
- var replies = collectReplies(comment).replies;
- var color = (Editor.isDarkMode()) ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');
-
- for (var i = 0; i < replies.length; i++)
- {
- replies[i].style.backgroundColor = color;
-
- var forOpenActions = replies[i].querySelectorAll('.geCommentAction');
-
- for (var j = 0; j < forOpenActions.length; j ++)
- {
- if (forOpenActions[j] == resolveActionLnk.parentNode) continue;
-
- forOpenActions[j].style.display = actionsDisplay;
- }
- if (!resolvedChecked)
- {
- replies[i].style.display = 'none';
- }
- }
-
- updateNoComments();
- };
-
- if (comment.isResolved)
- {
- addReply(mxResources.get('reOpened') + ': ', true, doToggle, false, true);
- }
- else
- {
- addReply(mxResources.get('markedAsResolved'), false, doToggle, true);
- }
- };
-
- addAction(comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'), toggleResolve);
- }
-
- cdiv.appendChild(actionsDiv);
-
- if (parent != null)
- {
- listDiv.insertBefore(cdiv, parent.nextSibling);
- }
- else
- {
- listDiv.appendChild(cdiv);
- }
-
- for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
- {
- var reply = comment.replies[i];
- reply.isResolved = comment.isResolved; //copy isResolved to child comments (replies)
- addComment(reply, comment.replies, null, level + 1, showResolved);
- }
-
- if (curEdited != null)
- {
- if (curEdited.comment.id == comment.id)
- {
- var origContent = comment.content;
- comment.content = curEdited.comment.content;
- editComment(comment, cdiv, curEdited.saveCallback, curEdited.deleteOnCancel);
- comment.content = origContent;
- }
- else if (curEdited.comment.id == null && curEdited.comment.pCommentId == comment.id)
- {
- listDiv.appendChild(curEdited.div);
- editComment(curEdited.comment, curEdited.div, curEdited.saveCallback, curEdited.deleteOnCancel);
- }
- }
- return cdiv;
- };
- if (!readOnly)
- {
- var addLink = link.cloneNode();
- addLink.innerHTML = '<div class="geSprite geSprite-plus" style="display:inline-block;"></div>';
- addLink.setAttribute('title', mxResources.get('create') + '...');
-
- mxEvent.addListener(addLink, 'click', function(evt)
- {
- var newComment = editorUi.newComment('', editorUi.getCurrentUser());
- var newCommentDiv = addComment(newComment, comments, null, 0);
-
- function doAddComment()
- {
- editComment(newComment, newCommentDiv, function(newComment)
- {
- showBusy(newCommentDiv);
-
- editorUi.addComment(newComment, function(id)
- {
- newComment.id = id;
- comments.push(newComment);
- showDone(newCommentDiv);
- }, function(err)
- {
- showError(newCommentDiv);
- doAddComment();
- editorUi.handleError(err, null, null, null,
- mxUtils.htmlEntities(mxResources.get('objectNotFound')));
- });
- }, true);
- }
-
- doAddComment();
- evt.preventDefault();
- mxEvent.consume(evt);
- });
-
- ldiv.appendChild(addLink);
- }
- var resolvedLink = link.cloneNode();
- resolvedLink.innerHTML = '<img src="' + IMAGE_PATH + '/check.png" style="width: 16px; padding: 2px;">';
- resolvedLink.setAttribute('title', mxResources.get('showResolved'));
- var resolvedChecked = false;
-
- if (Editor.isDarkMode())
- {
- resolvedLink.style.filter = 'invert(100%)';
- }
-
- mxEvent.addListener(resolvedLink, 'click', function(evt)
- {
- resolvedChecked = !resolvedChecked;
-
- this.className = resolvedChecked? 'geButton geCheckedBtn' : 'geButton';
- refresh();
-
- evt.preventDefault();
- mxEvent.consume(evt);
- });
-
- ldiv.appendChild(resolvedLink);
-
- if (editorUi.commentsRefreshNeeded())
- {
- var refreshLink = link.cloneNode();
- refreshLink.innerHTML = '<img src="' + IMAGE_PATH + '/update16.png" style="width: 16px; padding: 2px;">';
- refreshLink.setAttribute('title', mxResources.get('refresh'));
-
- if (Editor.isDarkMode())
- {
- refreshLink.style.filter = 'invert(100%)';
- }
-
- mxEvent.addListener(refreshLink, 'click', function(evt)
- {
- refresh();
-
- evt.preventDefault();
- mxEvent.consume(evt);
- });
-
- ldiv.appendChild(refreshLink);
- }
-
- if (editorUi.commentsSaveNeeded())
- {
- var saveLink = link.cloneNode();
- saveLink.innerHTML = '<img src="' + IMAGE_PATH + '/save.png" style="width: 20px; padding: 2px;">';
- saveLink.setAttribute('title', mxResources.get('save'));
-
- if (Editor.isDarkMode())
- {
- saveLink.style.filter = 'invert(100%)';
- }
-
- mxEvent.addListener(saveLink, 'click', function(evt)
- {
- saveCallback();
-
- evt.preventDefault();
- mxEvent.consume(evt);
- });
-
- ldiv.appendChild(saveLink);
- }
- div.appendChild(ldiv);
- var comments = [];
- var refresh = mxUtils.bind(this, function()
- {
- this.hasError = false;
-
- if (curEdited != null)
- {
- try
- {
- curEdited.div = curEdited.div.cloneNode(true);
- var commentEditTxt = curEdited.div.querySelector('.geCommentEditTxtArea');
- var commentEditBtns = curEdited.div.querySelector('.geCommentEditBtns');
-
- curEdited.comment.content = commentEditTxt.value;
- commentEditTxt.parentNode.removeChild(commentEditTxt);
- commentEditBtns.parentNode.removeChild(commentEditBtns);
- }
- catch (e)
- {
- editorUi.handleError(e);
- }
- }
-
- listDiv.innerHTML = '<div style="padding-top:10px;text-align:center;"><img src="' + IMAGE_PATH + '/spin.gif" valign="middle"> ' +
- mxUtils.htmlEntities(mxResources.get('loading')) + '...</div>';
-
- canReplyToReplies = editorUi.canReplyToReplies();
-
- if (editorUi.commentsSupported())
- {
- editorUi.getComments(function(list)
- {
- function sortReplies(replies)
- {
- if (replies != null)
- {
- //Sort replies old to new
- replies.sort(function(r1, r2)
- {
- return new Date(r1.modifiedDate) - new Date(r2.modifiedDate);
- });
-
- for (var i = 0; i < replies.length; i++)
- {
- sortReplies(replies[i].replies);
- }
- }
- };
-
- //Sort comments old to new
- list.sort(function(c1, c2)
- {
- return new Date(c1.modifiedDate) - new Date(c2.modifiedDate);
- });
- listDiv.innerHTML = '';
- listDiv.appendChild(noComments);
- noComments.style.display = 'block';
- comments = list;
-
- for (var i = 0; i < comments.length; i++)
- {
- sortReplies(comments[i].replies);
- addComment(comments[i], comments, null, 0, resolvedChecked);
- }
-
- //New comment case
- if (curEdited != null && curEdited.comment.id == null && curEdited.comment.pCommentId == null)
- {
- listDiv.appendChild(curEdited.div);
- editComment(curEdited.comment, curEdited.div, curEdited.saveCallback, curEdited.deleteOnCancel);
- }
-
- }, mxUtils.bind(this, function(err)
- {
- listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error') + (err && err.message? ': ' + err.message : ''));
- this.hasError = true;
- }));
- }
- else
- {
- //TODO if comments are not supported, close the dialog
- listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error'));
- }
- });
- refresh();
-
- this.refreshComments = refresh;
- //Refresh the modified date of each comment if the window is visible
- var refreshCommentsTime = mxUtils.bind(this, function()
- {
- if (!this.window.isVisible()) return; //only update if it is visible
-
- var modDateDivs = listDiv.querySelectorAll('.geCommentDate');
- var modDateDivsMap = {};
-
- for (var i = 0; i < modDateDivs.length; i++)
- {
- var div = modDateDivs[i];
- modDateDivsMap[div.getAttribute('data-commentId')] = div;
- }
-
- function processComment(comment)
- {
- var div = modDateDivsMap[comment.id];
-
- if (div == null) return; //resolved comments
-
- writeCommentDate(comment, div);
-
- for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
- {
- processComment(comment.replies[i]);
- }
- };
-
- for (var i = 0; i < comments.length; i++)
- {
- processComment(comments[i]);
- }
- });
- //Periodically refresh time every one minute
- setInterval(refreshCommentsTime, 60000);
- this.refreshCommentsTime = refreshCommentsTime;
-
- this.window = new mxWindow(mxResources.get('comments'), div, x, y, w, h, true, true);
- this.window.minimumSize = new mxRectangle(0, 0, 300, 200);
- this.window.destroyOnClose = false;
- this.window.setMaximizable(false);
- this.window.setResizable(true);
- this.window.setClosable(true);
- this.window.setVisible(true);
-
- this.window.addListener(mxEvent.SHOW, mxUtils.bind(this, function()
- {
- this.window.fit();
- }));
-
- this.window.setLocation = function(x, y)
- {
- var iw = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
- var ih = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
-
- x = Math.max(0, Math.min(x, iw - this.table.clientWidth));
- y = Math.max(0, Math.min(y, ih - this.table.clientHeight - 48));
- if (this.getX() != x || this.getY() != y)
- {
- mxWindow.prototype.setLocation.apply(this, arguments);
- }
- };
-
- var resizeListener = mxUtils.bind(this, function()
- {
- var x = this.window.getX();
- var y = this.window.getY();
-
- this.window.setLocation(x, y);
- });
-
- mxEvent.addListener(window, 'resize', resizeListener);
- this.destroy = function()
- {
- mxEvent.removeListener(window, 'resize', resizeListener);
- this.window.destroy();
- }
- };
- /**
- *
- */
- var ConfirmDialog = function(editorUi, message, okFn, cancelFn, okLabel, cancelLabel,
- okImg, cancelImg, showRememberOption, imgSrc, maxHeight)
- {
- var div = document.createElement('div');
- div.style.textAlign = 'center';
- maxHeight = (maxHeight != null) ? maxHeight : 44;
-
- var p2 = document.createElement('div');
- p2.style.padding = '6px';
- p2.style.overflow = 'auto';
- p2.style.maxHeight = maxHeight + 'px';
- p2.style.lineHeight = '1.2em';
-
- mxUtils.write(p2, message);
- div.appendChild(p2);
-
- if (imgSrc != null)
- {
- var p3 = document.createElement('div');
- p3.style.padding = '6px 0 6px 0';
- var img = document.createElement('img');
- img.setAttribute('src', imgSrc);
- p3.appendChild(img);
- div.appendChild(p3);
- }
-
- var btns = document.createElement('div');
- btns.style.textAlign = 'center';
- btns.style.whiteSpace = 'nowrap';
- var cb = document.createElement('input');
- cb.setAttribute('type', 'checkbox');
- var cancelBtn = mxUtils.button(cancelLabel || mxResources.get('cancel'), function()
- {
- editorUi.hideDialog();
-
- if (cancelFn != null)
- {
- cancelFn(cb.checked);
- }
- });
- cancelBtn.className = 'geBtn';
-
- if (cancelImg != null)
- {
- cancelBtn.innerHTML = cancelImg + '<br>' + cancelBtn.innerHTML;
- cancelBtn.style.paddingBottom = '8px';
- cancelBtn.style.paddingTop = '8px';
- cancelBtn.style.height = 'auto';
- cancelBtn.style.width = '40%';
- }
-
- if (editorUi.editor.cancelFirst)
- {
- btns.appendChild(cancelBtn);
- }
-
- var okBtn = mxUtils.button(okLabel || mxResources.get('ok'), function()
- {
- editorUi.hideDialog();
-
- if (okFn != null)
- {
- okFn(cb.checked);
- }
- });
- btns.appendChild(okBtn);
-
- if (okImg != null)
- {
- okBtn.innerHTML = okImg + '<br>' + okBtn.innerHTML + '<br>';
- okBtn.style.paddingBottom = '8px';
- okBtn.style.paddingTop = '8px';
- okBtn.style.height = 'auto';
- okBtn.className = 'geBtn';
- okBtn.style.width = '40%';
- }
- else
- {
- okBtn.className = 'geBtn gePrimaryBtn';
- }
-
- if (!editorUi.editor.cancelFirst)
- {
- btns.appendChild(cancelBtn);
- }
- div.appendChild(btns);
-
- if (showRememberOption)
- {
- btns.style.marginTop = '10px';
- var p2 = document.createElement('p');
- p2.style.marginTop = '20px';
- p2.style.marginBottom = '0px';
- p2.appendChild(cb);
- var span = document.createElement('span');
- mxUtils.write(span, ' ' + mxResources.get('rememberThisSetting'));
- p2.appendChild(span);
- div.appendChild(p2);
-
- mxEvent.addListener(span, 'click', function(evt)
- {
- cb.checked = !cb.checked;
- mxEvent.consume(evt);
- });
- }
- else
- {
- btns.style.marginTop = '12px';
- }
- this.init = function()
- {
- okBtn.focus();
- };
-
- this.container = div;
- };
|