EditorUi.js 250 KB

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