EditorUi.js 251 KB

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