EditorUi.js 223 KB

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