EditorUi.js 243 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. (function()
  6. {
  7. /**
  8. * Version
  9. */
  10. EditorUi.VERSION = '@DRAWIO-VERSION@';
  11. /**
  12. * Overrides compact UI setting.
  13. */
  14. EditorUi.compactUi = uiTheme != 'atlas';
  15. /**
  16. * Switch to disable logging for mode and search terms.
  17. */
  18. EditorUi.enableLogging = /.*\.draw\.io$/.test(window.location.hostname);
  19. /**
  20. * https://github.com/electron/electron/issues/2288
  21. */
  22. EditorUi.isElectronApp = window != null && window.process != null &&
  23. window.process.versions != null && window.process.versions['electron'] != null;
  24. /**
  25. * Contains the default XML for an empty diagram.
  26. */
  27. EditorUi.prototype.emptyDiagramXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
  28. /**
  29. *
  30. */
  31. EditorUi.prototype.emptyLibraryXml = '<mxlibrary>[]</mxlibrary>';
  32. /**
  33. * Sets the delay for autosave in milliseconds. Default is 2000.
  34. */
  35. EditorUi.prototype.mode = null;
  36. /**
  37. * Allows for two buttons in the sidebar footer.
  38. */
  39. EditorUi.prototype.sidebarFooterHeight = 36;
  40. /**
  41. * Specifies the default custom shape style.
  42. */
  43. 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;';
  44. /**
  45. * Defines the maximum size for images.
  46. */
  47. EditorUi.prototype.maxBackgroundSize = 1600;
  48. /**
  49. * Defines the maximum size for images.
  50. */
  51. EditorUi.prototype.maxImageSize = 520;
  52. /**
  53. * Images above 100K should be resampled.
  54. */
  55. EditorUi.prototype.resampleThreshold = 100000;
  56. /**
  57. * Maximum allowed size for images is 1 MB.
  58. */
  59. EditorUi.prototype.maxImageBytes = 1000000;
  60. /**
  61. * Maximum size for background images is 2.5 MB.
  62. */
  63. EditorUi.prototype.maxBackgroundBytes = 2500000;
  64. /**
  65. * Holds the current file.
  66. */
  67. EditorUi.prototype.currentFile = null;
  68. /**
  69. * Specifies if PDF export should be done via print dialog. Default is
  70. * false which uses the PhantomJS backend to create the PDF.
  71. */
  72. EditorUi.prototype.printPdfExport = false;
  73. /**
  74. * Specifies if PDF export with pages is enabled.
  75. */
  76. EditorUi.prototype.pdfPageExport = true;
  77. /**
  78. * Restores app defaults for UI
  79. */
  80. EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
  81. /**
  82. * Capability check for canvas export
  83. */
  84. (function()
  85. {
  86. EditorUi.prototype.useCanvasForExport = false;
  87. EditorUi.prototype.jpgSupported = false;
  88. try
  89. {
  90. var canvas = document.createElement('canvas');
  91. var img = new Image();
  92. // LATER: Capability check should not be async
  93. img.onload = function()
  94. {
  95. try
  96. {
  97. var ctx = canvas.getContext('2d');
  98. ctx.drawImage(img, 0, 0);
  99. // Works in Chrome, Firefox, Edge and Opera
  100. // LATER: Fix security error caused by foreignObjects in Safari for toDataUri (tainted canvas)
  101. var result = canvas.toDataURL('image/png');
  102. EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
  103. }
  104. catch (e)
  105. {
  106. // ignore
  107. }
  108. };
  109. // Checks if SVG with foreignObject can be exported
  110. 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>';
  111. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  112. }
  113. catch (e)
  114. {
  115. // ignore
  116. }
  117. // Checks for client-side JPG support
  118. try
  119. {
  120. var canvas = document.createElement('canvas');
  121. canvas.width = canvas.height = 1;
  122. var uri = canvas.toDataURL('image/jpeg');
  123. EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
  124. }
  125. catch (e)
  126. {
  127. // ignore
  128. }
  129. })();
  130. /**
  131. * Abstraction for local storage access.
  132. */
  133. EditorUi.prototype.getLocalData = function(key, fn)
  134. {
  135. fn(localStorage.getItem(key));
  136. };
  137. /**
  138. * Abstraction for local storage access.
  139. */
  140. EditorUi.prototype.setLocalData = function(key, data, fn)
  141. {
  142. localStorage.setItem(key, data);
  143. fn();
  144. };
  145. /**
  146. * Abstraction for local storage access.
  147. */
  148. EditorUi.prototype.removeLocalData = function(key, fn)
  149. {
  150. localStorage.removeItem(key)
  151. fn();
  152. };
  153. EditorUi.prototype.setMathEnabled = function(value)
  154. {
  155. this.editor.graph.mathEnabled = value;
  156. this.editor.updateGraphComponents();
  157. this.editor.graph.refresh();
  158. this.fireEvent(new mxEventObject('mathEnabledChanged'));
  159. };
  160. EditorUi.prototype.isMathEnabled = function(value)
  161. {
  162. return this.editor.graph.mathEnabled;
  163. };
  164. // Helper method to move picket to top
  165. EditorUi.prototype.movePickersToTop = function()
  166. {
  167. var divs = document.getElementsByTagName('div');
  168. for (var i = 0; i < divs.length; i++)
  169. {
  170. if (divs[i].className == 'picker modal-dialog picker-dialog')
  171. {
  172. divs[i].style.zIndex = mxPopupMenu.prototype.zIndex + 1;
  173. }
  174. }
  175. };
  176. /**
  177. * Translates this point by the given vector.
  178. *
  179. * @param {number} dx X-coordinate of the translation.
  180. * @param {number} dy Y-coordinate of the translation.
  181. */
  182. EditorUi.prototype.isOfflineApp = function()
  183. {
  184. return (urlParams['offline'] == '1');
  185. };
  186. /**
  187. * Returns true if this offline app is offline.
  188. */
  189. EditorUi.prototype.isOffline = function()
  190. {
  191. // In FF navigator.onLine is always true
  192. return (mxClient.IS_FF && this.isOfflineApp()) || !navigator.onLine || urlParams['stealth'] == '1';
  193. };
  194. /**
  195. * Translates this point by the given vector.
  196. *
  197. * @param {number} dx X-coordinate of the translation.
  198. * @param {number} dy Y-coordinate of the translation.
  199. */
  200. EditorUi.prototype.createSpinner = function(x, y, size)
  201. {
  202. size = (size != null) ? size : 24;
  203. var spinner = new Spinner({
  204. lines: 12, // The number of lines to draw
  205. length: size, // The length of each line
  206. width: Math.round(size / 3), // The line thickness
  207. radius: Math.round(size / 2), // The radius of the inner circle
  208. rotate: 0, // The rotation offset
  209. color: '#000', // #rgb or #rrggbb
  210. speed: 1.5, // Rounds per second
  211. trail: 60, // Afterglow percentage
  212. shadow: false, // Whether to render a shadow
  213. hwaccel: false, // Whether to use hardware acceleration
  214. zIndex: 2e9 // The z-index (defaults to 2000000000)
  215. });
  216. // Extends spin method to include an optional label
  217. var oldSpin = spinner.spin;
  218. spinner.spin = function(container, label)
  219. {
  220. var result = false;
  221. if (!this.active)
  222. {
  223. oldSpin.call(this, container);
  224. this.active = true;
  225. if (label != null)
  226. {
  227. var status = document.createElement('div');
  228. status.style.position = 'absolute';
  229. status.style.whiteSpace = 'nowrap';
  230. status.style.background = '#4B4243';
  231. status.style.color = 'white';
  232. status.style.fontFamily = 'Helvetica, Arial';
  233. status.style.fontSize = '9pt';
  234. status.style.padding = '6px';
  235. status.style.paddingLeft = '10px';
  236. status.style.paddingRight = '10px';
  237. status.style.zIndex = 2e9;
  238. status.style.left = Math.max(0, x) + 'px';
  239. status.style.top = Math.max(0, y + 70) + 'px';
  240. mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
  241. mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
  242. mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
  243. status.innerHTML = label + '...';
  244. container.appendChild(status);
  245. spinner.status = status;
  246. // Centers the label in older IE versions
  247. if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
  248. {
  249. status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
  250. status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
  251. }
  252. }
  253. // Pause returns a function to resume the spinner
  254. this.pause = mxUtils.bind(this, function()
  255. {
  256. var fn = function() { };
  257. if (this.active)
  258. {
  259. fn = mxUtils.bind(this, function()
  260. {
  261. this.spin(container, label);
  262. });
  263. }
  264. this.stop();
  265. return fn;
  266. });
  267. result = true;
  268. }
  269. return result;
  270. };
  271. // Extends stop method to remove the optional label
  272. var oldStop = spinner.stop;
  273. spinner.stop = function()
  274. {
  275. oldStop.call(this);
  276. this.active = false;
  277. if (spinner.status != null)
  278. {
  279. spinner.status.parentNode.removeChild(spinner.status);
  280. spinner.status = null;
  281. }
  282. };
  283. spinner.pause = function()
  284. {
  285. return function() {};
  286. };
  287. return spinner;
  288. };
  289. /**
  290. * Static method for pasing PNG files.
  291. */
  292. EditorUi.parsePng = function(f, fn, error)
  293. {
  294. var pos = 0;
  295. function fread(d, count)
  296. {
  297. var start = pos;
  298. pos += count;
  299. return d.substring(start, pos);
  300. };
  301. // Reads unsigned long 32 bit big endian
  302. function _freadint(d)
  303. {
  304. var bytes = fread(d, 4);
  305. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  306. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  307. };
  308. // Checks signature
  309. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  310. {
  311. if (error != null)
  312. {
  313. error();
  314. }
  315. return;
  316. }
  317. // Reads header chunk
  318. fread(f,4);
  319. if (fread(f,4) != 'IHDR')
  320. {
  321. if (error != null)
  322. {
  323. error();
  324. }
  325. return;
  326. }
  327. fread(f, 17);
  328. do
  329. {
  330. var n = _freadint(f);
  331. var type = fread(f,4);
  332. if (fn != null)
  333. {
  334. if (fn(pos - 8, type, n))
  335. {
  336. break;
  337. }
  338. }
  339. value = fread(f,n);
  340. fread(f,4);
  341. if (type == 'IEND')
  342. {
  343. break;
  344. }
  345. }
  346. while (n);
  347. };
  348. /**
  349. * Returns true if the given string contains a compatible graph model.
  350. */
  351. EditorUi.prototype.isCompatibleString = function(data)
  352. {
  353. try
  354. {
  355. var doc = mxUtils.parseXml(data);
  356. var node = this.editor.extractGraphModel(doc.documentElement, true);
  357. return node != null && node.getElementsByTagName('parsererror').length == 0;
  358. }
  359. catch (e)
  360. {
  361. // ignore
  362. }
  363. return false;
  364. };
  365. /**
  366. * Extracts the mxfile from the given HTML data from a data transfer event.
  367. */
  368. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  369. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  370. {
  371. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  372. if (result == null)
  373. {
  374. try
  375. {
  376. var idx = data.indexOf('&lt;mxfile ');
  377. if (idx >= 0)
  378. {
  379. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  380. if (idx2 > idx)
  381. {
  382. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  383. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  384. }
  385. }
  386. else
  387. {
  388. // Gets compressed data from mxgraph element in HTML document
  389. var doc = mxUtils.parseXml(data);
  390. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  391. result = (node != null) ? mxUtils.getXml(node) : '';
  392. }
  393. }
  394. catch (e)
  395. {
  396. // ignore
  397. }
  398. }
  399. return result;
  400. };
  401. /**
  402. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  403. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  404. */
  405. EditorUi.prototype.validateFileData = function(data)
  406. {
  407. if (data != null && data.length > 0)
  408. {
  409. var index = data.indexOf('<meta charset="utf-8">');
  410. if (index >= 0)
  411. {
  412. var replaceString = '<meta charset="utf-8"/>';
  413. var replaceStrLen = replaceString.length;
  414. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  415. }
  416. }
  417. return data;
  418. };
  419. /**
  420. *
  421. */
  422. EditorUi.prototype.replaceFileData = function(data)
  423. {
  424. data = this.validateFileData(data);
  425. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  426. // Some nodes must be extracted here to find the mxfile node
  427. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  428. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  429. if (tmp != null)
  430. {
  431. node = tmp;
  432. }
  433. if (node != null)
  434. {
  435. var graph = this.editor.graph;
  436. graph.model.beginUpdate();
  437. try
  438. {
  439. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  440. var nodes = node.getElementsByTagName('diagram');
  441. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  442. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  443. {
  444. this.fileNode = node;
  445. this.pages = (this.pages != null) ? this.pages : [];
  446. // Wraps page nodes
  447. for (var i = nodes.length - 1; i >= 0; i--)
  448. {
  449. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  450. // Checks for invalid page names
  451. if (page.getName() == null)
  452. {
  453. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  454. }
  455. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  456. }
  457. }
  458. else
  459. {
  460. // Creates tabbed file structure if enforced by URL
  461. if (urlParams['pages'] != '0' && this.fileNode == null)
  462. {
  463. this.fileNode = node.ownerDocument.createElement('mxfile');
  464. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  465. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  466. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  467. }
  468. // Avoids scroll offset when switching page
  469. this.editor.setGraphXml(node);
  470. // Avoids duplicate parsing of the XML stored in the node
  471. if (this.currentPage != null)
  472. {
  473. this.currentPage.root = this.editor.graph.model.root;
  474. }
  475. }
  476. if (oldPages != null)
  477. {
  478. for (var i = 0; i < oldPages.length; i++)
  479. {
  480. graph.model.execute(new ChangePage(this, oldPages[i], null));
  481. }
  482. }
  483. }
  484. finally
  485. {
  486. graph.model.endUpdate();
  487. }
  488. }
  489. };
  490. /**
  491. * Translates this point by the given vector.
  492. *
  493. * @param {number} dx X-coordinate of the translation.
  494. * @param {number} dy Y-coordinate of the translation.
  495. */
  496. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  497. {
  498. graph = (graph != null) ? graph : this.editor.graph;
  499. forceXml = (forceXml != null) ? forceXml : false;
  500. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  501. var editLink = null;
  502. var redirect = null;
  503. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  504. {
  505. editLink = '_blank';
  506. }
  507. else
  508. {
  509. editLink = url;
  510. redirect = editLink;
  511. }
  512. if (node == null)
  513. {
  514. return '';
  515. }
  516. else
  517. {
  518. var fileNode = node;
  519. // Ignores case for possible HTML or XML nodes
  520. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  521. {
  522. // Removes control chars in input for correct roundtrip check
  523. var text = graph.zapGremlins(mxUtils.getXml(node));
  524. var data = graph.compress(text);
  525. // Fallback to plain XML for invalid compression
  526. // TODO: Remove this fallback with active pages
  527. if (graph.decompress(data) != text)
  528. {
  529. return text;
  530. }
  531. else
  532. {
  533. var diagramNode = node.ownerDocument.createElement('diagram');
  534. mxUtils.setTextContent(diagramNode, data);
  535. fileNode = node.ownerDocument.createElement('mxfile');
  536. fileNode.appendChild(diagramNode);
  537. }
  538. }
  539. if (!compact)
  540. {
  541. fileNode.setAttribute('userAgent', navigator.userAgent);
  542. fileNode.setAttribute('version', EditorUi.VERSION);
  543. fileNode.setAttribute('editor', 'www.draw.io');
  544. var md = (file != null) ? file.getMode() : this.mode;
  545. if (md != null)
  546. {
  547. fileNode.setAttribute('type', md);
  548. }
  549. }
  550. else
  551. {
  552. fileNode = fileNode.cloneNode(true);
  553. fileNode.removeAttribute('userAgent');
  554. fileNode.removeAttribute('version');
  555. fileNode.removeAttribute('editor');
  556. fileNode.removeAttribute('type');
  557. }
  558. var xml = mxUtils.getXml(fileNode);
  559. // Writes the file as an embedded HTML file
  560. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  561. {
  562. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  563. }
  564. // Maps the XML data to the content attribute in the SVG node
  565. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  566. {
  567. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  568. {
  569. url = null;
  570. }
  571. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  572. }
  573. return xml;
  574. }
  575. };
  576. /**
  577. * Translates this point by the given vector.
  578. *
  579. * @param {number} dx X-coordinate of the translation.
  580. * @param {number} dy Y-coordinate of the translation.
  581. */
  582. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  583. {
  584. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  585. currentPage = (currentPage != null) ? currentPage : false;
  586. var node = this.editor.getGraphXml(ignoreSelection);
  587. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  588. {
  589. var data = this.editor.graph.compress(this.editor.graph.zapGremlins(mxUtils.getXml(node)));
  590. mxUtils.setTextContent(this.currentPage.node, data);
  591. node = this.fileNode.cloneNode(false);
  592. if (currentPage)
  593. {
  594. node.appendChild(this.currentPage.node);
  595. }
  596. else
  597. {
  598. // Restores order of pages
  599. for (var i = 0; i < this.pages.length; i++)
  600. {
  601. var mapping = this.pages[i].mapping;
  602. // Updates XML of all pages for realtime
  603. if (this.currentPage != this.pages[i] && mapping != null && mapping.needsUpdate)
  604. {
  605. var enc = new mxCodec(mxUtils.createXmlDocument());
  606. var temp = enc.encode(mapping.graphModel);
  607. // Uses the graph state from the realtime model
  608. mapping.writeRealtimeToNode(temp);
  609. var data = this.editor.graph.compress(this.editor.graph.zapGremlins(mxUtils.getXml(temp)));
  610. mxUtils.setTextContent(this.pages[i].node, data);
  611. // Marks the page as up-to-date
  612. mapping.needsUpdate = false;
  613. }
  614. node.appendChild(this.pages[i].node);
  615. }
  616. }
  617. }
  618. return node;
  619. };
  620. /**
  621. * Translates this point by the given vector.
  622. *
  623. * @param {number} dx X-coordinate of the translation.
  624. * @param {number} dy Y-coordinate of the translation.
  625. */
  626. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact)
  627. {
  628. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  629. currentPage = (currentPage != null) ? currentPage : false;
  630. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  631. var graph = this.editor.graph;
  632. var file = this.getCurrentFile();
  633. // Exports SVG for first page while other page is visible by creating a graph
  634. // LATER: Add caching for the graph or SVG while not on first page
  635. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  636. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  637. {
  638. graph = this.createTemporaryGraph(graph.getStylesheet());
  639. var graphGetGlobalVariable = graph.getGlobalVariable;
  640. var page = this.pages[0];
  641. graph.getGlobalVariable = function(name)
  642. {
  643. if (name == 'page')
  644. {
  645. return page.getName();
  646. }
  647. else if (name == 'pagenumber')
  648. {
  649. return 1;
  650. }
  651. return graphGetGlobalVariable.apply(this, arguments);
  652. };
  653. document.body.appendChild(graph.container);
  654. graph.model.setRoot(page.root);
  655. }
  656. var result = this.createFileData(node, graph, file, window.location.href,
  657. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  658. // Removes temporary graph from DOM
  659. if (graph != this.editor.graph)
  660. {
  661. graph.container.parentNode.removeChild(graph.container);
  662. }
  663. return result;
  664. };
  665. /**
  666. *
  667. */
  668. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  669. {
  670. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  671. var bg = null;
  672. var js = 'https://www.draw.io/js/embed-static.min.js';
  673. // LATER: Merge common code with EmbedDialog
  674. if (graph != null)
  675. {
  676. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  677. var scale = graph.view.scale;
  678. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  679. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  680. bg = graph.background;
  681. // Embed script only used if no redirect
  682. if (redirect == null)
  683. {
  684. var s = this.getBasenames().join(';');
  685. if (s.length > 0)
  686. {
  687. js = 'https://www.draw.io/embed.js?s=' + s;
  688. }
  689. }
  690. // Adds embed attributes
  691. node.setAttribute('x0', x0);
  692. node.setAttribute('y0', y0);
  693. }
  694. if (node != null)
  695. {
  696. node.setAttribute('pan', '1');
  697. node.setAttribute('zoom', '1');
  698. node.setAttribute('resize', '0');
  699. node.setAttribute('fit', '0');
  700. node.setAttribute('border', '20');
  701. // Hidden attributes
  702. node.setAttribute('links', '1');
  703. if (editLink != null)
  704. {
  705. node.setAttribute('edit', editLink);
  706. }
  707. }
  708. // Makes XHTML compatible
  709. if (redirect != null)
  710. {
  711. redirect = redirect.replace(/&/g, '&amp;');
  712. }
  713. // Removes control chars in input for correct roundtrip check
  714. var text = (node != null) ? this.editor.graph.zapGremlins(mxUtils.getXml(node)) : '';
  715. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  716. // embed clients that rely on this format. HTML files and export use getHtml2.
  717. var data = this.editor.graph.compress(text);
  718. // Fallback to URI encoded XML for invalid compression
  719. if (this.editor.graph.decompress(data) != text)
  720. {
  721. data = encodeURIComponent(text);
  722. }
  723. var style = 'position:relative;overflow:auto;width:100%;';
  724. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  725. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  726. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  727. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  728. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  729. '</head>\n<body' +
  730. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  731. '\n<div class="mxgraph" style="' + style + '">\n' +
  732. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  733. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  734. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  735. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  736. 'src="https://www.draw.io/images/drawlogo128.png"/></a>') +
  737. '\n</body>\n</html>\n';
  738. };
  739. /**
  740. * Same as above but using the new embed code.
  741. */
  742. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  743. {
  744. var bg = null;
  745. var js = 'https://www.draw.io/js/viewer.min.js';
  746. var s = '';
  747. // LATER: Merge common code with EmbedDialog
  748. if (graph != null)
  749. {
  750. // Embed script only used if no redirect
  751. if (redirect == null)
  752. {
  753. var s = this.getBasenames().join(';');
  754. if (s.length > 0)
  755. {
  756. js = 'https://www.draw.io/embed2.js?s=' + s;
  757. }
  758. }
  759. }
  760. // Makes XHTML compatible
  761. if (redirect != null)
  762. {
  763. redirect = redirect.replace(/&/g, '&amp;');
  764. }
  765. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  766. xml: this.editor.graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  767. if (this.pages != null && this.currentPage != null)
  768. {
  769. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  770. }
  771. var style = 'max-width:100%;border:1px solid transparent;';
  772. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  773. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  774. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  775. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  776. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  777. '<meta charset="utf-8"/>\n</head>\n<body>' +
  778. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  779. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  780. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  781. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  782. 'src="https://www.draw.io/images/drawlogo128.png"/></a>') +
  783. '\n</body>\n</html>\n';
  784. };
  785. /**
  786. *
  787. */
  788. EditorUi.prototype.setFileData = function(data)
  789. {
  790. data = this.validateFileData(data);
  791. this.currentPage = null;
  792. this.fileNode = null;
  793. this.pages = null;
  794. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  795. // Some nodes must be extracted here to find the mxfile node
  796. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  797. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  798. if (tmp != null)
  799. {
  800. node = tmp;
  801. }
  802. if (node != null && node.nodeName == 'mxfile')
  803. {
  804. var nodes = node.getElementsByTagName('diagram');
  805. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  806. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  807. {
  808. this.fileNode = node;
  809. this.pages = [];
  810. // Wraps page nodes
  811. for (var i = 0; i < nodes.length; i++)
  812. {
  813. var page = new DiagramPage(nodes[i]);
  814. // Checks for invalid page names
  815. if (page.getName() == null)
  816. {
  817. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  818. }
  819. this.pages.push(page);
  820. }
  821. this.currentPage = this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  822. node = this.currentPage.node;
  823. }
  824. }
  825. // Creates tabbed file structure if enforced by URL
  826. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  827. {
  828. this.fileNode = node.ownerDocument.createElement('mxfile');
  829. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  830. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  831. this.pages = [this.currentPage];
  832. }
  833. // Avoids scroll offset when switching page
  834. this.editor.setGraphXml(node);
  835. // Avoids duplicate parsing of the XML stored in the node
  836. if (this.currentPage != null)
  837. {
  838. this.currentPage.root = this.editor.graph.model.root;
  839. }
  840. };
  841. /**
  842. * Translates this point by the given vector.
  843. *
  844. * @param {number} dx X-coordinate of the translation.
  845. * @param {number} dy Y-coordinate of the translation.
  846. */
  847. EditorUi.prototype.getBaseFilename = function()
  848. {
  849. var file = this.getCurrentFile();
  850. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  851. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) || /(\.svg)$/i.test(basename))
  852. {
  853. basename = basename.substring(0, basename.lastIndexOf('.'));
  854. }
  855. return basename;
  856. };
  857. /**
  858. * Translates this point by the given vector.
  859. *
  860. * @param {number} dx X-coordinate of the translation.
  861. * @param {number} dy Y-coordinate of the translation.
  862. */
  863. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible)
  864. {
  865. try
  866. {
  867. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  868. var basename = this.getBaseFilename();
  869. var filename = basename + '.' + format;
  870. if (format == 'xml')
  871. {
  872. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  873. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  874. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  875. this.saveData(filename, format, data, 'text/xml');
  876. }
  877. else if (format == 'html')
  878. {
  879. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  880. this.saveData(filename, format, data, 'text/html');
  881. }
  882. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  883. {
  884. var svg = null;
  885. var saveSvg = mxUtils.bind(this, function(data)
  886. {
  887. if (data.length <= MAX_REQUEST_SIZE)
  888. {
  889. this.saveData(filename, 'svg', data, 'image/svg+xml');
  890. }
  891. else
  892. {
  893. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  894. {
  895. mxUtils.popup(svg);
  896. }));
  897. }
  898. });
  899. if (format == 'svg')
  900. {
  901. var bg = this.editor.graph.background;
  902. if (bg == mxConstants.NONE)
  903. {
  904. bg = null;
  905. }
  906. // Sets or disables alternate text for foreignObjects. Disabling is needed
  907. // because PhantomJS seems to ignore switch statements and paint all text.
  908. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  909. if (addShadow)
  910. {
  911. this.editor.graph.addSvgShadow(svgRoot);
  912. }
  913. // Embeds the images in the SVG output (async)
  914. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  915. {
  916. this.spinner.stop();
  917. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  918. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  919. mxUtils.getXml(svgRoot2));
  920. })));
  921. }
  922. else
  923. {
  924. filename = basename + '.svg';
  925. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  926. {
  927. this.spinner.stop();
  928. saveSvg(svg);
  929. }), ignoreSelection);
  930. }
  931. }
  932. else
  933. {
  934. if (format == 'xmlpng')
  935. {
  936. filename = basename + '.png';
  937. }
  938. else if (format == 'jpeg')
  939. {
  940. filename = basename + '.jpg';
  941. }
  942. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  943. {
  944. try
  945. {
  946. var prev = this.editor.graph.pageVisible;
  947. if (pageVisible != null)
  948. {
  949. this.editor.graph.pageVisible = pageVisible;
  950. }
  951. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64);
  952. this.editor.graph.pageVisible = prev;
  953. return req;
  954. }
  955. catch (e)
  956. {
  957. this.handleError(e);
  958. }
  959. }));
  960. }
  961. }
  962. catch (e)
  963. {
  964. this.handleError(e);
  965. }
  966. };
  967. /**
  968. * Translates this point by the given vector.
  969. *
  970. * @param {number} dx X-coordinate of the translation.
  971. * @param {number} dy Y-coordinate of the translation.
  972. */
  973. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64)
  974. {
  975. var bounds = this.editor.graph.getGraphBounds();
  976. // Exports only current page for PDF since it does not contain file data, but for
  977. // the other formats with XML included we need to send the complete data and use
  978. // the from/to URL parameters to specify the page to be exported.
  979. var data = this.getFileData(true, null, null, null, ignoreSelection, format != 'xmlpng');
  980. var range = '';
  981. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  982. {
  983. throw {message: mxResources.get('drawingTooLarge')};
  984. }
  985. var embed = '0';
  986. if (format == 'xmlpng')
  987. {
  988. embed = '1';
  989. format = 'png';
  990. // Finds the current page number
  991. if (this.pages != null && this.currentPage != null)
  992. {
  993. for (var i = 0; i < this.pages.length; i++)
  994. {
  995. if (this.pages[i] == this.currentPage)
  996. {
  997. range = '&from=' + i;
  998. break;
  999. }
  1000. }
  1001. }
  1002. }
  1003. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range +
  1004. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1005. encodeURIComponent(data) + ((filename != null) ?
  1006. '&filename=' + encodeURIComponent(filename) : ''));
  1007. };
  1008. /**
  1009. * Translates this point by the given vector.
  1010. *
  1011. * @param {number} dx X-coordinate of the translation.
  1012. * @param {number} dy Y-coordinate of the translation.
  1013. */
  1014. EditorUi.prototype.setMode = function(mode, remember)
  1015. {
  1016. this.mode = mode;
  1017. };
  1018. /**
  1019. * Translates this point by the given vector.
  1020. *
  1021. * @param {number} dx X-coordinate of the translation.
  1022. * @param {number} dy Y-coordinate of the translation.
  1023. */
  1024. EditorUi.prototype.fileLoaded = function(file)
  1025. {
  1026. var result = false;
  1027. this.hideDialog();
  1028. var oldFile = this.getCurrentFile();
  1029. this.setCurrentFile(null);
  1030. if (oldFile != null)
  1031. {
  1032. oldFile.removeListener(this.descriptorChangedListener);
  1033. oldFile.close();
  1034. }
  1035. this.editor.graph.model.clear();
  1036. this.editor.undoManager.clear();
  1037. var noFile = mxUtils.bind(this, function()
  1038. {
  1039. this.setGraphEnabled(false);
  1040. this.setCurrentFile(null);
  1041. // Keeps initial title if no file existed before
  1042. if (oldFile != null)
  1043. {
  1044. this.updateDocumentTitle();
  1045. }
  1046. // File might have been loaded halfway
  1047. this.editor.graph.model.clear();
  1048. this.editor.undoManager.clear();
  1049. // Avoids empty hash with no value
  1050. if (window.location.hash != null && window.location.hash.length > 0)
  1051. {
  1052. window.location.hash = '';
  1053. }
  1054. if (this.fname != null)
  1055. {
  1056. this.fnameWrapper.style.display = 'none';
  1057. this.fname.innerHTML = '';
  1058. this.fname.setAttribute('title', mxResources.get('rename'));
  1059. }
  1060. this.updateUi();
  1061. this.showSplash();
  1062. });
  1063. if (file != null)
  1064. {
  1065. try
  1066. {
  1067. // Order is significant, current file needed for correct
  1068. // file format for initial save after starting realtime
  1069. this.setCurrentFile(file);
  1070. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1071. file.addListener('contentChanged', this.descriptorChangedListener);
  1072. this.descriptorChanged();
  1073. file.open();
  1074. this.setGraphEnabled(true);
  1075. this.setMode(file.getMode());
  1076. this.editor.undoManager.clear();
  1077. this.updateUi();
  1078. // Realtime files have a valid status message
  1079. if (file.realtime == null)
  1080. {
  1081. if (!file.isEditable())
  1082. {
  1083. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get('readOnly')));
  1084. }
  1085. else
  1086. {
  1087. this.editor.setStatus('');
  1088. }
  1089. }
  1090. if (!this.editor.chromeless)
  1091. {
  1092. this.editor.graph.selectUnlockedLayer();
  1093. this.showLayersDialog();
  1094. this.restoreLibraries();
  1095. // Workaround for no initial focus in FF
  1096. if (window.self !== window.top)
  1097. {
  1098. window.focus();
  1099. }
  1100. }
  1101. else if (this.editor.graph.lightbox)
  1102. {
  1103. this.lightboxFit();
  1104. }
  1105. if (this.chromelessResize)
  1106. {
  1107. this.chromelessResize();
  1108. }
  1109. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1110. result = true;
  1111. if (this.enableLogging && !this.isOffline() && file.getMode() != null)
  1112. {
  1113. try
  1114. {
  1115. var img = new Image();
  1116. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  1117. img.src = logDomain + '/log?msg=storageMode:' + encodeURIComponent(file.getMode()) +
  1118. '&v=' + encodeURIComponent(EditorUi.VERSION);
  1119. }
  1120. catch (e)
  1121. {
  1122. // ignore
  1123. }
  1124. }
  1125. if (this.mode == file.getMode() && file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1126. {
  1127. try
  1128. {
  1129. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1130. }
  1131. catch (e)
  1132. {
  1133. // ignore
  1134. }
  1135. }
  1136. }
  1137. catch (e)
  1138. {
  1139. // Makes sure the file does not save the invalid UI model and overwrites anything important
  1140. if (window.console != null)
  1141. {
  1142. console.log('error in fileLoaded:', file, e);
  1143. }
  1144. if (this.enableLogging && !this.isOffline())
  1145. {
  1146. try
  1147. {
  1148. var img = new Image();
  1149. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  1150. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  1151. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  1152. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  1153. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  1154. }
  1155. catch (e)
  1156. {
  1157. // ignore
  1158. }
  1159. }
  1160. // Asynchronous handling of errors
  1161. this.handleError(e, mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
  1162. {
  1163. // Removes URL parameter and reloads the page
  1164. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  1165. {
  1166. window.location.search = this.getSearch(['url']);
  1167. }
  1168. else if (oldFile != null)
  1169. {
  1170. // Workaround for close realtime model is to reload the file from scratch
  1171. if (oldFile.constructor == DriveFile)
  1172. {
  1173. this.loadFile(oldFile.getHash());
  1174. }
  1175. else
  1176. {
  1177. this.fileLoaded(oldFile);
  1178. }
  1179. }
  1180. else
  1181. {
  1182. noFile();
  1183. }
  1184. }));
  1185. }
  1186. }
  1187. else
  1188. {
  1189. noFile();
  1190. }
  1191. return result;
  1192. };
  1193. /**
  1194. * Updates action states depending on the selection.
  1195. */
  1196. EditorUi.prototype.restoreLibraries = function()
  1197. {
  1198. // hook for subclassers
  1199. };
  1200. /**
  1201. * Translates this point by the given vector.
  1202. *
  1203. * @param {number} dx X-coordinate of the translation.
  1204. * @param {number} dy Y-coordinate of the translation.
  1205. */
  1206. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn)
  1207. {
  1208. // hook for subclassers
  1209. };
  1210. /**
  1211. * Shows or hides the scratchpad library.
  1212. */
  1213. EditorUi.prototype.toggleScratchpad = function()
  1214. {
  1215. if (isLocalStorage || mxClient.IS_CHROMEAPP)
  1216. {
  1217. if (this.scratchpad == null)
  1218. {
  1219. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  1220. {
  1221. if (xml == null)
  1222. {
  1223. xml = this.emptyLibraryXml;
  1224. }
  1225. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  1226. }));
  1227. }
  1228. else
  1229. {
  1230. this.closeLibrary(this.scratchpad);
  1231. }
  1232. }
  1233. };
  1234. /**
  1235. * Translates this point by the given vector.
  1236. *
  1237. * @param {number} dx X-coordinate of the translation.
  1238. * @param {number} dy Y-coordinate of the translation.
  1239. */
  1240. EditorUi.prototype.createLibraryDataFromImages = function(images)
  1241. {
  1242. var doc = mxUtils.createXmlDocument();
  1243. var library = doc.createElement('mxlibrary');
  1244. mxUtils.setTextContent(library, JSON.stringify(images));
  1245. doc.appendChild(library);
  1246. return mxUtils.getXml(doc);
  1247. };
  1248. /**
  1249. * Translates this point by the given vector.
  1250. *
  1251. * @param {number} dx X-coordinate of the translation.
  1252. * @param {number} dy Y-coordinate of the translation.
  1253. */
  1254. EditorUi.prototype.closeLibrary = function(file)
  1255. {
  1256. if (file != null)
  1257. {
  1258. this.removeLibrarySidebar(file.getHash());
  1259. if (file.constructor != LocalLibrary)
  1260. {
  1261. mxSettings.removeCustomLibrary(file.getHash());
  1262. }
  1263. if (file.title == '.scratchpad')
  1264. {
  1265. this.scratchpad = null;
  1266. }
  1267. }
  1268. };
  1269. /**
  1270. * Translates this point by the given vector.
  1271. *
  1272. * @param {number} dx X-coordinate of the translation.
  1273. * @param {number} dy Y-coordinate of the translation.
  1274. */
  1275. EditorUi.prototype.removeLibrarySidebar = function(id)
  1276. {
  1277. var elts = this.sidebar.palettes[id];
  1278. if (elts != null)
  1279. {
  1280. for (var i = 0; i < elts.length; i++)
  1281. {
  1282. elts[i].parentNode.removeChild(elts[i]);
  1283. }
  1284. delete this.sidebar.palettes[id];
  1285. }
  1286. };
  1287. /**
  1288. * Changes the position of the library in the sidebar
  1289. */
  1290. EditorUi.prototype.repositionLibrary = function(nextChild)
  1291. {
  1292. var c = this.sidebar.container;
  1293. if (nextChild == null)
  1294. {
  1295. var elts = this.sidebar.palettes['L.scratchpad'];
  1296. if (elts == null)
  1297. {
  1298. elts = this.sidebar.palettes['search'];
  1299. }
  1300. if (elts != null)
  1301. {
  1302. nextChild = elts[elts.length - 1].nextSibling;
  1303. }
  1304. }
  1305. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  1306. var content = c.lastChild;
  1307. var title = content.previousSibling;
  1308. c.insertBefore(content, nextChild);
  1309. c.insertBefore(title, content);
  1310. }
  1311. /**
  1312. * Translates this point by the given vector.
  1313. *
  1314. * @param {number} dx X-coordinate of the translation.
  1315. * @param {number} dy Y-coordinate of the translation.
  1316. */
  1317. EditorUi.prototype.loadLibrary = function(file)
  1318. {
  1319. var doc = mxUtils.parseXml(file.getData());
  1320. if (doc.documentElement.nodeName == 'mxlibrary')
  1321. {
  1322. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  1323. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  1324. }
  1325. else
  1326. {
  1327. throw {message: mxResources.get('notALibraryFile')};
  1328. }
  1329. };
  1330. /**
  1331. * Translates this point by the given vector.
  1332. *
  1333. * @param {number} dx X-coordinate of the translation.
  1334. * @param {number} dy Y-coordinate of the translation.
  1335. */
  1336. EditorUi.prototype.getLibraryStorageHint = function(file)
  1337. {
  1338. return '';
  1339. };
  1340. /**
  1341. * Translates this point by the given vector.
  1342. *
  1343. * @param {number} dx X-coordinate of the translation.
  1344. * @param {number} dy Y-coordinate of the translation.
  1345. */
  1346. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  1347. {
  1348. if (file.constructor != LocalLibrary)
  1349. {
  1350. mxSettings.addCustomLibrary(file.getHash());
  1351. }
  1352. if (file.title == '.scratchpad')
  1353. {
  1354. this.scratchpad = file;
  1355. }
  1356. var elts = this.sidebar.palettes[file.getHash()];
  1357. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  1358. // Removes existing sidebar entry for this library
  1359. this.removeLibrarySidebar(file.getHash());
  1360. var dropTarget = null;
  1361. var addImages = mxUtils.bind(this, function(imgs, content)
  1362. {
  1363. if (imgs.length == 0 && file.isEditable())
  1364. {
  1365. if (dropTarget == null)
  1366. {
  1367. dropTarget = document.createElement('div');
  1368. mxUtils.setPrefixedStyle(dropTarget.style, 'borderRadius', '6px');
  1369. dropTarget.style.border = '3px dotted lightGray';
  1370. dropTarget.style.textAlign = 'center';
  1371. dropTarget.style.padding = '8px';
  1372. dropTarget.style.color = '#B3B3B3';
  1373. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  1374. }
  1375. content.appendChild(dropTarget);
  1376. }
  1377. else
  1378. {
  1379. for (var i = 0; i < imgs.length; i++)
  1380. {
  1381. var img = imgs[i];
  1382. var data = img.data;
  1383. if (data != null)
  1384. {
  1385. data = this.convertDataUri(data);
  1386. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  1387. if (img.aspect == 'fixed')
  1388. {
  1389. s += 'aspect=fixed;'
  1390. }
  1391. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  1392. data, img.w, img.h, '', img.title || '', false, false, false));
  1393. }
  1394. else if (img.xml != null)
  1395. {
  1396. var cells = this.stringToCells(this.editor.graph.decompress(img.xml));
  1397. if (cells.length > 0)
  1398. {
  1399. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  1400. cells, img.w, img.h, img.title || '', true, false, false));
  1401. }
  1402. }
  1403. }
  1404. }
  1405. });
  1406. // Adds new sidebar entry for this library
  1407. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  1408. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  1409. {
  1410. addImages(images, content);
  1411. }));
  1412. this.repositionLibrary(nextSibling);
  1413. // Adds tooltip for backend
  1414. var title = contentDiv.parentNode.previousSibling;
  1415. var tip = title.getAttribute('title');
  1416. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  1417. {
  1418. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  1419. }
  1420. var buttons = document.createElement('div');
  1421. buttons.style.position = 'absolute';
  1422. buttons.style.right = '0px';
  1423. buttons.style.top = '5px';
  1424. // Workaround for CSS error in IE8 (standards and quirks)
  1425. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  1426. {
  1427. buttons.style.backgroundColor = 'inherit';
  1428. }
  1429. title.style.position = 'relative';
  1430. var btnWidth = 18;
  1431. var btn = document.createElement('img');
  1432. btn.setAttribute('src', Dialog.prototype.closeImage);
  1433. btn.setAttribute('title', mxResources.get('close'));
  1434. btn.setAttribute('align', 'top');
  1435. btn.setAttribute('border', '0');
  1436. btn.className = 'geButton';
  1437. btn.style.marginRight = '1px';
  1438. btn.style.marginTop = '-1px';
  1439. buttons.appendChild(btn);
  1440. var saveBtn = null;
  1441. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  1442. {
  1443. // Workaround for close after any button click in IE8/quirks
  1444. if (!mxEvent.isConsumed(evt))
  1445. {
  1446. var fn = mxUtils.bind(this, function()
  1447. {
  1448. this.closeLibrary(file);
  1449. });
  1450. if (saveBtn != null)
  1451. {
  1452. this.confirm(mxResources.get('allChangesLost'), null, fn,
  1453. mxResources.get('cancel'), mxResources.get('discardChanges'));
  1454. }
  1455. else
  1456. {
  1457. fn();
  1458. }
  1459. mxEvent.consume(evt);
  1460. }
  1461. }));
  1462. // Shows tooltip if mouse over background
  1463. mxEvent.addListener(contentDiv, 'mousemove', mxUtils.bind(this, function(evt)
  1464. {
  1465. if (mxEvent.getSource(evt) == contentDiv)
  1466. {
  1467. contentDiv.setAttribute('title', mxResources.get('libraryTooltip'));
  1468. }
  1469. else
  1470. {
  1471. contentDiv.removeAttribute('title');
  1472. }
  1473. }));
  1474. if (file.isEditable())
  1475. {
  1476. var graph = this.editor.graph;
  1477. var editLibrary = mxUtils.bind(this, function(evt)
  1478. {
  1479. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  1480. mxEvent.consume(evt);
  1481. });
  1482. var saveLibrary = mxUtils.bind(this, function(evt)
  1483. {
  1484. file.setModified(true);
  1485. if (file.isAutosave())
  1486. {
  1487. if (spinBtn != null && spinBtn.parentNode != null)
  1488. {
  1489. spinBtn.parentNode.removeChild(spinBtn);
  1490. }
  1491. spinBtn = btn.cloneNode(false);
  1492. spinBtn.setAttribute('src', Editor.spinImage);
  1493. spinBtn.setAttribute('title', mxResources.get('saving'));
  1494. spinBtn.style.cursor = 'default';
  1495. spinBtn.style.marginRight = '2px';
  1496. spinBtn.style.marginTop = '-2px';
  1497. buttons.insertBefore(spinBtn, buttons.firstChild);
  1498. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1499. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  1500. {
  1501. if (spinBtn != null && spinBtn.parentNode != null)
  1502. {
  1503. spinBtn.parentNode.removeChild(spinBtn);
  1504. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1505. }
  1506. });
  1507. }
  1508. else if (saveBtn == null)
  1509. {
  1510. saveBtn = btn.cloneNode(false);
  1511. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  1512. saveBtn.setAttribute('title', mxResources.get('save'));
  1513. buttons.insertBefore(saveBtn, buttons.firstChild);
  1514. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  1515. {
  1516. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  1517. file.constructor == LocalLibrary, true, function()
  1518. {
  1519. if (saveBtn != null && !file.isModified())
  1520. {
  1521. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1522. saveBtn.parentNode.removeChild(saveBtn);
  1523. saveBtn = null;
  1524. }
  1525. });
  1526. mxEvent.consume(evt);
  1527. }));
  1528. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1529. }
  1530. });
  1531. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  1532. {
  1533. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  1534. // Translates cells to origin
  1535. for (var i = 0; i < cells.length; i++)
  1536. {
  1537. var geo = graph.getCellGeometry(cells[i]);
  1538. if (geo != null)
  1539. {
  1540. geo.translate(-bounds.x, -bounds.y);
  1541. }
  1542. }
  1543. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  1544. cells, bounds.width, bounds.height, title || '', true, false, false));
  1545. var xml = this.editor.graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  1546. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  1547. if (title != null)
  1548. {
  1549. entry.title = title;
  1550. }
  1551. images.push(entry);
  1552. saveLibrary(evt);
  1553. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1554. {
  1555. dropTarget.parentNode.removeChild(dropTarget);
  1556. dropTarget = null;
  1557. }
  1558. });
  1559. var addSelection = mxUtils.bind(this, function(evt)
  1560. {
  1561. if (!graph.isSelectionEmpty())
  1562. {
  1563. var cells = graph.getSelectionCells();
  1564. var bounds = graph.view.getBounds(cells);
  1565. var s = graph.view.scale;
  1566. bounds.x /= s;
  1567. bounds.y /= s;
  1568. bounds.width /= s;
  1569. bounds.height /= s;
  1570. bounds.x -= graph.view.translate.x;
  1571. bounds.y -= graph.view.translate.y;
  1572. addCells(cells, bounds);
  1573. }
  1574. else if (graph.getRubberband().isActive())
  1575. {
  1576. graph.getRubberband().execute(evt);
  1577. graph.getRubberband().reset();
  1578. }
  1579. else
  1580. {
  1581. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  1582. }
  1583. mxEvent.consume(evt);
  1584. });
  1585. // Defines inactive border state
  1586. contentDiv.style.border = '3px solid transparent';
  1587. // Adds drop handler from graph
  1588. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  1589. {
  1590. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  1591. {
  1592. graph.graphHandler.shape.node.style.visibility = 'hidden';
  1593. if (dropTarget != null)
  1594. {
  1595. dropTarget.style.border = '3px dotted rgb(254, 137, 12)';
  1596. }
  1597. else
  1598. {
  1599. contentDiv.style.border = '3px dotted rgb(254, 137, 12)';
  1600. }
  1601. contentDiv.style.cursor = 'copy';
  1602. graph.panningManager.stop();
  1603. graph.autoScroll = false;
  1604. if (graph.graphHandler.guide != null)
  1605. {
  1606. graph.graphHandler.guide.setVisible(false);
  1607. }
  1608. if (graph.graphHandler.hint != null)
  1609. {
  1610. graph.graphHandler.hint.style.visibility = 'hidden';
  1611. }
  1612. mxEvent.consume(evt);
  1613. }
  1614. }), mxUtils.bind(this, function(evt)
  1615. {
  1616. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  1617. {
  1618. contentDiv.style.border = '3px solid transparent';
  1619. if (dropTarget != null)
  1620. {
  1621. dropTarget.style.border = '3px dotted lightGray';
  1622. }
  1623. contentDiv.style.cursor = 'default';
  1624. this.sidebar.showTooltips = true;
  1625. graph.panningManager.stop();
  1626. graph.graphHandler.reset();
  1627. graph.isMouseDown = false;
  1628. graph.autoScroll = true;
  1629. addSelection(evt);
  1630. mxEvent.consume(evt);
  1631. }
  1632. }));
  1633. // Handles mouse leaving the library and restoring move
  1634. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  1635. {
  1636. if (graph.isMouseDown && graph.graphHandler.shape != null)
  1637. {
  1638. graph.graphHandler.shape.node.style.visibility = 'visible';
  1639. contentDiv.style.border = '3px solid transparent';
  1640. contentDiv.style.cursor = '';
  1641. graph.autoScroll = true;
  1642. if (graph.graphHandler.guide != null)
  1643. {
  1644. graph.graphHandler.guide.setVisible(true);
  1645. }
  1646. if (graph.graphHandler.hint != null)
  1647. {
  1648. graph.graphHandler.hint.style.visibility = 'visible';
  1649. }
  1650. if (dropTarget != null)
  1651. {
  1652. dropTarget.style.border = '3px dotted lightGray';
  1653. }
  1654. }
  1655. }));
  1656. // Adds drop handler from filesystem
  1657. if (Graph.fileSupport)
  1658. {
  1659. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  1660. {
  1661. if (dropTarget != null)
  1662. {
  1663. dropTarget.style.border = '3px dotted rgb(254, 137, 12)';
  1664. }
  1665. else
  1666. {
  1667. contentDiv.style.border = '3px dotted rgb(254, 137, 12)';
  1668. }
  1669. evt.dataTransfer.dropEffect = 'copy';
  1670. contentDiv.style.cursor = 'copy';
  1671. this.sidebar.hideTooltip();
  1672. evt.stopPropagation();
  1673. evt.preventDefault();
  1674. }));
  1675. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  1676. {
  1677. contentDiv.style.border = '3px solid transparent';
  1678. contentDiv.style.cursor = '';
  1679. if (dropTarget != null)
  1680. {
  1681. dropTarget.style.border = '3px dotted lightGray';
  1682. }
  1683. if (evt.dataTransfer.files.length > 0)
  1684. {
  1685. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  1686. {
  1687. if (data != null && mimeType.substring(0, 6) == 'image/')
  1688. {
  1689. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  1690. this.convertDataUri(data);
  1691. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  1692. cells[0].vertex = true;
  1693. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  1694. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1695. {
  1696. dropTarget.parentNode.removeChild(dropTarget);
  1697. dropTarget = null;
  1698. }
  1699. }
  1700. else
  1701. {
  1702. var done = false;
  1703. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  1704. {
  1705. if (theData != null && theMimeType == 'text/xml')
  1706. {
  1707. var doc = mxUtils.parseXml(theData);
  1708. if (doc.documentElement.nodeName == 'mxlibrary')
  1709. {
  1710. try
  1711. {
  1712. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  1713. addImages(temp, contentDiv);
  1714. images = images.concat(temp);
  1715. saveLibrary(evt);
  1716. this.spinner.stop();
  1717. done = true;
  1718. }
  1719. catch (e)
  1720. {
  1721. // ignore
  1722. }
  1723. }
  1724. else if (doc.documentElement.nodeName == 'mxfile')
  1725. {
  1726. try
  1727. {
  1728. var pages = doc.documentElement.getElementsByTagName('diagram');
  1729. for (var i = 0; i < pages.length; i++)
  1730. {
  1731. var temp = mxUtils.getTextContent(pages[i]);
  1732. var cells = this.stringToCells(this.editor.graph.decompress(temp));
  1733. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  1734. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  1735. }
  1736. done = true;
  1737. }
  1738. catch (e)
  1739. {
  1740. if (window.console != null)
  1741. {
  1742. console.log('error in drop handler:', e);
  1743. }
  1744. }
  1745. }
  1746. }
  1747. if (!done)
  1748. {
  1749. this.spinner.stop();
  1750. this.handleError({message: mxResources.get('errorLoadingFile')})
  1751. }
  1752. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  1753. {
  1754. dropTarget.parentNode.removeChild(dropTarget);
  1755. dropTarget = null;
  1756. }
  1757. });
  1758. if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  1759. {
  1760. this.parseFile(file, mxUtils.bind(this, function(xhr)
  1761. {
  1762. if (xhr.readyState == 4)
  1763. {
  1764. this.spinner.stop();
  1765. if (xhr.status >= 200 && xhr.status <= 299)
  1766. {
  1767. doImport(xhr.responseText, 'text/xml');
  1768. }
  1769. else
  1770. {
  1771. this.handleError({message: mxResources.get((xhr.status == 413) ?
  1772. 'drawingTooLarge' : 'invalidOrMissingFile')},
  1773. mxResources.get('errorLoadingFile'));
  1774. }
  1775. }
  1776. }));
  1777. }
  1778. else
  1779. {
  1780. doImport(data, mimeType);
  1781. }
  1782. }
  1783. }));
  1784. }
  1785. evt.stopPropagation();
  1786. evt.preventDefault();
  1787. }));
  1788. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  1789. {
  1790. if (dropTarget != null)
  1791. {
  1792. dropTarget.style.border = '3px dotted lightGray';
  1793. }
  1794. else
  1795. {
  1796. contentDiv.style.border = '3px solid transparent';
  1797. contentDiv.style.cursor = '';
  1798. }
  1799. evt.stopPropagation();
  1800. evt.preventDefault();
  1801. });
  1802. }
  1803. btn = btn.cloneNode(false);
  1804. btn.setAttribute('src', IMAGE_PATH + '/edit.gif');
  1805. btn.setAttribute('title', mxResources.get('edit'));
  1806. buttons.insertBefore(btn, buttons.firstChild);
  1807. mxEvent.addListener(btn, 'click', editLibrary);
  1808. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  1809. {
  1810. if (mxEvent.getSource(evt) == contentDiv)
  1811. {
  1812. editLibrary(evt);
  1813. }
  1814. });
  1815. btn = btn.cloneNode(false);
  1816. btn.setAttribute('src', Editor.plusImage);
  1817. btn.setAttribute('title', mxResources.get('add'));
  1818. buttons.insertBefore(btn, buttons.firstChild);
  1819. if (!this.isOffline() && file.title == '.scratchpad')
  1820. {
  1821. var link = document.createElement('span');
  1822. link.setAttribute('title', mxResources.get('help'));
  1823. link.style.cssText = 'color:gray;text-decoration:none;';
  1824. link.className = 'geButton';
  1825. mxUtils.write(link, '?');
  1826. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  1827. {
  1828. window.open('https://support.draw.io/questions/10420280');
  1829. mxEvent.consume(evt);
  1830. }));
  1831. buttons.insertBefore(link, buttons.firstChild);
  1832. }
  1833. var spinBtn = null;
  1834. mxEvent.addListener(btn, 'click', addSelection);
  1835. }
  1836. title.appendChild(buttons);
  1837. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  1838. };
  1839. /**
  1840. * EditorUi Overrides
  1841. */
  1842. if (urlParams['offline'] == '1')
  1843. {
  1844. EditorUi.prototype.footerHeight = 4;
  1845. }
  1846. else
  1847. {
  1848. if (uiTheme == 'atlas')
  1849. {
  1850. if (typeof Toolbar !== 'undefined')
  1851. {
  1852. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  1853. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  1854. }
  1855. Editor.prototype.initialTopSpacing = 3;
  1856. EditorUi.prototype.menubarHeight = 41;
  1857. EditorUi.prototype.toolbarHeight = 38;
  1858. EditorUi.prototype.hsplitPosition = 188;
  1859. Sidebar.prototype.thumbWidth = 46;
  1860. Sidebar.prototype.thumbHeight = 46;
  1861. Sidebar.prototype.thumbPadding = (document.documentMode >= 5) ? 0 : 1;
  1862. Sidebar.prototype.thumbBorder = 2;
  1863. }
  1864. else
  1865. {
  1866. if (urlParams['savesidebar'] == '1')
  1867. {
  1868. Sidebar.prototype.thumbWidth = 64;
  1869. Sidebar.prototype.thumbHeight = 64;
  1870. }
  1871. }
  1872. EditorUi.prototype.footerHeight = (screen.height <= 740) ? 5 : 46;
  1873. // Fetches footer from page
  1874. EditorUi.prototype.createFooter = function()
  1875. {
  1876. var footer = document.getElementById('geFooter');
  1877. if (footer != null)
  1878. {
  1879. footer.style.visibility = 'visible';
  1880. // Adds button to hide the footer
  1881. var img = document.createElement('img');
  1882. img.setAttribute('border', '0');
  1883. img.setAttribute('src', Dialog.prototype.closeImage);
  1884. img.setAttribute('title', mxResources.get('hide'));
  1885. footer.appendChild(img)
  1886. if (mxClient.IS_QUIRKS)
  1887. {
  1888. img.style.position = 'relative';
  1889. img.style.styleFloat = 'right';
  1890. img.style.top = '-30px';
  1891. img.style.left = '164px';
  1892. img.style.cursor = 'pointer';
  1893. }
  1894. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  1895. {
  1896. this.hideFooter();
  1897. }));
  1898. }
  1899. return footer;
  1900. };
  1901. }
  1902. /**
  1903. * Hides the footer.
  1904. */
  1905. EditorUi.prototype.hideFooter = function()
  1906. {
  1907. var footer = document.getElementById('geFooter');
  1908. if (footer != null)
  1909. {
  1910. this.footerHeight = 0;
  1911. footer.style.display = 'none';
  1912. this.refresh();
  1913. }
  1914. };
  1915. /**
  1916. * Overrides image dialog to add image search and Google+.
  1917. */
  1918. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  1919. {
  1920. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  1921. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  1922. this.showDialog(dlg.container, (Graph.fileSupport) ? 420 : 340, (Graph.fileSupport) ? 200 : 90, true, true);
  1923. dlg.init();
  1924. };
  1925. /**
  1926. * Hides the current menu.
  1927. */
  1928. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  1929. {
  1930. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  1931. {
  1932. this.setBackgroundImage(image);
  1933. });
  1934. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  1935. {
  1936. apply(image);
  1937. }));
  1938. this.showDialog(dlg.container, 360, 200, true, true);
  1939. dlg.init();
  1940. };
  1941. /**
  1942. * Hides the current menu.
  1943. */
  1944. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  1945. {
  1946. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  1947. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  1948. {
  1949. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  1950. {
  1951. this.showSplash();
  1952. }
  1953. }));
  1954. dlg.init();
  1955. };
  1956. /**
  1957. * Hook for sidebar footer container.
  1958. */
  1959. EditorUi.prototype.createSidebarFooterContainer = function()
  1960. {
  1961. var div = this.createDiv('geSidebarContainer');
  1962. div.style.position = 'absolute';
  1963. div.style.overflow = 'hidden';
  1964. div.style.borderWidth = '3px';
  1965. var elt2 = document.createElement('a');
  1966. elt2.setAttribute('href', 'javascript:void(0);');
  1967. elt2.className = 'geTitle';
  1968. elt2.style.height = '100%';
  1969. elt2.style.paddingTop = '9px';
  1970. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  1971. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  1972. {
  1973. this.actions.get('shapes').funct();
  1974. mxEvent.consume(evt);
  1975. }));
  1976. div.appendChild(elt2);
  1977. return div;
  1978. };
  1979. /**
  1980. * Translates this point by the given vector.
  1981. *
  1982. * @param {number} dx X-coordinate of the translation.
  1983. * @param {number} dy Y-coordinate of the translation.
  1984. */
  1985. EditorUi.prototype.handleError = function(resp, title, fn)
  1986. {
  1987. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  1988. var e = (resp != null && resp.error != null) ? resp.error : resp;
  1989. if (e != null || title != null)
  1990. {
  1991. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  1992. var btn = mxResources.get('ok');
  1993. var retry = null;
  1994. title = (title != null) ? title : mxResources.get('error');
  1995. if (e != null)
  1996. {
  1997. if (e.retry != null)
  1998. {
  1999. btn = mxResources.get('cancel');
  2000. retry = function()
  2001. {
  2002. resume();
  2003. e.retry();
  2004. };
  2005. }
  2006. if (typeof(gapi) != 'undefined' && typeof(gapi.drive) != 'undefined' && typeof(gapi.drive.realtime) != 'undefined' &&
  2007. e.type == gapi.drive.realtime.ErrorType.FORBIDDEN)
  2008. {
  2009. msg = mxUtils.htmlEntities(mxResources.get('forbidden'));
  2010. }
  2011. else if (e.code == 404 || e.status == 404 || (typeof(gapi) != 'undefined' && typeof(gapi.drive) != 'undefined' &&
  2012. typeof(gapi.drive.realtime) != 'undefined' && e.type == gapi.drive.realtime.ErrorType.NOT_FOUND))
  2013. {
  2014. msg = mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied'));
  2015. var id = window.location.hash;
  2016. if (id != null && id.substring(0, 2) == '#G')
  2017. {
  2018. id = id.substring(2);
  2019. msg += ' <a href="https://drive.google.com/open?id=' + id + '" target="_blank">' +
  2020. mxUtils.htmlEntities(mxResources.get('tryOpeningViaThisPage')) + '</a>';
  2021. }
  2022. }
  2023. else if (e.code == App.ERROR_TIMEOUT)
  2024. {
  2025. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  2026. }
  2027. else if (e.code == App.ERROR_BUSY)
  2028. {
  2029. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  2030. }
  2031. else if (e.message != null)
  2032. {
  2033. msg = mxUtils.htmlEntities(e.message);
  2034. }
  2035. else if (e.response != null && e.response.error != null)
  2036. {
  2037. msg = mxUtils.htmlEntities(e.response.error);
  2038. }
  2039. }
  2040. this.showError(title, msg, btn, fn, retry);
  2041. }
  2042. else if (fn != null)
  2043. {
  2044. fn();
  2045. }
  2046. };
  2047. /**
  2048. * Translates this point by the given vector.
  2049. *
  2050. * @param {number} dx X-coordinate of the translation.
  2051. * @param {number} dy Y-coordinate of the translation.
  2052. */
  2053. EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2)
  2054. {
  2055. var dlg = new ErrorDialog(this, title, msg, btn, fn, retry, btn2, fn2);
  2056. this.showDialog(dlg.container, 340, 150, true, false);
  2057. dlg.init();
  2058. };
  2059. /**
  2060. * Translates this point by the given vector.
  2061. *
  2062. * @param {number} dx X-coordinate of the translation.
  2063. * @param {number} dy Y-coordinate of the translation.
  2064. */
  2065. EditorUi.prototype.alert = function(msg, fn)
  2066. {
  2067. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  2068. this.showDialog(dlg.container, 340, 100, true, false);
  2069. dlg.init();
  2070. };
  2071. /**
  2072. * Translates this point by the given vector.
  2073. *
  2074. * @param {number} dx X-coordinate of the translation.
  2075. * @param {number} dy Y-coordinate of the translation.
  2076. */
  2077. EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel)
  2078. {
  2079. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  2080. this.showDialog(new ConfirmDialog(this, msg, function()
  2081. {
  2082. resume();
  2083. if (okFn != null)
  2084. {
  2085. okFn();
  2086. }
  2087. }, function()
  2088. {
  2089. resume();
  2090. if (cancelFn != null)
  2091. {
  2092. cancelFn();
  2093. }
  2094. }, okLabel, cancelLabel).container, 340, 90, true, false);
  2095. };
  2096. /**
  2097. * Translates this point by the given vector.
  2098. *
  2099. * @param {number} dx X-coordinate of the translation.
  2100. * @param {number} dy Y-coordinate of the translation.
  2101. */
  2102. EditorUi.prototype.setCurrentFile = function(file)
  2103. {
  2104. this.currentFile = file;
  2105. };
  2106. /**
  2107. * Translates this point by the given vector.
  2108. *
  2109. * @param {number} dx X-coordinate of the translation.
  2110. * @param {number} dy Y-coordinate of the translation.
  2111. */
  2112. EditorUi.prototype.getCurrentFile = function()
  2113. {
  2114. return this.currentFile;
  2115. };
  2116. /**
  2117. * Translates this point by the given vector.
  2118. *
  2119. * @param {number} dx X-coordinate of the translation.
  2120. * @param {number} dy Y-coordinate of the translation.
  2121. */
  2122. EditorUi.prototype.isDiagramEmpty = function()
  2123. {
  2124. var model = this.editor.graph.getModel();
  2125. return model.getChildCount(model.root) == 1 && model.getChildCount(model.getChildAt(model.root, 0)) == 0;
  2126. };
  2127. /**
  2128. * Handling for canvas export.
  2129. */
  2130. /**
  2131. *
  2132. */
  2133. EditorUi.prototype.isExportToCanvas = function()
  2134. {
  2135. // LATER: Fix security error caused by foreignObjects in Safari for toDataUri (tainted canvas)
  2136. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  2137. };
  2138. /**
  2139. * Translates this point by the given vector.
  2140. *
  2141. * @param {number} dx X-coordinate of the translation.
  2142. * @param {number} dy Y-coordinate of the translation.
  2143. */
  2144. EditorUi.prototype.createSvgDataUri = function(svg)
  2145. {
  2146. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  2147. };
  2148. /**
  2149. *
  2150. */
  2151. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  2152. {
  2153. var data = canvas.toDataURL('image/' + format);
  2154. // Checks if output is invalid or empty
  2155. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  2156. {
  2157. throw {message: 'Invalid image'};
  2158. }
  2159. if (xml != null)
  2160. {
  2161. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(this.editor.graph.compress(xml)));
  2162. }
  2163. return data;
  2164. };
  2165. /**
  2166. *
  2167. */
  2168. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  2169. {
  2170. var ext = ((format == 'jpeg') ? 'jpg' : format);
  2171. var filename = this.getBaseFilename() + '.' + ext;
  2172. var data = this.createImageDataUri(canvas, xml, format);
  2173. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  2174. };
  2175. /**
  2176. * Returns true if files should be saved using <saveLocalFile>.
  2177. */
  2178. EditorUi.prototype.isLocalFileSave = function()
  2179. {
  2180. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  2181. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  2182. document.documentMode != 9 && document.documentMode != 8 &&
  2183. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  2184. this.isOfflineApp() || mxClient.IS_IOS);
  2185. };
  2186. /**
  2187. * Translates this point by the given vector.
  2188. *
  2189. * @param {number} dx X-coordinate of the translation.
  2190. * @param {number} dy Y-coordinate of the translation.
  2191. */
  2192. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  2193. {
  2194. // Newer versions of IE
  2195. if (window.Blob && navigator.msSaveOrOpenBlob)
  2196. {
  2197. var blob = (base64Encoded) ?
  2198. this.base64ToBlob(data, mimeType) :
  2199. new Blob([data], {type: mimeType})
  2200. navigator.msSaveOrOpenBlob(blob, filename);
  2201. }
  2202. // Older versions of IE (binary not supported)
  2203. else if (mxClient.IS_IE)
  2204. {
  2205. var win = window.open('about:blank', '_blank');
  2206. if (win == null)
  2207. {
  2208. mxUtils.popup(data, true);
  2209. }
  2210. else
  2211. {
  2212. win.document.write(data);
  2213. win.document.close();
  2214. win.document.execCommand('SaveAs', true, filename);
  2215. win.close();
  2216. }
  2217. }
  2218. else if (mxClient.IS_IOS)
  2219. {
  2220. // Poor man's saveAs in iOS via context menu of selected output
  2221. var dlg = new TextareaDialog(this, filename + ':', data, null, null, mxResources.get('close'));
  2222. dlg.textarea.style.width = '600px';
  2223. dlg.textarea.style.height = '380px';
  2224. this.showDialog(dlg.container, 620, 460, true, true);
  2225. dlg.init();
  2226. document.execCommand('selectall', false, null);
  2227. }
  2228. else
  2229. {
  2230. var a = document.createElement('a');
  2231. // Workaround for mxXmlRequest.simulate no longer working in Safari
  2232. // if this is used (ie PNG export broken after XML export in Safari).
  2233. var useDownload = !mxClient.IS_SF && typeof a.download !== 'undefined';
  2234. if (useDownload || this.isOffline())
  2235. {
  2236. a.href = URL.createObjectURL((base64Encoded) ?
  2237. this.base64ToBlob(data, mimeType) :
  2238. new Blob([data], {type: mimeType}));
  2239. if (useDownload)
  2240. {
  2241. a.download = filename;
  2242. }
  2243. else
  2244. {
  2245. // Workaround for same window in Safari
  2246. a.setAttribute('target', '_blank');
  2247. }
  2248. document.body.appendChild(a);
  2249. try
  2250. {
  2251. window.setTimeout(function()
  2252. {
  2253. URL.revokeObjectURL(a.href);
  2254. }, 0);
  2255. a.click();
  2256. a.parentNode.removeChild(a);
  2257. }
  2258. catch (e)
  2259. {
  2260. // ignore
  2261. }
  2262. }
  2263. else
  2264. {
  2265. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  2266. req.simulate(document, '_blank');
  2267. }
  2268. }
  2269. };
  2270. /**
  2271. * Translates this point by the given vector.
  2272. *
  2273. * @param {number} dx X-coordinate of the translation.
  2274. * @param {number} dy Y-coordinate of the translation.
  2275. */
  2276. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  2277. {
  2278. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  2279. 'data=' + encodeURIComponent(this.editor.graph.compress(data));
  2280. return new mxXmlRequest(SAVE_URL, param +
  2281. ((mimeType != null) ? '&mime=' + mimeType : '') +
  2282. ((format != null) ? '&format=' + format : '') +
  2283. ((base64Response != null) ? '&base64=' + base64Response : '') +
  2284. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  2285. ((base64Encoded) ? '&binary=1' : ''));
  2286. };
  2287. /**
  2288. * Translates this point by the given vector.
  2289. *
  2290. * @param {number} dx X-coordinate of the translation.
  2291. * @param {number} dy Y-coordinate of the translation.
  2292. */
  2293. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  2294. {
  2295. contentType = contentType || '';
  2296. var sliceSize = 1024;
  2297. var byteCharacters = atob(base64Data);
  2298. var bytesLength = byteCharacters.length;
  2299. var slicesCount = Math.ceil(bytesLength / sliceSize);
  2300. var byteArrays = new Array(slicesCount);
  2301. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  2302. {
  2303. var begin = sliceIndex * sliceSize;
  2304. var end = Math.min(begin + sliceSize, bytesLength);
  2305. var bytes = new Array(end - begin);
  2306. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  2307. {
  2308. bytes[i] = byteCharacters[offset].charCodeAt(0);
  2309. }
  2310. byteArrays[sliceIndex] = new Uint8Array(bytes);
  2311. }
  2312. return new Blob(byteArrays, {type: contentType});
  2313. };
  2314. /**
  2315. * Translates this point by the given vector.
  2316. *
  2317. * @param {number} dx X-coordinate of the translation.
  2318. * @param {number} dy Y-coordinate of the translation.
  2319. */
  2320. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser)
  2321. {
  2322. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  2323. var allowTab = (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  2324. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2325. {
  2326. try
  2327. {
  2328. // Opens a new window
  2329. if (mode == '_blank')
  2330. {
  2331. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  2332. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  2333. {
  2334. if (mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  2335. {
  2336. var win = window.open('about:blank');
  2337. if (win == null)
  2338. {
  2339. mxUtils.popup(data, true);
  2340. }
  2341. else
  2342. {
  2343. win.document.write('<html><img src="data:' +
  2344. mimeType + ((base64Encoded) ? ';base64,' +
  2345. data : ';charset=utf8,' + encodeURIComponent(data)) +
  2346. '"/></html>');
  2347. win.document.close();
  2348. }
  2349. }
  2350. else
  2351. {
  2352. // win.open is workaround for cleared contents in Chrome after delay
  2353. // when using location.replace
  2354. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  2355. data : ';charset=utf8,' + encodeURIComponent(data)));
  2356. if (win == null)
  2357. {
  2358. mxUtils.popup(data, true);
  2359. }
  2360. }
  2361. }
  2362. else
  2363. {
  2364. var win = window.open('about:blank');
  2365. if (win == null)
  2366. {
  2367. mxUtils.popup(data, true);
  2368. }
  2369. else
  2370. {
  2371. win.document.write(mxUtils.htmlEntities(data, false));
  2372. win.document.close();
  2373. }
  2374. }
  2375. }
  2376. else if (mode == App.MODE_DEVICE)
  2377. {
  2378. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  2379. }
  2380. else if (newTitle != null && newTitle.length > 0)
  2381. {
  2382. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2383. {
  2384. try
  2385. {
  2386. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  2387. }
  2388. catch (e)
  2389. {
  2390. this.handleError(e);
  2391. }
  2392. }));
  2393. }
  2394. }
  2395. catch (e)
  2396. {
  2397. this.handleError(e);
  2398. }
  2399. }), mxUtils.bind(this, function()
  2400. {
  2401. this.hideDialog();
  2402. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab, null, null, (allowBrowser) ? 3 : 4);
  2403. this.showDialog(dlg.container, 380, (this.getServiceCount(allowBrowser) - 1 <
  2404. ((allowBrowser) ? 4 : 5)) ? 270 : 390, true, true);
  2405. dlg.init();
  2406. };
  2407. /**
  2408. * Translates this point by the given vector.
  2409. *
  2410. * @param {number} dx X-coordinate of the translation.
  2411. * @param {number} dy Y-coordinate of the translation.
  2412. */
  2413. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  2414. {
  2415. if (this.isLocalFileSave())
  2416. {
  2417. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  2418. }
  2419. else
  2420. {
  2421. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  2422. {
  2423. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  2424. }), data, base64Encoded, mime);
  2425. }
  2426. };
  2427. /**
  2428. * Translates this point by the given vector.
  2429. *
  2430. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  2431. * side without requiring a server roundtrip.
  2432. *
  2433. * @param {number} dx X-coordinate of the translation.
  2434. * @param {number} dy Y-coordinate of the translation.
  2435. */
  2436. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType)
  2437. {
  2438. var allowTab = !mxClient.IS_IOS || !navigator.standalone;
  2439. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2440. {
  2441. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  2442. {
  2443. var base64 = (mode == App.MODE_DEVICE || mode == null || mode == '_blank') ? '0' : '1';
  2444. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  2445. if (xhr != null)
  2446. {
  2447. if (mode == App.MODE_DEVICE || mode == '_blank')
  2448. {
  2449. xhr.simulate(document, '_blank');
  2450. }
  2451. else
  2452. {
  2453. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2454. {
  2455. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  2456. 'application/pdf' : 'image/' + format);
  2457. // Workaround for no roundtrip required if data is available on client-side
  2458. // TODO: Refactor the saveData/saveRequest call chain for local data
  2459. if (data != null)
  2460. {
  2461. try
  2462. {
  2463. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  2464. }
  2465. catch (e)
  2466. {
  2467. this.handleError(e);
  2468. }
  2469. }
  2470. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  2471. {
  2472. // LATER: Catch possible mixed content error
  2473. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  2474. xhr.send(mxUtils.bind(this, function()
  2475. {
  2476. this.spinner.stop();
  2477. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  2478. {
  2479. try
  2480. {
  2481. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  2482. }
  2483. catch (e)
  2484. {
  2485. this.handleError(e);
  2486. }
  2487. }
  2488. else
  2489. {
  2490. this.handleError({message: mxResources.get('errorSavingFile')});
  2491. }
  2492. }), function(resp)
  2493. {
  2494. this.spinner.stop();
  2495. this.handleError(resp);
  2496. });
  2497. }
  2498. }));
  2499. }
  2500. }
  2501. }
  2502. }), mxUtils.bind(this, function()
  2503. {
  2504. this.hideDialog();
  2505. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab, null, null, 4);
  2506. this.showDialog(dlg.container, 380, (this.getServiceCount(false) - 1 < 5) ? 270 : 390, true, true);
  2507. dlg.init();
  2508. };
  2509. /**
  2510. * Hook for subclassers.
  2511. */
  2512. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  2513. {
  2514. // do nothing
  2515. };
  2516. /**
  2517. * Hook for subclassers.
  2518. */
  2519. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  2520. {
  2521. fn(null);
  2522. };
  2523. /**
  2524. *
  2525. */
  2526. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow, editable, embedImages, border, noCrop, currentPage)
  2527. {
  2528. if (this.spinner.spin(document.body, mxResources.get('export')))
  2529. {
  2530. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  2531. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  2532. var bg = (transparentBackground) ? null : this.editor.graph.background;
  2533. if (bg == mxConstants.NONE)
  2534. {
  2535. bg = null;
  2536. }
  2537. // Handles special case where background is null but transparent is false
  2538. if (bg == null && transparentBackground == false)
  2539. {
  2540. bg = '#ffffff';
  2541. }
  2542. // Sets or disables alternate text for foreignObjects. Disabling is needed
  2543. // because PhantomJS seems to ignore switch statements and paint all text.
  2544. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null, ignoreSelection);
  2545. if (addShadow)
  2546. {
  2547. this.editor.graph.addSvgShadow(svgRoot);
  2548. }
  2549. var filename = this.getBaseFilename() + '.svg';
  2550. var doSave = mxUtils.bind(this, function(svgRoot)
  2551. {
  2552. this.spinner.stop();
  2553. if (editable)
  2554. {
  2555. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  2556. }
  2557. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  2558. mxUtils.getXml(svgRoot);
  2559. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  2560. {
  2561. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  2562. }
  2563. else
  2564. {
  2565. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  2566. {
  2567. mxUtils.popup(svg);
  2568. }));
  2569. }
  2570. });
  2571. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  2572. {
  2573. if (embedImages)
  2574. {
  2575. // Caches images
  2576. if (this.thumbImageCache == null)
  2577. {
  2578. this.thumbImageCache = new Object();
  2579. }
  2580. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  2581. }
  2582. else
  2583. {
  2584. doSave(svgRoot);
  2585. }
  2586. }));
  2587. }
  2588. };
  2589. /**
  2590. *
  2591. */
  2592. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible)
  2593. {
  2594. visible = (visible != null) ? visible : true;
  2595. var cb = document.createElement('input');
  2596. cb.style.marginRight = '8px';
  2597. cb.style.marginTop = '16px';
  2598. cb.setAttribute('type', 'checkbox');
  2599. if (checked)
  2600. {
  2601. cb.setAttribute('checked', 'checked');
  2602. cb.defaultChecked = true;
  2603. }
  2604. if (disabled)
  2605. {
  2606. cb.setAttribute('disabled', 'disabled');
  2607. }
  2608. if (visible)
  2609. {
  2610. div.appendChild(cb);
  2611. mxUtils.write(div, label);
  2612. if (!disableNewline)
  2613. {
  2614. mxUtils.br(div);
  2615. }
  2616. }
  2617. return cb;
  2618. };
  2619. /**
  2620. *
  2621. */
  2622. EditorUi.prototype.addEditButton = function(div, lightbox)
  2623. {
  2624. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  2625. edit.style.marginLeft = '24px';
  2626. var file = this.getCurrentFile();
  2627. var editUrl = '';
  2628. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  2629. {
  2630. editUrl = window.location.href;
  2631. }
  2632. var editSelect = document.createElement('select');
  2633. editSelect.style.width = '120px';
  2634. editSelect.style.marginLeft = '8px';
  2635. editSelect.style.marginRight = '10px';
  2636. editSelect.className = 'geBtn';
  2637. var blankOption = document.createElement('option');
  2638. blankOption.setAttribute('value', 'blank');
  2639. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  2640. editSelect.appendChild(blankOption);
  2641. var customOption = document.createElement('option');
  2642. customOption.setAttribute('value', 'custom');
  2643. mxUtils.write(customOption, mxResources.get('custom') + '...');
  2644. editSelect.appendChild(customOption);
  2645. div.appendChild(editSelect);
  2646. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  2647. {
  2648. if (editSelect.value == 'custom')
  2649. {
  2650. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  2651. {
  2652. if (value != null)
  2653. {
  2654. editUrl = value;
  2655. }
  2656. else
  2657. {
  2658. editSelect.value = 'blank';
  2659. }
  2660. }, mxResources.get('url'), null, null, null, null, function()
  2661. {
  2662. editSelect.value = 'blank';
  2663. });
  2664. this.showDialog(dlg2.container, 300, 80, true, false);
  2665. dlg2.init();
  2666. }
  2667. }));
  2668. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  2669. {
  2670. if (edit.checked && (lightbox == null || lightbox.checked))
  2671. {
  2672. editSelect.removeAttribute('disabled');
  2673. }
  2674. else
  2675. {
  2676. editSelect.setAttribute('disabled', 'disabled');
  2677. }
  2678. }));
  2679. mxUtils.br(div);
  2680. return {
  2681. getLink: function()
  2682. {
  2683. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  2684. },
  2685. getEditInput: function()
  2686. {
  2687. return edit;
  2688. },
  2689. getEditSelect: function()
  2690. {
  2691. return editSelect;
  2692. }
  2693. };
  2694. }
  2695. /**
  2696. *
  2697. */
  2698. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  2699. {
  2700. mxUtils.write(div, mxResources.get('links') + ':');
  2701. var linkSelect = document.createElement('select');
  2702. linkSelect.style.width = '100px';
  2703. linkSelect.style.marginLeft = '8px';
  2704. linkSelect.style.marginRight = '10px';
  2705. linkSelect.className = 'geBtn';
  2706. var autoOption = document.createElement('option');
  2707. autoOption.setAttribute('value', 'auto');
  2708. mxUtils.write(autoOption, mxResources.get('automatic'));
  2709. linkSelect.appendChild(autoOption);
  2710. var blankOption = document.createElement('option');
  2711. blankOption.setAttribute('value', 'blank');
  2712. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  2713. linkSelect.appendChild(blankOption);
  2714. var selfOption = document.createElement('option');
  2715. selfOption.setAttribute('value', 'self');
  2716. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  2717. linkSelect.appendChild(selfOption);
  2718. if (showFrameOption)
  2719. {
  2720. var frameOption = document.createElement('option');
  2721. frameOption.setAttribute('value', 'frame');
  2722. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  2723. ' (' + mxResources.get('iframe') + ')');
  2724. linkSelect.appendChild(frameOption);
  2725. }
  2726. div.appendChild(linkSelect);
  2727. mxUtils.write(div, mxResources.get('borderColor') + ':');
  2728. var linkColor = '#0000ff';
  2729. var linkButton = null;
  2730. function updateLinkColor()
  2731. {
  2732. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  2733. ((linkColor != null && linkColor != mxConstants.NONE) ?
  2734. 'border:1px solid black;background-color:' + linkColor :
  2735. 'background-position:center center;background-repeat:no-repeat;' +
  2736. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  2737. };
  2738. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  2739. {
  2740. this.pickColor(linkColor || 'none', function(color)
  2741. {
  2742. linkColor = color;
  2743. updateLinkColor();
  2744. });
  2745. mxEvent.consume(evt);
  2746. }));
  2747. updateLinkColor();
  2748. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  2749. linkButton.style.marginLeft = '4px';
  2750. linkButton.style.height = '22px';
  2751. linkButton.style.width = '22px';
  2752. linkButton.style.position = 'relative';
  2753. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  2754. linkButton.className = 'geColorBtn';
  2755. div.appendChild(linkButton);
  2756. mxUtils.br(div);
  2757. return {
  2758. getColor: function()
  2759. {
  2760. return linkColor;
  2761. },
  2762. getTarget: function()
  2763. {
  2764. return linkSelect.value;
  2765. },
  2766. focus: function()
  2767. {
  2768. linkSelect.focus();
  2769. }
  2770. };
  2771. }
  2772. /**
  2773. *
  2774. */
  2775. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  2776. {
  2777. var file = this.getCurrentFile();
  2778. var params = [];
  2779. if (lightbox)
  2780. {
  2781. params.push('lightbox=1');
  2782. if (linkTarget != 'auto')
  2783. {
  2784. params.push('target=' + linkTarget);
  2785. }
  2786. if (linkColor != null && linkColor != mxConstants.NONE)
  2787. {
  2788. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  2789. }
  2790. if (editLink != null && editLink.length > 0)
  2791. {
  2792. params.push('edit=' + encodeURIComponent(editLink));
  2793. }
  2794. if (layers)
  2795. {
  2796. params.push('layers=1');
  2797. }
  2798. if (this.editor.graph.foldingEnabled)
  2799. {
  2800. params.push('nav=1');
  2801. }
  2802. }
  2803. if (allPages && this.pages != null && this.currentPage != null)
  2804. {
  2805. for (var i = 0; i < this.pages.length; i++)
  2806. {
  2807. if (this.pages[i] == this.currentPage)
  2808. {
  2809. if (i > 0)
  2810. {
  2811. params.push('page=' + i);
  2812. }
  2813. break;
  2814. }
  2815. }
  2816. }
  2817. var data = '';
  2818. var addTitle = true;
  2819. if (url != null)
  2820. {
  2821. data = '#U' + encodeURIComponent(url);
  2822. }
  2823. else
  2824. {
  2825. var file = this.getCurrentFile();
  2826. // Fallback to non-public URL for Drive files
  2827. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  2828. {
  2829. data = '#' + file.getHash();
  2830. addTitle = false;
  2831. }
  2832. else
  2833. {
  2834. data = '#R' + encodeURIComponent((allPages) ?
  2835. this.getFileData(true, null, null, null, null, null, null, true) :
  2836. this.editor.graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  2837. }
  2838. }
  2839. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  2840. {
  2841. params.push('title=' + encodeURIComponent(file.getTitle()));
  2842. }
  2843. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) ? 'https://www.draw.io/' : 'https://' + location.host + '/') +
  2844. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  2845. };
  2846. /**
  2847. *
  2848. */
  2849. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  2850. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  2851. {
  2852. var s = this.getBasenames();
  2853. var data = {};
  2854. if (linkColor != '' && linkColor != mxConstants.NONE)
  2855. {
  2856. data.highlight = linkColor;
  2857. }
  2858. if (linkTarget !== 'auto')
  2859. {
  2860. data.target = linkTarget;
  2861. }
  2862. if (!lightbox)
  2863. {
  2864. data.lightbox = false;
  2865. }
  2866. data.nav = this.editor.graph.foldingEnabled;
  2867. var zoom = parseInt(initialZoom);
  2868. if (!isNaN(zoom) && zoom != 100)
  2869. {
  2870. data.zoom = zoom / 100;
  2871. }
  2872. var tb = [];
  2873. if (allPages)
  2874. {
  2875. tb.push('pages');
  2876. data.resize = true;
  2877. if (this.pages != null && this.currentPage != null)
  2878. {
  2879. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  2880. }
  2881. }
  2882. if (zoomEnabled)
  2883. {
  2884. tb.push('zoom');
  2885. data.resize = true;
  2886. }
  2887. if (layers)
  2888. {
  2889. tb.push('layers');
  2890. }
  2891. if (tb.length > 0)
  2892. {
  2893. if (lightbox)
  2894. {
  2895. tb.push('lightbox');
  2896. }
  2897. data.toolbar = tb.join(' ');
  2898. }
  2899. if (editLink != null && editLink.length > 0)
  2900. {
  2901. data.edit = editLink;
  2902. }
  2903. if (publicUrl != null)
  2904. {
  2905. data.url = publicUrl;
  2906. }
  2907. else
  2908. {
  2909. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  2910. }
  2911. var value = '<div class="mxgraph" style="' +
  2912. ((fit) ? 'max-width:100%;' : '') +
  2913. ((tb != '') ? 'border:1px solid transparent;' : '') +
  2914. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  2915. var sParam = (s.length > 0) ? 's=' + s.join(';') : '';
  2916. var fetchParam = (publicUrl != null) ? 'fetch=' + encodeURIComponent(publicUrl) : '';
  2917. var s2 = (sParam.length > 0 || fetchParam.length > 0) ?
  2918. (((urlParams['dev'] == '1') ?
  2919. 'https://test.draw.io/embed2.js?dev=1&' + sParam :
  2920. 'https://www.draw.io/embed2.js?' + sParam)) + '&' + fetchParam :
  2921. (((urlParams['dev'] == '1') ?
  2922. 'https://test.draw.io/js/viewer.min.js' :
  2923. 'https://www.draw.io/js/viewer.min.js'));
  2924. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  2925. fn(value, scr);
  2926. };
  2927. /**
  2928. *
  2929. */
  2930. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  2931. {
  2932. var div = document.createElement('div');
  2933. div.style.whiteSpace = 'nowrap';
  2934. var graph = this.editor.graph;
  2935. var hd = document.createElement('h3');
  2936. mxUtils.write(hd, mxResources.get('html'));
  2937. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  2938. div.appendChild(hd);
  2939. var radioSection = document.createElement('div');
  2940. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  2941. var publicUrlRadio = document.createElement('input');
  2942. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  2943. publicUrlRadio.setAttribute('value', 'url');
  2944. publicUrlRadio.setAttribute('type', 'radio');
  2945. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  2946. var copyRadio = publicUrlRadio.cloneNode(true);
  2947. copyRadio.setAttribute('value', 'copy');
  2948. radioSection.appendChild(copyRadio);
  2949. var span = document.createElement('span');
  2950. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  2951. radioSection.appendChild(span);
  2952. mxUtils.br(radioSection);
  2953. radioSection.appendChild(publicUrlRadio);
  2954. var span = document.createElement('span');
  2955. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  2956. radioSection.appendChild(span);
  2957. var file = this.getCurrentFile();
  2958. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  2959. {
  2960. var testLink = document.createElement('a');
  2961. testLink.style.paddingLeft = '12px';
  2962. testLink.style.color = 'gray';
  2963. testLink.setAttribute('href', 'javascript:void(0);');
  2964. mxUtils.write(testLink, mxResources.get('share'));
  2965. radioSection.appendChild(testLink);
  2966. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  2967. {
  2968. this.hideDialog();
  2969. this.drive.showPermissions(file.getId());
  2970. }));
  2971. }
  2972. copyRadio.setAttribute('checked', 'checked');
  2973. if (publicUrl == null)
  2974. {
  2975. publicUrlRadio.setAttribute('disabled', 'disabled');
  2976. }
  2977. div.appendChild(radioSection);
  2978. var linkSection = this.addLinkSection(div);
  2979. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  2980. mxUtils.write(div, ':');
  2981. var zoomInput = document.createElement('input');
  2982. zoomInput.setAttribute('type', 'text');
  2983. zoomInput.style.marginRight = '16px';
  2984. zoomInput.style.width = '60px';
  2985. zoomInput.style.marginLeft = '4px';
  2986. zoomInput.style.marginRight = '12px';
  2987. zoomInput.value = '100%';
  2988. div.appendChild(zoomInput);
  2989. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  2990. var hasPages = this.pages != null && this.pages.length > 1;
  2991. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  2992. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  2993. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  2994. var editSection = this.addEditButton(div, lightbox);
  2995. var edit = editSection.getEditInput();
  2996. edit.style.marginBottom = '16px';
  2997. mxEvent.addListener(lightbox, 'change', function()
  2998. {
  2999. if (lightbox.checked)
  3000. {
  3001. edit.removeAttribute('disabled');
  3002. }
  3003. else
  3004. {
  3005. edit.setAttribute('disabled', 'disabled');
  3006. }
  3007. if (edit.checked && lightbox.checked)
  3008. {
  3009. editSection.getEditSelect().removeAttribute('disabled');
  3010. }
  3011. else
  3012. {
  3013. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3014. }
  3015. });
  3016. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3017. {
  3018. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  3019. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  3020. editSection.getLink());
  3021. }), null, btnLabel, helpLink);
  3022. this.showDialog(dlg.container, 340, 360, true, true);
  3023. copyRadio.focus();
  3024. };
  3025. /**
  3026. *
  3027. */
  3028. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  3029. {
  3030. var div = document.createElement('div');
  3031. div.style.whiteSpace = 'nowrap';
  3032. var graph = this.editor.graph;
  3033. var hd = document.createElement('h3');
  3034. mxUtils.write(hd, title || mxResources.get('link'));
  3035. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  3036. div.appendChild(hd);
  3037. var file = this.getCurrentFile();
  3038. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  3039. var dy = 0;
  3040. if (file != null && file.constructor == window.DriveFile && !hideShare)
  3041. {
  3042. dy = 80;
  3043. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  3044. var hintSection = document.createElement('div');
  3045. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  3046. var text = document.createElement('div');
  3047. text.style.whiteSpace = 'normal';
  3048. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  3049. hintSection.appendChild(text);
  3050. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  3051. {
  3052. this.drive.showPermissions(file.getId());
  3053. }));
  3054. shareBtn.style.marginTop = '12px';
  3055. shareBtn.className = 'geBtn';
  3056. hintSection.appendChild(shareBtn);
  3057. div.appendChild(hintSection);
  3058. var testLink = document.createElement('a');
  3059. testLink.style.paddingLeft = '12px';
  3060. testLink.style.color = 'gray';
  3061. testLink.style.fontSize = '11px';
  3062. testLink.setAttribute('href', 'javascript:void(0);');
  3063. mxUtils.write(testLink, mxResources.get('check'));
  3064. hintSection.appendChild(testLink);
  3065. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  3066. {
  3067. if (this.spinner.spin(document.body, mxResources.get('loading')))
  3068. {
  3069. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  3070. {
  3071. this.spinner.stop();
  3072. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  3073. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  3074. this.showDialog(dlg.container, 300, 80, true, false);
  3075. dlg.init();
  3076. }));
  3077. }
  3078. }));
  3079. }
  3080. var widthInput = null;
  3081. var heightInput = null;
  3082. if (width != null || height != null)
  3083. {
  3084. dy += 30;
  3085. mxUtils.write(div, mxResources.get('width') + ':');
  3086. widthInput = document.createElement('input');
  3087. widthInput.setAttribute('type', 'text');
  3088. widthInput.style.marginRight = '16px';
  3089. widthInput.style.width = '50px';
  3090. widthInput.style.marginLeft = '6px';
  3091. widthInput.style.marginRight = '16px';
  3092. widthInput.style.marginBottom = '10px';
  3093. widthInput.value = '100%';
  3094. div.appendChild(widthInput);
  3095. mxUtils.write(div, mxResources.get('height') + ':');
  3096. heightInput = document.createElement('input');
  3097. heightInput.setAttribute('type', 'text');
  3098. heightInput.style.width = '50px';
  3099. heightInput.style.marginLeft = '6px';
  3100. heightInput.style.marginBottom = '10px';
  3101. heightInput.value = height + 'px';
  3102. div.appendChild(heightInput);
  3103. mxUtils.br(div);
  3104. }
  3105. var linkSection = this.addLinkSection(div, showFrameOption);
  3106. var hasPages = this.pages != null && this.pages.length > 1;
  3107. var allPages = null;
  3108. if (file == null || file.constructor != window.DriveFile || hideShare)
  3109. {
  3110. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  3111. }
  3112. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3113. var editSection = this.addEditButton(div, lightbox);
  3114. var edit = editSection.getEditInput();
  3115. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  3116. layers.style.marginLeft = edit.style.marginLeft;
  3117. layers.style.marginBottom = '16px';
  3118. layers.style.marginTop = '8px';
  3119. mxEvent.addListener(lightbox, 'change', function()
  3120. {
  3121. if (lightbox.checked)
  3122. {
  3123. layers.removeAttribute('disabled');
  3124. edit.removeAttribute('disabled');
  3125. }
  3126. else
  3127. {
  3128. layers.setAttribute('disabled', 'disabled');
  3129. edit.setAttribute('disabled', 'disabled');
  3130. }
  3131. if (edit.checked && lightbox.checked)
  3132. {
  3133. editSection.getEditSelect().removeAttribute('disabled');
  3134. }
  3135. else
  3136. {
  3137. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3138. }
  3139. });
  3140. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3141. {
  3142. fn(linkSection.getTarget(), linkSection.getColor(),
  3143. (allPages == null) ? true : allPages.checked,
  3144. lightbox.checked, editSection.getLink(),
  3145. layers.checked, (widthInput != null) ? widthInput.value : null,
  3146. (heightInput != null) ? heightInput.value : null);
  3147. }), null, mxResources.get('create'), helpLink);
  3148. this.showDialog(dlg.container, 340, 246 + dy, true, true);
  3149. if (widthInput != null)
  3150. {
  3151. widthInput.focus();
  3152. if (mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3153. {
  3154. widthInput.select();
  3155. }
  3156. else
  3157. {
  3158. document.execCommand('selectAll', false, null);
  3159. }
  3160. }
  3161. else
  3162. {
  3163. linkSection.focus();
  3164. }
  3165. };
  3166. /**
  3167. *
  3168. */
  3169. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  3170. {
  3171. var div = document.createElement('div');
  3172. div.style.whiteSpace = 'nowrap';
  3173. var hd = document.createElement('h3');
  3174. mxUtils.write(hd, mxResources.get('image'));
  3175. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3176. div.appendChild(hd);
  3177. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  3178. this.editor.graph.isSelectionEmpty());
  3179. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  3180. if (include != null)
  3181. {
  3182. include.style.marginBottom = '16px';
  3183. }
  3184. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3185. {
  3186. callback(!selection.checked, (include != null) ? include.checked : false);
  3187. }), null, btnLabel, helpLink);
  3188. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 146, true, true);
  3189. };
  3190. /**
  3191. *
  3192. */
  3193. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  3194. cropOption, defaultInclude, format)
  3195. {
  3196. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  3197. var div = document.createElement('div');
  3198. div.style.whiteSpace = 'nowrap';
  3199. var graph = this.editor.graph;
  3200. var height = (format == 'jpeg') ? 170 : 280;
  3201. var hd = document.createElement('h3');
  3202. mxUtils.write(hd, title);
  3203. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  3204. div.appendChild(hd);
  3205. mxUtils.write(div, mxResources.get('zoom') + ':');
  3206. var zoomInput = document.createElement('input');
  3207. zoomInput.setAttribute('type', 'text');
  3208. zoomInput.style.marginRight = '16px';
  3209. zoomInput.style.width = '60px';
  3210. zoomInput.style.marginLeft = '4px';
  3211. zoomInput.style.marginRight = '12px';
  3212. zoomInput.value = this.lastExportZoom || '100%';
  3213. div.appendChild(zoomInput);
  3214. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  3215. var borderInput = document.createElement('input');
  3216. borderInput.setAttribute('type', 'text');
  3217. borderInput.style.marginRight = '16px';
  3218. borderInput.style.width = '60px';
  3219. borderInput.style.marginLeft = '4px';
  3220. borderInput.value = this.lastExportBorder || '0';
  3221. div.appendChild(borderInput);
  3222. mxUtils.br(div);
  3223. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  3224. graph.background == mxConstants.NONE || graph.background == null, null, null, format != 'jpeg');
  3225. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  3226. false, graph.isSelectionEmpty());
  3227. var cb6 = document.createElement('input');
  3228. cb6.style.marginTop = '16px';
  3229. cb6.style.marginRight = '8px';
  3230. cb6.setAttribute('type', 'checkbox');
  3231. if (cropOption)
  3232. {
  3233. div.appendChild(cb6);
  3234. mxUtils.write(div, mxResources.get('crop'));
  3235. mxUtils.br(div);
  3236. height += 26;
  3237. }
  3238. if (graph.isSelectionEmpty())
  3239. {
  3240. cb6.setAttribute('disabled', 'disabled');
  3241. }
  3242. else
  3243. {
  3244. cb6.setAttribute('checked', 'checked');
  3245. cb6.defaultChecked = true;
  3246. }
  3247. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  3248. var cb5 = document.createElement('input');
  3249. cb5.style.marginTop = '16px';
  3250. cb5.style.marginRight = '8px';
  3251. cb5.setAttribute('type', 'checkbox');
  3252. if (this.isOffline() || !this.canvasSupported)
  3253. {
  3254. cb5.setAttribute('disabled', 'disabled');
  3255. }
  3256. if (embedOption)
  3257. {
  3258. div.appendChild(cb5);
  3259. mxUtils.write(div, mxResources.get('embedImages'));
  3260. mxUtils.br(div);
  3261. height += 26;
  3262. }
  3263. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  3264. var hasPages = this.pages != null && this.pages.length > 1;
  3265. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  3266. allPages.style.marginLeft = '24px';
  3267. allPages.style.marginBottom = '16px';
  3268. if (!hasPages)
  3269. {
  3270. allPages.style.visibility = 'hidden';
  3271. }
  3272. mxEvent.addListener(include, 'change', function()
  3273. {
  3274. if (include.checked && hasPages)
  3275. {
  3276. allPages.removeAttribute('disabled');
  3277. }
  3278. else
  3279. {
  3280. allPages.setAttribute('disabled', 'disabled');
  3281. }
  3282. });
  3283. if (!defaultInclude || !hasPages)
  3284. {
  3285. allPages.setAttribute('disabled', 'disabled');
  3286. }
  3287. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3288. {
  3289. this.lastExportBorder = borderInput.value;
  3290. this.lastExportZoom = zoomInput.value;
  3291. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  3292. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked);
  3293. }), null, btnLabel, helpLink);
  3294. this.showDialog(dlg.container, 320, height, true, true);
  3295. zoomInput.focus();
  3296. if (mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3297. {
  3298. zoomInput.select();
  3299. }
  3300. else
  3301. {
  3302. document.execCommand('selectAll', false, null);
  3303. }
  3304. };
  3305. /**
  3306. *
  3307. */
  3308. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  3309. {
  3310. var div = document.createElement('div');
  3311. div.style.whiteSpace = 'nowrap';
  3312. var graph = this.editor.graph;
  3313. if (title != null)
  3314. {
  3315. var hd = document.createElement('h3');
  3316. mxUtils.write(hd, title);
  3317. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3318. div.appendChild(hd);
  3319. }
  3320. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  3321. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  3322. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  3323. var image = this.addCheckbox(div, imageLabel);
  3324. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3325. var editSection = this.addEditButton(div, lightbox);
  3326. var edit = editSection.getEditInput();
  3327. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  3328. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  3329. layers.style.marginLeft = edit.style.marginLeft;
  3330. layers.style.marginBottom = '12px';
  3331. layers.style.marginTop = '8px';
  3332. mxEvent.addListener(lightbox, 'change', function()
  3333. {
  3334. if (lightbox.checked)
  3335. {
  3336. if (hasLayers)
  3337. {
  3338. layers.removeAttribute('disabled');
  3339. }
  3340. edit.removeAttribute('disabled');
  3341. }
  3342. else
  3343. {
  3344. layers.setAttribute('disabled', 'disabled');
  3345. edit.setAttribute('disabled', 'disabled');
  3346. }
  3347. if (edit.checked && lightbox.checked)
  3348. {
  3349. editSection.getEditSelect().removeAttribute('disabled');
  3350. }
  3351. else
  3352. {
  3353. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  3354. }
  3355. });
  3356. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3357. {
  3358. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  3359. editSection.getLink(), layers.checked);
  3360. }), null, mxResources.get('embed'), helpLink);
  3361. this.showDialog(dlg.container, 280, 280, true, true);
  3362. };
  3363. /**
  3364. *
  3365. */
  3366. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  3367. {
  3368. var bounds = this.editor.graph.getGraphBounds();
  3369. function doUpdate(dataUri)
  3370. {
  3371. var onclick = ' ';
  3372. var css = '';
  3373. // Adds double click handling
  3374. if (lightbox)
  3375. {
  3376. // KNOWN: Message passing does not seem to work in IE11
  3377. 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(" +
  3378. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3379. ((edit) ? "&edit=_blank" : "") +
  3380. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3381. css += 'cursor:pointer;';
  3382. }
  3383. if (fit)
  3384. {
  3385. css += 'max-width:100%;';
  3386. }
  3387. var atts = '';
  3388. if (retina)
  3389. {
  3390. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  3391. }
  3392. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3393. };
  3394. if (this.isExportToCanvas())
  3395. {
  3396. var scale = 1;
  3397. var ignoreSelection = true;
  3398. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3399. {
  3400. var xml = (lightbox) ? this.getFileData(true) : null;
  3401. var data = this.createImageDataUri(canvas, xml, 'png');
  3402. doUpdate(data);
  3403. }), null, null, null, mxUtils.bind(this, function(e)
  3404. {
  3405. err({message: mxResources.get('unknownError')});
  3406. }), null, true, (retina) ? 2 : 1, null, shadow);
  3407. }
  3408. else
  3409. {
  3410. var data = this.getFileData(true);
  3411. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  3412. {
  3413. var size = '';
  3414. if (retina)
  3415. {
  3416. size = '&w=' + Math.round(2 * bounds.width) +
  3417. '&h=' + Math.round(2 * bounds.height);
  3418. }
  3419. var embed = (lightbox) ? '1' : '0';
  3420. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  3421. '&base64=1&embedXml=' + embed + size + '&xml=' +
  3422. encodeURIComponent(data));
  3423. // LATER: Updates on each change, add a delay
  3424. req.send(mxUtils.bind(this, function()
  3425. {
  3426. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  3427. {
  3428. // Fixes possible "incorrect function" for select() on
  3429. // DOM node which is no longer in document with IE11
  3430. doUpdate('data:image/png;base64,' + req.getText());
  3431. }
  3432. else
  3433. {
  3434. err({message: mxResources.get('unknownError')});
  3435. }
  3436. }));
  3437. }
  3438. else
  3439. {
  3440. err({message: mxResources.get('drawingTooLarge')});
  3441. }
  3442. }
  3443. };
  3444. /**
  3445. *
  3446. */
  3447. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  3448. {
  3449. var svgRoot = this.editor.graph.getSvg();
  3450. // Keeps hashtag links on same page
  3451. var links = svgRoot.getElementsByTagName('a');
  3452. if (links != null)
  3453. {
  3454. for (var i = 0; i < links.length; i++)
  3455. {
  3456. var href = links[i].getAttribute('href');
  3457. if (href != null && href.charAt(0) == '#' &&
  3458. links[i].getAttribute('target') == '_blank')
  3459. {
  3460. links[i].removeAttribute('target');
  3461. }
  3462. }
  3463. }
  3464. if (lightbox)
  3465. {
  3466. svgRoot.setAttribute('content', this.getFileData(true));
  3467. }
  3468. // Adds shadow filter
  3469. if (shadow)
  3470. {
  3471. this.editor.graph.addSvgShadow(svgRoot);
  3472. }
  3473. // SVG inside image tag
  3474. if (image)
  3475. {
  3476. var onclick = ' ';
  3477. var css = '';
  3478. // Adds double click handling
  3479. if (lightbox)
  3480. {
  3481. // KNOWN: Message passing does not seem to work in IE11
  3482. 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(" +
  3483. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3484. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3485. css += 'cursor:pointer;';
  3486. }
  3487. if (fit)
  3488. {
  3489. css += 'max-width:100%;';
  3490. }
  3491. // Images inside IMG don't seem to work so embed them all
  3492. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  3493. {
  3494. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  3495. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3496. }));
  3497. }
  3498. else
  3499. {
  3500. var css = '';
  3501. // Adds double click handling
  3502. if (lightbox)
  3503. {
  3504. // KNOWN: Message passing does not seem to work in IE11
  3505. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  3506. // Ignores link events
  3507. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  3508. // Focus existing lightbox
  3509. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  3510. // Message handling
  3511. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  3512. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  3513. "window.addEventListener('message',r);" +
  3514. // Opens lightbox window
  3515. "svg.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3516. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  3517. svgRoot.setAttribute('onclick', js);
  3518. css += 'cursor:pointer;';
  3519. }
  3520. // Adds responsive size
  3521. if (fit)
  3522. {
  3523. var w = parseInt(svgRoot.getAttribute('width'));
  3524. var h = parseInt(svgRoot.getAttribute('height'));
  3525. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  3526. css += 'max-width:100%;max-height:' + h + 'px;';
  3527. svgRoot.removeAttribute('height');
  3528. }
  3529. if (css != '')
  3530. {
  3531. svgRoot.setAttribute('style', css);
  3532. }
  3533. fn(mxUtils.getXml(svgRoot));
  3534. }
  3535. };
  3536. /**
  3537. * Translates this point by the given vector.
  3538. *
  3539. * @param {number} dx X-coordinate of the translation.
  3540. * @param {number} dy Y-coordinate of the translation.
  3541. */
  3542. EditorUi.prototype.timeSince = function(date)
  3543. {
  3544. var seconds = Math.floor((new Date() - date) / 1000);
  3545. var interval = Math.floor(seconds / 31536000);
  3546. if (interval > 1)
  3547. {
  3548. return interval + ' ' + mxResources.get('years');
  3549. }
  3550. interval = Math.floor(seconds / 2592000);
  3551. if (interval > 1)
  3552. {
  3553. return interval + ' ' + mxResources.get('months');
  3554. }
  3555. interval = Math.floor(seconds / 86400);
  3556. if (interval > 1)
  3557. {
  3558. return interval + ' ' + mxResources.get('days');
  3559. }
  3560. interval = Math.floor(seconds / 3600);
  3561. if (interval > 1)
  3562. {
  3563. return interval + ' ' + mxResources.get('hours');
  3564. }
  3565. interval = Math.floor(seconds / 60);
  3566. if (interval > 1)
  3567. {
  3568. return interval + ' ' + mxResources.get('minutes');
  3569. }
  3570. if (interval == 1)
  3571. {
  3572. return interval + ' ' + mxResources.get('minute');
  3573. }
  3574. return null;
  3575. };
  3576. /**
  3577. * Converts math in the given SVG
  3578. */
  3579. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  3580. {
  3581. // FIXME: Only horizontal dash in output so better no conversion at all
  3582. if (false && graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  3583. {
  3584. // Workaround for lost gradients in Chrome after remove from DOM
  3585. var elts = svgRoot.getElementsByTagName('*');
  3586. for (var i = 0; i < elts.length; i++)
  3587. {
  3588. if (elts[i].getAttribute('id') != null)
  3589. {
  3590. elts[i].setAttribute('id', 'mxTemporaryPrefix-' + elts[i].getAttribute('id'));
  3591. }
  3592. }
  3593. // Temporarily attaches to DOM for rendering
  3594. svgRoot.style.visibility = 'hidden';
  3595. document.body.appendChild(svgRoot);
  3596. Editor.MathJaxRender(svgRoot);
  3597. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  3598. {
  3599. // Removes from DOM
  3600. svgRoot.parentNode.removeChild(svgRoot);
  3601. svgRoot.style.visibility = '';
  3602. // Restores original IDs
  3603. for (var i = 0; i < elts.length; i++)
  3604. {
  3605. if (elts[i].getAttribute('id') != null)
  3606. {
  3607. elts[i].setAttribute('id', elts[i].getAttribute('id').substring('mxTemporaryPrefix-'.length));
  3608. }
  3609. }
  3610. // Keeping scale but moving translate only works for image export which
  3611. // is fine since we do not want the SVG export to contain a workaround.
  3612. // See https://github.com/mathjax/MathJax/issues/279
  3613. if (fixPosition && navigator.userAgent.indexOf('AppleWebKit/') >= 0)
  3614. {
  3615. var fo = svgRoot.getElementsByTagName('foreignObject');
  3616. for (var i = 0; i < fo.length; i++)
  3617. {
  3618. var tr = fo[i].parentNode.parentNode.getAttribute('transform');
  3619. var translate = /translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/.exec(tr);
  3620. fo[i].setAttribute('x', Math.round(translate[1]));
  3621. fo[i].setAttribute('y', Math.round(translate[2]));
  3622. // Must use translate for crisp rendering
  3623. fo[i].parentNode.parentNode.setAttribute('transform', 'translate(0.5,0.5)' + tr.substring(tr.indexOf(')') + 1));
  3624. }
  3625. }
  3626. callback();
  3627. }));
  3628. }
  3629. else
  3630. {
  3631. callback();
  3632. }
  3633. };
  3634. /**
  3635. * Returns the SVG of the diagram with embedded XML. If a callback function is
  3636. * used, the images are converted to data URIs.
  3637. */
  3638. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  3639. {
  3640. var bg = graph.background;
  3641. if (bg == mxConstants.NONE)
  3642. {
  3643. bg = null;
  3644. }
  3645. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3646. // because PhantomJS seems to ignore switch statements and paint all text.
  3647. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  3648. if (xml != null)
  3649. {
  3650. svgRoot.setAttribute('content', xml);
  3651. }
  3652. if (url != null)
  3653. {
  3654. svgRoot.setAttribute('resource', url);
  3655. }
  3656. // LATER: Click on SVG content to start editing
  3657. // if (redirect != null)
  3658. // {
  3659. // // TODO: Ignore anchor tag source for click event
  3660. // svgRoot.setAttribute('style', 'cursor:pointer;');
  3661. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  3662. // }
  3663. if (callback != null)
  3664. {
  3665. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  3666. {
  3667. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  3668. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  3669. mxUtils.getXml(svgRoot));
  3670. }));
  3671. }
  3672. else
  3673. {
  3674. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  3675. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  3676. mxUtils.getXml(svgRoot);
  3677. }
  3678. };
  3679. /**
  3680. *
  3681. */
  3682. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  3683. {
  3684. format = (format != null) ? format : 'png';
  3685. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  3686. {
  3687. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3688. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3689. // Caches images
  3690. if (this.thumbImageCache == null)
  3691. {
  3692. this.thumbImageCache = new Object();
  3693. }
  3694. try
  3695. {
  3696. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3697. {
  3698. this.spinner.stop();
  3699. try
  3700. {
  3701. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  3702. null, null, ignoreSelection, currentPage) : null, format);
  3703. }
  3704. catch (e)
  3705. {
  3706. // Fallback to server-side image export
  3707. if (e.message == 'Invalid image')
  3708. {
  3709. this.downloadFile(format);
  3710. }
  3711. else
  3712. {
  3713. this.handleError(e);
  3714. }
  3715. }
  3716. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3717. {
  3718. this.spinner.stop();
  3719. this.handleError(e);
  3720. }), null, ignoreSelection, scale || 1, transparentBackground,
  3721. addShadow, null, null, border, noCrop);
  3722. }
  3723. catch (e)
  3724. {
  3725. this.spinner.stop();
  3726. this.handleError(e);
  3727. }
  3728. }
  3729. };
  3730. /**
  3731. * For the fontCSS to be applied when rendering images on canvas, the actual
  3732. * font data must be made available via a data URI encoding of the file.
  3733. */
  3734. EditorUi.prototype.loadFonts = function(then)
  3735. {
  3736. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  3737. {
  3738. var parts = this.editor.fontCss.split('url(');
  3739. var waiting = 0;
  3740. var fonts = {};
  3741. var finish = mxUtils.bind(this, function()
  3742. {
  3743. if (waiting == 0)
  3744. {
  3745. // Constructs string
  3746. var result = [parts[0]];
  3747. for (var j = 1; j < parts.length; j++)
  3748. {
  3749. var idx = parts[j].indexOf(')');
  3750. result.push('url(');
  3751. result.push(fonts[parts[j].substring(0, idx)]);
  3752. result.push(parts[j].substring(idx));
  3753. }
  3754. this.editor.resolvedFontCss = result.join('');
  3755. then();
  3756. }
  3757. });
  3758. if (parts.length > 0)
  3759. {
  3760. for (var i = 1; i < parts.length; i++)
  3761. {
  3762. var idx = parts[i].indexOf(')');
  3763. (mxUtils.bind(this, function(url)
  3764. {
  3765. if (fonts[url] == null)
  3766. {
  3767. // Mark font es being fetched and fetch it
  3768. fonts[url] = url;
  3769. waiting++;
  3770. var mime = 'application/x-font-ttf';
  3771. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  3772. if (/(\.svg)($|\?)/i.test(url))
  3773. {
  3774. mime = 'image/svg+xml';
  3775. }
  3776. else if (/(\.otf)($|\?)/i.test(url))
  3777. {
  3778. mime = 'application/x-font-opentype';
  3779. }
  3780. else if (/(\.woff)($|\?)/i.test(url))
  3781. {
  3782. mime = 'application/font-woff';
  3783. }
  3784. else if (/(\.woff2)($|\?)/i.test(url))
  3785. {
  3786. mime = 'application/font-woff2';
  3787. }
  3788. else if (/(\.eot)($|\?)/i.test(url))
  3789. {
  3790. mime = 'application/vnd.ms-fontobject';
  3791. }
  3792. else if (/(\.sfnt)($|\?)/i.test(url))
  3793. {
  3794. mime = 'application/font-sfnt';
  3795. }
  3796. var realUrl = url;
  3797. if ((/^https?:\/\//.test(realUrl)) && !this.isCorsEnabledForUrl(realUrl))
  3798. {
  3799. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  3800. }
  3801. // LATER: Remove cache-control header
  3802. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  3803. {
  3804. fonts[url] = uri;
  3805. waiting--;
  3806. finish();
  3807. }), mxUtils.bind(this, function(err)
  3808. {
  3809. // LATER: handle error
  3810. waiting--;
  3811. finish();
  3812. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  3813. }
  3814. }))(parts[i].substring(0, idx));
  3815. }
  3816. }
  3817. }
  3818. else
  3819. {
  3820. then();
  3821. }
  3822. };
  3823. /**
  3824. *
  3825. */
  3826. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  3827. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  3828. {
  3829. limitHeight = (limitHeight != null) ? limitHeight : true;
  3830. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  3831. graph = (graph != null) ? graph : this.editor.graph;
  3832. border = (border != null) ? border : 0;
  3833. var bg = (transparentBackground) ? null : graph.background;
  3834. if (bg == mxConstants.NONE)
  3835. {
  3836. bg = null;
  3837. }
  3838. if (bg == null)
  3839. {
  3840. bg = background;
  3841. }
  3842. // Handles special case where background is null but transparent is false
  3843. if (bg == null && transparentBackground == false)
  3844. {
  3845. bg = '#ffffff';
  3846. }
  3847. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection), mxUtils.bind(this, function(svgRoot)
  3848. {
  3849. var img = new Image();
  3850. img.onload = mxUtils.bind(this, function()
  3851. {
  3852. try
  3853. {
  3854. var canvas = document.createElement('canvas');
  3855. var w = parseInt(svgRoot.getAttribute('width'));
  3856. var h = parseInt(svgRoot.getAttribute('height'));
  3857. scale = (scale != null) ? scale : 1;
  3858. if (width != null)
  3859. {
  3860. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  3861. }
  3862. w = Math.ceil(scale * w) + 2 * border;
  3863. h = Math.ceil(scale * h) + 2 * border;
  3864. canvas.setAttribute('width', w);
  3865. canvas.setAttribute('height', h);
  3866. var ctx = canvas.getContext('2d');
  3867. if (bg != null)
  3868. {
  3869. ctx.beginPath();
  3870. ctx.rect(0, 0, w, h);
  3871. ctx.fillStyle = bg;
  3872. ctx.fill();
  3873. }
  3874. ctx.scale(scale, scale);
  3875. ctx.drawImage(img, border / scale, border / scale);
  3876. callback(canvas);
  3877. }
  3878. catch (e)
  3879. {
  3880. if (error != null)
  3881. {
  3882. error(e);
  3883. }
  3884. }
  3885. });
  3886. img.onerror = function(e)
  3887. {
  3888. //console.log('img', e, img.src);
  3889. if (error != null)
  3890. {
  3891. error(e);
  3892. }
  3893. };
  3894. try
  3895. {
  3896. if (addShadow)
  3897. {
  3898. this.editor.graph.addSvgShadow(svgRoot);
  3899. }
  3900. var done = mxUtils.bind(this, function()
  3901. {
  3902. if (this.editor.resolvedFontCss != null)
  3903. {
  3904. var st = document.createElement('style');
  3905. st.setAttribute('type', 'text/css');
  3906. st.innerHTML = this.editor.resolvedFontCss;
  3907. // Must be in defs section for FF to work
  3908. var defs = svgRoot.getElementsByTagName('defs');
  3909. defs[0].appendChild(st);
  3910. }
  3911. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  3912. {
  3913. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  3914. }));
  3915. });
  3916. this.loadFonts(done);
  3917. }
  3918. catch (e)
  3919. {
  3920. //console.log('src', e, img.src);
  3921. if (error != null)
  3922. {
  3923. error(e);
  3924. }
  3925. }
  3926. }), imageCache, converter);
  3927. };
  3928. /**
  3929. * Converts all images in the SVG output to data URIs for immediate rendering
  3930. */
  3931. EditorUi.prototype.createImageUrlConverter = function()
  3932. {
  3933. var converter = new mxUrlConverter();
  3934. converter.updateBaseUrl();
  3935. // Extends convert to avoid CORS using an image proxy server
  3936. // LATER: Use img.crossOrigin="anonymous" to avoid proxy
  3937. var convert = converter.convert;
  3938. converter.convert = function(src)
  3939. {
  3940. if (src != null)
  3941. {
  3942. if ((src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://') &&
  3943. src.substring(0, converter.baseUrl.length) != converter.baseUrl)
  3944. {
  3945. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  3946. }
  3947. else if (src.substring(0, 19) != 'chrome-extension://')
  3948. {
  3949. src = convert.apply(this, arguments);
  3950. }
  3951. }
  3952. return src;
  3953. };
  3954. return converter;
  3955. };
  3956. /**
  3957. * Converts all images in the SVG output to data URIs for immediate rendering
  3958. */
  3959. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  3960. {
  3961. // Converts images to data URLs for immediate painting
  3962. if (converter == null)
  3963. {
  3964. converter = this.createImageUrlConverter();
  3965. }
  3966. // Barrier for asynchronous image loading
  3967. var counter = 0;
  3968. function inc()
  3969. {
  3970. counter++;
  3971. };
  3972. function dec()
  3973. {
  3974. counter--;
  3975. if (counter == 0)
  3976. {
  3977. callback(svgRoot);
  3978. }
  3979. };
  3980. var cache = imageCache || new Object();
  3981. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  3982. {
  3983. var images = svgRoot.getElementsByTagName(tagName);
  3984. for (var i = 0; i < images.length; i++)
  3985. {
  3986. (mxUtils.bind(this, function(img)
  3987. {
  3988. var src = converter.convert(img.getAttribute(srcAttr));
  3989. // Data URIs are pass-through
  3990. if (src != null && src.substring(0, 5) != 'data:')
  3991. {
  3992. var tmp = cache[src];
  3993. if (tmp == null)
  3994. {
  3995. inc();
  3996. this.convertImageToDataUri(src, function(uri)
  3997. {
  3998. if (uri != null)
  3999. {
  4000. cache[src] = uri;
  4001. img.setAttribute(srcAttr, uri);
  4002. }
  4003. dec();
  4004. });
  4005. }
  4006. else
  4007. {
  4008. img.setAttribute(srcAttr, tmp);
  4009. }
  4010. }
  4011. }))(images[i]);
  4012. }
  4013. });
  4014. // Converts all known image tags in output
  4015. // LATER: Add support for images in CSS
  4016. convertImages('image', 'xlink:href');
  4017. convertImages('img', 'src');
  4018. // All from cache or no images
  4019. if (counter == 0)
  4020. {
  4021. callback(svgRoot);
  4022. }
  4023. };
  4024. /**
  4025. * Checks if the client is authorized and calls the next step.
  4026. */
  4027. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix)
  4028. {
  4029. try
  4030. {
  4031. var binary = forceBinary || /(\.png)($|\?)/i.test(url) ||
  4032. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url);
  4033. retry = (retry != null) ? retry : true;
  4034. var fn = mxUtils.bind(this, function()
  4035. {
  4036. mxUtils.get(url, mxUtils.bind(this, function(req)
  4037. {
  4038. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4039. {
  4040. if (success != null)
  4041. {
  4042. var data = req.getText();
  4043. // Returns PNG as base64 encoded data URI
  4044. if (binary)
  4045. {
  4046. // NOTE: This requires BinaryToArray VB script in the page
  4047. if ((document.documentMode == 9 || document.documentMode == 10) &&
  4048. typeof window.mxUtilsBinaryToArray !== 'undefined')
  4049. {
  4050. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  4051. var tmp = new Array(bin.length);
  4052. for (var i = 0; i < bin.length; i++)
  4053. {
  4054. tmp[i] = String.fromCharCode(bin[i]);
  4055. }
  4056. data = tmp.join('');
  4057. }
  4058. // LATER: Could be JPG but modern browsers
  4059. // ignore the mime type in the data URI
  4060. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  4061. data = dataUriPrefix + this.base64Encode(data);
  4062. }
  4063. success(data);
  4064. }
  4065. }
  4066. else if (error != null)
  4067. {
  4068. error({code: App.ERROR_UNKNOWN});
  4069. }
  4070. }), function()
  4071. {
  4072. if (error != null)
  4073. {
  4074. error({code: App.ERROR_UNKNOWN});
  4075. }
  4076. }, binary, this.timeout, function()
  4077. {
  4078. if (retry && error != null)
  4079. {
  4080. error({code: App.ERROR_TIMEOUT, retry: fn});
  4081. }
  4082. });
  4083. });
  4084. fn();
  4085. }
  4086. catch (e)
  4087. {
  4088. if (error != null)
  4089. {
  4090. error(e);
  4091. }
  4092. }
  4093. };
  4094. /**
  4095. * Returns true if the given URL is known to have CORS headers.
  4096. */
  4097. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  4098. {
  4099. return url.substring(0, 34) === 'https?://raw.githubusercontent.com/' ||
  4100. /^https?:\/\/.*\.github\.io\//.test(url) ||
  4101. /^https?:\/\/(.*\.)?rawgit\.com\//.test(url);
  4102. };
  4103. /**
  4104. * Translates this point by the given vector.
  4105. *
  4106. * @param {number} dx X-coordinate of the translation.
  4107. * @param {number} dy Y-coordinate of the translation.
  4108. */
  4109. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  4110. {
  4111. if (/(\.svg)$/i.test(url))
  4112. {
  4113. mxUtils.get(url, mxUtils.bind(this, function(req)
  4114. {
  4115. callback(this.createSvgDataUri(req.getText()));
  4116. }),
  4117. function()
  4118. {
  4119. callback();
  4120. });
  4121. }
  4122. else
  4123. {
  4124. var img = new Image();
  4125. img.onload = function()
  4126. {
  4127. var canvas = document.createElement('canvas');
  4128. var ctx = canvas.getContext('2d');
  4129. canvas.height = img.height;
  4130. canvas.width = img.width;
  4131. ctx.drawImage(img, 0, 0);
  4132. callback(canvas.toDataURL());
  4133. };
  4134. img.onerror = function()
  4135. {
  4136. callback();
  4137. };
  4138. img.src = url;
  4139. }
  4140. };
  4141. /**
  4142. * Handling drag and drop and import.
  4143. */
  4144. /**
  4145. * Imports the given XML into the existing diagram.
  4146. */
  4147. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  4148. {
  4149. dx = (dx != null) ? dx : 0;
  4150. dy = (dy != null) ? dy : 0;
  4151. var cells = []
  4152. try
  4153. {
  4154. var graph = this.editor.graph;
  4155. if (xml != null && xml.length > 0)
  4156. {
  4157. var doc = mxUtils.parseXml(xml);
  4158. // Checks for mxfile with multiple pages
  4159. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  4160. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  4161. {
  4162. var diagrams = node.getElementsByTagName('diagram');
  4163. if (diagrams.length == 1)
  4164. {
  4165. node = mxUtils.parseXml(graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  4166. }
  4167. else if (diagrams.length > 1)
  4168. {
  4169. // Adds pages
  4170. graph.model.beginUpdate();
  4171. try
  4172. {
  4173. for (var i = 0; i < diagrams.length; i++)
  4174. {
  4175. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  4176. var index = this.pages.length;
  4177. // Checks for invalid page names
  4178. if (page.getName() == null)
  4179. {
  4180. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  4181. }
  4182. graph.model.execute(new ChangePage(this, page, page, index));
  4183. }
  4184. }
  4185. finally
  4186. {
  4187. graph.model.endUpdate();
  4188. }
  4189. }
  4190. }
  4191. if (node != null && node.nodeName === 'mxGraphModel')
  4192. {
  4193. var model = new mxGraphModel();
  4194. var codec = new mxCodec(node.ownerDocument);
  4195. codec.decode(node, model);
  4196. var childCount = model.getChildCount(model.getRoot());
  4197. var targetChildCount = graph.model.getChildCount(graph.model.getRoot());
  4198. // Merges into active layer if one layer is pasted
  4199. graph.model.beginUpdate();
  4200. try
  4201. {
  4202. // Mapping for multiple calls to cloneCells with the same set of cells
  4203. var mapping = new Object();
  4204. for (var i = 0; i < childCount; i++)
  4205. {
  4206. var parent = model.getChildAt(model.getRoot(), i);
  4207. // Adds cells to existing layer if not locked
  4208. if (childCount == 1 && !graph.isCellLocked(graph.getDefaultParent()))
  4209. {
  4210. var children = model.getChildren(parent);
  4211. cells = cells.concat(graph.importCells(children, dx, dy, graph.getDefaultParent(), null, mapping));
  4212. }
  4213. else
  4214. {
  4215. // Delta is non cascading, needs separate move for layers
  4216. parent = graph.importCells([parent], 0, 0, graph.model.getRoot(), null, mapping)[0];
  4217. var children = graph.model.getChildren(parent);
  4218. graph.moveCells(children, dx, dy);
  4219. cells = cells.concat(children);
  4220. }
  4221. }
  4222. if (crop)
  4223. {
  4224. if (graph.isGridEnabled())
  4225. {
  4226. dx = graph.snap(dx);
  4227. dy = graph.snap(dy);
  4228. }
  4229. var bounds = graph.getBoundingBoxFromGeometry(cells, true);
  4230. if (bounds != null)
  4231. {
  4232. graph.moveCells(cells, dx - bounds.x, dy - bounds.y);
  4233. }
  4234. }
  4235. }
  4236. finally
  4237. {
  4238. graph.model.endUpdate();
  4239. }
  4240. }
  4241. }
  4242. }
  4243. catch (e)
  4244. {
  4245. if (!noErrorHandling)
  4246. {
  4247. this.handleError(e, mxResources.get('invalidOrMissingFile'));
  4248. }
  4249. throw e;
  4250. }
  4251. return cells;
  4252. };
  4253. /**
  4254. * Automatic loading for lucidchart import.
  4255. */
  4256. EditorUi.prototype.insertLucidChart = function(g, dx, dy, crop)
  4257. {
  4258. var delayed = mxUtils.bind(this, function()
  4259. {
  4260. // Checks for signature method
  4261. if (this.pasteLucidChart)
  4262. {
  4263. try
  4264. {
  4265. this.pasteLucidChart(g, dx, dy, crop);
  4266. }
  4267. catch (e)
  4268. {
  4269. // ignore
  4270. }
  4271. }
  4272. });
  4273. if (!this.pasteLucidChart && !this.loadingExtensions && !this.isOffline())
  4274. {
  4275. this.loadingExtensions = true;
  4276. if (urlParams['dev'] == '1')
  4277. {
  4278. mxscript('/js/diagramly/Extensions.js', delayed);
  4279. }
  4280. else
  4281. {
  4282. mxscript('/js/extensions.min.js', delayed);
  4283. }
  4284. }
  4285. else
  4286. {
  4287. // Must be async for cell selection
  4288. window.setTimeout(delayed, 0);
  4289. }
  4290. };
  4291. /**
  4292. * Imports the given XML into the existing diagram.
  4293. * TODO: Make this function asynchronous
  4294. */
  4295. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop)
  4296. {
  4297. crop = (crop != null) ? crop : true;
  4298. // Handles special case for Gliffy data which requires async server-side for parsing
  4299. if (text != null)
  4300. {
  4301. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  4302. {
  4303. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  4304. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  4305. {
  4306. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  4307. {
  4308. this.editor.graph.setSelectionCells(this.insertTextAt(xhr.responseText, dx, dy, true));
  4309. }
  4310. }));
  4311. // Returns empty cells array as it is aysynchronous
  4312. return [];
  4313. }
  4314. // Handles special case of data URI which requires async loading for finding size
  4315. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() && (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  4316. {
  4317. var graph = this.editor.graph;
  4318. // Checks for embedded XML in PNG
  4319. if (text.substring(0, 22) == 'data:image/png;base64,')
  4320. {
  4321. var xml = this.extractGraphModelFromPng(text);
  4322. var result = this.importXml(xml, dx, dy, crop, true);
  4323. if (result.length > 0)
  4324. {
  4325. return result;
  4326. }
  4327. }
  4328. // Tries to extract embedded XML from SVG data URI
  4329. if (text.substring(0, 19) == 'data:image/svg+xml;')
  4330. {
  4331. try
  4332. {
  4333. var xml = null;
  4334. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  4335. {
  4336. xml = text.substring(text.indexOf(',') + 1);
  4337. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  4338. }
  4339. else
  4340. {
  4341. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  4342. }
  4343. var result = this.importXml(xml, dx, dy, crop, true);
  4344. if (result.length > 0)
  4345. {
  4346. return result;
  4347. }
  4348. }
  4349. catch (e)
  4350. {
  4351. // Ignore
  4352. }
  4353. }
  4354. this.loadImage(text, mxUtils.bind(this, function(img)
  4355. {
  4356. if (text.substring(0, 5) == 'data:')
  4357. {
  4358. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  4359. {
  4360. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4361. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4362. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  4363. }), true, this.maxImageSize);
  4364. }
  4365. else
  4366. {
  4367. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  4368. var w = Math.round(img.width * s);
  4369. var h = Math.round(img.height * s);
  4370. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4371. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4372. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  4373. }
  4374. }), mxUtils.bind(this, function()
  4375. {
  4376. var cell = null;
  4377. // Inserts invalid data URIs as text
  4378. graph.getModel().beginUpdate();
  4379. try
  4380. {
  4381. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  4382. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4383. graph.updateCellSize(cell);
  4384. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4385. }
  4386. finally
  4387. {
  4388. graph.getModel().endUpdate();
  4389. }
  4390. graph.setSelectionCell(cell);
  4391. }));
  4392. return [];
  4393. }
  4394. else
  4395. {
  4396. text = this.editor.graph.zapGremlins(mxUtils.trim(text));
  4397. if (this.isCompatibleString(text))
  4398. {
  4399. return this.importXml(text, dx, dy, crop);
  4400. }
  4401. else if (text.length > 0)
  4402. {
  4403. if (text.substring(0, 26) == '{"state":"{\\"Properties\\":')
  4404. {
  4405. // Finds and imports first page
  4406. var state = JSON.parse(JSON.parse(text).state);
  4407. var page = null;
  4408. for (var id in state.Pages)
  4409. {
  4410. var tmp = state.Pages[id];
  4411. if (tmp != null && tmp.Properties.Order == '0')
  4412. {
  4413. page = tmp;
  4414. break;
  4415. }
  4416. }
  4417. if (page != null)
  4418. {
  4419. this.insertLucidChart(page, dx, dy, crop);
  4420. }
  4421. }
  4422. else
  4423. {
  4424. var graph = this.editor.graph;
  4425. var cell = null;
  4426. graph.getModel().beginUpdate();
  4427. try
  4428. {
  4429. // Fires cellsInserted to apply the current style to the inserted text.
  4430. // This requires the value to be empty when the event is fired.
  4431. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  4432. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4433. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4434. // Apply value and updates the cell size to fit the text block
  4435. cell.value = text;
  4436. graph.updateCellSize(cell);
  4437. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  4438. var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
  4439. if (regexp.test(cell.value))
  4440. {
  4441. graph.setLinkForCell(cell, cell.value);
  4442. }
  4443. // Adds spacing
  4444. cell.geometry.width += graph.gridSize;
  4445. cell.geometry.height += graph.gridSize;
  4446. }
  4447. finally
  4448. {
  4449. graph.getModel().endUpdate();
  4450. }
  4451. return [cell];
  4452. }
  4453. }
  4454. }
  4455. }
  4456. return [];
  4457. };
  4458. /**
  4459. * Formats the given file size.
  4460. */
  4461. EditorUi.prototype.formatFileSize = function(size)
  4462. {
  4463. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  4464. var i = -1;
  4465. do
  4466. {
  4467. size = size / 1024;
  4468. i++;
  4469. } while (size > 1024);
  4470. return Math.max(size, 0.1).toFixed(1) + units[i];
  4471. };
  4472. /**
  4473. * Imports the given XML into the existing diagram.
  4474. */
  4475. EditorUi.prototype.convertDataUri = function(uri)
  4476. {
  4477. // Handles special case of data URI which needs to be rewritten
  4478. // to be used in a cell style to remove the semicolon
  4479. if (uri.substring(0, 5) == 'data:')
  4480. {
  4481. var semi = uri.indexOf(';');
  4482. if (semi > 0)
  4483. {
  4484. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  4485. }
  4486. }
  4487. return uri;
  4488. };
  4489. /**
  4490. * Returns true for Gliffy or GraphML data or .vsdx filenames.
  4491. */
  4492. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  4493. {
  4494. return /(\.*<graphml xmlns=\".*)/.test(data) ||
  4495. /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data) ||
  4496. (filename != null && /(\.vsdx)($|\?)/i.test(filename)) ||
  4497. (filename != null && /(\.vssx)($|\?)/i.test(filename));
  4498. };
  4499. /**
  4500. * Imports the given XML into the existing diagram.
  4501. */
  4502. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  4503. {
  4504. crop = (crop != null) ? crop : true;
  4505. var async = false;
  4506. var cells = null;
  4507. if (mimeType.substring(0, 5) == 'image')
  4508. {
  4509. var containsModel = false;
  4510. if (mimeType.substring(0, 9) == 'image/png')
  4511. {
  4512. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  4513. if (xml != null && xml.length > 0)
  4514. {
  4515. cells = this.importXml(xml, dx, dy, crop);
  4516. containsModel = true;
  4517. }
  4518. }
  4519. if (!containsModel)
  4520. {
  4521. var graph = this.editor.graph;
  4522. // Strips encoding bit (eg. ;base64,) for cell style
  4523. var semi = data.indexOf(';');
  4524. if (semi > 0)
  4525. {
  4526. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  4527. }
  4528. if (crop && graph.isGridEnabled())
  4529. {
  4530. dx = graph.snap(dx);
  4531. dy = graph.snap(dy);
  4532. }
  4533. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  4534. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4535. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  4536. }
  4537. }
  4538. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  4539. {
  4540. // LATER: done and async are a hack before making this asynchronous
  4541. async = true;
  4542. // Returns empty cells array as it is aysynchronous
  4543. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  4544. {
  4545. if (xhr.readyState == 4)
  4546. {
  4547. var importedCells = null;
  4548. if (xhr.status >= 200 && xhr.status <= 299)
  4549. {
  4550. var xml = xhr.responseText;
  4551. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  4552. {
  4553. if (filename != null && filename.toLowerCase().substring(filename.length - 5) == '.vssx')
  4554. {
  4555. filename = filename.substring(0, filename.length - 5) + '.xml';
  4556. }
  4557. this.loadLibrary(new LocalLibrary(this, xml, filename));
  4558. }
  4559. else
  4560. {
  4561. importedCells = this.importXml(xml, dx, dy, crop);
  4562. }
  4563. }
  4564. if (done != null)
  4565. {
  4566. done(importedCells);
  4567. }
  4568. }
  4569. }), filename);
  4570. }
  4571. else if (!/(\.vsd)($|\?)/i.test(filename))
  4572. {
  4573. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  4574. }
  4575. if (!async && done != null)
  4576. {
  4577. done(cells);
  4578. }
  4579. return cells;
  4580. };
  4581. /**
  4582. * Base64 encodes the given string. This method seems to be more
  4583. * robust for encoding PNG from binary AJAX responses.
  4584. */
  4585. EditorUi.prototype.base64Encode = function(str)
  4586. {
  4587. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4588. var out = "", i = 0, len = str.length, c1, c2, c3;
  4589. while (i < len)
  4590. {
  4591. c1 = str.charCodeAt(i++) & 0xff;
  4592. if (i == len)
  4593. {
  4594. out += CHARS.charAt(c1 >> 2);
  4595. out += CHARS.charAt((c1 & 0x3) << 4);
  4596. out += "==";
  4597. break;
  4598. }
  4599. c2 = str.charCodeAt(i++);
  4600. if (i == len)
  4601. {
  4602. out += CHARS.charAt(c1 >> 2);
  4603. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  4604. out += CHARS.charAt((c2 & 0xF) << 2);
  4605. out += "=";
  4606. break;
  4607. }
  4608. c3 = str.charCodeAt(i++);
  4609. out += CHARS.charAt(c1 >> 2);
  4610. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  4611. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  4612. out += CHARS.charAt(c3 & 0x3F);
  4613. }
  4614. return out;
  4615. };
  4616. /**
  4617. *
  4618. */
  4619. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeImages, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  4620. {
  4621. var crop = x != null && y != null;
  4622. x = (x != null) ? x : 0;
  4623. y = (y != null) ? y : 0;
  4624. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  4625. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  4626. resizeImages = (resizeImages != null) ? resizeImages : true;
  4627. var graph = this.editor.graph;
  4628. var gs = graph.gridSize;
  4629. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  4630. {
  4631. if (data != null && data.substring(0, 10) == '<mxlibrary')
  4632. {
  4633. this.spinner.stop();
  4634. this.loadLibrary(new LocalLibrary(this, data, filename));
  4635. return null;
  4636. }
  4637. else
  4638. {
  4639. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  4640. }
  4641. });
  4642. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  4643. {
  4644. graph.setSelectionCells(cells);
  4645. });
  4646. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4647. {
  4648. var count = files.length;
  4649. var remain = count;
  4650. var queue = [];
  4651. // Barrier waits for all files to be loaded asynchronously
  4652. var barrier = mxUtils.bind(this, function(index, fnc)
  4653. {
  4654. queue[index] = fnc;
  4655. if (--remain == 0)
  4656. {
  4657. this.spinner.stop();
  4658. if (barrierFn != null)
  4659. {
  4660. barrierFn(queue);
  4661. }
  4662. else
  4663. {
  4664. var cells = [];
  4665. graph.getModel().beginUpdate();
  4666. try
  4667. {
  4668. for (var j = 0; j < queue.length; j++)
  4669. {
  4670. var tmp = queue[j]();
  4671. if (tmp != null)
  4672. {
  4673. cells = cells.concat(tmp);
  4674. }
  4675. }
  4676. }
  4677. finally
  4678. {
  4679. graph.getModel().endUpdate();
  4680. }
  4681. }
  4682. resultFn(cells);
  4683. }
  4684. });
  4685. for (var i = 0; i < count; i++)
  4686. {
  4687. (mxUtils.bind(this, function(index)
  4688. {
  4689. var file = files[index];
  4690. var reader = new FileReader();
  4691. reader.onload = mxUtils.bind(this, function(e)
  4692. {
  4693. if (filterFn == null || filterFn(file))
  4694. {
  4695. if (file.type.substring(0, 6) == 'image/')
  4696. {
  4697. if (file.type.substring(0, 9) == 'image/svg')
  4698. {
  4699. // Checks if SVG contains content attribute
  4700. var data = e.target.result;
  4701. var comma = data.indexOf(',');
  4702. var svgText = atob(data.substring(comma + 1));
  4703. var root = mxUtils.parseXml(svgText);
  4704. var svgs = root.getElementsByTagName('svg');
  4705. if (svgs.length > 0)
  4706. {
  4707. var svgRoot = svgs[0];
  4708. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  4709. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  4710. {
  4711. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  4712. }
  4713. if (cont != null && cont.charAt(0) == '%')
  4714. {
  4715. cont = decodeURIComponent(cont);
  4716. }
  4717. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  4718. cont.substring(0, 14) === '<mxGraphModel '))
  4719. {
  4720. barrier(index, mxUtils.bind(this, function()
  4721. {
  4722. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  4723. }));
  4724. }
  4725. else
  4726. {
  4727. // SVG needs special handling to add viewbox if missing and
  4728. // find initial size from SVG attributes (only for IE11)
  4729. barrier(index, mxUtils.bind(this, function()
  4730. {
  4731. try
  4732. {
  4733. var prefix = data.substring(0, comma + 1);
  4734. // Parses SVG and find width and height
  4735. if (root != null)
  4736. {
  4737. var svgs = root.getElementsByTagName('svg');
  4738. if (svgs.length > 0)
  4739. {
  4740. var svgRoot = svgs[0];
  4741. var w = parseFloat(svgRoot.getAttribute('width'));
  4742. var h = parseFloat(svgRoot.getAttribute('height'));
  4743. // Check if viewBox attribute already exists
  4744. var vb = svgRoot.getAttribute('viewBox');
  4745. if (vb == null || vb.length == 0)
  4746. {
  4747. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  4748. }
  4749. // Uses width and height from viewbox for
  4750. // missing width and height attributes
  4751. else if (isNaN(w) || isNaN(h))
  4752. {
  4753. var tokens = vb.split(' ');
  4754. if (tokens.length > 3)
  4755. {
  4756. w = parseFloat(tokens[2]);
  4757. h = parseFloat(tokens[3]);
  4758. }
  4759. }
  4760. data = this.createSvgDataUri(mxUtils.getXml(svgs[0]));
  4761. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  4762. return fn(data, file.type, x + index * gs, y + index * gs,
  4763. Math.max(1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  4764. }
  4765. }
  4766. }
  4767. catch (e)
  4768. {
  4769. // ignores any SVG parsing errors
  4770. }
  4771. return null;
  4772. }));
  4773. }
  4774. }
  4775. }
  4776. else
  4777. {
  4778. // Checks if PNG+XML is available to bypass code below
  4779. var containsModel = false;
  4780. if (file.type == 'image/png')
  4781. {
  4782. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  4783. if (xml != null && xml.length > 0)
  4784. {
  4785. var img = new Image();
  4786. img.src = e.target.result;
  4787. barrier(index, mxUtils.bind(this, function()
  4788. {
  4789. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  4790. img.width, img.height, file.name);
  4791. }));
  4792. containsModel = true;
  4793. }
  4794. }
  4795. // Additional asynchronous step for finding image size
  4796. if (!containsModel)
  4797. {
  4798. // Cannot load local files in Chrome App
  4799. if (mxClient.IS_CHROMEAPP)
  4800. {
  4801. this.spinner.stop();
  4802. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  4803. mxResources.get('cancel'), mxUtils.bind(this, function()
  4804. {
  4805. // Hides the dialog
  4806. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  4807. {
  4808. // Redirects to import function
  4809. this.actions.get('import').funct();
  4810. })
  4811. );
  4812. }
  4813. else
  4814. {
  4815. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  4816. {
  4817. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  4818. {
  4819. barrier(index, mxUtils.bind(this, function()
  4820. {
  4821. // Refuses to insert images above a certain size as they kill the app
  4822. if (data2 != null && data2.length < maxBytes)
  4823. {
  4824. var s = (!resizeImages || !this.isResampleImage(e.target.result)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  4825. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  4826. }
  4827. else
  4828. {
  4829. this.handleError({message: mxResources.get('imageTooBig')});
  4830. return null;
  4831. }
  4832. }));
  4833. }), resizeImages, maxSize, resampleThreshold);
  4834. }));
  4835. }
  4836. }
  4837. }
  4838. }
  4839. else
  4840. {
  4841. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  4842. {
  4843. barrier(index, function()
  4844. {
  4845. return cells;
  4846. });
  4847. });
  4848. }
  4849. }
  4850. });
  4851. // Handles special case of binary file where the reader should not be used
  4852. if (/(\.vsdx)($|\?)/i.test(file.name) || /(\.vssx)($|\?)/i.test(file.name))
  4853. {
  4854. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  4855. {
  4856. barrier(index, function()
  4857. {
  4858. return cells;
  4859. });
  4860. }, file);
  4861. }
  4862. else if (file.type.substring(0, 5) == 'image')
  4863. {
  4864. reader.readAsDataURL(file);
  4865. }
  4866. else
  4867. {
  4868. reader.readAsText(file);
  4869. }
  4870. }))(i);
  4871. }
  4872. }
  4873. };
  4874. /**
  4875. * Parses the file using XHR2 via the server. File can be a blob or file object.
  4876. * Filename is an optional parameter for blobs (that do not have a filename).
  4877. */
  4878. EditorUi.prototype.parseFile = function(file, fn, filename)
  4879. {
  4880. filename = (filename != null) ? filename : file.name;
  4881. var formData = new FormData();
  4882. formData.append('format', 'xml');
  4883. formData.append('upfile', file, filename);
  4884. var xhr = new XMLHttpRequest();
  4885. xhr.open('POST', OPEN_URL);
  4886. xhr.onreadystatechange = function()
  4887. {
  4888. fn(xhr);
  4889. };
  4890. xhr.send(formData);
  4891. };
  4892. /**
  4893. *
  4894. */
  4895. EditorUi.prototype.isResampleImage = function(data, thresh)
  4896. {
  4897. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  4898. return data.length > thresh;
  4899. };
  4900. /**
  4901. * Resizes the given image if <maxImageBytes> is not null.
  4902. */
  4903. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  4904. {
  4905. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  4906. var w = Math.max(1, img.width);
  4907. var h = Math.max(1, img.height);
  4908. if (enabled && this.isResampleImage(data, thresh))
  4909. {
  4910. try
  4911. {
  4912. var factor = Math.max(w / maxSize, h / maxSize);
  4913. if (factor > 1)
  4914. {
  4915. var w2 = Math.round(w / factor);
  4916. var h2 = Math.round(h / factor);
  4917. var canvas = document.createElement('canvas');
  4918. canvas.width = w2;
  4919. canvas.height = h2;
  4920. var ctx = canvas.getContext('2d');
  4921. ctx.drawImage(img, 0, 0, w2, h2);
  4922. var tmp = canvas.toDataURL();
  4923. // Uses new image if smaller
  4924. if (tmp.length < data.length)
  4925. {
  4926. // Checks if the image is empty by comparing
  4927. // with an empty image of the same size
  4928. var canvas2 = document.createElement('canvas');
  4929. canvas2.width = w2;
  4930. canvas2.height = h2;
  4931. var tmp2 = canvas2.toDataURL();
  4932. if (tmp !== tmp2)
  4933. {
  4934. data = tmp;
  4935. w = w2;
  4936. h = h2;
  4937. }
  4938. }
  4939. }
  4940. }
  4941. catch (e)
  4942. {
  4943. // ignores image scaling errors
  4944. }
  4945. }
  4946. fn(data, w, h);
  4947. };
  4948. EditorUi.prototype.crcTable = [];
  4949. for (var n = 0; n < 256; n++)
  4950. {
  4951. var c = n;
  4952. for (var k = 0; k < 8; k++)
  4953. {
  4954. if ((c & 1) == 1)
  4955. {
  4956. c = 0xedb88320 ^ (c >>> 1);
  4957. }
  4958. else
  4959. {
  4960. c >>>= 1;
  4961. }
  4962. EditorUi.prototype.crcTable[n] = c;
  4963. }
  4964. }
  4965. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  4966. {
  4967. var c = crc;
  4968. for (var n = 0; n < len; n++)
  4969. {
  4970. c = EditorUi.prototype.crcTable[(c ^ data[off + n]) & 0xff] ^ (c >>> 8);
  4971. }
  4972. return c;
  4973. };
  4974. /**
  4975. * Adds the given text to the compressed or non-compressed text chunk.
  4976. */
  4977. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  4978. {
  4979. var base64 = data.substring(data.indexOf(',') + 1);
  4980. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  4981. var pos = 0;
  4982. function fread(d, count)
  4983. {
  4984. var start = pos;
  4985. pos += count;
  4986. return d.substring(start, pos);
  4987. };
  4988. // Reads unsigned long 32 bit big endian
  4989. function _freadint(d)
  4990. {
  4991. var bytes = fread(d, 4);
  4992. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  4993. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  4994. };
  4995. function writeInt(num)
  4996. {
  4997. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  4998. (num >> 8) & 0x000000ff, num & 0x000000ff);
  4999. };
  5000. // Checks signature
  5001. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  5002. {
  5003. if (error != null)
  5004. {
  5005. error();
  5006. }
  5007. return;
  5008. }
  5009. // Reads header chunk
  5010. fread(f,4);
  5011. if (fread(f,4) != 'IHDR')
  5012. {
  5013. if (error != null)
  5014. {
  5015. error();
  5016. }
  5017. return;
  5018. }
  5019. fread(f, 17);
  5020. var result = f.substring(0, pos);
  5021. do
  5022. {
  5023. var n = _freadint(f);
  5024. var chunk = fread(f,4);
  5025. if (chunk == 'IDAT')
  5026. {
  5027. result = f.substring(0, pos - 8);
  5028. var chunkData = key + String.fromCharCode(0) +
  5029. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  5030. value;
  5031. // FIXME: Wrong crc
  5032. var crc = 0xffffffff;
  5033. crc = this.updateCRC(crc, type, 0, 4);
  5034. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  5035. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  5036. result += f.substring(pos - 8, f.length);
  5037. break;
  5038. }
  5039. result += f.substring(pos - 8, pos - 4 + n);
  5040. value = fread(f,n);
  5041. fread(f,4);
  5042. }
  5043. while (n);
  5044. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  5045. }
  5046. /**
  5047. * Extracts the XML from the compressed or non-compressed text chunk.
  5048. */
  5049. EditorUi.prototype.extractGraphModelFromPng = function(data)
  5050. {
  5051. var result = null;
  5052. try
  5053. {
  5054. var base64 = data.substring(data.indexOf(',') + 1);
  5055. // Workaround for invalid character error in Safari
  5056. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  5057. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  5058. {
  5059. var value = binary.substring(pos + 8, pos + 8 + length);
  5060. if (type == 'zTXt')
  5061. {
  5062. var idx = value.indexOf(String.fromCharCode(0));
  5063. if (value.substring(0, idx) == 'mxGraphModel')
  5064. {
  5065. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  5066. var xmlData = this.editor.graph.bytesToString(pako.inflateRaw(
  5067. value.substring(idx + 2))).replace(/\+/g,' ');
  5068. if (xmlData != null && xmlData.length > 0)
  5069. {
  5070. result = xmlData;
  5071. }
  5072. }
  5073. }
  5074. // Uncompressed section is normally not used
  5075. else if (type == 'tEXt')
  5076. {
  5077. var vals = value.split(String.fromCharCode(0));
  5078. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  5079. {
  5080. result = vals[1];
  5081. }
  5082. }
  5083. if (result != null || type == 'IDAT')
  5084. {
  5085. // Stops processing the file as our text chunks
  5086. // are always placed before the data section
  5087. return true;
  5088. }
  5089. }));
  5090. }
  5091. catch (e)
  5092. {
  5093. // ignores decoding errors
  5094. }
  5095. if (result != null && result.charAt(0) == '%')
  5096. {
  5097. result = decodeURIComponent(result);
  5098. }
  5099. // Workaround for double encoded content
  5100. if (result != null && result.charAt(0) == '%')
  5101. {
  5102. result = decodeURIComponent(result);
  5103. }
  5104. return result;
  5105. };
  5106. /**
  5107. * Loads the image from the given URI.
  5108. *
  5109. * @param {number} dx X-coordinate of the translation.
  5110. * @param {number} dy Y-coordinate of the translation.
  5111. */
  5112. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  5113. {
  5114. var img = new Image();
  5115. img.onload = function()
  5116. {
  5117. onload(img);
  5118. }
  5119. if (onerror != null)
  5120. {
  5121. img.onerror = onerror;
  5122. }
  5123. img.src = uri;
  5124. };
  5125. // Initializes the user interface
  5126. var editorUiInit = EditorUi.prototype.init;
  5127. EditorUi.prototype.init = function()
  5128. {
  5129. // Must be set before UI is created in superclass
  5130. if (typeof window.mxSettings !== 'undefined')
  5131. {
  5132. this.formatWidth = mxSettings.getFormatWidth();
  5133. }
  5134. var ui = this;
  5135. var graph = this.editor.graph;
  5136. function pageLinkClicked(href)
  5137. {
  5138. var comma = href.indexOf(',');
  5139. if (comma > 0)
  5140. {
  5141. var page = ui.getPageById(href.substring(comma + 1));
  5142. if (page)
  5143. {
  5144. ui.selectPage(page)
  5145. }
  5146. }
  5147. };
  5148. // For chromeless mode and lightbox mode in viewer
  5149. // Must be overridden before supercall to be applied
  5150. // in case of chromeless initialization
  5151. var graphAddClickHandler = graph.addClickHandler;
  5152. graph.addClickHandler = function(highlight, beforeClick, onClick)
  5153. {
  5154. var tmp = beforeClick;
  5155. beforeClick = function(evt, href)
  5156. {
  5157. if (href == null)
  5158. {
  5159. var source = mxEvent.getSource(evt);
  5160. if (source.nodeName.toLowerCase() == 'a')
  5161. {
  5162. href = source.getAttribute('href');
  5163. }
  5164. }
  5165. if (href != null && graph.isPageLink(href))
  5166. {
  5167. pageLinkClicked(href);
  5168. mxEvent.consume(evt);
  5169. }
  5170. if (tmp != null)
  5171. {
  5172. tmp(evt);
  5173. }
  5174. };
  5175. // For some reason, local argument override is not enough in this case...
  5176. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  5177. };
  5178. editorUiInit.apply(this, arguments);
  5179. if (mxClient.IS_SVG)
  5180. {
  5181. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  5182. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  5183. }
  5184. // Overrides print dialog size
  5185. ui.actions.get('print').funct = function()
  5186. {
  5187. ui.showDialog(new PrintDialog(ui).container, 360,
  5188. (ui.pages != null && ui.pages.length > 1) ?
  5189. 420 : 360, true, true);
  5190. };
  5191. // Specifies the default filename
  5192. this.defaultFilename = mxResources.get('untitledDiagram');
  5193. // Adds placeholder for %page% and %pagenumber%
  5194. var graphGetGlobalVariable = graph.getGlobalVariable;
  5195. graph.getGlobalVariable = function(name)
  5196. {
  5197. if (name == 'page' && ui.currentPage != null)
  5198. {
  5199. return ui.currentPage.getName();
  5200. }
  5201. else if (name == 'pagenumber')
  5202. {
  5203. if (ui.currentPage != null && ui.pages != null)
  5204. {
  5205. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  5206. }
  5207. else
  5208. {
  5209. return 1;
  5210. }
  5211. }
  5212. return graphGetGlobalVariable.apply(this, arguments);
  5213. };
  5214. var graphCreateLinkForHint = graph.createLinkForHint;
  5215. graph.createLinkForHint = function(href, label)
  5216. {
  5217. var pageLink = graph.isPageLink(href);
  5218. if (pageLink)
  5219. {
  5220. var comma = href.indexOf(',');
  5221. if (comma > 0)
  5222. {
  5223. var page = ui.getPageById(href.substring(comma + 1));
  5224. if (page != null)
  5225. {
  5226. label = page.getName();
  5227. }
  5228. else
  5229. {
  5230. label = mxResources.get('pageNotFound');
  5231. }
  5232. }
  5233. }
  5234. var a = graphCreateLinkForHint.apply(this, arguments);
  5235. if (pageLink)
  5236. {
  5237. mxEvent.addListener(a, 'click', function(evt)
  5238. {
  5239. pageLinkClicked(href);
  5240. mxEvent.consume(evt);
  5241. });
  5242. }
  5243. return a;
  5244. };
  5245. var graphLabelLinkClicked = graph.labelLinkClicked;
  5246. graph.labelLinkClicked = function(state, elt, evt)
  5247. {
  5248. var href = elt.getAttribute('href');
  5249. if (graph.isPageLink(href))
  5250. {
  5251. pageLinkClicked(href);
  5252. mxEvent.consume(evt);
  5253. }
  5254. else
  5255. {
  5256. graphLabelLinkClicked.apply(this, arguments);
  5257. }
  5258. };
  5259. // Overrides editor filename
  5260. this.editor.getOrCreateFilename = function()
  5261. {
  5262. var filename = ui.defaultFilename;
  5263. var file = ui.getCurrentFile();
  5264. if (file != null)
  5265. {
  5266. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  5267. }
  5268. return filename;
  5269. };
  5270. // Disables print action for standalone apps on iOS
  5271. // because there is no way to close the new window
  5272. // LATER: Use iframe for print, disable preview
  5273. var printAction = this.actions.get('print');
  5274. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  5275. printAction.visible = printAction.isEnabled();
  5276. // Scales pages/graph to fit available size
  5277. if (!this.editor.chromeless)
  5278. {
  5279. // Defines additional hotkeys
  5280. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  5281. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  5282. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  5283. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  5284. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  5285. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  5286. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  5287. // Handles copy paste of images from clipboard
  5288. if (!mxClient.IS_IE)
  5289. {
  5290. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  5291. {
  5292. var graph = this.editor.graph;
  5293. if (!mxEvent.isConsumed(evt))
  5294. {
  5295. try
  5296. {
  5297. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  5298. var containsText = false;
  5299. // Workaround for asynchronous paste event processing in textInput
  5300. // is to ignore this event if it contains text/html/rtf (see below).
  5301. // NOTE: Image is not pasted into textInput so can't listen there.
  5302. for (var i = 0; i < data.types.length; i++)
  5303. {
  5304. if (data.types[i].substring(0, 5) === 'text/')
  5305. {
  5306. containsText = true;
  5307. break;
  5308. }
  5309. }
  5310. if (!containsText)
  5311. {
  5312. var items = data.items;
  5313. for (index in items)
  5314. {
  5315. var item = items[index];
  5316. if (item.kind === 'file')
  5317. {
  5318. if (graph.isEditing())
  5319. {
  5320. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  5321. {
  5322. // Inserts image into current text box
  5323. graph.insertImage(data, w, h);
  5324. }, function()
  5325. {
  5326. // No post processing
  5327. }, function(file)
  5328. {
  5329. // Handles only images
  5330. return file.type.substring(0, 6) == 'image/';
  5331. }, function(queue)
  5332. {
  5333. // Invokes elements of queue in order
  5334. for (var i = 0; i < queue.length; i++)
  5335. {
  5336. queue[i]();
  5337. }
  5338. });
  5339. }
  5340. else
  5341. {
  5342. var pt = this.editor.graph.getInsertPoint();
  5343. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  5344. mxEvent.consume(evt);
  5345. }
  5346. break;
  5347. }
  5348. }
  5349. }
  5350. }
  5351. catch (e)
  5352. {
  5353. // ignore
  5354. }
  5355. }
  5356. }), false);
  5357. }
  5358. // Focused but invisible textarea during control or meta key events
  5359. var textInput = document.createElement('div');
  5360. textInput.style.position = 'absolute';
  5361. textInput.style.whiteSpace = 'nowrap';
  5362. textInput.style.overflow = 'hidden';
  5363. textInput.style.display = 'block';
  5364. textInput.contentEditable = true;
  5365. mxUtils.setOpacity(textInput, 0);
  5366. textInput.style.width = '1px';
  5367. textInput.style.height = '1px';
  5368. textInput.innerHTML = '&nbsp;';
  5369. var restoreFocus = false;
  5370. // Disables built-in cut, copy and paste shortcuts
  5371. this.keyHandler.bindControlKey(88, null);
  5372. this.keyHandler.bindControlKey(67, null);
  5373. this.keyHandler.bindControlKey(86, null);
  5374. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  5375. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  5376. {
  5377. // No dialog visible
  5378. var source = mxEvent.getSource(evt);
  5379. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  5380. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  5381. {
  5382. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  5383. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  5384. {
  5385. // Cannot use parentNode for check in IE
  5386. if (!restoreFocus)
  5387. {
  5388. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  5389. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  5390. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  5391. graph.container.appendChild(textInput);
  5392. restoreFocus = true;
  5393. // Workaround for selected document content in quirks mode
  5394. if (mxClient.IS_QUIRKS)
  5395. {
  5396. window.setTimeout(function()
  5397. {
  5398. textInput.focus();
  5399. document.execCommand('selectAll', false, null);
  5400. }, 0);
  5401. }
  5402. else
  5403. {
  5404. textInput.focus();
  5405. document.execCommand('selectAll', false, null);
  5406. }
  5407. }
  5408. }
  5409. }
  5410. }));
  5411. // Clears input and restores focus and selection
  5412. function clearInput()
  5413. {
  5414. window.setTimeout(function()
  5415. {
  5416. textInput.innerHTML = '&nbsp;';
  5417. textInput.focus();
  5418. document.execCommand('selectAll', false, null);
  5419. }, 0);
  5420. };
  5421. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  5422. {
  5423. // Workaround for asynchronous event read invalid in IE quirks mode
  5424. var keyCode = evt.keyCode;
  5425. // Asynchronous workaround for scroll to origin after paste if the
  5426. // Ctrl-key is not pressed for long enough in FF on Windows
  5427. window.setTimeout(mxUtils.bind(this, function()
  5428. {
  5429. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  5430. keyCode == 91 /* Meta */))
  5431. {
  5432. restoreFocus = false;
  5433. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  5434. {
  5435. graph.container.focus();
  5436. }
  5437. textInput.parentNode.removeChild(textInput);
  5438. }
  5439. }), 0);
  5440. }));
  5441. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  5442. {
  5443. if (graph.isEnabled())
  5444. {
  5445. mxClipboard.copy(graph);
  5446. this.copyCells(textInput);
  5447. clearInput();
  5448. }
  5449. }));
  5450. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  5451. {
  5452. if (graph.isEnabled())
  5453. {
  5454. this.copyCells(textInput, true);
  5455. clearInput();
  5456. }
  5457. }));
  5458. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  5459. {
  5460. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  5461. {
  5462. textInput.innerHTML = '&nbsp;';
  5463. textInput.focus();
  5464. window.setTimeout(mxUtils.bind(this, function()
  5465. {
  5466. this.pasteCells(evt, textInput);
  5467. textInput.innerHTML = '&nbsp;';
  5468. }), 0);
  5469. }
  5470. }), true);
  5471. // Needed for IE11
  5472. var isSelectionAllowed2 = this.isSelectionAllowed;
  5473. this.isSelectionAllowed = function(evt)
  5474. {
  5475. if (mxEvent.getSource(evt) == textInput)
  5476. {
  5477. return true;
  5478. }
  5479. return isSelectionAllowed2.apply(this, arguments);
  5480. };
  5481. };
  5482. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  5483. var x = document.body.clientWidth / 2 - 2;
  5484. // Holds the x-coordinate of the point
  5485. this.spinner = this.createSpinner(x, y, 24);
  5486. // Installs drag and drop handler for rich text editor
  5487. if (Graph.fileSupport)
  5488. {
  5489. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  5490. {
  5491. // Setup the dnd listeners
  5492. var graph = this.editor.graph;
  5493. var textElt = graph.cellEditor.text2;
  5494. var dropElt = null;
  5495. if (textElt != null)
  5496. {
  5497. mxEvent.addListener(textElt, 'dragleave', function(evt)
  5498. {
  5499. if (dropElt != null)
  5500. {
  5501. dropElt.parentNode.removeChild(dropElt);
  5502. dropElt = null;
  5503. }
  5504. evt.stopPropagation();
  5505. evt.preventDefault();
  5506. });
  5507. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  5508. {
  5509. // IE 10 does not implement pointer-events so it can't have a drop highlight
  5510. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  5511. {
  5512. dropElt = this.highlightElement(textElt);
  5513. }
  5514. evt.stopPropagation();
  5515. evt.preventDefault();
  5516. }));
  5517. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  5518. {
  5519. if (dropElt != null)
  5520. {
  5521. dropElt.parentNode.removeChild(dropElt);
  5522. dropElt = null;
  5523. }
  5524. if (evt.dataTransfer.files.length > 0)
  5525. {
  5526. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  5527. {
  5528. // Inserts image into current text box
  5529. graph.insertImage(data, w, h);
  5530. }, function()
  5531. {
  5532. // No post processing
  5533. }, function(file)
  5534. {
  5535. // Handles only images
  5536. return file.type.substring(0, 6) == 'image/';
  5537. }, function(queue)
  5538. {
  5539. // Invokes elements of queue in order
  5540. for (var i = 0; i < queue.length; i++)
  5541. {
  5542. queue[i]();
  5543. }
  5544. }, !mxEvent.isControlDown(evt));
  5545. }
  5546. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  5547. {
  5548. var uri = evt.dataTransfer.getData('text/uri-list');
  5549. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  5550. {
  5551. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  5552. {
  5553. var w = Math.max(1, img.width);
  5554. var h = Math.max(1, img.height);
  5555. var maxSize = this.maxImageSize;
  5556. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  5557. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  5558. }));
  5559. }
  5560. else
  5561. {
  5562. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  5563. }
  5564. }
  5565. else
  5566. {
  5567. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  5568. {
  5569. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  5570. }
  5571. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  5572. {
  5573. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  5574. }
  5575. }
  5576. evt.stopPropagation();
  5577. evt.preventDefault();
  5578. }));
  5579. }
  5580. }));
  5581. }
  5582. // Adds an element to edit the style in the footer in test mode
  5583. if (urlParams['test'] == '1')
  5584. {
  5585. var footer = document.getElementById('geFooter');
  5586. if (footer != null)
  5587. {
  5588. this.styleInput = document.createElement('input');
  5589. this.styleInput.setAttribute('type', 'text');
  5590. this.styleInput.style.position = 'absolute';
  5591. this.styleInput.style.top = '14px';
  5592. this.styleInput.style.left = '2px';
  5593. // Workaround for ignore right CSS property in FF
  5594. this.styleInput.style.width = '98%';
  5595. this.styleInput.style.visibility = 'hidden';
  5596. this.styleInput.style.opacity = '0.9';
  5597. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  5598. {
  5599. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  5600. }));
  5601. footer.appendChild(this.styleInput);
  5602. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  5603. {
  5604. if (this.editor.graph.getSelectionCount() > 0)
  5605. {
  5606. var cell = this.editor.graph.getSelectionCell();
  5607. var style = this.editor.graph.getModel().getStyle(cell);
  5608. this.styleInput.value = style || '';
  5609. this.styleInput.style.visibility = 'visible';
  5610. } else
  5611. {
  5612. this.styleInput.style.visibility = 'hidden';
  5613. }
  5614. }));
  5615. }
  5616. var isSelectionAllowed = this.isSelectionAllowed;
  5617. this.isSelectionAllowed = function(evt)
  5618. {
  5619. if (mxEvent.getSource(evt) == this.styleInput)
  5620. {
  5621. return true;
  5622. }
  5623. return isSelectionAllowed.apply(this, arguments);
  5624. };
  5625. }
  5626. // Removes info text in page
  5627. var info = document.getElementById('geInfo');
  5628. if (info != null)
  5629. {
  5630. info.parentNode.removeChild(info);
  5631. }
  5632. // Installs drag and drop handler for files
  5633. // Enables dropping files
  5634. if (Graph.fileSupport)
  5635. {
  5636. // Setup the dnd listeners
  5637. var dropElt = null;
  5638. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  5639. {
  5640. if (graph.isEnabled())
  5641. {
  5642. if (dropElt != null)
  5643. {
  5644. dropElt.parentNode.removeChild(dropElt);
  5645. dropElt = null;
  5646. }
  5647. evt.stopPropagation();
  5648. evt.preventDefault();
  5649. }
  5650. });
  5651. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  5652. {
  5653. // IE 10 does not implement pointer-events so it can't have a drop highlight
  5654. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  5655. {
  5656. dropElt = this.highlightElement(graph.container);
  5657. }
  5658. if (this.sidebar != null)
  5659. {
  5660. this.sidebar.hideTooltip();
  5661. }
  5662. evt.stopPropagation();
  5663. evt.preventDefault();
  5664. }));
  5665. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  5666. {
  5667. if (dropElt != null)
  5668. {
  5669. dropElt.parentNode.removeChild(dropElt);
  5670. dropElt = null;
  5671. }
  5672. if (graph.isEnabled())
  5673. {
  5674. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  5675. var tr = graph.view.translate;
  5676. var scale = graph.view.scale;
  5677. var x = pt.x / scale - tr.x;
  5678. var y = pt.y / scale - tr.y;
  5679. if (mxEvent.isAltDown(evt))
  5680. {
  5681. x = 0;
  5682. y = 0;
  5683. }
  5684. if (evt.dataTransfer.files.length > 0)
  5685. {
  5686. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  5687. !mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  5688. }
  5689. else
  5690. {
  5691. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  5692. evt.dataTransfer.getData('text/uri-list') : null;
  5693. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  5694. if (data != null)
  5695. {
  5696. graph.setSelectionCells(this.importXml(data, x, y, true));
  5697. }
  5698. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  5699. {
  5700. var html = evt.dataTransfer.getData('text/html');
  5701. var div = document.createElement('div');
  5702. div.innerHTML = html;
  5703. // The default is based on the extension
  5704. var asImage = null;
  5705. // Extracts single image
  5706. var imgs = div.getElementsByTagName('img');
  5707. if (imgs != null && imgs.length == 1)
  5708. {
  5709. html = imgs[0].getAttribute('src');
  5710. // Handles special case where the src attribute has no valid extension
  5711. // in which case the text would be inserted as text with a link
  5712. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  5713. {
  5714. asImage = true;
  5715. }
  5716. }
  5717. else
  5718. {
  5719. // Extracts single link
  5720. var a = div.getElementsByTagName('a');
  5721. if (a != null && a.length == 1)
  5722. {
  5723. html = a[0].getAttribute('href');
  5724. }
  5725. }
  5726. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage));
  5727. }
  5728. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  5729. {
  5730. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  5731. {
  5732. var w = Math.max(1, img.width);
  5733. var h = Math.max(1, img.height);
  5734. var maxSize = this.maxImageSize;
  5735. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  5736. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  5737. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5738. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  5739. }), mxUtils.bind(this, function(img)
  5740. {
  5741. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  5742. }));
  5743. }
  5744. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  5745. {
  5746. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  5747. }
  5748. }
  5749. }
  5750. evt.stopPropagation();
  5751. evt.preventDefault();
  5752. }), false);
  5753. }
  5754. this.initPages();
  5755. // Embedded mode
  5756. if (urlParams['embed'] == '1')
  5757. {
  5758. this.initializeEmbedMode();
  5759. }
  5760. if (typeof window.mxSettings !== 'undefined')
  5761. {
  5762. this.installSettings();
  5763. }
  5764. };
  5765. /**
  5766. * Creates the format panel and adds overrides.
  5767. */
  5768. EditorUi.prototype.installSettings = function()
  5769. {
  5770. if (isLocalStorage || mxClient.IS_CHROMEAPP)
  5771. {
  5772. // Gets recent colors from settings
  5773. ColorDialog.recentColors = mxSettings.getRecentColors();
  5774. /**
  5775. * Persists current edge style.
  5776. */
  5777. this.editor.graph.currentEdgeStyle = mxSettings.getCurrentEdgeStyle();
  5778. this.editor.graph.currentVertexStyle = mxSettings.getCurrentVertexStyle();
  5779. // Updates UI to reflect current edge style
  5780. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  5781. this.addListener('styleChanged', mxUtils.bind(this, function(sender, evt)
  5782. {
  5783. mxSettings.setCurrentEdgeStyle(this.editor.graph.currentEdgeStyle);
  5784. mxSettings.setCurrentVertexStyle(this.editor.graph.currentVertexStyle);
  5785. mxSettings.save();
  5786. }));
  5787. /**
  5788. * Persists copy on connect switch.
  5789. */
  5790. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  5791. this.fireEvent(new mxEventObject('copyConnectChanged'));
  5792. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  5793. {
  5794. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  5795. mxSettings.save();
  5796. }));
  5797. /**
  5798. * Persists default page format.
  5799. */
  5800. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  5801. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  5802. {
  5803. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  5804. mxSettings.save();
  5805. }));
  5806. /**
  5807. * Persists default grid color.
  5808. */
  5809. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  5810. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  5811. {
  5812. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  5813. mxSettings.save();
  5814. }));
  5815. /**
  5816. * Persists autosave switch in Chrome app.
  5817. */
  5818. if (mxClient.IS_CHROMEAPP)
  5819. {
  5820. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  5821. {
  5822. mxSettings.setAutosave(this.editor.autosave);
  5823. mxSettings.save();
  5824. }));
  5825. this.editor.autosave = mxSettings.getAutosave();
  5826. }
  5827. /**
  5828. *
  5829. */
  5830. if (this.sidebar != null)
  5831. {
  5832. this.sidebar.showPalette('search', mxSettings.settings.search);
  5833. }
  5834. /**
  5835. * Shows scratchpad if never shown.
  5836. */
  5837. if (!this.editor.chromeless && this.sidebar != null && (mxSettings.settings.isNew ||
  5838. parseInt(mxSettings.settings.version || 0) <= 8))
  5839. {
  5840. this.toggleScratchpad();
  5841. mxSettings.save();
  5842. }
  5843. // Saves app defaults for UI
  5844. this.addListener('formatWidthChanged', function()
  5845. {
  5846. mxSettings.setFormatWidth(this.formatWidth);
  5847. mxSettings.save();
  5848. });
  5849. }
  5850. };
  5851. /**
  5852. * Creates the format panel and adds overrides.
  5853. */
  5854. EditorUi.prototype.copyCells = function(elt, removeCells)
  5855. {
  5856. var graph = this.editor.graph;
  5857. if (!graph.isSelectionEmpty())
  5858. {
  5859. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  5860. // LATER: Add span with XML in data attribute
  5861. // var span = document.createElement('span');
  5862. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  5863. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  5864. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  5865. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  5866. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  5867. if (removeCells)
  5868. {
  5869. graph.removeCells(cells, false);
  5870. graph.lastPasteXml = null;
  5871. }
  5872. else
  5873. {
  5874. graph.lastPasteXml = xml;
  5875. graph.pasteCounter = 0;
  5876. }
  5877. elt.focus();
  5878. document.execCommand('selectAll', false, null);
  5879. }
  5880. else
  5881. {
  5882. // Disables copy on focused element
  5883. elt.innerHTML = '';
  5884. }
  5885. };
  5886. /**
  5887. * Creates the format panel and adds overrides.
  5888. */
  5889. EditorUi.prototype.pasteCells = function(evt, elt)
  5890. {
  5891. if (!mxEvent.isConsumed(evt))
  5892. {
  5893. var spans = elt.getElementsByTagName('span');
  5894. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  5895. 'application/vnd.lucid.chart.objects')
  5896. {
  5897. var content = spans[0].getAttribute('data-lucid-content');
  5898. if (content != null && content.length > 0)
  5899. {
  5900. this.insertLucidChart(JSON.parse(content));
  5901. mxEvent.consume(evt);
  5902. }
  5903. }
  5904. else
  5905. {
  5906. var graph = this.editor.graph;
  5907. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  5908. mxUtils.getTextContent(elt) : elt.textContent);
  5909. var compat = false;
  5910. // Workaround for junk after XML in VM
  5911. try
  5912. {
  5913. var idx = xml.lastIndexOf('%3E');
  5914. if (idx >= 0 && idx < xml.length - 3)
  5915. {
  5916. xml = xml.substring(0, idx + 3);
  5917. }
  5918. }
  5919. catch (e)
  5920. {
  5921. // ignore
  5922. }
  5923. // Checks for embedded XML content
  5924. try
  5925. {
  5926. var spans = elt.getElementsByTagName('span');
  5927. var tmp = (spans != null && spans.length > 0) ?
  5928. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  5929. decodeURIComponent(xml);
  5930. if (this.isCompatibleString(tmp))
  5931. {
  5932. compat = true;
  5933. xml = tmp;
  5934. }
  5935. }
  5936. catch (e)
  5937. {
  5938. // ignore
  5939. }
  5940. if (graph.lastPasteXml == xml)
  5941. {
  5942. graph.pasteCounter++;
  5943. }
  5944. else
  5945. {
  5946. graph.lastPasteXml = xml;
  5947. graph.pasteCounter = 0;
  5948. }
  5949. var dx = graph.pasteCounter * graph.gridSize;
  5950. if (xml != null && xml.length > 0)
  5951. {
  5952. if (compat || this.isCompatibleString(xml))
  5953. {
  5954. graph.setSelectionCells(this.importXml(xml, dx, dx));
  5955. }
  5956. else
  5957. {
  5958. var pt = graph.getInsertPoint();
  5959. if (graph.isMouseInsertPoint())
  5960. {
  5961. dx = 0;
  5962. // No offset for insert at mouse position
  5963. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  5964. {
  5965. graph.pasteCounter--;
  5966. }
  5967. }
  5968. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  5969. }
  5970. if (!graph.isSelectionEmpty())
  5971. {
  5972. graph.scrollCellToVisible(graph.getSelectionCell());
  5973. if (this.hoverIcons != null)
  5974. {
  5975. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  5976. }
  5977. try
  5978. {
  5979. mxEvent.consume(evt);
  5980. }
  5981. catch (e)
  5982. {
  5983. // ignore event no longer exists in async handler in IE8-
  5984. }
  5985. }
  5986. }
  5987. }
  5988. }
  5989. };
  5990. /**
  5991. * Adds a file drop handler for opening local files.
  5992. */
  5993. EditorUi.prototype.addFileDropHandler = function(elts)
  5994. {
  5995. // Installs drag and drop handler for files
  5996. if (Graph.fileSupport)
  5997. {
  5998. var dropElt = null;
  5999. for (var i = 0; i < elts.length; i++)
  6000. {
  6001. // Setup the dnd listeners
  6002. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  6003. {
  6004. if (dropElt != null)
  6005. {
  6006. dropElt.parentNode.removeChild(dropElt);
  6007. dropElt = null;
  6008. }
  6009. evt.stopPropagation();
  6010. evt.preventDefault();
  6011. });
  6012. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  6013. {
  6014. // IE 10 does not implement pointer-events so it can't have a drop highlight
  6015. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  6016. {
  6017. dropElt = this.highlightElement();
  6018. }
  6019. evt.stopPropagation();
  6020. evt.preventDefault();
  6021. }));
  6022. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  6023. {
  6024. if (dropElt != null)
  6025. {
  6026. dropElt.parentNode.removeChild(dropElt);
  6027. dropElt = null;
  6028. }
  6029. if (evt.dataTransfer.files.length > 0)
  6030. {
  6031. this.hideDialog();
  6032. // Never open files in embed mode
  6033. if (urlParams['embed'] == '1')
  6034. {
  6035. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  6036. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  6037. }
  6038. else
  6039. {
  6040. this.openFiles(evt.dataTransfer.files);
  6041. }
  6042. }
  6043. else
  6044. {
  6045. // Handles open special files via text drag and drop
  6046. var data = this.extractGraphModelFromEvent(evt);
  6047. // Tries additional and async parsing of text content such as HTML, Gliffy data
  6048. if (data == null)
  6049. {
  6050. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  6051. if (provider != null)
  6052. {
  6053. if (document.documentMode == 10 || document.documentMode == 11)
  6054. {
  6055. data = provider.getData('Text');
  6056. }
  6057. else
  6058. {
  6059. var data = null;
  6060. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  6061. {
  6062. var data = evt.dataTransfer.getData('text/uri-list');
  6063. }
  6064. else
  6065. {
  6066. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  6067. }
  6068. if (data != null && data.length > 0)
  6069. {
  6070. var div = document.createElement('div');
  6071. div.innerHTML = data;
  6072. // Extracts single image
  6073. var imgs = div.getElementsByTagName('img');
  6074. if (imgs.length > 0)
  6075. {
  6076. data = imgs[0].getAttribute('src');
  6077. }
  6078. }
  6079. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  6080. {
  6081. data = provider.getData('text/plain');
  6082. }
  6083. }
  6084. if (data != null)
  6085. {
  6086. // Checks for embedded XML in PNG
  6087. if (data.substring(0, 22) == 'data:image/png;base64,')
  6088. {
  6089. var xml = this.extractGraphModelFromPng(data);
  6090. if (xml != null && xml.length > 0)
  6091. {
  6092. this.openLocalFile(xml, null, true);
  6093. }
  6094. }
  6095. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  6096. {
  6097. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  6098. {
  6099. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  6100. {
  6101. this.openLocalFile(req.getText(), null, true);
  6102. }
  6103. }));
  6104. }
  6105. else if (/^https?:\/\//.test(data))
  6106. {
  6107. if (this.getCurrentFile() == null)
  6108. {
  6109. window.location.hash = '#U' + encodeURIComponent(data);
  6110. }
  6111. else
  6112. {
  6113. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  6114. 'https://www.draw.io/' : 'https://' + location.host + '/') +
  6115. window.location.search + '#U' + encodeURIComponent(data));
  6116. }
  6117. }
  6118. }
  6119. }
  6120. }
  6121. else
  6122. {
  6123. this.openLocalFile(data, null, true);
  6124. }
  6125. }
  6126. evt.stopPropagation();
  6127. evt.preventDefault();
  6128. }));
  6129. }
  6130. }
  6131. };
  6132. /**
  6133. * Highlights the given element
  6134. */
  6135. EditorUi.prototype.highlightElement = function(elt)
  6136. {
  6137. var x = 0;
  6138. var y = 0;
  6139. var w = 0;
  6140. var h = 0;
  6141. if (elt == null)
  6142. {
  6143. var b = document.body;
  6144. var d = document.documentElement;
  6145. w = (b.clientWidth || d.clientWidth) - 3;
  6146. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  6147. }
  6148. else
  6149. {
  6150. x = elt.offsetTop;
  6151. y = elt.offsetLeft;
  6152. w = elt.clientWidth;
  6153. h = elt.clientHeight;
  6154. }
  6155. var hl = document.createElement('div');
  6156. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  6157. hl.style.border = '3px dotted rgb(254, 137, 12)';
  6158. hl.style.pointerEvents = 'none';
  6159. hl.style.position = 'absolute';
  6160. hl.style.top = x + 'px';
  6161. hl.style.left = y + 'px';
  6162. hl.style.width = Math.max(0, w - 3) + 'px';
  6163. hl.style.height = Math.max(0, h - 3) + 'px';
  6164. if (elt != null && elt.parentNode == this.editor.graph.container)
  6165. {
  6166. this.editor.graph.container.appendChild(hl);
  6167. }
  6168. else
  6169. {
  6170. document.body.appendChild(hl);
  6171. }
  6172. return hl;
  6173. };
  6174. /**
  6175. * Highlights the given element
  6176. */
  6177. EditorUi.prototype.stringToCells = function(xml)
  6178. {
  6179. var doc = mxUtils.parseXml(xml);
  6180. var node = this.editor.extractGraphModel(doc.documentElement);
  6181. var cells = [];
  6182. if (node != null)
  6183. {
  6184. var codec = new mxCodec(node.ownerDocument);
  6185. var model = new mxGraphModel();
  6186. codec.decode(node, model);
  6187. var parent = model.getChildAt(model.getRoot(), 0);
  6188. for (var j = 0; j < model.getChildCount(parent); j++)
  6189. {
  6190. cells.push(model.getChildAt(parent, j));
  6191. }
  6192. }
  6193. return cells;
  6194. };
  6195. /**
  6196. * Opens the given files in the editor.
  6197. */
  6198. EditorUi.prototype.openFiles = function(files)
  6199. {
  6200. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6201. {
  6202. for (var i = 0; i < files.length; i++)
  6203. {
  6204. (mxUtils.bind(this, function(file)
  6205. {
  6206. var reader = new FileReader();
  6207. reader.onload = mxUtils.bind(this, function(e)
  6208. {
  6209. var data = e.target.result;
  6210. var name = file.name;
  6211. if (name != null && name.length > 0)
  6212. {
  6213. if (/(\.png)$/i.test(name))
  6214. {
  6215. name = name.substring(0, name.length - 4) + '.xml';
  6216. }
  6217. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  6218. this.isRemoteFileFormat(data, name))
  6219. {
  6220. var dot = name.lastIndexOf('.');
  6221. if (dot >= 0)
  6222. {
  6223. name = name.substring(0, name.lastIndexOf('.')) + '.xml';
  6224. }
  6225. else
  6226. {
  6227. name = name + '.xml';
  6228. }
  6229. this.parseFile(file, mxUtils.bind(this, function(xhr)
  6230. {
  6231. if (xhr.readyState == 4)
  6232. {
  6233. this.spinner.stop();
  6234. if (xhr.status >= 200 && xhr.status <= 299)
  6235. {
  6236. this.openLocalFile(xhr.responseText, name);
  6237. }
  6238. else
  6239. {
  6240. this.handleError({message: mxResources.get((xhr.status == 413) ?
  6241. 'drawingTooLarge' : 'invalidOrMissingFile')},
  6242. mxResources.get('errorLoadingFile'));
  6243. }
  6244. }
  6245. }));
  6246. }
  6247. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  6248. {
  6249. this.spinner.stop();
  6250. try
  6251. {
  6252. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  6253. }
  6254. catch (e)
  6255. {
  6256. this.handleError(e, mxResources.get('errorLoadingFile'));
  6257. }
  6258. }
  6259. else
  6260. {
  6261. if (file.type.substring(0, 9) == 'image/png')
  6262. {
  6263. data = this.extractGraphModelFromPng(data);
  6264. }
  6265. this.spinner.stop();
  6266. this.openLocalFile(data, name);
  6267. }
  6268. }
  6269. });
  6270. reader.onerror = mxUtils.bind(this, function(e)
  6271. {
  6272. this.spinner.stop();
  6273. this.handleError(e);
  6274. window.openFile = null;
  6275. });
  6276. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  6277. {
  6278. reader.readAsDataURL(file);
  6279. }
  6280. else
  6281. {
  6282. reader.readAsText(file);
  6283. }
  6284. }))(files[i]);
  6285. }
  6286. }
  6287. };
  6288. /**
  6289. * Shows the layers dialog if the graph has more than one layer.
  6290. */
  6291. EditorUi.prototype.openLocalFile = function(data, name, temp)
  6292. {
  6293. var currentFile = this.getCurrentFile();
  6294. var fn = mxUtils.bind(this, function()
  6295. {
  6296. window.openFile = null;
  6297. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  6298. {
  6299. var doc = mxUtils.parseXml(data);
  6300. if (doc != null)
  6301. {
  6302. this.editor.setGraphXml(doc.documentElement);
  6303. this.editor.graph.selectAll();
  6304. }
  6305. }
  6306. else
  6307. {
  6308. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  6309. }
  6310. });
  6311. if (data != null && data.length > 0)
  6312. {
  6313. if (currentFile == null || !currentFile.isModified())
  6314. {
  6315. fn();
  6316. }
  6317. else
  6318. {
  6319. window.openFile = new OpenFile(function()
  6320. {
  6321. window.openFile = null;
  6322. });
  6323. window.openFile.setData(data, name);
  6324. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  6325. {
  6326. this.confirm(mxResources.get('allChangesLost'), null, fn,
  6327. mxResources.get('cancel'), mxResources.get('discardChanges'));
  6328. }));
  6329. }
  6330. }
  6331. };
  6332. /**
  6333. * Returns a list of all shapes used in the current file.
  6334. */
  6335. EditorUi.prototype.getBasenames = function()
  6336. {
  6337. var basenames = {};
  6338. if (this.pages != null)
  6339. {
  6340. for (var i = 0; i < this.pages.length; i++)
  6341. {
  6342. this.updatePageRoot(this.pages[i]);
  6343. this.addBasenamesForCell(this.pages[i].root, basenames);
  6344. }
  6345. }
  6346. else
  6347. {
  6348. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  6349. }
  6350. var result = [];
  6351. for (var key in basenames)
  6352. {
  6353. result.push(key);
  6354. }
  6355. return result;
  6356. };
  6357. /**
  6358. * Returns a list of all shapes used in the current file.
  6359. */
  6360. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  6361. {
  6362. function addName(name)
  6363. {
  6364. if (name != null)
  6365. {
  6366. // LATER: Check if this case exists
  6367. var dot = name.lastIndexOf('.');
  6368. if (dot > 0)
  6369. {
  6370. name = name.substring(dot + 1, name.length);
  6371. }
  6372. if (basenames[name] == null)
  6373. {
  6374. basenames[name] = true;
  6375. }
  6376. }
  6377. };
  6378. var graph = this.editor.graph;
  6379. var style = graph.getCellStyle(cell);
  6380. var shape = style[mxConstants.STYLE_SHAPE];
  6381. addName(mxStencilRegistry.getBasenameForStencil(shape));
  6382. // Adds package names for markers in edges
  6383. if (graph.model.isEdge(cell))
  6384. {
  6385. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  6386. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  6387. }
  6388. var childCount = graph.model.getChildCount(cell);
  6389. for (var i = 0; i < childCount; i++)
  6390. {
  6391. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  6392. }
  6393. };
  6394. /**
  6395. * Shows the layers dialog if the graph has more than one layer.
  6396. */
  6397. EditorUi.prototype.setGraphEnabled = function(enabled)
  6398. {
  6399. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  6400. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  6401. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  6402. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  6403. this.hsplit.style.display = (enabled) ? '' : 'none';
  6404. this.editor.graph.setEnabled(enabled);
  6405. };
  6406. /**
  6407. * Shows the layers dialog if the graph has more than one layer.
  6408. */
  6409. EditorUi.prototype.initializeEmbedMode = function()
  6410. {
  6411. this.setGraphEnabled(false);
  6412. var parent = window.opener || window.parent;
  6413. if (parent != window)
  6414. {
  6415. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  6416. {
  6417. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  6418. {
  6419. this.spinner.stop();
  6420. this.addEmbedButtons();
  6421. this.setGraphEnabled(true);
  6422. if (xml != null && xml.length > 0)
  6423. {
  6424. this.setFileData(xml);
  6425. this.showLayersDialog();
  6426. }
  6427. else
  6428. {
  6429. this.editor.graph.model.clear();
  6430. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  6431. }
  6432. this.editor.undoManager.clear();
  6433. this.editor.modified = (modified != null) ? modified : false;
  6434. this.updateUi();
  6435. // Workaround for no initial focus in FF
  6436. // (does not work in Conf Cloud with FF)
  6437. if (window.self !== window.top)
  6438. {
  6439. window.focus();
  6440. }
  6441. if (this.format != null)
  6442. {
  6443. this.format.refresh();
  6444. }
  6445. }));
  6446. }
  6447. }
  6448. };
  6449. /**
  6450. * Shows the layers dialog if the graph has more than one layer.
  6451. */
  6452. EditorUi.prototype.showLayersDialog = function()
  6453. {
  6454. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  6455. {
  6456. if (this.actions.layersWindow == null)
  6457. {
  6458. this.actions.get('layers').funct();
  6459. }
  6460. else
  6461. {
  6462. this.actions.layersWindow.window.setVisible(true);
  6463. }
  6464. }
  6465. };
  6466. /**
  6467. * Tries to find a public URL for the given file.
  6468. */
  6469. EditorUi.prototype.getPublicUrl = function(file, fn)
  6470. {
  6471. if (file != null)
  6472. {
  6473. file.getPublicUrl(fn);
  6474. }
  6475. else
  6476. {
  6477. fn(null);
  6478. }
  6479. };
  6480. /**
  6481. * Adds the buttons for embedded mode.
  6482. */
  6483. EditorUi.prototype.createLoadMessage = function(eventName)
  6484. {
  6485. var graph = this.editor.graph;
  6486. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  6487. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds(), bounds: graph.getGraphBounds()};
  6488. };
  6489. /**
  6490. * Adds the buttons for embedded mode.
  6491. */
  6492. EditorUi.prototype.installMessageHandler = function(fn)
  6493. {
  6494. var changeListener = null;
  6495. var ignoreChange = false;
  6496. var autosave = false;
  6497. var lastData = null;
  6498. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  6499. {
  6500. if (!this.editor.modified || urlParams['modified'] == '0')
  6501. {
  6502. this.editor.setStatus('');
  6503. }
  6504. else if (urlParams['modified'] != null)
  6505. {
  6506. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  6507. }
  6508. });
  6509. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  6510. // Receives XML message from opener and puts it into the graph
  6511. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  6512. {
  6513. var data = evt.data;
  6514. function extractDiagramXml(data)
  6515. {
  6516. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  6517. {
  6518. try
  6519. {
  6520. if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  6521. {
  6522. data = atob(data.substring(26));
  6523. }
  6524. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  6525. {
  6526. data = data.substring(24);
  6527. }
  6528. if (data != null)
  6529. {
  6530. if (data.charAt(0) == '%')
  6531. {
  6532. data = decodeURIComponent(data);
  6533. }
  6534. else if (data.charAt(0) != '<')
  6535. {
  6536. data = this.editor.graph.decompress(data);
  6537. }
  6538. }
  6539. }
  6540. catch (e)
  6541. {
  6542. // ignore compression errors and use empty data
  6543. }
  6544. }
  6545. return data;
  6546. };
  6547. if (urlParams['proto'] == 'json')
  6548. {
  6549. try
  6550. {
  6551. data = JSON.parse(data);
  6552. }
  6553. catch (e)
  6554. {
  6555. data = null;
  6556. }
  6557. if (data == null)
  6558. {
  6559. // Ignore
  6560. return;
  6561. }
  6562. else if (data.action == 'dialog')
  6563. {
  6564. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  6565. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  6566. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  6567. if (data.modified != null)
  6568. {
  6569. this.editor.modified = data.modified;
  6570. }
  6571. return;
  6572. }
  6573. else if (data.action == 'prompt')
  6574. {
  6575. this.spinner.stop();
  6576. var dlg = new FilenameDialog(this, data.defaultValue || '',
  6577. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  6578. {
  6579. if (value != null)
  6580. {
  6581. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  6582. }
  6583. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  6584. this.showDialog(dlg.container, 300, 80, true, false);
  6585. dlg.init();
  6586. return;
  6587. }
  6588. else if (data.action == 'draft')
  6589. {
  6590. var tmp = null;
  6591. if (data.xml.substring(0, 22) == 'data:image/png;base64,')
  6592. {
  6593. tmp = this.extractGraphModelFromPng(data.xml);
  6594. }
  6595. else
  6596. {
  6597. tmp = extractDiagramXml(data.xml);
  6598. }
  6599. this.spinner.stop();
  6600. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  6601. tmp, mxUtils.bind(this, function()
  6602. {
  6603. this.hideDialog();
  6604. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  6605. }), mxUtils.bind(this, function()
  6606. {
  6607. this.hideDialog();
  6608. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  6609. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  6610. (data.discardKey) ? mxResources.get(data.discardKey) : null);
  6611. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  6612. {
  6613. if (cancel)
  6614. {
  6615. this.actions.get('exit').funct();
  6616. }
  6617. }));
  6618. try
  6619. {
  6620. dlg.init();
  6621. }
  6622. catch (e)
  6623. {
  6624. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  6625. }
  6626. return;
  6627. }
  6628. else if (data.action == 'template')
  6629. {
  6630. this.spinner.stop();
  6631. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  6632. {
  6633. xml = xml || this.emptyDiagramXml;
  6634. // LATER: Add autosave option in template message
  6635. if (data.callback != null)
  6636. {
  6637. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  6638. blank: xml == this.emptyDiagramXml, name: name}), '*');
  6639. }
  6640. else
  6641. {
  6642. fn(xml, evt, xml != this.emptyDiagramXml);
  6643. // Workaround for status updated before modified applied
  6644. if (!this.editor.modified)
  6645. {
  6646. this.editor.setStatus('');
  6647. }
  6648. }
  6649. }));
  6650. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  6651. {
  6652. if (cancel)
  6653. {
  6654. this.actions.get('exit').funct();
  6655. }
  6656. }));
  6657. dlg.init();
  6658. return;
  6659. }
  6660. else if (data.action == 'status')
  6661. {
  6662. if (data.messageKey != null)
  6663. {
  6664. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  6665. }
  6666. else if (data.message != null)
  6667. {
  6668. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  6669. }
  6670. if (data.modified != null)
  6671. {
  6672. this.editor.modified = data.modified;
  6673. }
  6674. return;
  6675. }
  6676. else if (data.action == 'spinner')
  6677. {
  6678. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  6679. if (data.show != null && !data.show)
  6680. {
  6681. this.spinner.stop();
  6682. }
  6683. else
  6684. {
  6685. this.spinner.spin(document.body, msg)
  6686. }
  6687. return;
  6688. }
  6689. else if (data.action == 'export')
  6690. {
  6691. if (data.format == 'png' || data.format == 'xmlpng')
  6692. {
  6693. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  6694. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  6695. {
  6696. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  6697. this.editor.graph.setEnabled(false);
  6698. var graph = this.editor.graph;
  6699. var postDataBack = mxUtils.bind(this, function(uri)
  6700. {
  6701. this.editor.graph.setEnabled(true);
  6702. this.spinner.stop();
  6703. var msg = this.createLoadMessage('export');
  6704. msg.format = data.format;
  6705. msg.xml = encodeURIComponent(xml);
  6706. msg.data = uri;
  6707. parent.postMessage(JSON.stringify(msg), '*');
  6708. });
  6709. var processUri = mxUtils.bind(this, function(uri)
  6710. {
  6711. if (uri == null)
  6712. {
  6713. uri = Editor.blankImage;
  6714. }
  6715. if (data.format == 'xmlpng')
  6716. {
  6717. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  6718. atob(this.editor.graph.compress(xml)));
  6719. }
  6720. // Removes temporary graph from DOM
  6721. if (graph != this.editor.graph)
  6722. {
  6723. graph.container.parentNode.removeChild(graph.container);
  6724. }
  6725. postDataBack(uri);
  6726. });
  6727. // LATER: Uses external export if current page (not first page) has mathEnabled
  6728. if (this.isExportToCanvas())
  6729. {
  6730. // Exports PNG for first page while other page is visible by creating a graph
  6731. // LATER: Add caching for the graph or SVG while not on first page
  6732. if (this.pages != null && this.currentPage != this.pages[0])
  6733. {
  6734. graph = this.createTemporaryGraph(graph.getStylesheet());
  6735. var graphGetGlobalVariable = graph.getGlobalVariable;
  6736. var page = this.pages[0];
  6737. graph.getGlobalVariable = function(name)
  6738. {
  6739. if (name == 'page')
  6740. {
  6741. return page.getName();
  6742. }
  6743. else if (name == 'pagenumber')
  6744. {
  6745. return 1;
  6746. }
  6747. return graphGetGlobalVariable.apply(this, arguments);
  6748. };
  6749. document.body.appendChild(graph.container);
  6750. graph.model.setRoot(page.root);
  6751. }
  6752. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  6753. {
  6754. processUri(canvas.toDataURL('image/png'));
  6755. }), null, null, null, mxUtils.bind(this, function()
  6756. {
  6757. processUri(null);
  6758. }), null, null, null, null, null, null, graph);
  6759. }
  6760. else
  6761. {
  6762. // Data from server is base64 encoded to avoid binary XHR
  6763. // Double encoding for XML arg is needed for UTF8 encoding
  6764. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  6765. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  6766. encodeURIComponent(encodeURIComponent(xml)));
  6767. req.send(mxUtils.bind(this, function(req)
  6768. {
  6769. // Temp graph was never created at this point so we can
  6770. // skip processUri since it already contains the XML
  6771. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  6772. {
  6773. postDataBack('data:image/png;base64,' + req.getText());
  6774. }
  6775. else
  6776. {
  6777. processUri(null);
  6778. }
  6779. }), mxUtils.bind(this, function()
  6780. {
  6781. processUri(null);
  6782. }));
  6783. }
  6784. }
  6785. }
  6786. else
  6787. {
  6788. // SVG is generated from graph so parse optional XML
  6789. if (data.xml != null && data.xml.length > 0)
  6790. {
  6791. this.setFileData(data.xml);
  6792. }
  6793. var msg = this.createLoadMessage('export');
  6794. // Forces new HTML format if pages exists
  6795. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  6796. (this.pages != null && this.pages.length > 1))))
  6797. {
  6798. var node = this.getXmlFileData();
  6799. msg.xml = mxUtils.getXml(node);
  6800. msg.data = this.getFileData(null, null, true, null, null, null, node);
  6801. msg.format = data.format;
  6802. }
  6803. else if (data.format == 'html')
  6804. {
  6805. var xml = this.editor.getGraphXml();
  6806. msg.data = this.getHtml(xml, this.editor.graph);
  6807. msg.xml = mxUtils.getXml(xml);
  6808. msg.format = data.format;
  6809. }
  6810. else
  6811. {
  6812. // Creates a preview with no alt text for unsupported browsers
  6813. mxSvgCanvas2D.prototype.foAltText = null;
  6814. var bg = this.editor.graph.background;
  6815. if (bg == mxConstants.NONE)
  6816. {
  6817. bg = null;
  6818. }
  6819. msg.xml = this.getFileData(true);
  6820. msg.format = 'svg';
  6821. if (data.embedImages || data.embedImages == null)
  6822. {
  6823. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  6824. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  6825. {
  6826. this.editor.graph.setEnabled(false);
  6827. if (data.format == 'xmlsvg')
  6828. {
  6829. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  6830. {
  6831. this.editor.graph.setEnabled(true);
  6832. this.spinner.stop();
  6833. msg.data = this.createSvgDataUri(svg);
  6834. parent.postMessage(JSON.stringify(msg), '*');
  6835. }));
  6836. }
  6837. else
  6838. {
  6839. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  6840. {
  6841. this.editor.graph.setEnabled(true);
  6842. this.spinner.stop();
  6843. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6844. parent.postMessage(JSON.stringify(msg), '*');
  6845. }));
  6846. }
  6847. }
  6848. return;
  6849. }
  6850. else
  6851. {
  6852. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  6853. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  6854. msg.data = this.createSvgDataUri(svg);
  6855. }
  6856. }
  6857. parent.postMessage(JSON.stringify(msg), '*');
  6858. }
  6859. return;
  6860. }
  6861. else if (data.action == 'load')
  6862. {
  6863. autosave = data.autosave == 1;
  6864. this.hideDialog();
  6865. if (data.modified != null && urlParams['modified'] == null)
  6866. {
  6867. urlParams['modified'] = data.modified;
  6868. }
  6869. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  6870. {
  6871. urlParams['saveAndExit'] = data.saveAndExit;
  6872. }
  6873. if (data.title != null && this.buttonContainer != null)
  6874. {
  6875. var tmp = document.createElement('span');
  6876. mxUtils.write(tmp, data.title);
  6877. if (uiTheme == 'atlas')
  6878. {
  6879. this.buttonContainer.style.paddingRight = '12px';
  6880. this.buttonContainer.style.paddingTop = '12px';
  6881. }
  6882. else
  6883. {
  6884. this.buttonContainer.style.paddingRight = '38px';
  6885. this.buttonContainer.style.paddingTop = '6px';
  6886. }
  6887. this.buttonContainer.appendChild(tmp);
  6888. }
  6889. if (data.xmlpng != null)
  6890. {
  6891. data = this.extractGraphModelFromPng(data.xmlpng);
  6892. }
  6893. else if (data.xml != null && data.xml.substring(0, 22) == 'data:image/png;base64,')
  6894. {
  6895. data = this.extractGraphModelFromPng(data.xml);
  6896. }
  6897. else
  6898. {
  6899. data = data.xml;
  6900. }
  6901. }
  6902. else
  6903. {
  6904. // Unknown message must stop execution
  6905. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  6906. return;
  6907. }
  6908. }
  6909. data = extractDiagramXml(data);
  6910. ignoreChange = true;
  6911. try
  6912. {
  6913. fn(data, evt);
  6914. }
  6915. catch (e)
  6916. {
  6917. this.handleError(e);
  6918. }
  6919. ignoreChange = false;
  6920. if (urlParams['modified'] != null)
  6921. {
  6922. this.editor.setStatus('');
  6923. }
  6924. var getData = mxUtils.bind(this, function()
  6925. {
  6926. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  6927. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  6928. });;
  6929. lastData = getData();
  6930. if (autosave && changeListener == null)
  6931. {
  6932. changeListener = mxUtils.bind(this, function(sender, eventObject)
  6933. {
  6934. var data = getData();
  6935. if (data != lastData && !ignoreChange)
  6936. {
  6937. var msg = this.createLoadMessage('autosave');
  6938. msg.xml = data;
  6939. data = JSON.stringify(msg);
  6940. var parent = window.opener || window.parent;
  6941. parent.postMessage(data, '*');
  6942. }
  6943. lastData = data;
  6944. });
  6945. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  6946. // Some options trigger autosave
  6947. this.editor.graph.addListener('gridSizeChanged', changeListener);
  6948. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  6949. this.addListener('pageFormatChanged', changeListener);
  6950. this.addListener('pageScaleChanged', changeListener);
  6951. this.addListener('backgroundColorChanged', changeListener);
  6952. this.addListener('backgroundImageChanged', changeListener);
  6953. this.addListener('foldingEnabledChanged', changeListener);
  6954. this.addListener('mathEnabledChanged', changeListener);
  6955. this.addListener('gridEnabledChanged', changeListener);
  6956. this.addListener('guidesEnabledChanged', changeListener);
  6957. this.addListener('pageViewChanged', changeListener);
  6958. }
  6959. // Sends the bounds of the graph to the host after parsing
  6960. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  6961. {
  6962. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  6963. }
  6964. }));
  6965. // Requests data from the sender. This is a workaround for not allowing
  6966. // the opener to listen for the onload event if not in the same origin.
  6967. var parent = window.opener || window.parent;
  6968. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  6969. parent.postMessage(msg, '*');
  6970. };
  6971. /**
  6972. * Adds the buttons for embedded mode.
  6973. */
  6974. EditorUi.prototype.addEmbedButtons = function()
  6975. {
  6976. if (this.menubar != null)
  6977. {
  6978. var div = document.createElement('div');
  6979. div.style.display = 'inline-block';
  6980. div.style.position = 'absolute';
  6981. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  6982. div.style.paddingLeft = '8px';
  6983. div.style.paddingBottom = '2px';
  6984. var button = document.createElement('button');
  6985. mxUtils.write(button, mxResources.get('save'));
  6986. button.setAttribute('title', mxResources.get('save') + ' (Ctrl+S)');
  6987. button.className = 'geBigButton';
  6988. button.style.fontSize = '12px';
  6989. button.style.padding = '4px 6px 4px 6px';
  6990. button.style.borderRadius = '3px';
  6991. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  6992. {
  6993. this.actions.get('save').funct();
  6994. }));
  6995. div.appendChild(button);
  6996. if (urlParams['saveAndExit'] == '1')
  6997. {
  6998. button = document.createElement('a');
  6999. mxUtils.write(button, mxResources.get('saveAndExit'));
  7000. button.setAttribute('title', mxResources.get('saveAndExit'));
  7001. button.style.fontSize = '12px';
  7002. button.style.marginLeft = '6px';
  7003. button.style.padding = '4px';
  7004. button.style.cursor = 'pointer';
  7005. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  7006. {
  7007. this.actions.get('saveAndExit').funct();
  7008. }));
  7009. div.appendChild(button);
  7010. }
  7011. button = document.createElement('a');
  7012. mxUtils.write(button, mxResources.get('exit'));
  7013. button.setAttribute('title', mxResources.get('exit'));
  7014. button.style.fontSize = '12px';
  7015. button.style.marginLeft = '6px';
  7016. button.style.marginRight = '20px';
  7017. button.style.padding = '4px';
  7018. button.style.cursor = 'pointer';
  7019. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  7020. {
  7021. this.actions.get('exit').funct();
  7022. }));
  7023. div.appendChild(button);
  7024. this.toolbar.container.appendChild(div);
  7025. this.toolbar.staticElements.push(div);
  7026. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  7027. }
  7028. };
  7029. /**
  7030. *
  7031. */
  7032. EditorUi.prototype.showImportCsvDialog = function()
  7033. {
  7034. if (this.importCsvDialog == null)
  7035. {
  7036. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  7037. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  7038. {
  7039. this.importCsv(newValue);
  7040. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  7041. }
  7042. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  7043. this.importCsvDialog.init();
  7044. };
  7045. /**
  7046. * TODO: Move to Editor
  7047. */
  7048. EditorUi.prototype.importCsv = function(text)
  7049. {
  7050. try
  7051. {
  7052. var lines = text.split('\n');
  7053. var cells = [];
  7054. if (lines.length > 0)
  7055. {
  7056. // Internal lookup table
  7057. var lookups = {};
  7058. // Default values
  7059. var style = null;
  7060. var identity = null;
  7061. var width = 'auto';
  7062. var height = 'auto';
  7063. var edgespacing = 40;
  7064. var nodespacing = 40;
  7065. var padding = 0;
  7066. var graph = this.editor.graph;
  7067. var view = graph.view;
  7068. var bds = graph.getGraphBounds();
  7069. // Delayed after optional layout
  7070. var afterInsert = function()
  7071. {
  7072. graph.setSelectionCells(select);
  7073. graph.scrollCellToVisible(graph.getSelectionCell());
  7074. };
  7075. // Computes unscaled, untranslated graph bounds
  7076. var pt = graph.getFreeInsertPoint();
  7077. var x0 = pt.x;
  7078. var y0 = pt.y;
  7079. var y = y0;
  7080. // Default label value depends on column names
  7081. var label = null;
  7082. // Default layout to run.
  7083. var layout = 'auto';
  7084. // Name of the attribute that contains the parent reference
  7085. var parent = null;
  7086. // Name of the attribute that contains the references for creating edges
  7087. var edges = [];
  7088. // Name of the column for hyperlinks
  7089. var link = null;
  7090. // String array of names to remove from metadata
  7091. var ignore = null;
  7092. // Read processing instructions first
  7093. var index = 0;
  7094. while (index < lines.length && lines[index].charAt(0) == '#')
  7095. {
  7096. var text = lines[index];
  7097. index++;
  7098. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  7099. lines[index].charAt(0) == '#')
  7100. {
  7101. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  7102. index++;
  7103. }
  7104. if (text.charAt(1) != '#')
  7105. {
  7106. // Processing instruction
  7107. var idx = text.indexOf(':');
  7108. if (idx > 0)
  7109. {
  7110. var key = mxUtils.trim(text.substring(1, idx));
  7111. var value = mxUtils.trim(text.substring(idx + 1));
  7112. if (key == 'label')
  7113. {
  7114. label = graph.sanitizeHtml(value);
  7115. }
  7116. else if (key == 'style')
  7117. {
  7118. style = value;
  7119. }
  7120. else if (key == 'identity' && value.length > 0 && value != '-')
  7121. {
  7122. identity = value;
  7123. }
  7124. else if (key == 'width')
  7125. {
  7126. width = value;
  7127. }
  7128. else if (key == 'height')
  7129. {
  7130. height = value;
  7131. }
  7132. else if (key == 'ignore')
  7133. {
  7134. ignore = value.split(',');
  7135. }
  7136. else if (key == 'connect')
  7137. {
  7138. edges.push(JSON.parse(value));
  7139. }
  7140. else if (key == 'link')
  7141. {
  7142. link = value;
  7143. }
  7144. else if (key == 'padding')
  7145. {
  7146. padding = parseFloat(value);
  7147. }
  7148. else if (key == 'edgespacing')
  7149. {
  7150. edgespacing = parseFloat(value);
  7151. }
  7152. else if (key == 'nodespacing')
  7153. {
  7154. nodespacing = parseFloat(value);
  7155. }
  7156. else if (key == 'layout')
  7157. {
  7158. layout = value;
  7159. }
  7160. }
  7161. }
  7162. }
  7163. var keys = this.editor.csvToArray(lines[index]);
  7164. // Converts name of identity to index of column
  7165. var identityIndex = null;
  7166. if (identity != null)
  7167. {
  7168. for (var i = 0; i < keys.length; i++)
  7169. {
  7170. if (identity == keys[i])
  7171. {
  7172. identityIndex = i;
  7173. break;
  7174. }
  7175. }
  7176. }
  7177. if (label == null)
  7178. {
  7179. label = '%' + keys[0] + '%';
  7180. }
  7181. if (edges != null)
  7182. {
  7183. for (var e = 0; e < edges.length; e++)
  7184. {
  7185. if (lookups[edges[e].to] == null)
  7186. {
  7187. lookups[edges[e].to] = {};
  7188. }
  7189. }
  7190. }
  7191. graph.model.beginUpdate();
  7192. try
  7193. {
  7194. for (var i = index + 1; i < lines.length; i++)
  7195. {
  7196. var values = this.editor.csvToArray(lines[i]);
  7197. if (values.length == keys.length)
  7198. {
  7199. var cell = null;
  7200. var id = (identityIndex != null) ? values[identityIndex] : null;
  7201. if (id != null)
  7202. {
  7203. cell = graph.model.getCell(id);
  7204. }
  7205. if (cell == null)
  7206. {
  7207. var cell = new mxCell(label, new mxGeometry(x0, y,
  7208. 0, 0), style || 'whiteSpace=wrap;html=1;');
  7209. cell.vertex = true;
  7210. cell.id = id;
  7211. }
  7212. for (var j = 0; j < values.length; j++)
  7213. {
  7214. graph.setAttributeForCell(cell, keys[j], values[j]);
  7215. }
  7216. graph.setAttributeForCell(cell, 'placeholders', '1');
  7217. cell.style = graph.replacePlaceholders(cell, cell.style);
  7218. for (var e = 0; e < edges.length; e++)
  7219. {
  7220. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  7221. }
  7222. if (link != null && link != 'link')
  7223. {
  7224. graph.setLinkForCell(cell, cell.getAttribute(link));
  7225. // Removes attribute
  7226. graph.setAttributeForCell(cell, link, null);
  7227. }
  7228. // Sets the size
  7229. var size = this.editor.graph.getPreferredSizeForCell(cell);
  7230. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  7231. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  7232. y += cell.geometry.height + nodespacing;
  7233. cells.push(graph.addCell(cell));
  7234. }
  7235. }
  7236. if (style == null)
  7237. {
  7238. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', cells));
  7239. }
  7240. var roots = cells.slice();
  7241. var select = cells.slice();
  7242. for (var e = 0; e < edges.length; e++)
  7243. {
  7244. var edge = edges[e];
  7245. for (var i = 0; i < cells.length; i++)
  7246. {
  7247. var cell = cells[i];
  7248. var tmp = cell.getAttribute(edge.from);
  7249. if (tmp != null)
  7250. {
  7251. // Removes attribute
  7252. graph.setAttributeForCell(cell, edge.from, null);
  7253. var refs = tmp.split(',');
  7254. for (var j = 0; j < refs.length; j++)
  7255. {
  7256. var ref = lookups[edge.to][refs[j]];
  7257. if (ref != null)
  7258. {
  7259. select.push(graph.insertEdge(null, null, edge.label || '',
  7260. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  7261. edge.style || graph.createCurrentEdgeStyle()));
  7262. mxUtils.remove((edge.invert) ? cell : ref, roots);
  7263. }
  7264. }
  7265. }
  7266. }
  7267. }
  7268. // Removes ignored attributes after processing above
  7269. if (ignore != null)
  7270. {
  7271. for (var i = 0; i < cells.length; i++)
  7272. {
  7273. var cell = cells[i];
  7274. for (var j = 0; j < ignore.length; j++)
  7275. {
  7276. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  7277. }
  7278. }
  7279. }
  7280. var edgeLayout = new mxParallelEdgeLayout(graph);
  7281. edgeLayout.spacing = edgespacing;
  7282. var postProcess = function()
  7283. {
  7284. edgeLayout.execute(graph.getDefaultParent());
  7285. // Aligns cells to grid and/or rounds positions
  7286. for (var i = 0; i < cells.length; i++)
  7287. {
  7288. var geo = graph.getCellGeometry(cells[i]);
  7289. geo.x = Math.round(graph.snap(geo.x));
  7290. geo.y = Math.round(graph.snap(geo.y));
  7291. if (width == 'auto')
  7292. {
  7293. geo.width = Math.round(graph.snap(geo.width));
  7294. }
  7295. if (height == 'auto')
  7296. {
  7297. geo.height = Math.round(graph.snap(geo.height));
  7298. }
  7299. }
  7300. };
  7301. if (layout == 'circle')
  7302. {
  7303. var circleLayout = new mxCircleLayout(graph);
  7304. circleLayout.resetEdges = false;
  7305. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  7306. // Ignore other cells
  7307. circleLayout.isVertexIgnored = function(vertex)
  7308. {
  7309. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  7310. mxUtils.indexOf(cells, vertex) < 0;
  7311. };
  7312. this.executeLayout(function()
  7313. {
  7314. circleLayout.execute(graph.getDefaultParent());
  7315. postProcess();
  7316. }, true, afterInsert);
  7317. afterInsert = null;
  7318. }
  7319. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  7320. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  7321. {
  7322. // Required for layouts to work with new cells
  7323. graph.view.validate();
  7324. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  7325. treeLayout.levelDistance = nodespacing;
  7326. treeLayout.edgeRouting = false;
  7327. treeLayout.resetEdges = false;
  7328. this.executeLayout(function()
  7329. {
  7330. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  7331. }, true, afterInsert);
  7332. afterInsert = null;
  7333. }
  7334. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  7335. (layout == 'auto' && roots.length == 1))
  7336. {
  7337. // Required for layouts to work with new cells
  7338. graph.view.validate();
  7339. var flowLayout = new mxHierarchicalLayout(graph,
  7340. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  7341. flowLayout.intraCellSpacing = nodespacing;
  7342. flowLayout.disableEdgeStyle = false;
  7343. this.executeLayout(function()
  7344. {
  7345. flowLayout.execute(graph.getDefaultParent(), select);
  7346. // Workaround for flow layout moving cells to origin
  7347. graph.moveCells(select, x0, y0);
  7348. }, true, afterInsert);
  7349. afterInsert = null;
  7350. }
  7351. else if (layout == 'organic' || (layout == 'auto' &&
  7352. select.length > cells.length))
  7353. {
  7354. // Required for layouts to work with new cells
  7355. graph.view.validate();
  7356. var organicLayout = new mxFastOrganicLayout(graph);
  7357. organicLayout.forceConstant = nodespacing * 3;
  7358. organicLayout.resetEdges = false;
  7359. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  7360. // Ignore other cells
  7361. organicLayout.isVertexIgnored = function(vertex)
  7362. {
  7363. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  7364. mxUtils.indexOf(cells, vertex) < 0;
  7365. };
  7366. var edgeLayout = new mxParallelEdgeLayout(graph);
  7367. edgeLayout.spacing = edgespacing;
  7368. this.executeLayout(function()
  7369. {
  7370. organicLayout.execute(graph.getDefaultParent());
  7371. postProcess();
  7372. }, true, afterInsert);
  7373. afterInsert = null;
  7374. }
  7375. this.hideDialog();
  7376. }
  7377. finally
  7378. {
  7379. graph.model.endUpdate();
  7380. }
  7381. if (afterInsert != null)
  7382. {
  7383. afterInsert();
  7384. }
  7385. }
  7386. }
  7387. catch (e)
  7388. {
  7389. this.handleError(e);
  7390. }
  7391. };
  7392. /**
  7393. * Translates this point by the given vector.
  7394. *
  7395. * @param {number} dx X-coordinate of the translation.
  7396. * @param {number} dy Y-coordinate of the translation.
  7397. */
  7398. EditorUi.prototype.getSearch = function(exclude)
  7399. {
  7400. var result = '';
  7401. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  7402. {
  7403. var amp = '?';
  7404. for (var key in urlParams)
  7405. {
  7406. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  7407. {
  7408. result += amp + key + '=' + urlParams[key];
  7409. amp = '&';
  7410. }
  7411. }
  7412. }
  7413. else
  7414. {
  7415. result = window.location.search;
  7416. }
  7417. return result;
  7418. };
  7419. /**
  7420. * Returns the URL for a copy of this editor with no state.
  7421. */
  7422. EditorUi.prototype.getUrl = function(pathname)
  7423. {
  7424. var href = (pathname != null) ? pathname : window.location.pathname;
  7425. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  7426. if (urlParams['offline'] == '1')
  7427. {
  7428. href += window.location.search;
  7429. }
  7430. else
  7431. {
  7432. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  7433. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  7434. // Removes template URL parameter for new blank diagram
  7435. for (var key in urlParams)
  7436. {
  7437. if (mxUtils.indexOf(ignored, key) < 0)
  7438. {
  7439. if (parms == 0)
  7440. {
  7441. href += '?';
  7442. }
  7443. else
  7444. {
  7445. href += '&';
  7446. }
  7447. if (urlParams[key] != null)
  7448. {
  7449. href += key + '=' + urlParams[key];
  7450. parms++;
  7451. }
  7452. }
  7453. }
  7454. }
  7455. return href;
  7456. };
  7457. /**
  7458. * Overrides link dialog.
  7459. */
  7460. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  7461. {
  7462. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  7463. this.showDialog(dlg.container, 420, 120, true, true);
  7464. dlg.init();
  7465. };
  7466. /**
  7467. * Overrides createOutline
  7468. */
  7469. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  7470. EditorUi.prototype.createOutline = function(wnd)
  7471. {
  7472. var outline = editorUiCreateOutline.apply(this, arguments);
  7473. var graph = this.editor.graph;
  7474. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  7475. outline.getSourceGraphBounds = function()
  7476. {
  7477. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  7478. {
  7479. var pb = this.source.getPagePadding();
  7480. var s = this.source.view.scale;
  7481. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  7482. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  7483. return result;
  7484. }
  7485. return outlineGetSourceGraphBounds.apply(this, arguments);
  7486. };
  7487. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  7488. outline.getSourceContainerSize = function()
  7489. {
  7490. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  7491. {
  7492. var pad = this.source.getPagePadding();
  7493. var s = this.source.view.scale;
  7494. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  7495. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  7496. }
  7497. return outlineGetSourceContainerSize.apply(this, arguments);
  7498. };
  7499. outline.getOutlineOffset = function(scale)
  7500. {
  7501. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  7502. {
  7503. var pb = this.source.getPagePadding();
  7504. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  7505. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  7506. // Why is vertical offset negative relative to dy
  7507. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  7508. }
  7509. return new mxPoint(8 / scale, 8 / scale);
  7510. };
  7511. var outlineInit = outline.init;
  7512. outline.init = function()
  7513. {
  7514. outlineInit.apply(this, arguments);
  7515. // Problem: Need to override a function in the view but the view is created
  7516. // with the graph so a refresh of the page is needed to see this change.
  7517. outline.outline.view.getBackgroundPageBounds = function()
  7518. {
  7519. var layout = graph.getPageLayout();
  7520. var page = graph.getPageSize();
  7521. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  7522. this.scale * (this.translate.y + layout.y * page.height),
  7523. this.scale * layout.width * page.width,
  7524. this.scale * layout.height * page.height);
  7525. };
  7526. outline.outline.view.validateBackgroundPage();
  7527. };
  7528. this.editor.addListener('pageSelected', function(sender, evt)
  7529. {
  7530. var change = evt.getProperty('change');
  7531. var graph = outline.source;
  7532. var g = outline.outline;
  7533. g.pageScale = graph.pageScale;
  7534. g.pageFormat = graph.pageFormat;
  7535. g.background = graph.background;
  7536. g.pageVisible = graph.pageVisible;
  7537. g.background = graph.background;
  7538. var current = mxUtils.getCurrentStyle(graph.container);
  7539. g.container.style.backgroundColor = current.backgroundColor;
  7540. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  7541. {
  7542. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  7543. }
  7544. outline.outline.view.clear(change.previousPage.root, true);
  7545. outline.outline.view.validate();
  7546. });
  7547. return outline;
  7548. };
  7549. /**
  7550. * Returns the number of storage options enabled
  7551. */
  7552. EditorUi.prototype.getServiceCount = function(allowBrowser)
  7553. {
  7554. var serviceCount = 0;
  7555. if (this.drive != null || typeof window.DriveClient === 'function')
  7556. {
  7557. serviceCount++
  7558. }
  7559. if (this.dropbox != null || typeof window.DropboxClient === 'function')
  7560. {
  7561. serviceCount++
  7562. }
  7563. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  7564. {
  7565. serviceCount++
  7566. }
  7567. if (this.gitHub != null)
  7568. {
  7569. serviceCount++
  7570. }
  7571. if (allowBrowser && isLocalStorage && (urlParams['browser'] == '1' || mxClient.IS_IOS))
  7572. {
  7573. serviceCount++
  7574. }
  7575. if (!mxClient.IS_IOS)
  7576. {
  7577. serviceCount++
  7578. }
  7579. return serviceCount;
  7580. }
  7581. /**
  7582. * Updates action and menu states depending on the file.
  7583. */
  7584. EditorUi.prototype.updateUi = function()
  7585. {
  7586. this.updateButtonContainer();
  7587. this.updateActionStates();
  7588. // Action states that only need update for new files
  7589. var file = this.getCurrentFile();
  7590. var active = file != null || (urlParams['embed'] == '1' &&
  7591. this.editor.graph.isEnabled());
  7592. this.menus.get('viewPanels').setEnabled(active);
  7593. this.menus.get('viewZoom').setEnabled(active);
  7594. var restricted = (urlParams['embed'] != '1' ||
  7595. !this.editor.graph.isEnabled()) &&
  7596. (file == null || file.isRestricted());
  7597. this.actions.get('makeCopy').setEnabled(!restricted);
  7598. this.actions.get('print').setEnabled(!restricted);
  7599. this.menus.get('exportAs').setEnabled(!restricted);
  7600. this.menus.get('embed').setEnabled(!restricted);
  7601. // Disables libraries and extras menu in embed mode
  7602. // while waiting for file data
  7603. var libsEnabled = urlParams['embed'] != '1' ||
  7604. this.editor.graph.isEnabled();
  7605. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  7606. this.menus.get('newLibrary').setEnabled(libsEnabled);
  7607. this.menus.get('extras').setEnabled(libsEnabled);
  7608. // Disables actions in the toolbar
  7609. var editable = (urlParams['embed'] == '1' &&
  7610. this.editor.graph.isEnabled()) ||
  7611. (file != null && file.isEditable());
  7612. this.actions.get('image').setEnabled(active);
  7613. this.actions.get('zoomIn').setEnabled(active);
  7614. this.actions.get('zoomOut').setEnabled(active);
  7615. this.actions.get('resetView').setEnabled(active);
  7616. // Disables menus
  7617. this.menus.get('edit').setEnabled(active);
  7618. this.menus.get('view').setEnabled(active);
  7619. this.menus.get('importFrom').setEnabled(editable);
  7620. this.menus.get('arrange').setEnabled(editable);
  7621. // Disables connection drop downs in toolbar
  7622. if (this.toolbar != null)
  7623. {
  7624. if (this.toolbar.edgeShapeMenu != null)
  7625. {
  7626. this.toolbar.edgeShapeMenu.setEnabled(editable);
  7627. }
  7628. if (this.toolbar.edgeStyleMenu != null)
  7629. {
  7630. this.toolbar.edgeStyleMenu.setEnabled(editable);
  7631. }
  7632. }
  7633. if (this.isOfflineApp())
  7634. {
  7635. var appCache = applicationCache;
  7636. // NOTE: HTML5 Cache is deprecated
  7637. if (appCache != null && this.offlineStatus == null)
  7638. {
  7639. this.offlineStatus = document.createElement('div');
  7640. this.offlineStatus.className = 'geItem';
  7641. this.offlineStatus.style.position = 'absolute';
  7642. this.offlineStatus.style.fontSize = '8pt';
  7643. this.offlineStatus.style.top = '2px';
  7644. this.offlineStatus.style.right = '12px';
  7645. this.offlineStatus.style.color = '#666';
  7646. this.offlineStatus.style.margin = '4px';
  7647. this.offlineStatus.style.padding = '2px';
  7648. this.offlineStatus.style.verticalAlign = 'middle';
  7649. this.offlineStatus.innerHTML = '';
  7650. this.menubarContainer.appendChild(this.offlineStatus);
  7651. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  7652. {
  7653. var img = this.offlineStatus.getElementsByTagName('img');
  7654. if (img != null && img.length > 0)
  7655. {
  7656. this.alert(img[0].getAttribute('title'));
  7657. }
  7658. }));
  7659. var appCache = window.applicationCache;
  7660. var lastStatus = null;
  7661. var updateStatus = mxUtils.bind(this, function()
  7662. {
  7663. var newStatus = appCache.status;
  7664. var html = '';
  7665. if (newStatus == appCache.CHECKING)
  7666. {
  7667. newStatus = appCache.DOWNLOADING;
  7668. }
  7669. switch (newStatus)
  7670. {
  7671. case appCache.UNCACHED: // UNCACHED == 0
  7672. html = '';
  7673. break;
  7674. case appCache.IDLE: // IDLE == 1
  7675. html = '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  7676. break;
  7677. case appCache.DOWNLOADING: // DOWNLOADING == 3
  7678. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  7679. break;
  7680. case appCache.UPDATEREADY: // UPDATEREADY == 4
  7681. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  7682. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  7683. break;
  7684. case appCache.OBSOLETE: // OBSOLETE == 5
  7685. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  7686. break;
  7687. default:
  7688. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  7689. break;
  7690. }
  7691. if (newStatus != lastStatus)
  7692. {
  7693. this.offlineStatus.innerHTML = html;
  7694. lastStatus = newStatus;
  7695. }
  7696. });
  7697. mxEvent.addListener(appCache, 'checking', updateStatus);
  7698. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  7699. mxEvent.addListener(appCache, 'downloading', updateStatus);
  7700. mxEvent.addListener(appCache, 'progress', updateStatus);
  7701. mxEvent.addListener(appCache, 'cached', updateStatus);
  7702. mxEvent.addListener(appCache, 'updateready', updateStatus);
  7703. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  7704. mxEvent.addListener(appCache, 'error', updateStatus);
  7705. updateStatus();
  7706. }
  7707. }
  7708. else
  7709. {
  7710. this.updateUserElement();
  7711. }
  7712. };
  7713. /**
  7714. * Hook for subclassers
  7715. */
  7716. EditorUi.prototype.updateButtonContainer = function()
  7717. {
  7718. // do nothing
  7719. };
  7720. /**
  7721. * Hook for subclassers
  7722. */
  7723. EditorUi.prototype.updateUserElement = function()
  7724. {
  7725. // do nothing
  7726. };
  7727. /**
  7728. * Updates action states depending on the selection.
  7729. */
  7730. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  7731. EditorUi.prototype.updateActionStates = function()
  7732. {
  7733. editorUiUpdateActionStates.apply(this, arguments);
  7734. var graph = this.editor.graph;
  7735. var file = this.getCurrentFile();
  7736. var active = (file != null && file.isEditable()) ||
  7737. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  7738. this.actions.get('pageSetup').setEnabled(active);
  7739. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  7740. this.actions.get('guides').setEnabled(active);
  7741. this.actions.get('shadowVisible').setEnabled(active);
  7742. this.actions.get('connectionArrows').setEnabled(active);
  7743. this.actions.get('connectionPoints').setEnabled(active);
  7744. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  7745. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  7746. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  7747. this.actions.get('createShape').setEnabled(active);
  7748. this.actions.get('createRevision').setEnabled(active);
  7749. this.actions.get('moveToFolder').setEnabled(file != null);
  7750. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  7751. this.actions.get('editDiagram').setEnabled((urlParams['embed'] == '1' &&
  7752. this.editor.graph.isEnabled()) || (file != null && !file.isRestricted()));
  7753. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  7754. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  7755. var state = graph.view.getState(graph.getSelectionCell());
  7756. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  7757. };
  7758. /**
  7759. * Overrides export dialog for using ui functions for save and setting global switches.
  7760. */
  7761. if (window.ExportDialog != null)
  7762. {
  7763. ExportDialog.showXmlOption = false;
  7764. ExportDialog.showGifOption = false;
  7765. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  7766. {
  7767. var graph = editorUi.editor.graph;
  7768. if (format == 'xml')
  7769. {
  7770. editorUi.hideDialog();
  7771. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  7772. }
  7773. else if (format == 'svg')
  7774. {
  7775. editorUi.hideDialog();
  7776. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  7777. }
  7778. else
  7779. {
  7780. var data = editorUi.getFileData(true, null, null, null, null, true);
  7781. var bounds = graph.getGraphBounds();
  7782. var w = Math.floor(bounds.width * s / graph.view.scale);
  7783. var h = Math.floor(bounds.height * s / graph.view.scale);
  7784. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  7785. {
  7786. editorUi.hideDialog();
  7787. editorUi.saveRequest(name, format,
  7788. function(newTitle, base64)
  7789. {
  7790. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  7791. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  7792. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  7793. '&border=' + b + '&xml=' + encodeURIComponent(data));
  7794. });
  7795. }
  7796. else
  7797. {
  7798. mxUtils.alert(mxResources.get('drawingTooLarge'));
  7799. }
  7800. }
  7801. };
  7802. }
  7803. })();