EditorUi.js 255 KB

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