EditorUi.js 230 KB

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