EditorUi.js 237 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835
  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 = (uiTheme == 'atlas') ? 36 : 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. // Workaround for failing local saves in MS Edge Creators Update
  2181. return !mxClient.IS_EDGE && ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  2182. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  2183. document.documentMode != 9 && document.documentMode != 8 &&
  2184. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  2185. this.isOfflineApp() || mxClient.IS_IOS);
  2186. };
  2187. /**
  2188. * Translates this point by the given vector.
  2189. *
  2190. * @param {number} dx X-coordinate of the translation.
  2191. * @param {number} dy Y-coordinate of the translation.
  2192. */
  2193. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  2194. {
  2195. // Newer versions of IE (except Edge which uses the standard API below)
  2196. if (!mxClient.IS_EDGE && window.MSBlobBuilder && navigator.msSaveOrOpenBlob)
  2197. {
  2198. var builder = new MSBlobBuilder();
  2199. builder.append(data);
  2200. var blob = builder.getBlob(mimeType);
  2201. navigator.msSaveOrOpenBlob(blob, filename);
  2202. }
  2203. // Older versions of IE (binary not supported)
  2204. else if (mxClient.IS_IE)
  2205. {
  2206. var win = window.open('about:blank', '_blank');
  2207. if (win == null)
  2208. {
  2209. mxUtils.popup(data, true);
  2210. }
  2211. else
  2212. {
  2213. win.document.write(data);
  2214. win.document.close();
  2215. win.document.execCommand('SaveAs', true, filename);
  2216. win.close();
  2217. }
  2218. }
  2219. else if (mxClient.IS_IOS)
  2220. {
  2221. // Poor man's saveAs in iOS via context menu of selected output
  2222. var dlg = new TextareaDialog(this, filename + ':', data, null, null, mxResources.get('close'));
  2223. dlg.textarea.style.width = '600px';
  2224. dlg.textarea.style.height = '380px';
  2225. this.showDialog(dlg.container, 620, 460, true, true);
  2226. dlg.init();
  2227. document.execCommand('selectall', false, null);
  2228. }
  2229. else
  2230. {
  2231. var a = document.createElement('a');
  2232. // Workaround for mxXmlRequest.simulate no longer working in Safari
  2233. // if this is used (ie PNG export broken after XML export in Safari).
  2234. var useDownload = !mxClient.IS_SF && typeof a.download !== 'undefined';
  2235. if (useDownload || this.isOffline())
  2236. {
  2237. a.href = URL.createObjectURL((base64Encoded) ?
  2238. this.base64ToBlob(data, mimeType) :
  2239. new Blob([data], {type: mimeType}));
  2240. if (useDownload)
  2241. {
  2242. a.download = filename;
  2243. }
  2244. else
  2245. {
  2246. // Workaround for same window in Safari
  2247. a.setAttribute('target', '_blank');
  2248. }
  2249. document.body.appendChild(a);
  2250. try
  2251. {
  2252. window.setTimeout(function()
  2253. {
  2254. URL.revokeObjectURL(a.href);
  2255. }, 0);
  2256. a.click();
  2257. a.parentNode.removeChild(a);
  2258. }
  2259. catch (e)
  2260. {
  2261. // ignore
  2262. }
  2263. }
  2264. else
  2265. {
  2266. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  2267. req.simulate(document, '_blank');
  2268. }
  2269. }
  2270. };
  2271. /**
  2272. * Translates this point by the given vector.
  2273. *
  2274. * @param {number} dx X-coordinate of the translation.
  2275. * @param {number} dy Y-coordinate of the translation.
  2276. */
  2277. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  2278. {
  2279. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  2280. 'data=' + encodeURIComponent(this.editor.graph.compress(data));
  2281. return new mxXmlRequest(SAVE_URL, param +
  2282. ((mimeType != null) ? '&mime=' + mimeType : '') +
  2283. ((format != null) ? '&format=' + format : '') +
  2284. ((base64Response != null) ? '&base64=' + base64Response : '') +
  2285. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  2286. ((base64Encoded) ? '&binary=1' : ''));
  2287. };
  2288. /**
  2289. * Translates this point by the given vector.
  2290. *
  2291. * @param {number} dx X-coordinate of the translation.
  2292. * @param {number} dy Y-coordinate of the translation.
  2293. */
  2294. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  2295. {
  2296. contentType = contentType || '';
  2297. var sliceSize = 1024;
  2298. var byteCharacters = atob(base64Data);
  2299. var bytesLength = byteCharacters.length;
  2300. var slicesCount = Math.ceil(bytesLength / sliceSize);
  2301. var byteArrays = new Array(slicesCount);
  2302. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  2303. {
  2304. var begin = sliceIndex * sliceSize;
  2305. var end = Math.min(begin + sliceSize, bytesLength);
  2306. var bytes = new Array(end - begin);
  2307. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  2308. {
  2309. bytes[i] = byteCharacters[offset].charCodeAt(0);
  2310. }
  2311. byteArrays[sliceIndex] = new Uint8Array(bytes);
  2312. }
  2313. return new Blob(byteArrays, {type: contentType});
  2314. };
  2315. /**
  2316. * Translates this point by the given vector.
  2317. *
  2318. * @param {number} dx X-coordinate of the translation.
  2319. * @param {number} dy Y-coordinate of the translation.
  2320. */
  2321. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser)
  2322. {
  2323. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  2324. var allowTab = (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  2325. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2326. {
  2327. try
  2328. {
  2329. // Opens a new window
  2330. if (mode == '_blank')
  2331. {
  2332. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  2333. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  2334. {
  2335. if (mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  2336. {
  2337. var win = window.open('about:blank');
  2338. if (win == null)
  2339. {
  2340. mxUtils.popup(data, true);
  2341. }
  2342. else
  2343. {
  2344. win.document.write('<html><img src="data:' +
  2345. mimeType + ((base64Encoded) ? ';base64,' +
  2346. data : ';charset=utf8,' + encodeURIComponent(data)) +
  2347. '"/></html>');
  2348. win.document.close();
  2349. }
  2350. }
  2351. else
  2352. {
  2353. // win.open is workaround for cleared contents in Chrome after delay
  2354. // when using location.replace
  2355. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  2356. data : ';charset=utf8,' + encodeURIComponent(data)));
  2357. if (win == null)
  2358. {
  2359. mxUtils.popup(data, true);
  2360. }
  2361. }
  2362. }
  2363. else
  2364. {
  2365. var win = window.open('about:blank');
  2366. if (win == null)
  2367. {
  2368. mxUtils.popup(data, true);
  2369. }
  2370. else
  2371. {
  2372. win.document.write(mxUtils.htmlEntities(data, false));
  2373. win.document.close();
  2374. }
  2375. }
  2376. }
  2377. else if (mode == App.MODE_DEVICE)
  2378. {
  2379. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  2380. }
  2381. else if (newTitle != null && newTitle.length > 0)
  2382. {
  2383. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2384. {
  2385. try
  2386. {
  2387. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  2388. }
  2389. catch (e)
  2390. {
  2391. this.handleError(e);
  2392. }
  2393. }));
  2394. }
  2395. }
  2396. catch (e)
  2397. {
  2398. this.handleError(e);
  2399. }
  2400. }), mxUtils.bind(this, function()
  2401. {
  2402. this.hideDialog();
  2403. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab, null, null, (allowBrowser) ? 3 : 4);
  2404. this.showDialog(dlg.container, 380, (this.getServiceCount(allowBrowser) - 1 <
  2405. ((allowBrowser) ? 4 : 5)) ? 270 : 390, true, true);
  2406. dlg.init();
  2407. };
  2408. /**
  2409. * Translates this point by the given vector.
  2410. *
  2411. * @param {number} dx X-coordinate of the translation.
  2412. * @param {number} dy Y-coordinate of the translation.
  2413. */
  2414. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  2415. {
  2416. if (this.isLocalFileSave())
  2417. {
  2418. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  2419. }
  2420. else
  2421. {
  2422. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  2423. {
  2424. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  2425. }));
  2426. }
  2427. };
  2428. /**
  2429. * Translates this point by the given vector.
  2430. *
  2431. * @param {number} dx X-coordinate of the translation.
  2432. * @param {number} dy Y-coordinate of the translation.
  2433. */
  2434. EditorUi.prototype.saveRequest = function(filename, format, fn)
  2435. {
  2436. var allowTab = !mxClient.IS_IOS || !navigator.standalone;
  2437. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  2438. {
  2439. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  2440. {
  2441. var base64 = (mode == App.MODE_DEVICE || mode == null || mode == '_blank') ? '0' : '1';
  2442. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  2443. if (xhr != null)
  2444. {
  2445. if (mode == App.MODE_DEVICE || mode == '_blank')
  2446. {
  2447. xhr.simulate(document, '_blank');
  2448. }
  2449. else
  2450. {
  2451. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  2452. {
  2453. if (this.spinner.spin(document.body, mxResources.get('saving')))
  2454. {
  2455. // LATER: Catch possible mixed content error
  2456. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  2457. xhr.send(mxUtils.bind(this, function()
  2458. {
  2459. this.spinner.stop();
  2460. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  2461. {
  2462. try
  2463. {
  2464. var mimeType = (format == 'pdf') ? 'application/pdf' : 'image/' + format;
  2465. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  2466. }
  2467. catch (e)
  2468. {
  2469. this.handleError(e);
  2470. }
  2471. }
  2472. else
  2473. {
  2474. this.handleError({message: mxResources.get('errorSavingFile')});
  2475. }
  2476. }), function(resp)
  2477. {
  2478. this.spinner.stop();
  2479. this.handleError(resp);
  2480. });
  2481. }
  2482. }));
  2483. }
  2484. }
  2485. }
  2486. }), mxUtils.bind(this, function()
  2487. {
  2488. this.hideDialog();
  2489. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab, null, null, 4);
  2490. this.showDialog(dlg.container, 380, (this.getServiceCount(false) - 1 < 5) ? 270 : 390, true, true);
  2491. dlg.init();
  2492. };
  2493. /**
  2494. * Hook for subclassers.
  2495. */
  2496. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  2497. {
  2498. // do nothing
  2499. };
  2500. /**
  2501. * Hook for subclassers.
  2502. */
  2503. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  2504. {
  2505. fn(null);
  2506. };
  2507. /**
  2508. *
  2509. */
  2510. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow, editable, embedImages, border, noCrop, currentPage)
  2511. {
  2512. if (this.spinner.spin(document.body, mxResources.get('export')))
  2513. {
  2514. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  2515. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  2516. var bg = (transparentBackground) ? null : this.editor.graph.background;
  2517. if (bg == mxConstants.NONE)
  2518. {
  2519. bg = null;
  2520. }
  2521. // Handles special case where background is null but transparent is false
  2522. if (bg == null && transparentBackground == false)
  2523. {
  2524. bg = '#ffffff';
  2525. }
  2526. // Sets or disables alternate text for foreignObjects. Disabling is needed
  2527. // because PhantomJS seems to ignore switch statements and paint all text.
  2528. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null, ignoreSelection);
  2529. if (addShadow)
  2530. {
  2531. this.editor.graph.addSvgShadow(svgRoot);
  2532. }
  2533. var filename = this.getBaseFilename() + '.svg';
  2534. var doSave = mxUtils.bind(this, function(svgRoot)
  2535. {
  2536. this.spinner.stop();
  2537. if (editable)
  2538. {
  2539. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  2540. }
  2541. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  2542. mxUtils.getXml(svgRoot);
  2543. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  2544. {
  2545. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  2546. }
  2547. else
  2548. {
  2549. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  2550. {
  2551. mxUtils.popup(svg);
  2552. }));
  2553. }
  2554. });
  2555. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  2556. {
  2557. if (embedImages)
  2558. {
  2559. // Caches images
  2560. if (this.thumbImageCache == null)
  2561. {
  2562. this.thumbImageCache = new Object();
  2563. }
  2564. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  2565. }
  2566. else
  2567. {
  2568. doSave(svgRoot);
  2569. }
  2570. }));
  2571. }
  2572. };
  2573. /**
  2574. *
  2575. */
  2576. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline)
  2577. {
  2578. var cb = document.createElement('input');
  2579. cb.style.marginRight = '8px';
  2580. cb.style.marginTop = '16px';
  2581. cb.setAttribute('type', 'checkbox');
  2582. if (checked)
  2583. {
  2584. cb.setAttribute('checked', 'checked');
  2585. cb.defaultChecked = true;
  2586. }
  2587. if (disabled)
  2588. {
  2589. cb.setAttribute('disabled', 'disabled');
  2590. }
  2591. div.appendChild(cb);
  2592. mxUtils.write(div, label);
  2593. if (!disableNewline)
  2594. {
  2595. mxUtils.br(div);
  2596. }
  2597. return cb;
  2598. };
  2599. /**
  2600. *
  2601. */
  2602. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  2603. {
  2604. mxUtils.write(div, mxResources.get('links') + ':');
  2605. var linkSelect = document.createElement('select');
  2606. linkSelect.style.width = '100px';
  2607. linkSelect.style.marginLeft = '4px';
  2608. linkSelect.style.marginRight = '10px';
  2609. linkSelect.className = 'geBtn';
  2610. var autoOption = document.createElement('option');
  2611. autoOption.setAttribute('value', 'auto');
  2612. mxUtils.write(autoOption, mxResources.get('automatic'));
  2613. linkSelect.appendChild(autoOption);
  2614. var blankOption = document.createElement('option');
  2615. blankOption.setAttribute('value', 'blank');
  2616. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  2617. linkSelect.appendChild(blankOption);
  2618. var selfOption = document.createElement('option');
  2619. selfOption.setAttribute('value', 'self');
  2620. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  2621. linkSelect.appendChild(selfOption);
  2622. if (showFrameOption)
  2623. {
  2624. var frameOption = document.createElement('option');
  2625. frameOption.setAttribute('value', 'frame');
  2626. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  2627. ' (' + mxResources.get('iframe') + ')');
  2628. linkSelect.appendChild(frameOption);
  2629. }
  2630. div.appendChild(linkSelect);
  2631. mxUtils.write(div, mxResources.get('borderColor') + ':');
  2632. var linkColor = '#0000ff';
  2633. var linkButton = null;
  2634. function updateLinkColor()
  2635. {
  2636. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  2637. ((linkColor != null && linkColor != mxConstants.NONE) ?
  2638. 'border:1px solid black;background-color:' + linkColor :
  2639. 'background-position:center center;background-repeat:no-repeat;' +
  2640. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  2641. };
  2642. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  2643. {
  2644. this.pickColor(linkColor || 'none', function(color)
  2645. {
  2646. linkColor = color;
  2647. updateLinkColor();
  2648. });
  2649. mxEvent.consume(evt);
  2650. }));
  2651. updateLinkColor();
  2652. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  2653. linkButton.style.marginLeft = '4px';
  2654. linkButton.style.height = '22px';
  2655. linkButton.style.width = '22px';
  2656. linkButton.style.position = 'relative';
  2657. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  2658. linkButton.className = 'geColorBtn';
  2659. div.appendChild(linkButton);
  2660. mxUtils.br(div);
  2661. return {
  2662. getColor: function()
  2663. {
  2664. return linkColor;
  2665. },
  2666. getTarget: function()
  2667. {
  2668. return linkSelect.value;
  2669. },
  2670. focus: function()
  2671. {
  2672. linkSelect.focus();
  2673. }
  2674. };
  2675. }
  2676. /**
  2677. *
  2678. */
  2679. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, edit, layers, url, ignoreFile)
  2680. {
  2681. var file = this.getCurrentFile();
  2682. var params = [];
  2683. if (lightbox)
  2684. {
  2685. params.push('lightbox=1');
  2686. if (linkTarget != 'auto')
  2687. {
  2688. params.push('target=' + linkTarget);
  2689. }
  2690. if (linkColor != null && linkColor != mxConstants.NONE)
  2691. {
  2692. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  2693. }
  2694. if (edit)
  2695. {
  2696. params.push('edit=_blank');
  2697. }
  2698. if (layers)
  2699. {
  2700. params.push('layers=1');
  2701. }
  2702. if (this.editor.graph.foldingEnabled)
  2703. {
  2704. params.push('nav=1');
  2705. }
  2706. }
  2707. if (allPages && this.pages != null && this.currentPage != null)
  2708. {
  2709. for (var i = 0; i < this.pages.length; i++)
  2710. {
  2711. if (this.pages[i] == this.currentPage)
  2712. {
  2713. if (i > 0)
  2714. {
  2715. params.push('page=' + i);
  2716. }
  2717. break;
  2718. }
  2719. }
  2720. }
  2721. var data = '';
  2722. var addTitle = true;
  2723. if (url != null)
  2724. {
  2725. data = '#U' + encodeURIComponent(url);
  2726. }
  2727. else
  2728. {
  2729. var file = this.getCurrentFile();
  2730. // Fallback to non-public URL for Drive files
  2731. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  2732. {
  2733. data = '#' + file.getHash();
  2734. addTitle = false;
  2735. }
  2736. else
  2737. {
  2738. data = '#R' + encodeURIComponent((allPages) ?
  2739. this.getFileData(true, null, null, null, null, null, null, true) :
  2740. this.editor.graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  2741. }
  2742. }
  2743. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  2744. {
  2745. params.push('title=' + encodeURIComponent(file.getTitle()));
  2746. }
  2747. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) ? 'https://www.draw.io/' : 'https://' + location.host + '/') +
  2748. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  2749. };
  2750. /**
  2751. *
  2752. */
  2753. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  2754. linkColor, fit, allPages, layers, lightbox, edit, fn)
  2755. {
  2756. var s = this.getBasenames();
  2757. var data = {};
  2758. if (linkColor != '' && linkColor != mxConstants.NONE)
  2759. {
  2760. data.highlight = linkColor;
  2761. }
  2762. if (linkTarget !== 'auto')
  2763. {
  2764. data.target = linkTarget;
  2765. }
  2766. if (!lightbox)
  2767. {
  2768. data.lightbox = false;
  2769. }
  2770. data.nav = this.editor.graph.foldingEnabled;
  2771. var zoom = parseInt(initialZoom);
  2772. if (!isNaN(zoom) && zoom != 100)
  2773. {
  2774. data.zoom = zoom / 100;
  2775. }
  2776. var tb = [];
  2777. if (allPages)
  2778. {
  2779. tb.push('pages');
  2780. data.resize = true;
  2781. if (this.pages != null && this.currentPage != null)
  2782. {
  2783. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  2784. }
  2785. }
  2786. if (zoomEnabled)
  2787. {
  2788. tb.push('zoom');
  2789. data.resize = true;
  2790. }
  2791. if (layers)
  2792. {
  2793. tb.push('layers');
  2794. }
  2795. if (tb.length > 0)
  2796. {
  2797. if (lightbox)
  2798. {
  2799. tb.push('lightbox');
  2800. }
  2801. data.toolbar = tb.join(' ');
  2802. }
  2803. if (edit)
  2804. {
  2805. if (publicUrl != null)
  2806. {
  2807. data.edit = publicUrl;
  2808. }
  2809. else
  2810. {
  2811. data.edit = '_blank';
  2812. }
  2813. }
  2814. if (publicUrl != null)
  2815. {
  2816. data.url = publicUrl;
  2817. }
  2818. else
  2819. {
  2820. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  2821. }
  2822. var value = '<div class="mxgraph" style="' +
  2823. ((fit) ? 'max-width:100%;' : '') +
  2824. ((tb != '') ? 'border:1px solid transparent;' : '') +
  2825. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  2826. var sParam = (s.length > 0) ? 's=' + s.join(';') : '';
  2827. var fetchParam = (publicUrl != null) ? 'fetch=' + encodeURIComponent(publicUrl) : '';
  2828. var s2 = (sParam.length > 0 || fetchParam.length > 0) ?
  2829. (((urlParams['dev'] == '1') ?
  2830. 'https://test.draw.io/embed2.js?dev=1&' + sParam :
  2831. 'https://www.draw.io/embed2.js?' + sParam)) + '&' + fetchParam :
  2832. (((urlParams['dev'] == '1') ?
  2833. 'https://test.draw.io/js/viewer.min.js' :
  2834. 'https://www.draw.io/js/viewer.min.js'));
  2835. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  2836. fn(value, scr);
  2837. };
  2838. /**
  2839. *
  2840. */
  2841. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  2842. {
  2843. var div = document.createElement('div');
  2844. div.style.whiteSpace = 'nowrap';
  2845. var graph = this.editor.graph;
  2846. var hd = document.createElement('h3');
  2847. mxUtils.write(hd, mxResources.get('html'));
  2848. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  2849. div.appendChild(hd);
  2850. var radioSection = document.createElement('div');
  2851. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  2852. var publicUrlRadio = document.createElement('input');
  2853. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  2854. publicUrlRadio.setAttribute('value', 'url');
  2855. publicUrlRadio.setAttribute('type', 'radio');
  2856. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  2857. var copyRadio = publicUrlRadio.cloneNode(true);
  2858. copyRadio.setAttribute('value', 'copy');
  2859. radioSection.appendChild(copyRadio);
  2860. var span = document.createElement('span');
  2861. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  2862. radioSection.appendChild(span);
  2863. mxUtils.br(radioSection);
  2864. radioSection.appendChild(publicUrlRadio);
  2865. var span = document.createElement('span');
  2866. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  2867. radioSection.appendChild(span);
  2868. var file = this.getCurrentFile();
  2869. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  2870. {
  2871. var testLink = document.createElement('a');
  2872. testLink.style.paddingLeft = '12px';
  2873. testLink.style.color = 'gray';
  2874. testLink.setAttribute('href', 'javascript:void(0);');
  2875. mxUtils.write(testLink, mxResources.get('share'));
  2876. radioSection.appendChild(testLink);
  2877. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  2878. {
  2879. this.hideDialog();
  2880. this.drive.showPermissions(file.getId());
  2881. }));
  2882. }
  2883. copyRadio.setAttribute('checked', 'checked');
  2884. if (publicUrl == null)
  2885. {
  2886. publicUrlRadio.setAttribute('disabled', 'disabled');
  2887. }
  2888. div.appendChild(radioSection);
  2889. var linkSection = this.addLinkSection(div);
  2890. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  2891. mxUtils.write(div, ':');
  2892. var zoomInput = document.createElement('input');
  2893. zoomInput.setAttribute('type', 'text');
  2894. zoomInput.style.marginRight = '16px';
  2895. zoomInput.style.width = '60px';
  2896. zoomInput.style.marginLeft = '4px';
  2897. zoomInput.style.marginRight = '12px';
  2898. zoomInput.value = '100%';
  2899. div.appendChild(zoomInput);
  2900. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  2901. var hasPages = this.pages != null && this.pages.length > 1;
  2902. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  2903. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  2904. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  2905. var edit = this.addCheckbox(div, mxResources.get('showEditButton'), true);
  2906. edit.style.marginLeft = '24px';
  2907. edit.style.marginBottom = '16px';
  2908. mxEvent.addListener(lightbox, 'change', function()
  2909. {
  2910. if (lightbox.checked)
  2911. {
  2912. edit.removeAttribute('disabled');
  2913. }
  2914. else
  2915. {
  2916. edit.setAttribute('disabled', 'disabled');
  2917. }
  2918. });
  2919. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  2920. {
  2921. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  2922. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked, edit.checked);
  2923. }), null, btnLabel, helpLink);
  2924. this.showDialog(dlg.container, 340, 360, true, true);
  2925. copyRadio.focus();
  2926. };
  2927. /**
  2928. *
  2929. */
  2930. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  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, title || mxResources.get('link'));
  2937. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  2938. div.appendChild(hd);
  2939. var file = this.getCurrentFile();
  2940. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  2941. var dy = 0;
  2942. if (file != null && file.constructor == window.DriveFile && !hideShare)
  2943. {
  2944. dy = 80;
  2945. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  2946. var hintSection = document.createElement('div');
  2947. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  2948. var text = document.createElement('div');
  2949. text.style.whiteSpace = 'normal';
  2950. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  2951. hintSection.appendChild(text);
  2952. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  2953. {
  2954. this.drive.showPermissions(file.getId());
  2955. }));
  2956. shareBtn.style.marginTop = '12px';
  2957. shareBtn.className = 'geBtn';
  2958. hintSection.appendChild(shareBtn);
  2959. div.appendChild(hintSection);
  2960. var testLink = document.createElement('a');
  2961. testLink.style.paddingLeft = '12px';
  2962. testLink.style.color = 'gray';
  2963. testLink.style.fontSize = '11px';
  2964. testLink.setAttribute('href', 'javascript:void(0);');
  2965. mxUtils.write(testLink, mxResources.get('check'));
  2966. hintSection.appendChild(testLink);
  2967. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  2968. {
  2969. if (this.spinner.spin(document.body, mxResources.get('loading')))
  2970. {
  2971. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  2972. {
  2973. this.spinner.stop();
  2974. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  2975. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  2976. this.showDialog(dlg.container, 300, 80, true, false);
  2977. dlg.init();
  2978. }));
  2979. }
  2980. }));
  2981. }
  2982. var widthInput = null;
  2983. var heightInput = null;
  2984. if (width != null || height != null)
  2985. {
  2986. dy += 30;
  2987. mxUtils.write(div, mxResources.get('width') + ':');
  2988. widthInput = document.createElement('input');
  2989. widthInput.setAttribute('type', 'text');
  2990. widthInput.style.marginRight = '16px';
  2991. widthInput.style.width = '50px';
  2992. widthInput.style.marginLeft = '6px';
  2993. widthInput.style.marginRight = '16px';
  2994. widthInput.style.marginBottom = '10px';
  2995. widthInput.value = '100%';
  2996. div.appendChild(widthInput);
  2997. mxUtils.write(div, mxResources.get('height') + ':');
  2998. heightInput = document.createElement('input');
  2999. heightInput.setAttribute('type', 'text');
  3000. heightInput.style.width = '50px';
  3001. heightInput.style.marginLeft = '6px';
  3002. heightInput.style.marginBottom = '10px';
  3003. heightInput.value = height + 'px';
  3004. div.appendChild(heightInput);
  3005. mxUtils.br(div);
  3006. }
  3007. var linkSection = this.addLinkSection(div, showFrameOption);
  3008. var hasPages = this.pages != null && this.pages.length > 1;
  3009. var allPages = null;
  3010. if (file == null || file.constructor != window.DriveFile || hideShare)
  3011. {
  3012. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  3013. }
  3014. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3015. var edit = this.addCheckbox(div, mxResources.get('showEditButton'), true);
  3016. edit.style.marginLeft = '24px';
  3017. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  3018. layers.style.marginLeft = edit.style.marginLeft;
  3019. layers.style.marginBottom = '16px';
  3020. mxEvent.addListener(lightbox, 'change', function()
  3021. {
  3022. if (lightbox.checked)
  3023. {
  3024. layers.removeAttribute('disabled');
  3025. edit.removeAttribute('disabled');
  3026. }
  3027. else
  3028. {
  3029. layers.setAttribute('disabled', 'disabled');
  3030. edit.setAttribute('disabled', 'disabled');
  3031. }
  3032. });
  3033. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3034. {
  3035. fn(linkSection.getTarget(), linkSection.getColor(),
  3036. (allPages == null) ? true : allPages.checked,
  3037. lightbox.checked, edit.checked, layers.checked,
  3038. (widthInput != null) ? widthInput.value : null,
  3039. (heightInput != null) ? heightInput.value : null);
  3040. }), null, mxResources.get('create'), helpLink);
  3041. this.showDialog(dlg.container, 340, 246 + dy, true, true);
  3042. if (widthInput != null)
  3043. {
  3044. widthInput.focus();
  3045. if (mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3046. {
  3047. widthInput.select();
  3048. }
  3049. else
  3050. {
  3051. document.execCommand('selectAll', false, null);
  3052. }
  3053. }
  3054. else
  3055. {
  3056. linkSection.focus();
  3057. }
  3058. };
  3059. /**
  3060. *
  3061. */
  3062. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  3063. {
  3064. var div = document.createElement('div');
  3065. div.style.whiteSpace = 'nowrap';
  3066. var hd = document.createElement('h3');
  3067. mxUtils.write(hd, mxResources.get('image'));
  3068. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3069. div.appendChild(hd);
  3070. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  3071. this.editor.graph.isSelectionEmpty());
  3072. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  3073. if (include != null)
  3074. {
  3075. include.style.marginBottom = '16px';
  3076. }
  3077. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3078. {
  3079. callback(!selection.checked, (include != null) ? include.checked : false);
  3080. }), null, btnLabel, helpLink);
  3081. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 146, true, true);
  3082. };
  3083. /**
  3084. *
  3085. */
  3086. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback, cropOption, defaultInclude)
  3087. {
  3088. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  3089. var div = document.createElement('div');
  3090. div.style.whiteSpace = 'nowrap';
  3091. var graph = this.editor.graph;
  3092. var height = 280;
  3093. var hd = document.createElement('h3');
  3094. mxUtils.write(hd, title);
  3095. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  3096. div.appendChild(hd);
  3097. mxUtils.write(div, mxResources.get('zoom') + ':');
  3098. var zoomInput = document.createElement('input');
  3099. zoomInput.setAttribute('type', 'text');
  3100. zoomInput.style.marginRight = '16px';
  3101. zoomInput.style.width = '60px';
  3102. zoomInput.style.marginLeft = '4px';
  3103. zoomInput.style.marginRight = '12px';
  3104. zoomInput.value = '100%';
  3105. div.appendChild(zoomInput);
  3106. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  3107. var borderInput = document.createElement('input');
  3108. borderInput.setAttribute('type', 'text');
  3109. borderInput.style.marginRight = '16px';
  3110. borderInput.style.width = '60px';
  3111. borderInput.style.marginLeft = '4px';
  3112. borderInput.value = '0';
  3113. div.appendChild(borderInput);
  3114. mxUtils.br(div);
  3115. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  3116. graph.background == mxConstants.NONE || graph.background == null);
  3117. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  3118. false, graph.isSelectionEmpty());
  3119. var cb6 = document.createElement('input');
  3120. cb6.style.marginTop = '16px';
  3121. cb6.style.marginRight = '8px';
  3122. cb6.setAttribute('type', 'checkbox');
  3123. if (cropOption)
  3124. {
  3125. div.appendChild(cb6);
  3126. mxUtils.write(div, mxResources.get('crop'));
  3127. mxUtils.br(div);
  3128. height += 26;
  3129. }
  3130. if (graph.isSelectionEmpty())
  3131. {
  3132. cb6.setAttribute('disabled', 'disabled');
  3133. }
  3134. else
  3135. {
  3136. cb6.setAttribute('checked', 'checked');
  3137. cb6.defaultChecked = true;
  3138. }
  3139. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  3140. var cb5 = document.createElement('input');
  3141. cb5.style.marginTop = '16px';
  3142. cb5.style.marginRight = '8px';
  3143. cb5.setAttribute('type', 'checkbox');
  3144. if (this.isOffline() || !this.canvasSupported)
  3145. {
  3146. cb5.setAttribute('disabled', 'disabled');
  3147. }
  3148. if (embedOption)
  3149. {
  3150. div.appendChild(cb5);
  3151. mxUtils.write(div, mxResources.get('embedImages'));
  3152. mxUtils.br(div);
  3153. height += 26;
  3154. }
  3155. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude);
  3156. var hasPages = this.pages != null && this.pages.length > 1;
  3157. var allPages = allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages);
  3158. allPages.style.marginLeft = '24px';
  3159. allPages.style.marginBottom = '16px';
  3160. if (!hasPages)
  3161. {
  3162. allPages.style.visibility = 'hidden';
  3163. }
  3164. mxEvent.addListener(include, 'change', function()
  3165. {
  3166. if (include.checked && hasPages)
  3167. {
  3168. allPages.removeAttribute('disabled');
  3169. }
  3170. else
  3171. {
  3172. allPages.setAttribute('disabled', 'disabled');
  3173. }
  3174. });
  3175. if (!defaultInclude || !hasPages)
  3176. {
  3177. allPages.setAttribute('disabled', 'disabled');
  3178. }
  3179. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3180. {
  3181. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  3182. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked);
  3183. }), null, btnLabel, helpLink);
  3184. this.showDialog(dlg.container, 320, height, true, true);
  3185. zoomInput.focus();
  3186. if (mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3187. {
  3188. zoomInput.select();
  3189. }
  3190. else
  3191. {
  3192. document.execCommand('selectAll', false, null);
  3193. }
  3194. };
  3195. /**
  3196. *
  3197. */
  3198. EditorUi.prototype.showExportJpgDialog = function(helpLink, callback)
  3199. {
  3200. var div = document.createElement('div');
  3201. div.style.whiteSpace = 'nowrap';
  3202. var graph = this.editor.graph;
  3203. var hd = document.createElement('h3');
  3204. mxUtils.write(hd, mxResources.get('formatJpg'));
  3205. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  3206. div.appendChild(hd);
  3207. mxUtils.write(div, mxResources.get('zoom') + ':');
  3208. var zoomInput = document.createElement('input');
  3209. zoomInput.setAttribute('type', 'text');
  3210. zoomInput.style.marginRight = '16px';
  3211. zoomInput.style.width = '60px';
  3212. zoomInput.style.marginLeft = '4px';
  3213. zoomInput.style.marginBottom = '4px';
  3214. zoomInput.value = '100%';
  3215. div.appendChild(zoomInput);
  3216. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  3217. var borderInput = document.createElement('input');
  3218. borderInput.setAttribute('type', 'text');
  3219. borderInput.style.marginRight = '16px';
  3220. borderInput.style.width = '60px';
  3221. borderInput.style.marginLeft = '4px';
  3222. borderInput.value = '0';
  3223. div.appendChild(borderInput);
  3224. mxUtils.br(div);
  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. div.appendChild(cb6);
  3232. mxUtils.write(div, mxResources.get('crop'));
  3233. mxUtils.br(div);
  3234. if (graph.isSelectionEmpty())
  3235. {
  3236. cb6.setAttribute('disabled', 'disabled');
  3237. }
  3238. else
  3239. {
  3240. cb6.setAttribute('checked', 'checked');
  3241. cb6.defaultChecked = true;
  3242. }
  3243. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  3244. var cb5 = document.createElement('input');
  3245. cb5.style.marginTop = '16px';
  3246. cb5.style.marginRight = '8px';
  3247. cb5.setAttribute('type', 'checkbox');
  3248. if (this.isOffline() || !this.canvasSupported)
  3249. {
  3250. cb5.setAttribute('disabled', 'disabled');
  3251. }
  3252. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3253. {
  3254. callback(zoomInput.value, !selection.checked, shadow.checked, borderInput.value, cb6.checked);
  3255. }), null, mxResources.get('export'), helpLink);
  3256. this.showDialog(dlg.container, 320, 190, true, true);
  3257. zoomInput.focus();
  3258. if (mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  3259. {
  3260. zoomInput.select();
  3261. }
  3262. else
  3263. {
  3264. document.execCommand('selectAll', false, null);
  3265. }
  3266. };
  3267. /**
  3268. *
  3269. */
  3270. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  3271. {
  3272. var div = document.createElement('div');
  3273. div.style.whiteSpace = 'nowrap';
  3274. var graph = this.editor.graph;
  3275. if (title != null)
  3276. {
  3277. var hd = document.createElement('h3');
  3278. mxUtils.write(hd, title);
  3279. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  3280. div.appendChild(hd);
  3281. }
  3282. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  3283. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  3284. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  3285. var image = this.addCheckbox(div, imageLabel);
  3286. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  3287. var edit = this.addCheckbox(div, mxResources.get('showEditButton'), true);
  3288. edit.style.marginLeft = '24px';
  3289. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  3290. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  3291. layers.style.marginLeft = edit.style.marginLeft;
  3292. layers.style.marginBottom = '12px';
  3293. mxEvent.addListener(lightbox, 'change', function()
  3294. {
  3295. if (lightbox.checked)
  3296. {
  3297. if (hasLayers)
  3298. {
  3299. layers.removeAttribute('disabled');
  3300. }
  3301. edit.removeAttribute('disabled');
  3302. }
  3303. else
  3304. {
  3305. layers.setAttribute('disabled', 'disabled');
  3306. edit.setAttribute('disabled', 'disabled');
  3307. }
  3308. });
  3309. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  3310. {
  3311. fn(fit.checked, shadow.checked, image.checked, lightbox.checked, edit.checked, layers.checked);
  3312. }), null, mxResources.get('embed'), helpLink);
  3313. this.showDialog(dlg.container, 280, 280, true, true);
  3314. };
  3315. /**
  3316. *
  3317. */
  3318. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  3319. {
  3320. var bounds = this.editor.graph.getGraphBounds();
  3321. function doUpdate(dataUri)
  3322. {
  3323. var onclick = ' ';
  3324. var css = '';
  3325. // Adds double click handling
  3326. if (lightbox)
  3327. {
  3328. // KNOWN: Message passing does not seem to work in IE11
  3329. 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(" +
  3330. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3331. ((edit) ? "&edit=_blank" : "") +
  3332. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3333. css += 'cursor:pointer;';
  3334. }
  3335. if (fit)
  3336. {
  3337. css += 'max-width:100%;';
  3338. }
  3339. var atts = '';
  3340. if (retina)
  3341. {
  3342. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  3343. }
  3344. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3345. };
  3346. if (this.isExportToCanvas())
  3347. {
  3348. var scale = 1;
  3349. var ignoreSelection = true;
  3350. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3351. {
  3352. var xml = (lightbox) ? this.getFileData(true) : null;
  3353. var data = this.createImageDataUri(canvas, xml, 'png');
  3354. doUpdate(data);
  3355. }), null, null, null, mxUtils.bind(this, function(e)
  3356. {
  3357. err({message: mxResources.get('unknownError')});
  3358. }), null, true, (retina) ? 2 : 1, null, shadow);
  3359. }
  3360. else
  3361. {
  3362. var data = this.getFileData(true);
  3363. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  3364. {
  3365. var size = '';
  3366. if (retina)
  3367. {
  3368. size = '&w=' + Math.round(2 * bounds.width) +
  3369. '&h=' + Math.round(2 * bounds.height);
  3370. }
  3371. var embed = (lightbox) ? '1' : '0';
  3372. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  3373. '&base64=1&embedXml=' + embed + size + '&xml=' +
  3374. encodeURIComponent(data));
  3375. // LATER: Updates on each change, add a delay
  3376. req.send(mxUtils.bind(this, function()
  3377. {
  3378. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  3379. {
  3380. // Fixes possible "incorrect function" for select() on
  3381. // DOM node which is no longer in document with IE11
  3382. doUpdate('data:image/png;base64,' + req.getText());
  3383. }
  3384. else
  3385. {
  3386. err({message: mxResources.get('unknownError')});
  3387. }
  3388. }));
  3389. }
  3390. else
  3391. {
  3392. err({message: mxResources.get('drawingTooLarge')});
  3393. }
  3394. }
  3395. };
  3396. /**
  3397. *
  3398. */
  3399. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  3400. {
  3401. var svgRoot = this.editor.graph.getSvg();
  3402. // Keeps hashtag links on same page
  3403. var links = svgRoot.getElementsByTagName('a');
  3404. if (links != null)
  3405. {
  3406. for (var i = 0; i < links.length; i++)
  3407. {
  3408. var href = links[i].getAttribute('href');
  3409. if (href != null && href.charAt(0) == '#' &&
  3410. links[i].getAttribute('target') == '_blank')
  3411. {
  3412. links[i].removeAttribute('target');
  3413. }
  3414. }
  3415. }
  3416. if (lightbox)
  3417. {
  3418. svgRoot.setAttribute('content', this.getFileData(true));
  3419. }
  3420. // Adds shadow filter
  3421. if (shadow)
  3422. {
  3423. this.editor.graph.addSvgShadow(svgRoot);
  3424. }
  3425. // SVG inside image tag
  3426. if (image)
  3427. {
  3428. var onclick = ' ';
  3429. var css = '';
  3430. // Adds double click handling
  3431. if (lightbox)
  3432. {
  3433. // KNOWN: Message passing does not seem to work in IE11
  3434. 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(" +
  3435. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3436. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  3437. css += 'cursor:pointer;';
  3438. }
  3439. if (fit)
  3440. {
  3441. css += 'max-width:100%;';
  3442. }
  3443. // Images inside IMG don't seem to work so embed them all
  3444. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  3445. {
  3446. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  3447. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  3448. }));
  3449. }
  3450. else
  3451. {
  3452. var css = '';
  3453. // Adds double click handling
  3454. if (lightbox)
  3455. {
  3456. // KNOWN: Message passing does not seem to work in IE11
  3457. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  3458. // Ignores link events
  3459. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  3460. // Focus existing lightbox
  3461. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  3462. // Message handling
  3463. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  3464. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  3465. "window.addEventListener('message',r);" +
  3466. // Opens lightbox window
  3467. "svg.wnd=window.open('https://www.draw.io/?client=1&lightbox=1" +
  3468. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  3469. svgRoot.setAttribute('onclick', js);
  3470. css += 'cursor:pointer;';
  3471. }
  3472. // Adds responsive size
  3473. if (fit)
  3474. {
  3475. var w = parseInt(svgRoot.getAttribute('width'));
  3476. var h = parseInt(svgRoot.getAttribute('height'));
  3477. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  3478. css += 'max-width:100%;max-height:' + h + 'px;';
  3479. svgRoot.removeAttribute('height');
  3480. }
  3481. if (css != '')
  3482. {
  3483. svgRoot.setAttribute('style', css);
  3484. }
  3485. fn(mxUtils.getXml(svgRoot));
  3486. }
  3487. };
  3488. /**
  3489. * Translates this point by the given vector.
  3490. *
  3491. * @param {number} dx X-coordinate of the translation.
  3492. * @param {number} dy Y-coordinate of the translation.
  3493. */
  3494. EditorUi.prototype.timeSince = function(date)
  3495. {
  3496. var seconds = Math.floor((new Date() - date) / 1000);
  3497. var interval = Math.floor(seconds / 31536000);
  3498. if (interval > 1)
  3499. {
  3500. return interval + ' ' + mxResources.get('years');
  3501. }
  3502. interval = Math.floor(seconds / 2592000);
  3503. if (interval > 1)
  3504. {
  3505. return interval + ' ' + mxResources.get('months');
  3506. }
  3507. interval = Math.floor(seconds / 86400);
  3508. if (interval > 1)
  3509. {
  3510. return interval + ' ' + mxResources.get('days');
  3511. }
  3512. interval = Math.floor(seconds / 3600);
  3513. if (interval > 1)
  3514. {
  3515. return interval + ' ' + mxResources.get('hours');
  3516. }
  3517. interval = Math.floor(seconds / 60);
  3518. if (interval > 1)
  3519. {
  3520. return interval + ' ' + mxResources.get('minutes');
  3521. }
  3522. if (interval == 1)
  3523. {
  3524. return interval + ' ' + mxResources.get('minute');
  3525. }
  3526. return null;
  3527. };
  3528. /**
  3529. * Converts math in the given SVG
  3530. */
  3531. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  3532. {
  3533. // FIXME: Only horizontal dash in output so better no conversion at all
  3534. if (false && graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  3535. {
  3536. // Workaround for lost gradients in Chrome after remove from DOM
  3537. var elts = svgRoot.getElementsByTagName('*');
  3538. for (var i = 0; i < elts.length; i++)
  3539. {
  3540. if (elts[i].getAttribute('id') != null)
  3541. {
  3542. elts[i].setAttribute('id', 'mxTemporaryPrefix-' + elts[i].getAttribute('id'));
  3543. }
  3544. }
  3545. // Temporarily attaches to DOM for rendering
  3546. svgRoot.style.visibility = 'hidden';
  3547. document.body.appendChild(svgRoot);
  3548. Editor.MathJaxRender(svgRoot);
  3549. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  3550. {
  3551. // Removes from DOM
  3552. svgRoot.parentNode.removeChild(svgRoot);
  3553. svgRoot.style.visibility = '';
  3554. // Restores original IDs
  3555. for (var i = 0; i < elts.length; i++)
  3556. {
  3557. if (elts[i].getAttribute('id') != null)
  3558. {
  3559. elts[i].setAttribute('id', elts[i].getAttribute('id').substring('mxTemporaryPrefix-'.length));
  3560. }
  3561. }
  3562. // Keeping scale but moving translate only works for image export which
  3563. // is fine since we do not want the SVG export to contain a workaround.
  3564. // See https://github.com/mathjax/MathJax/issues/279
  3565. if (fixPosition && navigator.userAgent.indexOf('AppleWebKit/') >= 0)
  3566. {
  3567. var fo = svgRoot.getElementsByTagName('foreignObject');
  3568. for (var i = 0; i < fo.length; i++)
  3569. {
  3570. var tr = fo[i].parentNode.parentNode.getAttribute('transform');
  3571. var translate = /translate\(\s*([^\s,)]+)[ ,]([^\s,)]+)/.exec(tr);
  3572. fo[i].setAttribute('x', Math.round(translate[1]));
  3573. fo[i].setAttribute('y', Math.round(translate[2]));
  3574. // Must use translate for crisp rendering
  3575. fo[i].parentNode.parentNode.setAttribute('transform', 'translate(0.5,0.5)' + tr.substring(tr.indexOf(')') + 1));
  3576. }
  3577. }
  3578. callback();
  3579. }));
  3580. }
  3581. else
  3582. {
  3583. callback();
  3584. }
  3585. };
  3586. /**
  3587. * Returns the SVG of the diagram with embedded XML. If a callback function is
  3588. * used, the images are converted to data URIs.
  3589. */
  3590. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  3591. {
  3592. var bg = graph.background;
  3593. if (bg == mxConstants.NONE)
  3594. {
  3595. bg = null;
  3596. }
  3597. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3598. // because PhantomJS seems to ignore switch statements and paint all text.
  3599. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  3600. if (xml != null)
  3601. {
  3602. svgRoot.setAttribute('content', xml);
  3603. }
  3604. if (url != null)
  3605. {
  3606. svgRoot.setAttribute('resource', url);
  3607. }
  3608. // LATER: Click on SVG content to start editing
  3609. // if (redirect != null)
  3610. // {
  3611. // // TODO: Ignore anchor tag source for click event
  3612. // svgRoot.setAttribute('style', 'cursor:pointer;');
  3613. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  3614. // }
  3615. if (callback != null)
  3616. {
  3617. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  3618. {
  3619. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  3620. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  3621. mxUtils.getXml(svgRoot));
  3622. }));
  3623. }
  3624. else
  3625. {
  3626. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  3627. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  3628. mxUtils.getXml(svgRoot);
  3629. }
  3630. };
  3631. /**
  3632. *
  3633. */
  3634. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  3635. {
  3636. format = (format != null) ? format : 'png';
  3637. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  3638. {
  3639. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3640. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3641. // Caches images
  3642. if (this.thumbImageCache == null)
  3643. {
  3644. this.thumbImageCache = new Object();
  3645. }
  3646. try
  3647. {
  3648. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3649. {
  3650. this.spinner.stop();
  3651. try
  3652. {
  3653. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  3654. null, null, ignoreSelection, currentPage) : null, format);
  3655. }
  3656. catch (e)
  3657. {
  3658. // Fallback to server-side image export
  3659. if (e.message == 'Invalid image')
  3660. {
  3661. this.downloadFile(format);
  3662. }
  3663. else
  3664. {
  3665. this.handleError(e);
  3666. }
  3667. }
  3668. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3669. {
  3670. this.spinner.stop();
  3671. this.handleError(e);
  3672. }), null, ignoreSelection, scale || 1, transparentBackground,
  3673. addShadow, null, null, border, noCrop);
  3674. }
  3675. catch (e)
  3676. {
  3677. this.spinner.stop();
  3678. this.handleError(e);
  3679. }
  3680. }
  3681. };
  3682. /**
  3683. *
  3684. */
  3685. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  3686. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  3687. {
  3688. limitHeight = (limitHeight != null) ? limitHeight : true;
  3689. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  3690. graph = (graph != null) ? graph : this.editor.graph;
  3691. border = (border != null) ? border : 0;
  3692. var bg = (transparentBackground) ? null : graph.background;
  3693. if (bg == mxConstants.NONE)
  3694. {
  3695. bg = null;
  3696. }
  3697. if (bg == null)
  3698. {
  3699. bg = background;
  3700. }
  3701. // Handles special case where background is null but transparent is false
  3702. if (bg == null && transparentBackground == false)
  3703. {
  3704. bg = '#ffffff';
  3705. }
  3706. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection), mxUtils.bind(this, function(svgRoot)
  3707. {
  3708. var img = new Image();
  3709. img.onload = mxUtils.bind(this, function()
  3710. {
  3711. try
  3712. {
  3713. var canvas = document.createElement('canvas');
  3714. var w = parseInt(svgRoot.getAttribute('width'));
  3715. var h = parseInt(svgRoot.getAttribute('height'));
  3716. scale = (scale != null) ? scale : 1;
  3717. if (width != null)
  3718. {
  3719. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  3720. }
  3721. w = Math.ceil(scale * w) + 2 * border;
  3722. h = Math.ceil(scale * h) + 2 * border;
  3723. canvas.setAttribute('width', w);
  3724. canvas.setAttribute('height', h);
  3725. var ctx = canvas.getContext('2d');
  3726. if (bg != null)
  3727. {
  3728. ctx.beginPath();
  3729. ctx.rect(0, 0, w, h);
  3730. ctx.fillStyle = bg;
  3731. ctx.fill();
  3732. }
  3733. ctx.scale(scale, scale);
  3734. ctx.drawImage(img, border / scale, border / scale);
  3735. callback(canvas);
  3736. }
  3737. catch (e)
  3738. {
  3739. if (error != null)
  3740. {
  3741. error(e);
  3742. }
  3743. }
  3744. });
  3745. img.onerror = function(e)
  3746. {
  3747. //console.log('img', e, img.src);
  3748. if (error != null)
  3749. {
  3750. error(e);
  3751. }
  3752. };
  3753. try
  3754. {
  3755. if (addShadow)
  3756. {
  3757. this.editor.graph.addSvgShadow(svgRoot);
  3758. }
  3759. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  3760. {
  3761. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  3762. }));
  3763. }
  3764. catch (e)
  3765. {
  3766. //console.log('src', e, img.src);
  3767. if (error != null)
  3768. {
  3769. error(e);
  3770. }
  3771. }
  3772. }), imageCache, converter);
  3773. };
  3774. /**
  3775. * Converts all images in the SVG output to data URIs for immediate rendering
  3776. */
  3777. EditorUi.prototype.createImageUrlConverter = function()
  3778. {
  3779. var converter = new mxUrlConverter();
  3780. converter.updateBaseUrl();
  3781. // Extends convert to avoid CORS using an image proxy server
  3782. // LATER: Use img.crossOrigin="anonymous" to avoid proxy
  3783. var convert = converter.convert;
  3784. converter.convert = function(src)
  3785. {
  3786. if (src != null)
  3787. {
  3788. if ((src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://') &&
  3789. src.substring(0, converter.baseUrl.length) != converter.baseUrl)
  3790. {
  3791. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  3792. }
  3793. else if (src.substring(0, 19) != 'chrome-extension://')
  3794. {
  3795. src = convert.apply(this, arguments);
  3796. }
  3797. }
  3798. return src;
  3799. };
  3800. return converter;
  3801. };
  3802. /**
  3803. * Converts all images in the SVG output to data URIs for immediate rendering
  3804. */
  3805. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  3806. {
  3807. // Converts images to data URLs for immediate painting
  3808. if (converter == null)
  3809. {
  3810. converter = this.createImageUrlConverter();
  3811. }
  3812. // Barrier for asynchronous image loading
  3813. var counter = 0;
  3814. function inc()
  3815. {
  3816. counter++;
  3817. };
  3818. function dec()
  3819. {
  3820. counter--;
  3821. if (counter == 0)
  3822. {
  3823. callback(svgRoot);
  3824. }
  3825. };
  3826. var cache = imageCache || new Object();
  3827. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  3828. {
  3829. var images = svgRoot.getElementsByTagName(tagName);
  3830. for (var i = 0; i < images.length; i++)
  3831. {
  3832. (mxUtils.bind(this, function(img)
  3833. {
  3834. var src = converter.convert(img.getAttribute(srcAttr));
  3835. // Data URIs are pass-through
  3836. if (src != null && src.substring(0, 5) != 'data:')
  3837. {
  3838. var tmp = cache[src];
  3839. if (tmp == null)
  3840. {
  3841. inc();
  3842. this.convertImageToDataUri(src, function(uri)
  3843. {
  3844. if (uri != null)
  3845. {
  3846. cache[src] = uri;
  3847. img.setAttribute(srcAttr, uri);
  3848. }
  3849. dec();
  3850. });
  3851. }
  3852. else
  3853. {
  3854. img.setAttribute(srcAttr, tmp);
  3855. }
  3856. }
  3857. }))(images[i]);
  3858. }
  3859. });
  3860. // Converts all known image tags in output
  3861. // LATER: Add support for images in CSS
  3862. convertImages('image', 'xlink:href');
  3863. convertImages('img', 'src');
  3864. // All from cache or no images
  3865. if (counter == 0)
  3866. {
  3867. callback(svgRoot);
  3868. }
  3869. };
  3870. /**
  3871. * Returns true if the given URL is known to have CORS headers.
  3872. */
  3873. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  3874. {
  3875. return url.substring(0, 34) === 'https?://raw.githubusercontent.com/' ||
  3876. /^https?:\/\/.*\.github\.io\//.test(url) ||
  3877. /^https?:\/\/(.*\.)?rawgit\.com\//.test(url);
  3878. };
  3879. /**
  3880. * Translates this point by the given vector.
  3881. *
  3882. * @param {number} dx X-coordinate of the translation.
  3883. * @param {number} dy Y-coordinate of the translation.
  3884. */
  3885. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  3886. {
  3887. if (/(\.svg)$/i.test(url))
  3888. {
  3889. mxUtils.get(url, mxUtils.bind(this, function(req)
  3890. {
  3891. callback(this.createSvgDataUri(req.getText()));
  3892. }),
  3893. function()
  3894. {
  3895. callback();
  3896. });
  3897. }
  3898. else
  3899. {
  3900. var img = new Image();
  3901. img.onload = function()
  3902. {
  3903. var canvas = document.createElement('canvas');
  3904. var ctx = canvas.getContext('2d');
  3905. canvas.height = img.height;
  3906. canvas.width = img.width;
  3907. ctx.drawImage(img, 0, 0);
  3908. callback(canvas.toDataURL());
  3909. };
  3910. img.onerror = function()
  3911. {
  3912. callback();
  3913. };
  3914. img.src = url;
  3915. }
  3916. };
  3917. /**
  3918. * Handling drag and drop and import.
  3919. */
  3920. /**
  3921. * Imports the given XML into the existing diagram.
  3922. */
  3923. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  3924. {
  3925. dx = (dx != null) ? dx : 0;
  3926. dy = (dy != null) ? dy : 0;
  3927. var cells = []
  3928. try
  3929. {
  3930. var graph = this.editor.graph;
  3931. if (xml != null && xml.length > 0)
  3932. {
  3933. var doc = mxUtils.parseXml(xml);
  3934. // Checks for mxfile with multiple pages
  3935. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  3936. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  3937. {
  3938. var diagrams = node.getElementsByTagName('diagram');
  3939. if (diagrams.length == 1)
  3940. {
  3941. node = mxUtils.parseXml(graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  3942. }
  3943. else if (diagrams.length > 1)
  3944. {
  3945. // Adds pages
  3946. graph.model.beginUpdate();
  3947. try
  3948. {
  3949. for (var i = 0; i < diagrams.length; i++)
  3950. {
  3951. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  3952. var index = this.pages.length;
  3953. // Checks for invalid page names
  3954. if (page.getName() == null)
  3955. {
  3956. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  3957. }
  3958. graph.model.execute(new ChangePage(this, page, page, index));
  3959. }
  3960. }
  3961. finally
  3962. {
  3963. graph.model.endUpdate();
  3964. }
  3965. }
  3966. }
  3967. if (node != null && node.nodeName === 'mxGraphModel')
  3968. {
  3969. var model = new mxGraphModel();
  3970. var codec = new mxCodec(node.ownerDocument);
  3971. codec.decode(node, model);
  3972. var childCount = model.getChildCount(model.getRoot());
  3973. var targetChildCount = graph.model.getChildCount(graph.model.getRoot());
  3974. // Merges into active layer if one layer is pasted
  3975. graph.model.beginUpdate();
  3976. try
  3977. {
  3978. // Mapping for multiple calls to cloneCells with the same set of cells
  3979. var mapping = new Object();
  3980. for (var i = 0; i < childCount; i++)
  3981. {
  3982. var parent = model.getChildAt(model.getRoot(), i);
  3983. // Adds cells to existing layer if not locked
  3984. if (childCount == 1 && !graph.isCellLocked(graph.getDefaultParent()))
  3985. {
  3986. var children = model.getChildren(parent);
  3987. cells = cells.concat(graph.importCells(children, dx, dy, graph.getDefaultParent(), null, mapping));
  3988. }
  3989. else
  3990. {
  3991. // Delta is non cascading, needs separate move for layers
  3992. parent = graph.importCells([parent], 0, 0, graph.model.getRoot(), null, mapping)[0];
  3993. var children = graph.model.getChildren(parent);
  3994. graph.moveCells(children, dx, dy);
  3995. cells = cells.concat(children);
  3996. }
  3997. }
  3998. if (crop)
  3999. {
  4000. if (graph.isGridEnabled())
  4001. {
  4002. dx = graph.snap(dx);
  4003. dy = graph.snap(dy);
  4004. }
  4005. var bounds = graph.getBoundingBoxFromGeometry(cells, true);
  4006. if (bounds != null)
  4007. {
  4008. graph.moveCells(cells, dx - bounds.x, dy - bounds.y);
  4009. }
  4010. }
  4011. }
  4012. finally
  4013. {
  4014. graph.model.endUpdate();
  4015. }
  4016. }
  4017. }
  4018. }
  4019. catch (e)
  4020. {
  4021. if (!noErrorHandling)
  4022. {
  4023. this.handleError(e, mxResources.get('invalidOrMissingFile'));
  4024. }
  4025. throw e;
  4026. }
  4027. return cells;
  4028. };
  4029. /**
  4030. * Automatic loading for lucidchart import.
  4031. */
  4032. EditorUi.prototype.insertLucidChart = function(g, dx, dy, crop)
  4033. {
  4034. var delayed = mxUtils.bind(this, function()
  4035. {
  4036. // Checks for signature method
  4037. if (this.pasteLucidChart)
  4038. {
  4039. try
  4040. {
  4041. this.pasteLucidChart(g, dx, dy, crop);
  4042. }
  4043. catch (e)
  4044. {
  4045. // ignore
  4046. }
  4047. }
  4048. });
  4049. if (!this.pasteLucidChart && !this.loadingExtensions && !this.isOffline())
  4050. {
  4051. this.loadingExtensions = true;
  4052. if (urlParams['dev'] == '1')
  4053. {
  4054. mxscript('/js/diagramly/Extensions.js', delayed);
  4055. }
  4056. else
  4057. {
  4058. mxscript('/js/extensions.min.js', delayed);
  4059. }
  4060. }
  4061. else
  4062. {
  4063. // Must be async for cell selection
  4064. window.setTimeout(delayed, 0);
  4065. }
  4066. };
  4067. /**
  4068. * Imports the given XML into the existing diagram.
  4069. * TODO: Make this function asynchronous
  4070. */
  4071. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop)
  4072. {
  4073. crop = (crop != null) ? crop : true;
  4074. // Handles special case for Gliffy data which requires async server-side for parsing
  4075. if (text != null)
  4076. {
  4077. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  4078. {
  4079. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  4080. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  4081. {
  4082. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  4083. {
  4084. this.editor.graph.setSelectionCells(this.insertTextAt(xhr.responseText, dx, dy, true));
  4085. }
  4086. }));
  4087. // Returns empty cells array as it is aysynchronous
  4088. return [];
  4089. }
  4090. // Handles special case of data URI which requires async loading for finding size
  4091. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() && (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  4092. {
  4093. var graph = this.editor.graph;
  4094. // Checks for embedded XML in PNG
  4095. if (text.substring(0, 22) == 'data:image/png;base64,')
  4096. {
  4097. var xml = this.extractGraphModelFromPng(text);
  4098. var result = this.importXml(xml, dx, dy, crop, true);
  4099. if (result.length > 0)
  4100. {
  4101. return result;
  4102. }
  4103. }
  4104. // Tries to extract embedded XML from SVG data URI
  4105. if (text.substring(0, 19) == 'data:image/svg+xml;')
  4106. {
  4107. try
  4108. {
  4109. var xml = null;
  4110. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  4111. {
  4112. xml = text.substring(text.indexOf(',') + 1);
  4113. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  4114. }
  4115. else
  4116. {
  4117. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  4118. }
  4119. var result = this.importXml(xml, dx, dy, crop, true);
  4120. if (result.length > 0)
  4121. {
  4122. return result;
  4123. }
  4124. }
  4125. catch (e)
  4126. {
  4127. // Ignore
  4128. }
  4129. }
  4130. this.loadImage(text, mxUtils.bind(this, function(img)
  4131. {
  4132. if (text.substring(0, 5) == 'data:')
  4133. {
  4134. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  4135. {
  4136. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4137. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4138. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  4139. }), true, this.maxImageSize);
  4140. }
  4141. else
  4142. {
  4143. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  4144. var w = Math.round(img.width * s);
  4145. var h = Math.round(img.height * s);
  4146. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  4147. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4148. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  4149. }
  4150. }), mxUtils.bind(this, function()
  4151. {
  4152. var cell = null;
  4153. // Inserts invalid data URIs as text
  4154. graph.getModel().beginUpdate();
  4155. try
  4156. {
  4157. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  4158. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4159. graph.updateCellSize(cell);
  4160. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4161. }
  4162. finally
  4163. {
  4164. graph.getModel().endUpdate();
  4165. }
  4166. graph.setSelectionCell(cell);
  4167. }));
  4168. return [];
  4169. }
  4170. else
  4171. {
  4172. text = this.editor.graph.zapGremlins(mxUtils.trim(text));
  4173. if (this.isCompatibleString(text))
  4174. {
  4175. return this.importXml(text, dx, dy, crop);
  4176. }
  4177. else if (text.length > 0)
  4178. {
  4179. if (text.substring(0, 26) == '{"state":"{\\"Properties\\":')
  4180. {
  4181. // Finds and imports first page
  4182. var state = JSON.parse(JSON.parse(text).state);
  4183. var page = null;
  4184. for (var id in state.Pages)
  4185. {
  4186. var tmp = state.Pages[id];
  4187. if (tmp != null && tmp.Properties.Order == '0')
  4188. {
  4189. page = tmp;
  4190. break;
  4191. }
  4192. }
  4193. if (page != null)
  4194. {
  4195. this.insertLucidChart(page, dx, dy, crop);
  4196. }
  4197. }
  4198. else
  4199. {
  4200. var graph = this.editor.graph;
  4201. var cell = null;
  4202. graph.getModel().beginUpdate();
  4203. try
  4204. {
  4205. // Fires cellsInserted to apply the current style to the inserted text.
  4206. // This requires the value to be empty when the event is fired.
  4207. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  4208. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  4209. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  4210. // Apply value and updates the cell size to fit the text block
  4211. cell.value = text;
  4212. graph.updateCellSize(cell);
  4213. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  4214. 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;
  4215. if (regexp.test(cell.value))
  4216. {
  4217. graph.setLinkForCell(cell, cell.value);
  4218. }
  4219. // Adds spacing
  4220. cell.geometry.width += graph.gridSize;
  4221. cell.geometry.height += graph.gridSize;
  4222. }
  4223. finally
  4224. {
  4225. graph.getModel().endUpdate();
  4226. }
  4227. return [cell];
  4228. }
  4229. }
  4230. }
  4231. }
  4232. return [];
  4233. };
  4234. /**
  4235. * Formats the given file size.
  4236. */
  4237. EditorUi.prototype.formatFileSize = function(size)
  4238. {
  4239. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  4240. var i = -1;
  4241. do
  4242. {
  4243. size = size / 1024;
  4244. i++;
  4245. } while (size > 1024);
  4246. return Math.max(size, 0.1).toFixed(1) + units[i];
  4247. };
  4248. /**
  4249. * Imports the given XML into the existing diagram.
  4250. */
  4251. EditorUi.prototype.convertDataUri = function(uri)
  4252. {
  4253. // Handles special case of data URI which needs to be rewritten
  4254. // to be used in a cell style to remove the semicolon
  4255. if (uri.substring(0, 5) == 'data:')
  4256. {
  4257. var semi = uri.indexOf(';');
  4258. if (semi > 0)
  4259. {
  4260. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  4261. }
  4262. }
  4263. return uri;
  4264. };
  4265. /**
  4266. * Returns true for Gliffy or GraphML data or .vsdx filenames.
  4267. */
  4268. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  4269. {
  4270. return /(\.*<graphml xmlns=\".*)/.test(data) ||
  4271. /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data) ||
  4272. (filename != null && /(\.vsdx)($|\?)/i.test(filename)) ||
  4273. (filename != null && /(\.vssx)($|\?)/i.test(filename));
  4274. };
  4275. /**
  4276. * Imports the given XML into the existing diagram.
  4277. */
  4278. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  4279. {
  4280. crop = (crop != null) ? crop : true;
  4281. var async = false;
  4282. var cells = null;
  4283. if (mimeType.substring(0, 5) == 'image')
  4284. {
  4285. var containsModel = false;
  4286. if (mimeType.substring(0, 9) == 'image/png')
  4287. {
  4288. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  4289. if (xml != null && xml.length > 0)
  4290. {
  4291. cells = this.importXml(xml, dx, dy, crop);
  4292. containsModel = true;
  4293. }
  4294. }
  4295. if (!containsModel)
  4296. {
  4297. var graph = this.editor.graph;
  4298. // Strips encoding bit (eg. ;base64,) for cell style
  4299. var semi = data.indexOf(';');
  4300. if (semi > 0)
  4301. {
  4302. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  4303. }
  4304. if (crop && graph.isGridEnabled())
  4305. {
  4306. dx = graph.snap(dx);
  4307. dy = graph.snap(dy);
  4308. }
  4309. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  4310. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  4311. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  4312. }
  4313. }
  4314. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  4315. {
  4316. // LATER: done and async are a hack before making this asynchronous
  4317. async = true;
  4318. // Returns empty cells array as it is aysynchronous
  4319. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  4320. {
  4321. if (xhr.readyState == 4)
  4322. {
  4323. var importedCells = null;
  4324. if (xhr.status >= 200 && xhr.status <= 299)
  4325. {
  4326. var xml = xhr.responseText;
  4327. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  4328. {
  4329. if (filename != null && filename.toLowerCase().substring(filename.length - 5) == '.vssx')
  4330. {
  4331. filename = filename.substring(0, filename.length - 5) + '.xml';
  4332. }
  4333. this.loadLibrary(new LocalLibrary(this, xml, filename));
  4334. }
  4335. else
  4336. {
  4337. importedCells = this.importXml(xml, dx, dy, crop);
  4338. }
  4339. }
  4340. if (done != null)
  4341. {
  4342. done(importedCells);
  4343. }
  4344. }
  4345. }), filename);
  4346. }
  4347. else if (!/(\.vsd)($|\?)/i.test(filename))
  4348. {
  4349. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  4350. }
  4351. if (!async && done != null)
  4352. {
  4353. done(cells);
  4354. }
  4355. return cells;
  4356. };
  4357. /**
  4358. * Base64 encodes the given string. This method seems to be more
  4359. * robust for encoding PNG from binary AJAX responses.
  4360. */
  4361. EditorUi.prototype.base64Encode = function(str)
  4362. {
  4363. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4364. var out = "", i = 0, len = str.length, c1, c2, c3;
  4365. while (i < len)
  4366. {
  4367. c1 = str.charCodeAt(i++) & 0xff;
  4368. if (i == len)
  4369. {
  4370. out += CHARS.charAt(c1 >> 2);
  4371. out += CHARS.charAt((c1 & 0x3) << 4);
  4372. out += "==";
  4373. break;
  4374. }
  4375. c2 = str.charCodeAt(i++);
  4376. if (i == len)
  4377. {
  4378. out += CHARS.charAt(c1 >> 2);
  4379. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  4380. out += CHARS.charAt((c2 & 0xF) << 2);
  4381. out += "=";
  4382. break;
  4383. }
  4384. c3 = str.charCodeAt(i++);
  4385. out += CHARS.charAt(c1 >> 2);
  4386. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  4387. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  4388. out += CHARS.charAt(c3 & 0x3F);
  4389. }
  4390. return out;
  4391. };
  4392. /**
  4393. *
  4394. */
  4395. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeImages, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  4396. {
  4397. var crop = x != null && y != null;
  4398. x = (x != null) ? x : 0;
  4399. y = (y != null) ? y : 0;
  4400. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  4401. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  4402. resizeImages = (resizeImages != null) ? resizeImages : true;
  4403. var graph = this.editor.graph;
  4404. var gs = graph.gridSize;
  4405. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  4406. {
  4407. if (data != null && data.substring(0, 10) == '<mxlibrary')
  4408. {
  4409. this.spinner.stop();
  4410. this.loadLibrary(new LocalLibrary(this, data, filename));
  4411. return null;
  4412. }
  4413. else
  4414. {
  4415. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  4416. }
  4417. });
  4418. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  4419. {
  4420. graph.setSelectionCells(cells);
  4421. });
  4422. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4423. {
  4424. var count = files.length;
  4425. var remain = count;
  4426. var queue = [];
  4427. // Barrier waits for all files to be loaded asynchronously
  4428. var barrier = mxUtils.bind(this, function(index, fnc)
  4429. {
  4430. queue[index] = fnc;
  4431. if (--remain == 0)
  4432. {
  4433. this.spinner.stop();
  4434. if (barrierFn != null)
  4435. {
  4436. barrierFn(queue);
  4437. }
  4438. else
  4439. {
  4440. var cells = [];
  4441. graph.getModel().beginUpdate();
  4442. try
  4443. {
  4444. for (var j = 0; j < queue.length; j++)
  4445. {
  4446. var tmp = queue[j]();
  4447. if (tmp != null)
  4448. {
  4449. cells = cells.concat(tmp);
  4450. }
  4451. }
  4452. }
  4453. finally
  4454. {
  4455. graph.getModel().endUpdate();
  4456. }
  4457. }
  4458. resultFn(cells);
  4459. }
  4460. });
  4461. for (var i = 0; i < count; i++)
  4462. {
  4463. (mxUtils.bind(this, function(index)
  4464. {
  4465. var file = files[index];
  4466. var reader = new FileReader();
  4467. reader.onload = mxUtils.bind(this, function(e)
  4468. {
  4469. if (filterFn == null || filterFn(file))
  4470. {
  4471. if (file.type.substring(0, 6) == 'image/')
  4472. {
  4473. if (file.type.substring(0, 9) == 'image/svg')
  4474. {
  4475. // Checks if SVG contains content attribute
  4476. var data = e.target.result;
  4477. var comma = data.indexOf(',');
  4478. var svgText = atob(data.substring(comma + 1));
  4479. var root = mxUtils.parseXml(svgText);
  4480. var svgs = root.getElementsByTagName('svg');
  4481. if (svgs.length > 0)
  4482. {
  4483. var svgRoot = svgs[0];
  4484. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  4485. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  4486. {
  4487. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  4488. }
  4489. if (cont != null && cont.charAt(0) == '%')
  4490. {
  4491. cont = decodeURIComponent(cont);
  4492. }
  4493. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  4494. cont.substring(0, 14) === '<mxGraphModel '))
  4495. {
  4496. barrier(index, mxUtils.bind(this, function()
  4497. {
  4498. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  4499. }));
  4500. }
  4501. else
  4502. {
  4503. // SVG needs special handling to add viewbox if missing and
  4504. // find initial size from SVG attributes (only for IE11)
  4505. barrier(index, mxUtils.bind(this, function()
  4506. {
  4507. try
  4508. {
  4509. var prefix = data.substring(0, comma + 1);
  4510. // Parses SVG and find width and height
  4511. if (root != null)
  4512. {
  4513. var svgs = root.getElementsByTagName('svg');
  4514. if (svgs.length > 0)
  4515. {
  4516. var svgRoot = svgs[0];
  4517. var w = parseFloat(svgRoot.getAttribute('width'));
  4518. var h = parseFloat(svgRoot.getAttribute('height'));
  4519. // Check if viewBox attribute already exists
  4520. var vb = svgRoot.getAttribute('viewBox');
  4521. if (vb == null || vb.length == 0)
  4522. {
  4523. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  4524. }
  4525. // Uses width and height from viewbox for
  4526. // missing width and height attributes
  4527. else if (isNaN(w) || isNaN(h))
  4528. {
  4529. var tokens = vb.split(' ');
  4530. if (tokens.length > 3)
  4531. {
  4532. w = parseFloat(tokens[2]);
  4533. h = parseFloat(tokens[3]);
  4534. }
  4535. }
  4536. data = this.createSvgDataUri(mxUtils.getXml(svgs[0]));
  4537. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  4538. return fn(data, file.type, x + index * gs, y + index * gs,
  4539. Math.max(1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  4540. }
  4541. }
  4542. }
  4543. catch (e)
  4544. {
  4545. // ignores any SVG parsing errors
  4546. }
  4547. return null;
  4548. }));
  4549. }
  4550. }
  4551. }
  4552. else
  4553. {
  4554. // Checks if PNG+XML is available to bypass code below
  4555. var containsModel = false;
  4556. if (file.type == 'image/png')
  4557. {
  4558. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  4559. if (xml != null && xml.length > 0)
  4560. {
  4561. var img = new Image();
  4562. img.src = e.target.result;
  4563. barrier(index, mxUtils.bind(this, function()
  4564. {
  4565. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  4566. img.width, img.height, file.name);
  4567. }));
  4568. containsModel = true;
  4569. }
  4570. }
  4571. // Additional asynchronous step for finding image size
  4572. if (!containsModel)
  4573. {
  4574. // Cannot load local files in Chrome App
  4575. if (mxClient.IS_CHROMEAPP)
  4576. {
  4577. this.spinner.stop();
  4578. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  4579. mxResources.get('cancel'), mxUtils.bind(this, function()
  4580. {
  4581. // Hides the dialog
  4582. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  4583. {
  4584. // Redirects to import function
  4585. this.actions.get('import').funct();
  4586. })
  4587. );
  4588. }
  4589. else
  4590. {
  4591. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  4592. {
  4593. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  4594. {
  4595. barrier(index, mxUtils.bind(this, function()
  4596. {
  4597. // Refuses to insert images above a certain size as they kill the app
  4598. if (data2 != null && data2.length < maxBytes)
  4599. {
  4600. var s = (!resizeImages || !this.isResampleImage(e.target.result)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  4601. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  4602. }
  4603. else
  4604. {
  4605. this.handleError({message: mxResources.get('imageTooBig')});
  4606. return null;
  4607. }
  4608. }));
  4609. }), resizeImages, maxSize, resampleThreshold);
  4610. }));
  4611. }
  4612. }
  4613. }
  4614. }
  4615. else
  4616. {
  4617. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  4618. {
  4619. barrier(index, function()
  4620. {
  4621. return cells;
  4622. });
  4623. });
  4624. }
  4625. }
  4626. });
  4627. // Handles special case of binary file where the reader should not be used
  4628. if (/(\.vsdx)($|\?)/i.test(file.name) || /(\.vssx)($|\?)/i.test(file.name))
  4629. {
  4630. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  4631. {
  4632. barrier(index, function()
  4633. {
  4634. return cells;
  4635. });
  4636. }, file);
  4637. }
  4638. else if (file.type.substring(0, 5) == 'image')
  4639. {
  4640. reader.readAsDataURL(file);
  4641. }
  4642. else
  4643. {
  4644. reader.readAsText(file);
  4645. }
  4646. }))(i);
  4647. }
  4648. }
  4649. };
  4650. /**
  4651. * Parses the file using XHR2 via the server. File can be a blob or file object.
  4652. * Filename is an optional parameter for blobs (that do not have a filename).
  4653. */
  4654. EditorUi.prototype.parseFile = function(file, fn, filename)
  4655. {
  4656. filename = (filename != null) ? filename : file.name;
  4657. var formData = new FormData();
  4658. formData.append('format', 'xml');
  4659. formData.append('upfile', file, filename);
  4660. var xhr = new XMLHttpRequest();
  4661. xhr.open('POST', OPEN_URL);
  4662. xhr.onreadystatechange = function()
  4663. {
  4664. fn(xhr);
  4665. };
  4666. xhr.send(formData);
  4667. };
  4668. /**
  4669. *
  4670. */
  4671. EditorUi.prototype.isResampleImage = function(data, thresh)
  4672. {
  4673. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  4674. return data.length > thresh;
  4675. };
  4676. /**
  4677. * Resizes the given image if <maxImageBytes> is not null.
  4678. */
  4679. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  4680. {
  4681. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  4682. var w = Math.max(1, img.width);
  4683. var h = Math.max(1, img.height);
  4684. if (enabled && this.isResampleImage(data, thresh))
  4685. {
  4686. try
  4687. {
  4688. var factor = Math.max(w / maxSize, h / maxSize);
  4689. if (factor > 1)
  4690. {
  4691. var w2 = Math.round(w / factor);
  4692. var h2 = Math.round(h / factor);
  4693. var canvas = document.createElement('canvas');
  4694. canvas.width = w2;
  4695. canvas.height = h2;
  4696. var ctx = canvas.getContext('2d');
  4697. ctx.drawImage(img, 0, 0, w2, h2);
  4698. var tmp = canvas.toDataURL();
  4699. // Uses new image if smaller
  4700. if (tmp.length < data.length)
  4701. {
  4702. // Checks if the image is empty by comparing
  4703. // with an empty image of the same size
  4704. var canvas2 = document.createElement('canvas');
  4705. canvas2.width = w2;
  4706. canvas2.height = h2;
  4707. var tmp2 = canvas2.toDataURL();
  4708. if (tmp !== tmp2)
  4709. {
  4710. data = tmp;
  4711. w = w2;
  4712. h = h2;
  4713. }
  4714. }
  4715. }
  4716. }
  4717. catch (e)
  4718. {
  4719. // ignores image scaling errors
  4720. }
  4721. }
  4722. fn(data, w, h);
  4723. };
  4724. EditorUi.prototype.crcTable = [];
  4725. for (var n = 0; n < 256; n++)
  4726. {
  4727. var c = n;
  4728. for (var k = 0; k < 8; k++)
  4729. {
  4730. if ((c & 1) == 1)
  4731. {
  4732. c = 0xedb88320 ^ (c >>> 1);
  4733. }
  4734. else
  4735. {
  4736. c >>>= 1;
  4737. }
  4738. EditorUi.prototype.crcTable[n] = c;
  4739. }
  4740. }
  4741. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  4742. {
  4743. var c = crc;
  4744. for (var n = 0; n < len; n++)
  4745. {
  4746. c = EditorUi.prototype.crcTable[(c ^ data[off + n]) & 0xff] ^ (c >>> 8);
  4747. }
  4748. return c;
  4749. };
  4750. /**
  4751. * Adds the given text to the compressed or non-compressed text chunk.
  4752. */
  4753. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  4754. {
  4755. var base64 = data.substring(data.indexOf(',') + 1);
  4756. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  4757. var pos = 0;
  4758. function fread(d, count)
  4759. {
  4760. var start = pos;
  4761. pos += count;
  4762. return d.substring(start, pos);
  4763. };
  4764. // Reads unsigned long 32 bit big endian
  4765. function _freadint(d)
  4766. {
  4767. var bytes = fread(d, 4);
  4768. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  4769. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  4770. };
  4771. function writeInt(num)
  4772. {
  4773. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  4774. (num >> 8) & 0x000000ff, num & 0x000000ff);
  4775. };
  4776. // Checks signature
  4777. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  4778. {
  4779. if (error != null)
  4780. {
  4781. error();
  4782. }
  4783. return;
  4784. }
  4785. // Reads header chunk
  4786. fread(f,4);
  4787. if (fread(f,4) != 'IHDR')
  4788. {
  4789. if (error != null)
  4790. {
  4791. error();
  4792. }
  4793. return;
  4794. }
  4795. fread(f, 17);
  4796. var result = f.substring(0, pos);
  4797. do
  4798. {
  4799. var n = _freadint(f);
  4800. var chunk = fread(f,4);
  4801. if (chunk == 'IDAT')
  4802. {
  4803. result = f.substring(0, pos - 8);
  4804. var chunkData = key + String.fromCharCode(0) +
  4805. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  4806. value;
  4807. // FIXME: Wrong crc
  4808. var crc = 0xffffffff;
  4809. crc = this.updateCRC(crc, type, 0, 4);
  4810. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  4811. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  4812. result += f.substring(pos - 8, f.length);
  4813. break;
  4814. }
  4815. result += f.substring(pos - 8, pos - 4 + n);
  4816. value = fread(f,n);
  4817. fread(f,4);
  4818. }
  4819. while (n);
  4820. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  4821. }
  4822. /**
  4823. * Extracts the XML from the compressed or non-compressed text chunk.
  4824. */
  4825. EditorUi.prototype.extractGraphModelFromPng = function(data)
  4826. {
  4827. var result = null;
  4828. try
  4829. {
  4830. var base64 = data.substring(data.indexOf(',') + 1);
  4831. // Workaround for invalid character error in Safari
  4832. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  4833. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  4834. {
  4835. var value = binary.substring(pos + 8, pos + 8 + length);
  4836. if (type == 'zTXt')
  4837. {
  4838. var idx = value.indexOf(String.fromCharCode(0));
  4839. if (value.substring(0, idx) == 'mxGraphModel')
  4840. {
  4841. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  4842. var xmlData = this.editor.graph.bytesToString(pako.inflateRaw(
  4843. value.substring(idx + 2))).replace(/\+/g,' ');
  4844. if (xmlData != null && xmlData.length > 0)
  4845. {
  4846. result = xmlData;
  4847. }
  4848. }
  4849. }
  4850. // Uncompressed section is normally not used
  4851. else if (type == 'tEXt')
  4852. {
  4853. var vals = value.split(String.fromCharCode(0));
  4854. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  4855. {
  4856. result = vals[1];
  4857. }
  4858. }
  4859. if (result != null || type == 'IDAT')
  4860. {
  4861. // Stops processing the file as our text chunks
  4862. // are always placed before the data section
  4863. return true;
  4864. }
  4865. }));
  4866. }
  4867. catch (e)
  4868. {
  4869. // ignores decoding errors
  4870. }
  4871. if (result != null && result.charAt(0) == '%')
  4872. {
  4873. result = decodeURIComponent(result);
  4874. }
  4875. // Workaround for double encoded content
  4876. if (result != null && result.charAt(0) == '%')
  4877. {
  4878. result = decodeURIComponent(result);
  4879. }
  4880. return result;
  4881. };
  4882. /**
  4883. * Loads the image from the given URI.
  4884. *
  4885. * @param {number} dx X-coordinate of the translation.
  4886. * @param {number} dy Y-coordinate of the translation.
  4887. */
  4888. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  4889. {
  4890. var img = new Image();
  4891. img.onload = function()
  4892. {
  4893. onload(img);
  4894. }
  4895. if (onerror != null)
  4896. {
  4897. img.onerror = onerror;
  4898. }
  4899. img.src = uri;
  4900. };
  4901. // Initializes the user interface
  4902. var editorUiInit = EditorUi.prototype.init;
  4903. EditorUi.prototype.init = function()
  4904. {
  4905. // Must be set before UI is created in superclass
  4906. if (typeof window.mxSettings !== 'undefined')
  4907. {
  4908. this.formatWidth = mxSettings.getFormatWidth();
  4909. }
  4910. var ui = this;
  4911. var graph = this.editor.graph;
  4912. function pageLinkClicked(href)
  4913. {
  4914. var comma = href.indexOf(',');
  4915. if (comma > 0)
  4916. {
  4917. var page = ui.getPageById(href.substring(comma + 1));
  4918. if (page)
  4919. {
  4920. ui.selectPage(page)
  4921. }
  4922. }
  4923. };
  4924. // For chromeless mode and lightbox mode in viewer
  4925. // Must be overridden before supercall to be applied
  4926. // in case of chromeless initialization
  4927. var graphAddClickHandler = graph.addClickHandler;
  4928. graph.addClickHandler = function(highlight, beforeClick, onClick)
  4929. {
  4930. var tmp = beforeClick;
  4931. beforeClick = function(evt, href)
  4932. {
  4933. if (href == null)
  4934. {
  4935. var source = mxEvent.getSource(evt);
  4936. if (source.nodeName.toLowerCase() == 'a')
  4937. {
  4938. href = source.getAttribute('href');
  4939. }
  4940. }
  4941. if (href != null && graph.isPageLink(href))
  4942. {
  4943. pageLinkClicked(href);
  4944. mxEvent.consume(evt);
  4945. }
  4946. if (tmp != null)
  4947. {
  4948. tmp(evt);
  4949. }
  4950. };
  4951. // For some reason, local argument override is not enough in this case...
  4952. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  4953. };
  4954. editorUiInit.apply(this, arguments);
  4955. if (mxClient.IS_SVG)
  4956. {
  4957. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  4958. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  4959. }
  4960. // Overrides print dialog size
  4961. ui.actions.get('print').funct = function()
  4962. {
  4963. ui.showDialog(new PrintDialog(ui).container, 360,
  4964. (ui.pages != null && ui.pages.length > 1) ?
  4965. 420 : 360, true, true);
  4966. };
  4967. // Specifies the default filename
  4968. this.defaultFilename = mxResources.get('untitledDiagram');
  4969. // Adds placeholder for %page% and %pagenumber%
  4970. var graphGetGlobalVariable = graph.getGlobalVariable;
  4971. graph.getGlobalVariable = function(name)
  4972. {
  4973. if (name == 'page' && ui.currentPage != null)
  4974. {
  4975. return ui.currentPage.getName();
  4976. }
  4977. else if (name == 'pagenumber')
  4978. {
  4979. if (ui.currentPage != null && ui.pages != null)
  4980. {
  4981. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  4982. }
  4983. else
  4984. {
  4985. return 1;
  4986. }
  4987. }
  4988. return graphGetGlobalVariable.apply(this, arguments);
  4989. };
  4990. var graphCreateLinkForHint = graph.createLinkForHint;
  4991. graph.createLinkForHint = function(href, label)
  4992. {
  4993. var pageLink = graph.isPageLink(href);
  4994. if (pageLink)
  4995. {
  4996. var comma = href.indexOf(',');
  4997. if (comma > 0)
  4998. {
  4999. var page = ui.getPageById(href.substring(comma + 1));
  5000. if (page != null)
  5001. {
  5002. label = page.getName();
  5003. }
  5004. else
  5005. {
  5006. label = mxResources.get('pageNotFound');
  5007. }
  5008. }
  5009. }
  5010. var a = graphCreateLinkForHint.apply(this, arguments);
  5011. if (pageLink)
  5012. {
  5013. mxEvent.addListener(a, 'click', function(evt)
  5014. {
  5015. pageLinkClicked(href);
  5016. mxEvent.consume(evt);
  5017. });
  5018. }
  5019. return a;
  5020. };
  5021. var graphLabelLinkClicked = graph.labelLinkClicked;
  5022. graph.labelLinkClicked = function(state, elt, evt)
  5023. {
  5024. var href = elt.getAttribute('href');
  5025. if (graph.isPageLink(href))
  5026. {
  5027. pageLinkClicked(href);
  5028. mxEvent.consume(evt);
  5029. }
  5030. else
  5031. {
  5032. graphLabelLinkClicked.apply(this, arguments);
  5033. }
  5034. };
  5035. // Overrides editor filename
  5036. this.editor.getOrCreateFilename = function()
  5037. {
  5038. var filename = ui.defaultFilename;
  5039. var file = ui.getCurrentFile();
  5040. if (file != null)
  5041. {
  5042. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  5043. }
  5044. return filename;
  5045. };
  5046. // Disables print action for standalone apps on iOS
  5047. // because there is no way to close the new window
  5048. // LATER: Use iframe for print, disable preview
  5049. var printAction = this.actions.get('print');
  5050. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  5051. printAction.visible = printAction.isEnabled();
  5052. // Scales pages/graph to fit available size
  5053. if (!this.editor.chromeless)
  5054. {
  5055. // Defines additional hotkeys
  5056. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  5057. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  5058. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  5059. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  5060. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  5061. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  5062. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  5063. // Handles copy paste of images from clipboard
  5064. if (!mxClient.IS_IE)
  5065. {
  5066. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  5067. {
  5068. var graph = this.editor.graph;
  5069. if (!mxEvent.isConsumed(evt))
  5070. {
  5071. try
  5072. {
  5073. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  5074. var containsText = false;
  5075. // Workaround for asynchronous paste event processing in textInput
  5076. // is to ignore this event if it contains text/html/rtf (see below).
  5077. // NOTE: Image is not pasted into textInput so can't listen there.
  5078. for (var i = 0; i < data.types.length; i++)
  5079. {
  5080. if (data.types[i].substring(0, 5) === 'text/')
  5081. {
  5082. containsText = true;
  5083. break;
  5084. }
  5085. }
  5086. if (!containsText)
  5087. {
  5088. var items = data.items;
  5089. for (index in items)
  5090. {
  5091. var item = items[index];
  5092. if (item.kind === 'file')
  5093. {
  5094. if (graph.isEditing())
  5095. {
  5096. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  5097. {
  5098. // Inserts image into current text box
  5099. graph.insertImage(data, w, h);
  5100. }, function()
  5101. {
  5102. // No post processing
  5103. }, function(file)
  5104. {
  5105. // Handles only images
  5106. return file.type.substring(0, 6) == 'image/';
  5107. }, function(queue)
  5108. {
  5109. // Invokes elements of queue in order
  5110. for (var i = 0; i < queue.length; i++)
  5111. {
  5112. queue[i]();
  5113. }
  5114. });
  5115. }
  5116. else
  5117. {
  5118. var pt = this.editor.graph.getInsertPoint();
  5119. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  5120. mxEvent.consume(evt);
  5121. }
  5122. break;
  5123. }
  5124. }
  5125. }
  5126. }
  5127. catch (e)
  5128. {
  5129. // ignore
  5130. }
  5131. }
  5132. }), false);
  5133. }
  5134. // Focused but invisible textarea during control or meta key events
  5135. var textInput = document.createElement('div');
  5136. textInput.style.position = 'absolute';
  5137. textInput.style.whiteSpace = 'nowrap';
  5138. textInput.style.overflow = 'hidden';
  5139. textInput.style.display = 'block';
  5140. textInput.contentEditable = true;
  5141. mxUtils.setOpacity(textInput, 0);
  5142. textInput.style.width = '1px';
  5143. textInput.style.height = '1px';
  5144. textInput.innerHTML = '&nbsp;';
  5145. var restoreFocus = false;
  5146. // Disables built-in cut, copy and paste shortcuts
  5147. this.keyHandler.bindControlKey(88, null);
  5148. this.keyHandler.bindControlKey(67, null);
  5149. this.keyHandler.bindControlKey(86, null);
  5150. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  5151. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  5152. {
  5153. // No dialog visible
  5154. var source = mxEvent.getSource(evt);
  5155. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  5156. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  5157. {
  5158. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  5159. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  5160. {
  5161. // Cannot use parentNode for check in IE
  5162. if (!restoreFocus)
  5163. {
  5164. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  5165. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  5166. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  5167. graph.container.appendChild(textInput);
  5168. restoreFocus = true;
  5169. // Workaround for selected document content in quirks mode
  5170. if (mxClient.IS_QUIRKS)
  5171. {
  5172. window.setTimeout(function()
  5173. {
  5174. textInput.focus();
  5175. document.execCommand('selectAll', false, null);
  5176. }, 0);
  5177. }
  5178. else
  5179. {
  5180. textInput.focus();
  5181. document.execCommand('selectAll', false, null);
  5182. }
  5183. }
  5184. }
  5185. }
  5186. }));
  5187. // Clears input and restores focus and selection
  5188. function clearInput()
  5189. {
  5190. window.setTimeout(function()
  5191. {
  5192. textInput.innerHTML = '&nbsp;';
  5193. textInput.focus();
  5194. document.execCommand('selectAll', false, null);
  5195. }, 0);
  5196. };
  5197. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  5198. {
  5199. // Workaround for asynchronous event read invalid in IE quirks mode
  5200. var keyCode = evt.keyCode;
  5201. // Asynchronous workaround for scroll to origin after paste if the
  5202. // Ctrl-key is not pressed for long enough in FF on Windows
  5203. window.setTimeout(mxUtils.bind(this, function()
  5204. {
  5205. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  5206. keyCode == 91 /* Meta */))
  5207. {
  5208. restoreFocus = false;
  5209. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  5210. {
  5211. graph.container.focus();
  5212. }
  5213. textInput.parentNode.removeChild(textInput);
  5214. }
  5215. }), 0);
  5216. }));
  5217. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  5218. {
  5219. if (graph.isEnabled())
  5220. {
  5221. mxClipboard.copy(graph);
  5222. this.copyCells(textInput);
  5223. clearInput();
  5224. }
  5225. }));
  5226. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  5227. {
  5228. if (graph.isEnabled())
  5229. {
  5230. this.copyCells(textInput, true);
  5231. clearInput();
  5232. }
  5233. }));
  5234. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  5235. {
  5236. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  5237. {
  5238. textInput.innerHTML = '&nbsp;';
  5239. textInput.focus();
  5240. window.setTimeout(mxUtils.bind(this, function()
  5241. {
  5242. this.pasteCells(evt, textInput);
  5243. textInput.innerHTML = '&nbsp;';
  5244. }), 0);
  5245. }
  5246. }), true);
  5247. // Needed for IE11
  5248. var isSelectionAllowed2 = this.isSelectionAllowed;
  5249. this.isSelectionAllowed = function(evt)
  5250. {
  5251. if (mxEvent.getSource(evt) == textInput)
  5252. {
  5253. return true;
  5254. }
  5255. return isSelectionAllowed2.apply(this, arguments);
  5256. };
  5257. };
  5258. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  5259. var x = document.body.clientWidth / 2 - 2;
  5260. // Holds the x-coordinate of the point
  5261. this.spinner = this.createSpinner(x, y, 24);
  5262. // Installs drag and drop handler for rich text editor
  5263. if (Graph.fileSupport)
  5264. {
  5265. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  5266. {
  5267. // Setup the dnd listeners
  5268. var graph = this.editor.graph;
  5269. var textElt = graph.cellEditor.text2;
  5270. var dropElt = null;
  5271. if (textElt != null)
  5272. {
  5273. mxEvent.addListener(textElt, 'dragleave', function(evt)
  5274. {
  5275. if (dropElt != null)
  5276. {
  5277. dropElt.parentNode.removeChild(dropElt);
  5278. dropElt = null;
  5279. }
  5280. evt.stopPropagation();
  5281. evt.preventDefault();
  5282. });
  5283. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  5284. {
  5285. // IE 10 does not implement pointer-events so it can't have a drop highlight
  5286. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  5287. {
  5288. dropElt = this.highlightElement(textElt);
  5289. }
  5290. evt.stopPropagation();
  5291. evt.preventDefault();
  5292. }));
  5293. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  5294. {
  5295. if (dropElt != null)
  5296. {
  5297. dropElt.parentNode.removeChild(dropElt);
  5298. dropElt = null;
  5299. }
  5300. if (evt.dataTransfer.files.length > 0)
  5301. {
  5302. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  5303. {
  5304. // Inserts image into current text box
  5305. graph.insertImage(data, w, h);
  5306. }, function()
  5307. {
  5308. // No post processing
  5309. }, function(file)
  5310. {
  5311. // Handles only images
  5312. return file.type.substring(0, 6) == 'image/';
  5313. }, function(queue)
  5314. {
  5315. // Invokes elements of queue in order
  5316. for (var i = 0; i < queue.length; i++)
  5317. {
  5318. queue[i]();
  5319. }
  5320. }, !mxEvent.isControlDown(evt));
  5321. }
  5322. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  5323. {
  5324. var uri = evt.dataTransfer.getData('text/uri-list');
  5325. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  5326. {
  5327. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  5328. {
  5329. var w = Math.max(1, img.width);
  5330. var h = Math.max(1, img.height);
  5331. var maxSize = this.maxImageSize;
  5332. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  5333. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  5334. }));
  5335. }
  5336. else
  5337. {
  5338. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  5339. }
  5340. }
  5341. else
  5342. {
  5343. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  5344. {
  5345. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  5346. }
  5347. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  5348. {
  5349. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  5350. }
  5351. }
  5352. evt.stopPropagation();
  5353. evt.preventDefault();
  5354. }));
  5355. }
  5356. }));
  5357. }
  5358. // Adds an element to edit the style in the footer in test mode
  5359. if (urlParams['test'] == '1')
  5360. {
  5361. var footer = document.getElementById('geFooter');
  5362. if (footer != null)
  5363. {
  5364. this.styleInput = document.createElement('input');
  5365. this.styleInput.setAttribute('type', 'text');
  5366. this.styleInput.style.position = 'absolute';
  5367. this.styleInput.style.top = '14px';
  5368. this.styleInput.style.left = '2px';
  5369. // Workaround for ignore right CSS property in FF
  5370. this.styleInput.style.width = '98%';
  5371. this.styleInput.style.visibility = 'hidden';
  5372. this.styleInput.style.opacity = '0.9';
  5373. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  5374. {
  5375. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  5376. }));
  5377. footer.appendChild(this.styleInput);
  5378. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  5379. {
  5380. if (this.editor.graph.getSelectionCount() > 0)
  5381. {
  5382. var cell = this.editor.graph.getSelectionCell();
  5383. var style = this.editor.graph.getModel().getStyle(cell);
  5384. this.styleInput.value = style || '';
  5385. this.styleInput.style.visibility = 'visible';
  5386. } else
  5387. {
  5388. this.styleInput.style.visibility = 'hidden';
  5389. }
  5390. }));
  5391. }
  5392. var isSelectionAllowed = this.isSelectionAllowed;
  5393. this.isSelectionAllowed = function(evt)
  5394. {
  5395. if (mxEvent.getSource(evt) == this.styleInput)
  5396. {
  5397. return true;
  5398. }
  5399. return isSelectionAllowed.apply(this, arguments);
  5400. };
  5401. }
  5402. // Removes info text in page
  5403. var info = document.getElementById('geInfo');
  5404. if (info != null)
  5405. {
  5406. info.parentNode.removeChild(info);
  5407. }
  5408. // Installs drag and drop handler for files
  5409. // Enables dropping files
  5410. if (Graph.fileSupport)
  5411. {
  5412. // Setup the dnd listeners
  5413. var dropElt = null;
  5414. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  5415. {
  5416. if (graph.isEnabled())
  5417. {
  5418. if (dropElt != null)
  5419. {
  5420. dropElt.parentNode.removeChild(dropElt);
  5421. dropElt = null;
  5422. }
  5423. evt.stopPropagation();
  5424. evt.preventDefault();
  5425. }
  5426. });
  5427. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  5428. {
  5429. // IE 10 does not implement pointer-events so it can't have a drop highlight
  5430. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  5431. {
  5432. dropElt = this.highlightElement(graph.container);
  5433. }
  5434. if (this.sidebar != null)
  5435. {
  5436. this.sidebar.hideTooltip();
  5437. }
  5438. evt.stopPropagation();
  5439. evt.preventDefault();
  5440. }));
  5441. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  5442. {
  5443. if (dropElt != null)
  5444. {
  5445. dropElt.parentNode.removeChild(dropElt);
  5446. dropElt = null;
  5447. }
  5448. if (graph.isEnabled())
  5449. {
  5450. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  5451. var tr = graph.view.translate;
  5452. var scale = graph.view.scale;
  5453. var x = pt.x / scale - tr.x;
  5454. var y = pt.y / scale - tr.y;
  5455. if (mxEvent.isAltDown(evt))
  5456. {
  5457. x = 0;
  5458. y = 0;
  5459. }
  5460. if (evt.dataTransfer.files.length > 0)
  5461. {
  5462. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  5463. !mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  5464. }
  5465. else
  5466. {
  5467. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  5468. evt.dataTransfer.getData('text/uri-list') : null;
  5469. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  5470. if (data != null)
  5471. {
  5472. graph.setSelectionCells(this.importXml(data, x, y, true));
  5473. }
  5474. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  5475. {
  5476. var html = evt.dataTransfer.getData('text/html');
  5477. var div = document.createElement('div');
  5478. div.innerHTML = html;
  5479. // The default is based on the extension
  5480. var asImage = null;
  5481. // Extracts single image
  5482. var imgs = div.getElementsByTagName('img');
  5483. if (imgs != null && imgs.length == 1)
  5484. {
  5485. html = imgs[0].getAttribute('src');
  5486. // Handles special case where the src attribute has no valid extension
  5487. // in which case the text would be inserted as text with a link
  5488. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  5489. {
  5490. asImage = true;
  5491. }
  5492. }
  5493. else
  5494. {
  5495. // Extracts single link
  5496. var a = div.getElementsByTagName('a');
  5497. if (a != null && a.length == 1)
  5498. {
  5499. html = a[0].getAttribute('href');
  5500. }
  5501. }
  5502. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage));
  5503. }
  5504. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  5505. {
  5506. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  5507. {
  5508. var w = Math.max(1, img.width);
  5509. var h = Math.max(1, img.height);
  5510. var maxSize = this.maxImageSize;
  5511. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  5512. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  5513. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5514. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  5515. }), mxUtils.bind(this, function(img)
  5516. {
  5517. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  5518. }));
  5519. }
  5520. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  5521. {
  5522. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  5523. }
  5524. }
  5525. }
  5526. evt.stopPropagation();
  5527. evt.preventDefault();
  5528. }), false);
  5529. }
  5530. this.initPages();
  5531. // Embedded mode
  5532. if (urlParams['embed'] == '1')
  5533. {
  5534. this.initializeEmbedMode();
  5535. }
  5536. if (typeof window.mxSettings !== 'undefined')
  5537. {
  5538. this.installSettings();
  5539. }
  5540. };
  5541. /**
  5542. * Creates the format panel and adds overrides.
  5543. */
  5544. EditorUi.prototype.installSettings = function()
  5545. {
  5546. if (isLocalStorage || mxClient.IS_CHROMEAPP)
  5547. {
  5548. // Gets recent colors from settings
  5549. ColorDialog.recentColors = mxSettings.getRecentColors();
  5550. /**
  5551. * Persists current edge style.
  5552. */
  5553. this.editor.graph.currentEdgeStyle = mxSettings.getCurrentEdgeStyle();
  5554. this.editor.graph.currentVertexStyle = mxSettings.getCurrentVertexStyle();
  5555. // Updates UI to reflect current edge style
  5556. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  5557. this.addListener('styleChanged', mxUtils.bind(this, function(sender, evt)
  5558. {
  5559. mxSettings.setCurrentEdgeStyle(this.editor.graph.currentEdgeStyle);
  5560. mxSettings.setCurrentVertexStyle(this.editor.graph.currentVertexStyle);
  5561. mxSettings.save();
  5562. }));
  5563. /**
  5564. * Persists copy on connect switch.
  5565. */
  5566. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  5567. this.fireEvent(new mxEventObject('copyConnectChanged'));
  5568. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  5569. {
  5570. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  5571. mxSettings.save();
  5572. }));
  5573. /**
  5574. * Persists default page format.
  5575. */
  5576. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  5577. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  5578. {
  5579. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  5580. mxSettings.save();
  5581. }));
  5582. /**
  5583. * Persists default grid color.
  5584. */
  5585. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  5586. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  5587. {
  5588. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  5589. mxSettings.save();
  5590. }));
  5591. /**
  5592. * Persists autosave switch in Chrome app.
  5593. */
  5594. if (mxClient.IS_CHROMEAPP)
  5595. {
  5596. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  5597. {
  5598. mxSettings.setAutosave(this.editor.autosave);
  5599. mxSettings.save();
  5600. }));
  5601. this.editor.autosave = mxSettings.getAutosave();
  5602. }
  5603. /**
  5604. *
  5605. */
  5606. if (this.sidebar != null)
  5607. {
  5608. this.sidebar.showPalette('search', mxSettings.settings.search);
  5609. }
  5610. /**
  5611. * Shows scratchpad if never shown.
  5612. */
  5613. if (!this.editor.chromeless && this.sidebar != null && (mxSettings.settings.isNew ||
  5614. parseInt(mxSettings.settings.version || 0) <= 8))
  5615. {
  5616. this.toggleScratchpad();
  5617. mxSettings.save();
  5618. }
  5619. // Saves app defaults for UI
  5620. this.addListener('formatWidthChanged', function()
  5621. {
  5622. mxSettings.setFormatWidth(this.formatWidth);
  5623. mxSettings.save();
  5624. });
  5625. }
  5626. };
  5627. /**
  5628. * Creates the format panel and adds overrides.
  5629. */
  5630. EditorUi.prototype.copyCells = function(elt, removeCells)
  5631. {
  5632. var graph = this.editor.graph;
  5633. if (!graph.isSelectionEmpty())
  5634. {
  5635. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  5636. // LATER: Add span with XML in data attribute
  5637. // var span = document.createElement('span');
  5638. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  5639. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  5640. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  5641. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  5642. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  5643. if (removeCells)
  5644. {
  5645. graph.removeCells(cells, false);
  5646. graph.lastPasteXml = null;
  5647. }
  5648. else
  5649. {
  5650. graph.lastPasteXml = xml;
  5651. graph.pasteCounter = 0;
  5652. }
  5653. elt.focus();
  5654. document.execCommand('selectAll', false, null);
  5655. }
  5656. else
  5657. {
  5658. // Disables copy on focused element
  5659. elt.innerHTML = '';
  5660. }
  5661. };
  5662. /**
  5663. * Creates the format panel and adds overrides.
  5664. */
  5665. EditorUi.prototype.pasteCells = function(evt, elt)
  5666. {
  5667. if (!mxEvent.isConsumed(evt))
  5668. {
  5669. var spans = elt.getElementsByTagName('span');
  5670. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  5671. 'application/vnd.lucid.chart.objects')
  5672. {
  5673. var content = spans[0].getAttribute('data-lucid-content');
  5674. if (content != null && content.length > 0)
  5675. {
  5676. this.insertLucidChart(JSON.parse(content));
  5677. mxEvent.consume(evt);
  5678. }
  5679. }
  5680. else
  5681. {
  5682. var graph = this.editor.graph;
  5683. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  5684. mxUtils.getTextContent(elt) : elt.textContent);
  5685. var compat = false;
  5686. // Workaround for junk after XML in VM
  5687. try
  5688. {
  5689. var idx = xml.lastIndexOf('%3E');
  5690. if (idx >= 0 && idx < xml.length - 3)
  5691. {
  5692. xml = xml.substring(0, idx + 3);
  5693. }
  5694. }
  5695. catch (e)
  5696. {
  5697. // ignore
  5698. }
  5699. // Checks for embedded XML content
  5700. try
  5701. {
  5702. var spans = elt.getElementsByTagName('span');
  5703. var tmp = (spans != null && spans.length > 0) ?
  5704. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  5705. decodeURIComponent(xml);
  5706. if (this.isCompatibleString(tmp))
  5707. {
  5708. compat = true;
  5709. xml = tmp;
  5710. }
  5711. }
  5712. catch (e)
  5713. {
  5714. // ignore
  5715. }
  5716. if (graph.lastPasteXml == xml)
  5717. {
  5718. graph.pasteCounter++;
  5719. }
  5720. else
  5721. {
  5722. graph.lastPasteXml = xml;
  5723. graph.pasteCounter = 0;
  5724. }
  5725. var dx = graph.pasteCounter * graph.gridSize;
  5726. if (xml != null && xml.length > 0)
  5727. {
  5728. if (compat || this.isCompatibleString(xml))
  5729. {
  5730. graph.setSelectionCells(this.importXml(xml, dx, dx));
  5731. }
  5732. else
  5733. {
  5734. var pt = graph.getInsertPoint();
  5735. if (graph.isMouseInsertPoint())
  5736. {
  5737. dx = 0;
  5738. // No offset for insert at mouse position
  5739. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  5740. {
  5741. graph.pasteCounter--;
  5742. }
  5743. }
  5744. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  5745. }
  5746. if (!graph.isSelectionEmpty())
  5747. {
  5748. graph.scrollCellToVisible(graph.getSelectionCell());
  5749. if (this.hoverIcons != null)
  5750. {
  5751. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  5752. }
  5753. try
  5754. {
  5755. mxEvent.consume(evt);
  5756. }
  5757. catch (e)
  5758. {
  5759. // ignore event no longer exists in async handler in IE8-
  5760. }
  5761. }
  5762. }
  5763. }
  5764. }
  5765. };
  5766. /**
  5767. * Adds a file drop handler for opening local files.
  5768. */
  5769. EditorUi.prototype.addFileDropHandler = function(elts)
  5770. {
  5771. // Installs drag and drop handler for files
  5772. if (Graph.fileSupport)
  5773. {
  5774. var dropElt = null;
  5775. for (var i = 0; i < elts.length; i++)
  5776. {
  5777. // Setup the dnd listeners
  5778. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  5779. {
  5780. if (dropElt != null)
  5781. {
  5782. dropElt.parentNode.removeChild(dropElt);
  5783. dropElt = null;
  5784. }
  5785. evt.stopPropagation();
  5786. evt.preventDefault();
  5787. });
  5788. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  5789. {
  5790. // IE 10 does not implement pointer-events so it can't have a drop highlight
  5791. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  5792. {
  5793. dropElt = this.highlightElement();
  5794. }
  5795. evt.stopPropagation();
  5796. evt.preventDefault();
  5797. }));
  5798. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  5799. {
  5800. if (dropElt != null)
  5801. {
  5802. dropElt.parentNode.removeChild(dropElt);
  5803. dropElt = null;
  5804. }
  5805. if (evt.dataTransfer.files.length > 0)
  5806. {
  5807. this.hideDialog();
  5808. // Never open files in embed mode
  5809. if (urlParams['embed'] == '1')
  5810. {
  5811. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  5812. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  5813. }
  5814. else
  5815. {
  5816. this.openFiles(evt.dataTransfer.files);
  5817. }
  5818. }
  5819. else
  5820. {
  5821. // Handles open special files via text drag and drop
  5822. var data = this.extractGraphModelFromEvent(evt);
  5823. // Tries additional and async parsing of text content such as HTML, Gliffy data
  5824. if (data == null)
  5825. {
  5826. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  5827. if (provider != null)
  5828. {
  5829. if (document.documentMode == 10 || document.documentMode == 11)
  5830. {
  5831. data = provider.getData('Text');
  5832. }
  5833. else
  5834. {
  5835. var data = null;
  5836. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  5837. {
  5838. var data = evt.dataTransfer.getData('text/uri-list');
  5839. }
  5840. else
  5841. {
  5842. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  5843. }
  5844. if (data != null && data.length > 0)
  5845. {
  5846. var div = document.createElement('div');
  5847. div.innerHTML = data;
  5848. // Extracts single image
  5849. var imgs = div.getElementsByTagName('img');
  5850. if (imgs.length > 0)
  5851. {
  5852. data = imgs[0].getAttribute('src');
  5853. }
  5854. }
  5855. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  5856. {
  5857. data = provider.getData('text/plain');
  5858. }
  5859. }
  5860. if (data != null)
  5861. {
  5862. // Checks for embedded XML in PNG
  5863. if (data.substring(0, 22) == 'data:image/png;base64,')
  5864. {
  5865. var xml = this.extractGraphModelFromPng(data);
  5866. if (xml != null && xml.length > 0)
  5867. {
  5868. this.openLocalFile(xml, null, true);
  5869. }
  5870. }
  5871. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  5872. {
  5873. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  5874. {
  5875. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  5876. {
  5877. this.openLocalFile(req.getText(), null, true);
  5878. }
  5879. }));
  5880. }
  5881. else if (/^https?:\/\//.test(data))
  5882. {
  5883. if (this.getCurrentFile() == null)
  5884. {
  5885. window.location.hash = '#U' + encodeURIComponent(data);
  5886. }
  5887. else
  5888. {
  5889. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  5890. 'https://www.draw.io/' : 'https://' + location.host + '/') +
  5891. window.location.search + '#U' + encodeURIComponent(data));
  5892. }
  5893. }
  5894. }
  5895. }
  5896. }
  5897. else
  5898. {
  5899. this.openLocalFile(data, null, true);
  5900. }
  5901. }
  5902. evt.stopPropagation();
  5903. evt.preventDefault();
  5904. }));
  5905. }
  5906. }
  5907. };
  5908. /**
  5909. * Highlights the given element
  5910. */
  5911. EditorUi.prototype.highlightElement = function(elt)
  5912. {
  5913. var x = 0;
  5914. var y = 0;
  5915. var w = 0;
  5916. var h = 0;
  5917. if (elt == null)
  5918. {
  5919. var b = document.body;
  5920. var d = document.documentElement;
  5921. w = (b.clientWidth || d.clientWidth) - 3;
  5922. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  5923. }
  5924. else
  5925. {
  5926. x = elt.offsetTop;
  5927. y = elt.offsetLeft;
  5928. w = elt.clientWidth;
  5929. h = elt.clientHeight;
  5930. }
  5931. var hl = document.createElement('div');
  5932. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  5933. hl.style.border = '3px dotted rgb(254, 137, 12)';
  5934. hl.style.pointerEvents = 'none';
  5935. hl.style.position = 'absolute';
  5936. hl.style.top = x + 'px';
  5937. hl.style.left = y + 'px';
  5938. hl.style.width = Math.max(0, w - 3) + 'px';
  5939. hl.style.height = Math.max(0, h - 3) + 'px';
  5940. if (elt != null && elt.parentNode == this.editor.graph.container)
  5941. {
  5942. this.editor.graph.container.appendChild(hl);
  5943. }
  5944. else
  5945. {
  5946. document.body.appendChild(hl);
  5947. }
  5948. return hl;
  5949. };
  5950. /**
  5951. * Highlights the given element
  5952. */
  5953. EditorUi.prototype.stringToCells = function(xml)
  5954. {
  5955. var doc = mxUtils.parseXml(xml);
  5956. var node = this.editor.extractGraphModel(doc.documentElement);
  5957. var cells = [];
  5958. if (node != null)
  5959. {
  5960. var codec = new mxCodec(node.ownerDocument);
  5961. var model = new mxGraphModel();
  5962. codec.decode(node, model);
  5963. var parent = model.getChildAt(model.getRoot(), 0);
  5964. for (var j = 0; j < model.getChildCount(parent); j++)
  5965. {
  5966. cells.push(model.getChildAt(parent, j));
  5967. }
  5968. }
  5969. return cells;
  5970. };
  5971. /**
  5972. * Opens the given files in the editor.
  5973. */
  5974. EditorUi.prototype.openFiles = function(files)
  5975. {
  5976. if (this.spinner.spin(document.body, mxResources.get('loading')))
  5977. {
  5978. for (var i = 0; i < files.length; i++)
  5979. {
  5980. (mxUtils.bind(this, function(file)
  5981. {
  5982. var reader = new FileReader();
  5983. reader.onload = mxUtils.bind(this, function(e)
  5984. {
  5985. var data = e.target.result;
  5986. var name = file.name;
  5987. if (name != null && name.length > 0)
  5988. {
  5989. if (/(\.png)$/i.test(name))
  5990. {
  5991. name = name.substring(0, name.length - 4) + '.xml';
  5992. }
  5993. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  5994. this.isRemoteFileFormat(data, name))
  5995. {
  5996. var dot = name.lastIndexOf('.');
  5997. if (dot >= 0)
  5998. {
  5999. name = name.substring(0, name.lastIndexOf('.')) + '.xml';
  6000. }
  6001. else
  6002. {
  6003. name = name + '.xml';
  6004. }
  6005. this.parseFile(file, mxUtils.bind(this, function(xhr)
  6006. {
  6007. if (xhr.readyState == 4)
  6008. {
  6009. this.spinner.stop();
  6010. if (xhr.status >= 200 && xhr.status <= 299)
  6011. {
  6012. this.openLocalFile(xhr.responseText, name);
  6013. }
  6014. else
  6015. {
  6016. this.handleError({message: mxResources.get((xhr.status == 413) ?
  6017. 'drawingTooLarge' : 'invalidOrMissingFile')},
  6018. mxResources.get('errorLoadingFile'));
  6019. }
  6020. }
  6021. }));
  6022. }
  6023. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  6024. {
  6025. this.spinner.stop();
  6026. try
  6027. {
  6028. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  6029. }
  6030. catch (e)
  6031. {
  6032. this.handleError(e, mxResources.get('errorLoadingFile'));
  6033. }
  6034. }
  6035. else
  6036. {
  6037. if (file.type.substring(0, 9) == 'image/png')
  6038. {
  6039. data = this.extractGraphModelFromPng(data);
  6040. }
  6041. this.spinner.stop();
  6042. this.openLocalFile(data, name);
  6043. }
  6044. }
  6045. });
  6046. reader.onerror = mxUtils.bind(this, function(e)
  6047. {
  6048. this.spinner.stop();
  6049. this.handleError(e);
  6050. window.openFile = null;
  6051. });
  6052. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  6053. {
  6054. reader.readAsDataURL(file);
  6055. }
  6056. else
  6057. {
  6058. reader.readAsText(file);
  6059. }
  6060. }))(files[i]);
  6061. }
  6062. }
  6063. };
  6064. /**
  6065. * Shows the layers dialog if the graph has more than one layer.
  6066. */
  6067. EditorUi.prototype.openLocalFile = function(data, name, temp)
  6068. {
  6069. var currentFile = this.getCurrentFile();
  6070. var fn = mxUtils.bind(this, function()
  6071. {
  6072. window.openFile = null;
  6073. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  6074. {
  6075. var doc = mxUtils.parseXml(data);
  6076. if (doc != null)
  6077. {
  6078. this.editor.setGraphXml(doc.documentElement);
  6079. this.editor.graph.selectAll();
  6080. }
  6081. }
  6082. else
  6083. {
  6084. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  6085. }
  6086. });
  6087. if (data != null && data.length > 0)
  6088. {
  6089. if (currentFile == null || !currentFile.isModified())
  6090. {
  6091. fn();
  6092. }
  6093. else
  6094. {
  6095. window.openFile = new OpenFile(function()
  6096. {
  6097. window.openFile = null;
  6098. });
  6099. window.openFile.setData(data, name);
  6100. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  6101. {
  6102. this.confirm(mxResources.get('allChangesLost'), null, fn,
  6103. mxResources.get('cancel'), mxResources.get('discardChanges'));
  6104. }));
  6105. }
  6106. }
  6107. };
  6108. /**
  6109. * Returns a list of all shapes used in the current file.
  6110. */
  6111. EditorUi.prototype.getBasenames = function()
  6112. {
  6113. var basenames = {};
  6114. if (this.pages != null)
  6115. {
  6116. for (var i = 0; i < this.pages.length; i++)
  6117. {
  6118. this.updatePageRoot(this.pages[i]);
  6119. this.addBasenamesForCell(this.pages[i].root, basenames);
  6120. }
  6121. }
  6122. else
  6123. {
  6124. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  6125. }
  6126. var result = [];
  6127. for (var key in basenames)
  6128. {
  6129. result.push(key);
  6130. }
  6131. return result;
  6132. };
  6133. /**
  6134. * Returns a list of all shapes used in the current file.
  6135. */
  6136. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  6137. {
  6138. function addName(name)
  6139. {
  6140. if (name != null)
  6141. {
  6142. // LATER: Check if this case exists
  6143. var dot = name.lastIndexOf('.');
  6144. if (dot > 0)
  6145. {
  6146. name = name.substring(dot + 1, name.length);
  6147. }
  6148. if (basenames[name] == null)
  6149. {
  6150. basenames[name] = true;
  6151. }
  6152. }
  6153. };
  6154. var graph = this.editor.graph;
  6155. var style = graph.getCellStyle(cell);
  6156. var shape = style[mxConstants.STYLE_SHAPE];
  6157. addName(mxStencilRegistry.getBasenameForStencil(shape));
  6158. // Adds package names for markers in edges
  6159. if (graph.model.isEdge(cell))
  6160. {
  6161. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  6162. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  6163. }
  6164. var childCount = graph.model.getChildCount(cell);
  6165. for (var i = 0; i < childCount; i++)
  6166. {
  6167. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  6168. }
  6169. };
  6170. /**
  6171. * Shows the layers dialog if the graph has more than one layer.
  6172. */
  6173. EditorUi.prototype.setGraphEnabled = function(enabled)
  6174. {
  6175. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  6176. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  6177. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  6178. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  6179. this.hsplit.style.display = (enabled) ? '' : 'none';
  6180. this.editor.graph.setEnabled(enabled);
  6181. };
  6182. /**
  6183. * Shows the layers dialog if the graph has more than one layer.
  6184. */
  6185. EditorUi.prototype.initializeEmbedMode = function()
  6186. {
  6187. this.setGraphEnabled(false);
  6188. var parent = window.opener || window.parent;
  6189. if (parent != window)
  6190. {
  6191. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  6192. {
  6193. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  6194. {
  6195. this.spinner.stop();
  6196. this.addEmbedButtons();
  6197. this.setGraphEnabled(true);
  6198. if (xml != null && xml.length > 0)
  6199. {
  6200. this.setFileData(xml);
  6201. this.showLayersDialog();
  6202. }
  6203. else
  6204. {
  6205. this.editor.graph.model.clear();
  6206. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  6207. }
  6208. this.editor.undoManager.clear();
  6209. this.editor.modified = (modified != null) ? modified : false;
  6210. this.updateUi();
  6211. // Workaround for no initial focus in FF
  6212. // (does not work in Conf Cloud with FF)
  6213. if (window.self !== window.top)
  6214. {
  6215. window.focus();
  6216. }
  6217. if (this.format != null)
  6218. {
  6219. this.format.refresh();
  6220. }
  6221. }));
  6222. }
  6223. }
  6224. };
  6225. /**
  6226. * Shows the layers dialog if the graph has more than one layer.
  6227. */
  6228. EditorUi.prototype.showLayersDialog = function()
  6229. {
  6230. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  6231. {
  6232. if (this.actions.layersWindow == null)
  6233. {
  6234. this.actions.get('layers').funct();
  6235. }
  6236. else
  6237. {
  6238. this.actions.layersWindow.window.setVisible(true);
  6239. }
  6240. }
  6241. };
  6242. /**
  6243. * Tries to find a public URL for the given file.
  6244. */
  6245. EditorUi.prototype.getPublicUrl = function(file, fn)
  6246. {
  6247. if (file != null)
  6248. {
  6249. file.getPublicUrl(fn);
  6250. }
  6251. else
  6252. {
  6253. fn(null);
  6254. }
  6255. };
  6256. /**
  6257. * Adds the buttons for embedded mode.
  6258. */
  6259. EditorUi.prototype.createLoadMessage = function(eventName)
  6260. {
  6261. var graph = this.editor.graph;
  6262. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  6263. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds(), bounds: graph.getGraphBounds()};
  6264. };
  6265. /**
  6266. * Adds the buttons for embedded mode.
  6267. */
  6268. EditorUi.prototype.installMessageHandler = function(fn)
  6269. {
  6270. var changeListener = null;
  6271. var ignoreChange = false;
  6272. var autosave = false;
  6273. var lastData = null;
  6274. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  6275. {
  6276. if (!this.editor.modified || urlParams['modified'] == '0')
  6277. {
  6278. this.editor.setStatus('');
  6279. }
  6280. else if (urlParams['modified'] != null)
  6281. {
  6282. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  6283. }
  6284. });
  6285. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  6286. // Receives XML message from opener and puts it into the graph
  6287. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  6288. {
  6289. var data = evt.data;
  6290. function extractDiagramXml(data)
  6291. {
  6292. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  6293. {
  6294. try
  6295. {
  6296. if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  6297. {
  6298. data = atob(data.substring(26));
  6299. }
  6300. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  6301. {
  6302. data = data.substring(24);
  6303. }
  6304. if (data != null)
  6305. {
  6306. if (data.charAt(0) == '%')
  6307. {
  6308. data = decodeURIComponent(data);
  6309. }
  6310. else if (data.charAt(0) != '<')
  6311. {
  6312. data = this.editor.graph.decompress(data);
  6313. }
  6314. }
  6315. }
  6316. catch (e)
  6317. {
  6318. // ignore compression errors and use empty data
  6319. }
  6320. }
  6321. return data;
  6322. };
  6323. if (urlParams['proto'] == 'json')
  6324. {
  6325. try
  6326. {
  6327. data = JSON.parse(data);
  6328. }
  6329. catch (e)
  6330. {
  6331. data = null;
  6332. }
  6333. if (data == null)
  6334. {
  6335. // Ignore
  6336. return;
  6337. }
  6338. else if (data.action == 'dialog')
  6339. {
  6340. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  6341. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  6342. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  6343. if (data.modified != null)
  6344. {
  6345. this.editor.modified = data.modified;
  6346. }
  6347. return;
  6348. }
  6349. else if (data.action == 'prompt')
  6350. {
  6351. this.spinner.stop();
  6352. var dlg = new FilenameDialog(this, data.defaultValue || '',
  6353. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  6354. {
  6355. if (value != null)
  6356. {
  6357. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  6358. }
  6359. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  6360. this.showDialog(dlg.container, 300, 80, true, false);
  6361. dlg.init();
  6362. return;
  6363. }
  6364. else if (data.action == 'draft')
  6365. {
  6366. var tmp = null;
  6367. if (data.xml.substring(0, 22) == 'data:image/png;base64,')
  6368. {
  6369. tmp = this.extractGraphModelFromPng(data.xml);
  6370. }
  6371. else
  6372. {
  6373. tmp = extractDiagramXml(data.xml);
  6374. }
  6375. this.spinner.stop();
  6376. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  6377. tmp, mxUtils.bind(this, function()
  6378. {
  6379. this.hideDialog();
  6380. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  6381. }), mxUtils.bind(this, function()
  6382. {
  6383. this.hideDialog();
  6384. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  6385. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  6386. (data.discardKey) ? mxResources.get(data.discardKey) : null);
  6387. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  6388. {
  6389. if (cancel)
  6390. {
  6391. this.actions.get('exit').funct();
  6392. }
  6393. }));
  6394. try
  6395. {
  6396. dlg.init();
  6397. }
  6398. catch (e)
  6399. {
  6400. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  6401. }
  6402. return;
  6403. }
  6404. else if (data.action == 'template')
  6405. {
  6406. this.spinner.stop();
  6407. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  6408. {
  6409. xml = xml || this.emptyDiagramXml;
  6410. // LATER: Add autosave option in template message
  6411. if (data.callback != null)
  6412. {
  6413. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  6414. blank: xml == this.emptyDiagramXml, name: name}), '*');
  6415. }
  6416. else
  6417. {
  6418. fn(xml, evt, xml != this.emptyDiagramXml);
  6419. // Workaround for status updated before modified applied
  6420. if (!this.editor.modified)
  6421. {
  6422. this.editor.setStatus('');
  6423. }
  6424. }
  6425. }));
  6426. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  6427. {
  6428. if (cancel)
  6429. {
  6430. this.actions.get('exit').funct();
  6431. }
  6432. }));
  6433. dlg.init();
  6434. return;
  6435. }
  6436. else if (data.action == 'status')
  6437. {
  6438. if (data.messageKey != null)
  6439. {
  6440. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  6441. }
  6442. else if (data.message != null)
  6443. {
  6444. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  6445. }
  6446. if (data.modified != null)
  6447. {
  6448. this.editor.modified = data.modified;
  6449. }
  6450. return;
  6451. }
  6452. else if (data.action == 'spinner')
  6453. {
  6454. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  6455. if (data.show != null && !data.show)
  6456. {
  6457. this.spinner.stop();
  6458. }
  6459. else
  6460. {
  6461. this.spinner.spin(document.body, msg)
  6462. }
  6463. return;
  6464. }
  6465. else if (data.action == 'export')
  6466. {
  6467. if (data.format == 'png' || data.format == 'xmlpng')
  6468. {
  6469. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  6470. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  6471. {
  6472. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  6473. this.editor.graph.setEnabled(false);
  6474. var graph = this.editor.graph;
  6475. var postDataBack = mxUtils.bind(this, function(uri)
  6476. {
  6477. this.editor.graph.setEnabled(true);
  6478. this.spinner.stop();
  6479. var msg = this.createLoadMessage('export');
  6480. msg.format = data.format;
  6481. msg.xml = encodeURIComponent(xml);
  6482. msg.data = uri;
  6483. parent.postMessage(JSON.stringify(msg), '*');
  6484. });
  6485. var processUri = mxUtils.bind(this, function(uri)
  6486. {
  6487. if (uri == null)
  6488. {
  6489. uri = Editor.blankImage;
  6490. }
  6491. if (data.format == 'xmlpng')
  6492. {
  6493. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  6494. atob(this.editor.graph.compress(xml)));
  6495. }
  6496. // Removes temporary graph from DOM
  6497. if (graph != this.editor.graph)
  6498. {
  6499. graph.container.parentNode.removeChild(graph.container);
  6500. }
  6501. postDataBack(uri);
  6502. });
  6503. // LATER: Uses external export if current page (not first page) has mathEnabled
  6504. if (this.isExportToCanvas())
  6505. {
  6506. // Exports PNG for first page while other page is visible by creating a graph
  6507. // LATER: Add caching for the graph or SVG while not on first page
  6508. if (this.pages != null && this.currentPage != this.pages[0])
  6509. {
  6510. graph = this.createTemporaryGraph(graph.getStylesheet());
  6511. var graphGetGlobalVariable = graph.getGlobalVariable;
  6512. var page = this.pages[0];
  6513. graph.getGlobalVariable = function(name)
  6514. {
  6515. if (name == 'page')
  6516. {
  6517. return page.getName();
  6518. }
  6519. else if (name == 'pagenumber')
  6520. {
  6521. return 1;
  6522. }
  6523. return graphGetGlobalVariable.apply(this, arguments);
  6524. };
  6525. document.body.appendChild(graph.container);
  6526. graph.model.setRoot(page.root);
  6527. }
  6528. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  6529. {
  6530. processUri(canvas.toDataURL('image/png'));
  6531. }), null, null, null, mxUtils.bind(this, function()
  6532. {
  6533. processUri(null);
  6534. }), null, null, null, null, null, null, graph);
  6535. }
  6536. else
  6537. {
  6538. // Data from server is base64 encoded to avoid binary XHR
  6539. // Double encoding for XML arg is needed for UTF8 encoding
  6540. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  6541. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  6542. encodeURIComponent(encodeURIComponent(xml)));
  6543. req.send(mxUtils.bind(this, function(req)
  6544. {
  6545. // Temp graph was never created at this point so we can
  6546. // skip processUri since it already contains the XML
  6547. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  6548. {
  6549. postDataBack('data:image/png;base64,' + req.getText());
  6550. }
  6551. else
  6552. {
  6553. processUri(null);
  6554. }
  6555. }), mxUtils.bind(this, function()
  6556. {
  6557. processUri(null);
  6558. }));
  6559. }
  6560. }
  6561. }
  6562. else
  6563. {
  6564. // SVG is generated from graph so parse optional XML
  6565. if (data.xml != null && data.xml.length > 0)
  6566. {
  6567. this.setFileData(data.xml);
  6568. }
  6569. var msg = this.createLoadMessage('export');
  6570. // Forces new HTML format if pages exists
  6571. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  6572. (this.pages != null && this.pages.length > 1))))
  6573. {
  6574. var node = this.getXmlFileData();
  6575. msg.xml = mxUtils.getXml(node);
  6576. msg.data = this.getFileData(null, null, true, null, null, null, node);
  6577. msg.format = data.format;
  6578. }
  6579. else if (data.format == 'html')
  6580. {
  6581. var xml = this.editor.getGraphXml();
  6582. msg.data = this.getHtml(xml, this.editor.graph);
  6583. msg.xml = mxUtils.getXml(xml);
  6584. msg.format = data.format;
  6585. }
  6586. else
  6587. {
  6588. // Creates a preview with no alt text for unsupported browsers
  6589. mxSvgCanvas2D.prototype.foAltText = null;
  6590. var bg = this.editor.graph.background;
  6591. if (bg == mxConstants.NONE)
  6592. {
  6593. bg = null;
  6594. }
  6595. msg.xml = this.getFileData(true);
  6596. msg.format = 'svg';
  6597. if (data.embedImages || data.embedImages == null)
  6598. {
  6599. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  6600. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  6601. {
  6602. this.editor.graph.setEnabled(false);
  6603. if (data.format == 'xmlsvg')
  6604. {
  6605. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  6606. {
  6607. this.editor.graph.setEnabled(true);
  6608. this.spinner.stop();
  6609. msg.data = this.createSvgDataUri(svg);
  6610. parent.postMessage(JSON.stringify(msg), '*');
  6611. }));
  6612. }
  6613. else
  6614. {
  6615. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  6616. {
  6617. this.editor.graph.setEnabled(true);
  6618. this.spinner.stop();
  6619. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6620. parent.postMessage(JSON.stringify(msg), '*');
  6621. }));
  6622. }
  6623. }
  6624. return;
  6625. }
  6626. else
  6627. {
  6628. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  6629. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  6630. msg.data = this.createSvgDataUri(svg);
  6631. }
  6632. }
  6633. parent.postMessage(JSON.stringify(msg), '*');
  6634. }
  6635. return;
  6636. }
  6637. else if (data.action == 'load')
  6638. {
  6639. autosave = data.autosave == 1;
  6640. this.hideDialog();
  6641. if (data.modified != null && urlParams['modified'] == null)
  6642. {
  6643. urlParams['modified'] = data.modified;
  6644. }
  6645. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  6646. {
  6647. urlParams['saveAndExit'] = data.saveAndExit;
  6648. }
  6649. if (data.title != null && this.buttonContainer != null)
  6650. {
  6651. var tmp = document.createElement('span');
  6652. mxUtils.write(tmp, data.title);
  6653. if (uiTheme == 'atlas')
  6654. {
  6655. this.buttonContainer.style.paddingRight = '12px';
  6656. this.buttonContainer.style.paddingTop = '12px';
  6657. }
  6658. else
  6659. {
  6660. this.buttonContainer.style.paddingRight = '38px';
  6661. this.buttonContainer.style.paddingTop = '6px';
  6662. }
  6663. this.buttonContainer.appendChild(tmp);
  6664. }
  6665. if (data.xmlpng != null)
  6666. {
  6667. data = this.extractGraphModelFromPng(data.xmlpng);
  6668. }
  6669. else if (data.xml != null && data.xml.substring(0, 22) == 'data:image/png;base64,')
  6670. {
  6671. data = this.extractGraphModelFromPng(data.xml);
  6672. }
  6673. else
  6674. {
  6675. data = data.xml;
  6676. }
  6677. }
  6678. else
  6679. {
  6680. // Unknown message must stop execution
  6681. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  6682. return;
  6683. }
  6684. }
  6685. data = extractDiagramXml(data);
  6686. ignoreChange = true;
  6687. try
  6688. {
  6689. fn(data, evt);
  6690. }
  6691. catch (e)
  6692. {
  6693. this.handleError(e);
  6694. }
  6695. ignoreChange = false;
  6696. if (urlParams['modified'] != null)
  6697. {
  6698. this.editor.setStatus('');
  6699. }
  6700. var getData = mxUtils.bind(this, function()
  6701. {
  6702. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  6703. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  6704. });;
  6705. lastData = getData();
  6706. if (autosave && changeListener == null)
  6707. {
  6708. changeListener = mxUtils.bind(this, function(sender, eventObject)
  6709. {
  6710. var data = getData();
  6711. if (data != lastData && !ignoreChange)
  6712. {
  6713. var msg = this.createLoadMessage('autosave');
  6714. msg.xml = data;
  6715. data = JSON.stringify(msg);
  6716. var parent = window.opener || window.parent;
  6717. parent.postMessage(data, '*');
  6718. }
  6719. lastData = data;
  6720. });
  6721. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  6722. // Some options trigger autosave
  6723. this.editor.graph.addListener('gridSizeChanged', changeListener);
  6724. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  6725. this.addListener('pageFormatChanged', changeListener);
  6726. this.addListener('pageScaleChanged', changeListener);
  6727. this.addListener('backgroundColorChanged', changeListener);
  6728. this.addListener('backgroundImageChanged', changeListener);
  6729. this.addListener('foldingEnabledChanged', changeListener);
  6730. this.addListener('mathEnabledChanged', changeListener);
  6731. this.addListener('gridEnabledChanged', changeListener);
  6732. this.addListener('guidesEnabledChanged', changeListener);
  6733. this.addListener('pageViewChanged', changeListener);
  6734. }
  6735. // Sends the bounds of the graph to the host after parsing
  6736. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  6737. {
  6738. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  6739. }
  6740. }));
  6741. // Requests data from the sender. This is a workaround for not allowing
  6742. // the opener to listen for the onload event if not in the same origin.
  6743. var parent = window.opener || window.parent;
  6744. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  6745. parent.postMessage(msg, '*');
  6746. };
  6747. /**
  6748. * Adds the buttons for embedded mode.
  6749. */
  6750. EditorUi.prototype.addEmbedButtons = function()
  6751. {
  6752. if (this.menubar != null)
  6753. {
  6754. var div = document.createElement('div');
  6755. div.style.display = 'inline-block';
  6756. div.style.position = 'absolute';
  6757. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  6758. div.style.paddingLeft = '8px';
  6759. div.style.paddingBottom = '2px';
  6760. var button = document.createElement('button');
  6761. mxUtils.write(button, mxResources.get('save'));
  6762. button.setAttribute('title', mxResources.get('save') + ' (Ctrl+S)');
  6763. button.className = 'geBigButton';
  6764. button.style.fontSize = '12px';
  6765. button.style.padding = '4px 6px 4px 6px';
  6766. button.style.borderRadius = '3px';
  6767. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  6768. {
  6769. this.actions.get('save').funct();
  6770. }));
  6771. div.appendChild(button);
  6772. if (urlParams['saveAndExit'] == '1')
  6773. {
  6774. button = document.createElement('a');
  6775. mxUtils.write(button, mxResources.get('saveAndExit'));
  6776. button.setAttribute('title', mxResources.get('saveAndExit'));
  6777. button.style.fontSize = '12px';
  6778. button.style.marginLeft = '6px';
  6779. button.style.padding = '4px';
  6780. button.style.cursor = 'pointer';
  6781. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  6782. {
  6783. this.actions.get('saveAndExit').funct();
  6784. }));
  6785. div.appendChild(button);
  6786. }
  6787. button = document.createElement('a');
  6788. mxUtils.write(button, mxResources.get('exit'));
  6789. button.setAttribute('title', mxResources.get('exit'));
  6790. button.style.fontSize = '12px';
  6791. button.style.marginLeft = '6px';
  6792. button.style.marginRight = '20px';
  6793. button.style.padding = '4px';
  6794. button.style.cursor = 'pointer';
  6795. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  6796. {
  6797. this.actions.get('exit').funct();
  6798. }));
  6799. div.appendChild(button);
  6800. this.toolbar.container.appendChild(div);
  6801. this.toolbar.staticElements.push(div);
  6802. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  6803. }
  6804. };
  6805. /**
  6806. *
  6807. */
  6808. EditorUi.prototype.showImportCsvDialog = function()
  6809. {
  6810. if (this.importCsvDialog == null)
  6811. {
  6812. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  6813. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  6814. {
  6815. this.importCsv(newValue);
  6816. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  6817. }
  6818. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  6819. this.importCsvDialog.init();
  6820. };
  6821. /**
  6822. * TODO: Move to Editor
  6823. */
  6824. EditorUi.prototype.importCsv = function(text)
  6825. {
  6826. try
  6827. {
  6828. var lines = text.split('\n');
  6829. var cells = [];
  6830. if (lines.length > 0)
  6831. {
  6832. // Internal lookup table
  6833. var lookups = {};
  6834. // Default values
  6835. var style = null;
  6836. var identity = null;
  6837. var width = 'auto';
  6838. var height = 'auto';
  6839. var edgespacing = 40;
  6840. var nodespacing = 40;
  6841. var padding = 0;
  6842. var graph = this.editor.graph;
  6843. var view = graph.view;
  6844. var bds = graph.getGraphBounds();
  6845. // Delayed after optional layout
  6846. var afterInsert = function()
  6847. {
  6848. graph.setSelectionCells(select);
  6849. graph.scrollCellToVisible(graph.getSelectionCell());
  6850. };
  6851. // Computes unscaled, untranslated graph bounds
  6852. var pt = graph.getFreeInsertPoint();
  6853. var x0 = pt.x;
  6854. var y0 = pt.y;
  6855. var y = y0;
  6856. // Default label value depends on column names
  6857. var label = null;
  6858. // Default layout to run.
  6859. var layout = 'auto';
  6860. // Name of the attribute that contains the parent reference
  6861. var parent = null;
  6862. // Name of the attribute that contains the references for creating edges
  6863. var edges = [];
  6864. // Name of the column for hyperlinks
  6865. var link = null;
  6866. // String array of names to remove from metadata
  6867. var ignore = null;
  6868. // Read processing instructions first
  6869. var index = 0;
  6870. while (index < lines.length && lines[index].charAt(0) == '#')
  6871. {
  6872. var text = lines[index];
  6873. index++;
  6874. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  6875. lines[index].charAt(0) == '#')
  6876. {
  6877. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  6878. index++;
  6879. }
  6880. if (text.charAt(1) != '#')
  6881. {
  6882. // Processing instruction
  6883. var idx = text.indexOf(':');
  6884. if (idx > 0)
  6885. {
  6886. var key = mxUtils.trim(text.substring(1, idx));
  6887. var value = mxUtils.trim(text.substring(idx + 1));
  6888. if (key == 'label')
  6889. {
  6890. label = graph.sanitizeHtml(value);
  6891. }
  6892. else if (key == 'style')
  6893. {
  6894. style = value;
  6895. }
  6896. else if (key == 'identity' && value.length > 0 && value != '-')
  6897. {
  6898. identity = value;
  6899. }
  6900. else if (key == 'width')
  6901. {
  6902. width = value;
  6903. }
  6904. else if (key == 'height')
  6905. {
  6906. height = value;
  6907. }
  6908. else if (key == 'ignore')
  6909. {
  6910. ignore = value.split(',');
  6911. }
  6912. else if (key == 'connect')
  6913. {
  6914. edges.push(JSON.parse(value));
  6915. }
  6916. else if (key == 'link')
  6917. {
  6918. link = value;
  6919. }
  6920. else if (key == 'padding')
  6921. {
  6922. padding = parseFloat(value);
  6923. }
  6924. else if (key == 'edgespacing')
  6925. {
  6926. edgespacing = parseFloat(value);
  6927. }
  6928. else if (key == 'nodespacing')
  6929. {
  6930. nodespacing = parseFloat(value);
  6931. }
  6932. else if (key == 'layout')
  6933. {
  6934. layout = value;
  6935. }
  6936. }
  6937. }
  6938. }
  6939. var keys = this.editor.csvToArray(lines[index]);
  6940. // Converts name of identity to index of column
  6941. var identityIndex = null;
  6942. if (identity != null)
  6943. {
  6944. for (var i = 0; i < keys.length; i++)
  6945. {
  6946. if (identity == keys[i])
  6947. {
  6948. identityIndex = i;
  6949. break;
  6950. }
  6951. }
  6952. }
  6953. if (label == null)
  6954. {
  6955. label = '%' + keys[0] + '%';
  6956. }
  6957. if (edges != null)
  6958. {
  6959. for (var e = 0; e < edges.length; e++)
  6960. {
  6961. if (lookups[edges[e].to] == null)
  6962. {
  6963. lookups[edges[e].to] = {};
  6964. }
  6965. }
  6966. }
  6967. graph.model.beginUpdate();
  6968. try
  6969. {
  6970. for (var i = index + 1; i < lines.length; i++)
  6971. {
  6972. var values = this.editor.csvToArray(lines[i]);
  6973. if (values.length == keys.length)
  6974. {
  6975. var cell = null;
  6976. var id = (identityIndex != null) ? values[identityIndex] : null;
  6977. if (id != null)
  6978. {
  6979. cell = graph.model.getCell(id);
  6980. }
  6981. if (cell == null)
  6982. {
  6983. var cell = new mxCell(label, new mxGeometry(x0, y,
  6984. 0, 0), style || 'whiteSpace=wrap;html=1;');
  6985. cell.vertex = true;
  6986. cell.id = id;
  6987. }
  6988. for (var j = 0; j < values.length; j++)
  6989. {
  6990. graph.setAttributeForCell(cell, keys[j], values[j]);
  6991. }
  6992. graph.setAttributeForCell(cell, 'placeholders', '1');
  6993. cell.style = graph.replacePlaceholders(cell, cell.style);
  6994. for (var e = 0; e < edges.length; e++)
  6995. {
  6996. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  6997. }
  6998. if (link != null && link != 'link')
  6999. {
  7000. graph.setLinkForCell(cell, cell.getAttribute(link));
  7001. // Removes attribute
  7002. graph.setAttributeForCell(cell, link, null);
  7003. }
  7004. // Sets the size
  7005. var size = this.editor.graph.getPreferredSizeForCell(cell);
  7006. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  7007. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  7008. y += cell.geometry.height + nodespacing;
  7009. cells.push(graph.addCell(cell));
  7010. }
  7011. }
  7012. if (style == null)
  7013. {
  7014. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', cells));
  7015. }
  7016. var roots = cells.slice();
  7017. var select = cells.slice();
  7018. for (var e = 0; e < edges.length; e++)
  7019. {
  7020. var edge = edges[e];
  7021. for (var i = 0; i < cells.length; i++)
  7022. {
  7023. var cell = cells[i];
  7024. var tmp = cell.getAttribute(edge.from);
  7025. if (tmp != null)
  7026. {
  7027. // Removes attribute
  7028. graph.setAttributeForCell(cell, edge.from, null);
  7029. var refs = tmp.split(',');
  7030. for (var j = 0; j < refs.length; j++)
  7031. {
  7032. var ref = lookups[edge.to][refs[j]];
  7033. if (ref != null)
  7034. {
  7035. select.push(graph.insertEdge(null, null, edge.label || '',
  7036. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  7037. edge.style || graph.createCurrentEdgeStyle()));
  7038. mxUtils.remove((edge.invert) ? cell : ref, roots);
  7039. }
  7040. }
  7041. }
  7042. }
  7043. }
  7044. // Removes ignored attributes after processing above
  7045. if (ignore != null)
  7046. {
  7047. for (var i = 0; i < cells.length; i++)
  7048. {
  7049. var cell = cells[i];
  7050. for (var j = 0; j < ignore.length; j++)
  7051. {
  7052. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  7053. }
  7054. }
  7055. }
  7056. var edgeLayout = new mxParallelEdgeLayout(graph);
  7057. edgeLayout.spacing = edgespacing;
  7058. var postProcess = function()
  7059. {
  7060. edgeLayout.execute(graph.getDefaultParent());
  7061. // Aligns cells to grid and/or rounds positions
  7062. for (var i = 0; i < cells.length; i++)
  7063. {
  7064. var geo = graph.getCellGeometry(cells[i]);
  7065. geo.x = Math.round(graph.snap(geo.x));
  7066. geo.y = Math.round(graph.snap(geo.y));
  7067. if (width == 'auto')
  7068. {
  7069. geo.width = Math.round(graph.snap(geo.width));
  7070. }
  7071. if (height == 'auto')
  7072. {
  7073. geo.height = Math.round(graph.snap(geo.height));
  7074. }
  7075. }
  7076. };
  7077. if (layout == 'circle')
  7078. {
  7079. var circleLayout = new mxCircleLayout(graph);
  7080. circleLayout.resetEdges = false;
  7081. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  7082. // Ignore other cells
  7083. circleLayout.isVertexIgnored = function(vertex)
  7084. {
  7085. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  7086. mxUtils.indexOf(cells, vertex) < 0;
  7087. };
  7088. this.executeLayout(function()
  7089. {
  7090. circleLayout.execute(graph.getDefaultParent());
  7091. postProcess();
  7092. }, true, afterInsert);
  7093. afterInsert = null;
  7094. }
  7095. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  7096. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  7097. {
  7098. // Required for layouts to work with new cells
  7099. graph.view.validate();
  7100. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  7101. treeLayout.levelDistance = nodespacing;
  7102. treeLayout.edgeRouting = false;
  7103. treeLayout.resetEdges = false;
  7104. this.executeLayout(function()
  7105. {
  7106. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  7107. }, true, afterInsert);
  7108. afterInsert = null;
  7109. }
  7110. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  7111. (layout == 'auto' && roots.length == 1))
  7112. {
  7113. // Required for layouts to work with new cells
  7114. graph.view.validate();
  7115. var flowLayout = new mxHierarchicalLayout(graph,
  7116. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  7117. flowLayout.intraCellSpacing = nodespacing;
  7118. flowLayout.disableEdgeStyle = false;
  7119. this.executeLayout(function()
  7120. {
  7121. flowLayout.execute(graph.getDefaultParent(), select);
  7122. // Workaround for flow layout moving cells to origin
  7123. graph.moveCells(select, x0, y0);
  7124. }, true, afterInsert);
  7125. afterInsert = null;
  7126. }
  7127. else if (layout == 'organic' || (layout == 'auto' &&
  7128. select.length > cells.length))
  7129. {
  7130. // Required for layouts to work with new cells
  7131. graph.view.validate();
  7132. var organicLayout = new mxFastOrganicLayout(graph);
  7133. organicLayout.forceConstant = nodespacing * 3;
  7134. organicLayout.resetEdges = false;
  7135. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  7136. // Ignore other cells
  7137. organicLayout.isVertexIgnored = function(vertex)
  7138. {
  7139. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  7140. mxUtils.indexOf(cells, vertex) < 0;
  7141. };
  7142. var edgeLayout = new mxParallelEdgeLayout(graph);
  7143. edgeLayout.spacing = edgespacing;
  7144. this.executeLayout(function()
  7145. {
  7146. organicLayout.execute(graph.getDefaultParent());
  7147. postProcess();
  7148. }, true, afterInsert);
  7149. afterInsert = null;
  7150. }
  7151. this.hideDialog();
  7152. }
  7153. finally
  7154. {
  7155. graph.model.endUpdate();
  7156. }
  7157. if (afterInsert != null)
  7158. {
  7159. afterInsert();
  7160. }
  7161. }
  7162. }
  7163. catch (e)
  7164. {
  7165. this.handleError(e);
  7166. }
  7167. };
  7168. /**
  7169. * Translates this point by the given vector.
  7170. *
  7171. * @param {number} dx X-coordinate of the translation.
  7172. * @param {number} dy Y-coordinate of the translation.
  7173. */
  7174. EditorUi.prototype.getSearch = function(exclude)
  7175. {
  7176. var result = '';
  7177. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  7178. {
  7179. var amp = '?';
  7180. for (var key in urlParams)
  7181. {
  7182. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  7183. {
  7184. result += amp + key + '=' + urlParams[key];
  7185. amp = '&';
  7186. }
  7187. }
  7188. }
  7189. else
  7190. {
  7191. result = window.location.search;
  7192. }
  7193. return result;
  7194. };
  7195. /**
  7196. * Returns the URL for a copy of this editor with no state.
  7197. */
  7198. EditorUi.prototype.getUrl = function(pathname)
  7199. {
  7200. var href = (pathname != null) ? pathname : window.location.pathname;
  7201. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  7202. if (urlParams['offline'] == '1')
  7203. {
  7204. href += window.location.search;
  7205. }
  7206. else
  7207. {
  7208. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  7209. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  7210. // Removes template URL parameter for new blank diagram
  7211. for (var key in urlParams)
  7212. {
  7213. if (mxUtils.indexOf(ignored, key) < 0)
  7214. {
  7215. if (parms == 0)
  7216. {
  7217. href += '?';
  7218. }
  7219. else
  7220. {
  7221. href += '&';
  7222. }
  7223. if (urlParams[key] != null)
  7224. {
  7225. href += key + '=' + urlParams[key];
  7226. parms++;
  7227. }
  7228. }
  7229. }
  7230. }
  7231. return href;
  7232. };
  7233. /**
  7234. * Overrides link dialog.
  7235. */
  7236. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  7237. {
  7238. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  7239. this.showDialog(dlg.container, 420, 120, true, true);
  7240. dlg.init();
  7241. };
  7242. /**
  7243. * Overrides createOutline
  7244. */
  7245. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  7246. EditorUi.prototype.createOutline = function(wnd)
  7247. {
  7248. var outline = editorUiCreateOutline.apply(this, arguments);
  7249. var graph = this.editor.graph;
  7250. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  7251. outline.getSourceGraphBounds = function()
  7252. {
  7253. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  7254. {
  7255. var pb = this.source.getPagePadding();
  7256. var s = this.source.view.scale;
  7257. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  7258. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  7259. return result;
  7260. }
  7261. return outlineGetSourceGraphBounds.apply(this, arguments);
  7262. };
  7263. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  7264. outline.getSourceContainerSize = function()
  7265. {
  7266. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  7267. {
  7268. var pad = this.source.getPagePadding();
  7269. var s = this.source.view.scale;
  7270. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  7271. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  7272. }
  7273. return outlineGetSourceContainerSize.apply(this, arguments);
  7274. };
  7275. outline.getOutlineOffset = function(scale)
  7276. {
  7277. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  7278. {
  7279. var pb = this.source.getPagePadding();
  7280. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  7281. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  7282. // Why is vertical offset negative relative to dy
  7283. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  7284. }
  7285. return new mxPoint(8 / scale, 8 / scale);
  7286. };
  7287. var outlineInit = outline.init;
  7288. outline.init = function()
  7289. {
  7290. outlineInit.apply(this, arguments);
  7291. // Problem: Need to override a function in the view but the view is created
  7292. // with the graph so a refresh of the page is needed to see this change.
  7293. outline.outline.view.getBackgroundPageBounds = function()
  7294. {
  7295. var layout = graph.getPageLayout();
  7296. var page = graph.getPageSize();
  7297. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  7298. this.scale * (this.translate.y + layout.y * page.height),
  7299. this.scale * layout.width * page.width,
  7300. this.scale * layout.height * page.height);
  7301. };
  7302. outline.outline.view.validateBackgroundPage();
  7303. };
  7304. this.editor.addListener('pageSelected', function(sender, evt)
  7305. {
  7306. var change = evt.getProperty('change');
  7307. var graph = outline.source;
  7308. var g = outline.outline;
  7309. g.pageScale = graph.pageScale;
  7310. g.pageFormat = graph.pageFormat;
  7311. g.background = graph.background;
  7312. g.pageVisible = graph.pageVisible;
  7313. g.background = graph.background;
  7314. var current = mxUtils.getCurrentStyle(graph.container);
  7315. g.container.style.backgroundColor = current.backgroundColor;
  7316. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  7317. {
  7318. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  7319. }
  7320. outline.outline.view.clear(change.previousPage.root, true);
  7321. outline.outline.view.validate();
  7322. });
  7323. return outline;
  7324. };
  7325. /**
  7326. * Returns the number of storage options enabled
  7327. */
  7328. EditorUi.prototype.getServiceCount = function(allowBrowser)
  7329. {
  7330. var serviceCount = 0;
  7331. if (this.drive != null || typeof window.DriveClient === 'function')
  7332. {
  7333. serviceCount++
  7334. }
  7335. if (this.dropbox != null || typeof window.DropboxClient === 'function')
  7336. {
  7337. serviceCount++
  7338. }
  7339. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  7340. {
  7341. serviceCount++
  7342. }
  7343. if (this.gitHub != null)
  7344. {
  7345. serviceCount++
  7346. }
  7347. if (allowBrowser && isLocalStorage && (urlParams['browser'] == '1' || mxClient.IS_IOS))
  7348. {
  7349. serviceCount++
  7350. }
  7351. if (!mxClient.IS_IOS)
  7352. {
  7353. serviceCount++
  7354. }
  7355. return serviceCount;
  7356. }
  7357. /**
  7358. * Updates action and menu states depending on the file.
  7359. */
  7360. EditorUi.prototype.updateUi = function()
  7361. {
  7362. this.updateButtonContainer();
  7363. this.updateActionStates();
  7364. // Action states that only need update for new files
  7365. var file = this.getCurrentFile();
  7366. var active = file != null || (urlParams['embed'] == '1' &&
  7367. this.editor.graph.isEnabled());
  7368. this.menus.get('viewPanels').setEnabled(active);
  7369. this.menus.get('viewZoom').setEnabled(active);
  7370. var restricted = (urlParams['embed'] != '1' ||
  7371. !this.editor.graph.isEnabled()) &&
  7372. (file == null || file.isRestricted());
  7373. this.actions.get('makeCopy').setEnabled(!restricted);
  7374. this.actions.get('print').setEnabled(!restricted);
  7375. this.menus.get('exportAs').setEnabled(!restricted);
  7376. this.menus.get('embed').setEnabled(!restricted);
  7377. // Disables libraries and extras menu in embed mode
  7378. // while waiting for file data
  7379. var libsEnabled = urlParams['embed'] != '1' ||
  7380. this.editor.graph.isEnabled();
  7381. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  7382. this.menus.get('newLibrary').setEnabled(libsEnabled);
  7383. this.menus.get('extras').setEnabled(libsEnabled);
  7384. // Disables actions in the toolbar
  7385. var editable = (urlParams['embed'] == '1' &&
  7386. this.editor.graph.isEnabled()) ||
  7387. (file != null && file.isEditable());
  7388. this.actions.get('image').setEnabled(active);
  7389. this.actions.get('zoomIn').setEnabled(active);
  7390. this.actions.get('zoomOut').setEnabled(active);
  7391. this.actions.get('resetView').setEnabled(active);
  7392. // Disables menus
  7393. this.menus.get('edit').setEnabled(active);
  7394. this.menus.get('view').setEnabled(active);
  7395. this.menus.get('importFrom').setEnabled(editable);
  7396. this.menus.get('arrange').setEnabled(editable);
  7397. // Disables connection drop downs in toolbar
  7398. if (this.toolbar != null)
  7399. {
  7400. if (this.toolbar.edgeShapeMenu != null)
  7401. {
  7402. this.toolbar.edgeShapeMenu.setEnabled(editable);
  7403. }
  7404. if (this.toolbar.edgeStyleMenu != null)
  7405. {
  7406. this.toolbar.edgeStyleMenu.setEnabled(editable);
  7407. }
  7408. }
  7409. if (this.isOfflineApp())
  7410. {
  7411. var appCache = applicationCache;
  7412. // NOTE: HTML5 Cache is deprecated
  7413. if (appCache != null && this.offlineStatus == null)
  7414. {
  7415. this.offlineStatus = document.createElement('div');
  7416. this.offlineStatus.className = 'geItem';
  7417. this.offlineStatus.style.position = 'absolute';
  7418. this.offlineStatus.style.fontSize = '8pt';
  7419. this.offlineStatus.style.top = '2px';
  7420. this.offlineStatus.style.right = '12px';
  7421. this.offlineStatus.style.color = '#666';
  7422. this.offlineStatus.style.margin = '4px';
  7423. this.offlineStatus.style.padding = '2px';
  7424. this.offlineStatus.style.verticalAlign = 'middle';
  7425. this.offlineStatus.innerHTML = '';
  7426. this.menubarContainer.appendChild(this.offlineStatus);
  7427. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  7428. {
  7429. var img = this.offlineStatus.getElementsByTagName('img');
  7430. if (img != null && img.length > 0)
  7431. {
  7432. this.alert(img[0].getAttribute('title'));
  7433. }
  7434. }));
  7435. var appCache = window.applicationCache;
  7436. var lastStatus = null;
  7437. var updateStatus = mxUtils.bind(this, function()
  7438. {
  7439. var newStatus = appCache.status;
  7440. var html = '';
  7441. if (newStatus == appCache.CHECKING)
  7442. {
  7443. newStatus = appCache.DOWNLOADING;
  7444. }
  7445. switch (newStatus)
  7446. {
  7447. case appCache.UNCACHED: // UNCACHED == 0
  7448. html = '';
  7449. break;
  7450. case appCache.IDLE: // IDLE == 1
  7451. html = '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  7452. break;
  7453. case appCache.DOWNLOADING: // DOWNLOADING == 3
  7454. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  7455. break;
  7456. case appCache.UPDATEREADY: // UPDATEREADY == 4
  7457. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  7458. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  7459. break;
  7460. case appCache.OBSOLETE: // OBSOLETE == 5
  7461. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  7462. break;
  7463. default:
  7464. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  7465. break;
  7466. }
  7467. if (newStatus != lastStatus)
  7468. {
  7469. this.offlineStatus.innerHTML = html;
  7470. lastStatus = newStatus;
  7471. }
  7472. });
  7473. mxEvent.addListener(appCache, 'checking', updateStatus);
  7474. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  7475. mxEvent.addListener(appCache, 'downloading', updateStatus);
  7476. mxEvent.addListener(appCache, 'progress', updateStatus);
  7477. mxEvent.addListener(appCache, 'cached', updateStatus);
  7478. mxEvent.addListener(appCache, 'updateready', updateStatus);
  7479. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  7480. mxEvent.addListener(appCache, 'error', updateStatus);
  7481. updateStatus();
  7482. }
  7483. }
  7484. else
  7485. {
  7486. this.updateUserElement();
  7487. }
  7488. };
  7489. /**
  7490. * Hook for subclassers
  7491. */
  7492. EditorUi.prototype.updateButtonContainer = function()
  7493. {
  7494. // do nothing
  7495. };
  7496. /**
  7497. * Hook for subclassers
  7498. */
  7499. EditorUi.prototype.updateUserElement = function()
  7500. {
  7501. // do nothing
  7502. };
  7503. /**
  7504. * Updates action states depending on the selection.
  7505. */
  7506. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  7507. EditorUi.prototype.updateActionStates = function()
  7508. {
  7509. editorUiUpdateActionStates.apply(this, arguments);
  7510. var graph = this.editor.graph;
  7511. var file = this.getCurrentFile();
  7512. var active = (file != null && file.isEditable()) ||
  7513. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  7514. this.actions.get('pageSetup').setEnabled(active);
  7515. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  7516. this.actions.get('guides').setEnabled(active);
  7517. this.actions.get('shadowVisible').setEnabled(active);
  7518. this.actions.get('connectionArrows').setEnabled(active);
  7519. this.actions.get('connectionPoints').setEnabled(active);
  7520. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  7521. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  7522. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  7523. this.actions.get('createShape').setEnabled(active);
  7524. this.actions.get('createRevision').setEnabled(active);
  7525. this.actions.get('moveToFolder').setEnabled(file != null);
  7526. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  7527. this.actions.get('editDiagram').setEnabled((urlParams['embed'] == '1' &&
  7528. this.editor.graph.isEnabled()) || (file != null && !file.isRestricted()));
  7529. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  7530. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  7531. var state = graph.view.getState(graph.getSelectionCell());
  7532. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  7533. };
  7534. /**
  7535. * Overrides export dialog for using ui functions for save and setting global switches.
  7536. */
  7537. if (window.ExportDialog != null)
  7538. {
  7539. ExportDialog.showXmlOption = false;
  7540. ExportDialog.showGifOption = false;
  7541. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  7542. {
  7543. var graph = editorUi.editor.graph;
  7544. if (format == 'xml')
  7545. {
  7546. editorUi.hideDialog();
  7547. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  7548. }
  7549. else if (format == 'svg')
  7550. {
  7551. editorUi.hideDialog();
  7552. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  7553. }
  7554. else
  7555. {
  7556. var data = editorUi.getFileData(true, null, null, null, null, true);
  7557. var bounds = graph.getGraphBounds();
  7558. var w = Math.floor(bounds.width * s / graph.view.scale);
  7559. var h = Math.floor(bounds.height * s / graph.view.scale);
  7560. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  7561. {
  7562. editorUi.hideDialog();
  7563. editorUi.saveRequest(name, format,
  7564. function(newTitle, base64)
  7565. {
  7566. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  7567. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  7568. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  7569. '&border=' + b + '&xml=' + encodeURIComponent(data));
  7570. });
  7571. }
  7572. else
  7573. {
  7574. mxUtils.alert(mxResources.get('drawingTooLarge'));
  7575. }
  7576. }
  7577. };
  7578. }
  7579. })();