EditorUi.js 225 KB

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