EditorUi.js 322 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. (function()
  6. {
  7. /**
  8. * Version
  9. */
  10. EditorUi.VERSION = '@DRAWIO-VERSION@';
  11. /**
  12. * Overrides compact UI setting.
  13. */
  14. EditorUi.compactUi = uiTheme != 'atlas';
  15. /**
  16. * Switch to disable logging for mode and search terms.
  17. */
  18. EditorUi.enableLogging = urlParams['stealth'] != '1' &&
  19. /.*\.draw\.io$/.test(window.location.hostname) &&
  20. window.location.hostname != 'support.draw.io';
  21. /**
  22. * Protocol and hostname to use for embedded files. Default is https://www.draw.io
  23. */
  24. EditorUi.drawHost = 'https://www.draw.io';
  25. /**
  26. * Switch to disable logging for mode and search terms.
  27. */
  28. EditorUi.lastErrorMessage = null;
  29. /**
  30. * Switch to disable logging for mode and search terms.
  31. */
  32. EditorUi.ignoredAnonymizedChars = '\n\t`~!@#$%^&*()_+{}|:"<>?-=[]\;\'.\/,\n\t';
  33. /**
  34. * Updates action states depending on the selection.
  35. */
  36. EditorUi.logError = function(message, url, linenumber, colno, err)
  37. {
  38. if (urlParams['dev'] == '1')
  39. {
  40. EditorUi.debug('logError', message, url, linenumber, colno, err);
  41. }
  42. else if (EditorUi.enableLogging)
  43. {
  44. try
  45. {
  46. if (message == EditorUi.lastErrorMessage || (message != null && url != null &&
  47. ((message.indexOf('Script error') != -1) || (message.indexOf('extension') != -1))))
  48. {
  49. // TODO log external domain script failure "Script error." is
  50. // reported when the error occurs in a script that is hosted
  51. // on a domain other than the domain of the current page
  52. }
  53. // DocumentClosedError seems to be an FF bug an can be ignored for now
  54. else if (message != null && message.indexOf('DocumentClosedError') < 0)
  55. {
  56. EditorUi.lastErrorMessage = message;
  57. var severity = (message.indexOf('NetworkError') >= 0 || message.indexOf('SecurityError') >= 0 ||
  58. message.indexOf('NS_ERROR_FAILURE') >= 0 || message.indexOf('out of memory') >= 0) ?
  59. 'CONFIG' : 'SEVERE';
  60. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  61. err = (err != null) ? err : new Error(message);
  62. var img = new Image();
  63. img.src = logDomain + '/log?severity=' + severity + '&v=' + encodeURIComponent(EditorUi.VERSION) +
  64. '&msg=clientError:' + encodeURIComponent(message) + ':url:' + encodeURIComponent(window.location.href) +
  65. ':lnum:' + encodeURIComponent(linenumber) + ((colno != null) ? ':colno:' + encodeURIComponent(colno) : '') +
  66. ((err != null && err.stack != null) ? '&stack=' + encodeURIComponent(err.stack) : '');
  67. }
  68. }
  69. catch (err)
  70. {
  71. // do nothing
  72. }
  73. }
  74. };
  75. /**
  76. * Updates action states depending on the selection.
  77. */
  78. EditorUi.logEvent = function(data)
  79. {
  80. if (urlParams['dev'] == '1')
  81. {
  82. EditorUi.debug('logEvent', data);
  83. }
  84. else if (EditorUi.enableLogging)
  85. {
  86. try
  87. {
  88. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  89. var img = new Image();
  90. img.src = logDomain + '/images/1x1.png?' +
  91. 'v=' + encodeURIComponent(EditorUi.VERSION) +
  92. ((data != null) ? '&data=' + encodeURIComponent(JSON.stringify(data)) : '');
  93. }
  94. catch (e)
  95. {
  96. // ignore
  97. }
  98. }
  99. };
  100. /**
  101. * Sending error reports.
  102. */
  103. EditorUi.sendReport = function(data, maxLength)
  104. {
  105. if (urlParams['dev'] == '1')
  106. {
  107. EditorUi.debug('sendReport', data);
  108. }
  109. else if (EditorUi.enableLogging)
  110. {
  111. try
  112. {
  113. maxLength = (maxLength != null) ? maxLength : 50000;
  114. if (data.length > maxLength)
  115. {
  116. data = data.substring(0, maxLength) + '\n...[SHORTENED]'
  117. }
  118. mxUtils.post('/email', 'version=' + encodeURIComponent(EditorUi.VERSION) +
  119. '&url=' + encodeURIComponent(window.location.href) +
  120. '&data=' + encodeURIComponent(data));
  121. }
  122. catch (e)
  123. {
  124. // ignore
  125. }
  126. }
  127. };
  128. /**
  129. * Adds the listener for automatically saving the diagram for local changes.
  130. */
  131. EditorUi.debug = function()
  132. {
  133. try
  134. {
  135. if (window.console != null && urlParams['dev'] == '1')
  136. {
  137. var args = [new Date().toISOString()];
  138. for (var i = 0; i < arguments.length; i++)
  139. {
  140. args.push(arguments[i]);
  141. }
  142. console.log.apply(console, args);
  143. }
  144. }
  145. catch (e)
  146. {
  147. // ignore
  148. }
  149. };
  150. /**
  151. * Specifies the URL for the templates index file.
  152. */
  153. EditorUi.templateFile = TEMPLATE_PATH + '/index.xml';
  154. /**
  155. * Specifies the URL for the diffsync cache.
  156. */
  157. EditorUi.cacheUrl = (urlParams['dev'] == '1') ? '/cache' : 'https://rt.draw.io/cache';
  158. /**
  159. * Switch to enable PlantUML in the insert from text dialog.
  160. * NOTE: This must also be enabled on the server-side.
  161. */
  162. EditorUi.enablePlantUml = EditorUi.enableLogging;
  163. /**
  164. * https://github.com/electron/electron/issues/2288
  165. */
  166. EditorUi.isElectronApp = window != null && window.process != null &&
  167. window.process.versions != null && window.process.versions['electron'] != null;
  168. /**
  169. * Link for scratchpad help.
  170. */
  171. EditorUi.scratchpadHelpLink = 'https://desk.draw.io/support/solutions/articles/16000042367';
  172. /**
  173. * Contains the default XML for an empty diagram.
  174. */
  175. EditorUi.prototype.emptyDiagramXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
  176. /**
  177. *
  178. */
  179. EditorUi.prototype.emptyLibraryXml = '<mxlibrary>[]</mxlibrary>';
  180. /**
  181. * Sets the delay for autosave in milliseconds. Default is 2000.
  182. */
  183. EditorUi.prototype.mode = null;
  184. /**
  185. * General timeout is 25 seconds.
  186. */
  187. EditorUi.prototype.timeout = 25000;
  188. /**
  189. * Allows for two buttons in the sidebar footer.
  190. */
  191. EditorUi.prototype.sidebarFooterHeight = 38;
  192. /**
  193. * Specifies the default custom shape style.
  194. */
  195. 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;';
  196. /**
  197. * Broken image symbol for offline SVG.
  198. */
  199. EditorUi.prototype.svgBrokenImage = Graph.createSvgImage(10, 10, '<rect x="0" y="0" width="10" height="10" stroke="#000" fill="transparent"/><path d="m 0 0 L 10 10 L 0 10 L 10 0" stroke="#000" fill="transparent"/>');
  200. /**
  201. * Specifies if img.crossOrigin is supported. This is true for all browsers except IE10 and earlier.
  202. */
  203. EditorUi.prototype.crossOriginImages = !mxClient.IS_IE;
  204. /**
  205. * Defines the maximum size for images.
  206. */
  207. EditorUi.prototype.maxBackgroundSize = 1600;
  208. /**
  209. * Defines the maximum size for images.
  210. */
  211. EditorUi.prototype.maxImageSize = 520;
  212. /**
  213. * Images above 100K should be resampled.
  214. */
  215. EditorUi.prototype.resampleThreshold = 100000;
  216. /**
  217. * Maximum allowed size for images is 1 MB.
  218. */
  219. EditorUi.prototype.maxImageBytes = 1000000;
  220. /**
  221. * Maximum size for background images is 2.5 MB.
  222. */
  223. EditorUi.prototype.maxBackgroundBytes = 2500000;
  224. /**
  225. * Holds the current file.
  226. */
  227. EditorUi.prototype.currentFile = null;
  228. /**
  229. * Specifies if PDF export should be done via print dialog. Default is
  230. * false which uses the PhantomJS backend to create the PDF.
  231. */
  232. EditorUi.prototype.printPdfExport = false;
  233. /**
  234. * Specifies if PDF export with pages is enabled.
  235. */
  236. EditorUi.prototype.pdfPageExport = true;
  237. /**
  238. * Restores app defaults for UI
  239. */
  240. EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
  241. /**
  242. * Whether template action should be shown in insert menu.
  243. */
  244. EditorUi.prototype.insertTemplateEnabled = true;
  245. /**
  246. * Restores app defaults for UI
  247. */
  248. EditorUi.prototype.closableScratchpad = true;
  249. /**
  250. * Capability check for canvas export
  251. */
  252. (function()
  253. {
  254. EditorUi.prototype.useCanvasForExport = false;
  255. EditorUi.prototype.jpgSupported = false;
  256. // Checks if canvas is supported
  257. try
  258. {
  259. var cnv = document.createElement('canvas');
  260. EditorUi.prototype.canvasSupported = !!(cnv.getContext && cnv.getContext('2d'));
  261. }
  262. catch (e)
  263. {
  264. // ignore
  265. }
  266. try
  267. {
  268. var canvas = document.createElement('canvas');
  269. var img = new Image();
  270. // LATER: Capability check should not be async
  271. img.onload = function()
  272. {
  273. try
  274. {
  275. var ctx = canvas.getContext('2d');
  276. ctx.drawImage(img, 0, 0);
  277. // Works in Chrome, Firefox, Edge, Safari and Opera
  278. var result = canvas.toDataURL('image/png');
  279. EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
  280. }
  281. catch (e)
  282. {
  283. // ignore
  284. }
  285. };
  286. // Checks if SVG with foreignObject can be exported
  287. 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>';
  288. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  289. }
  290. catch (e)
  291. {
  292. // ignore
  293. }
  294. // Checks for client-side JPG support
  295. try
  296. {
  297. var canvas = document.createElement('canvas');
  298. canvas.width = canvas.height = 1;
  299. var uri = canvas.toDataURL('image/jpeg');
  300. EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
  301. }
  302. catch (e)
  303. {
  304. // ignore
  305. }
  306. })();
  307. /**
  308. * Hook for subclassers.
  309. */
  310. EditorUi.prototype.openLink = function(url, target, allowOpener)
  311. {
  312. // LATER: Replace this with direct calls to graph
  313. return this.editor.graph.openLink(url, target, allowOpener);
  314. };
  315. /**
  316. * Hook for subclassers.
  317. */
  318. EditorUi.prototype.showSplash = function(force) { };
  319. /**
  320. * Abstraction for local storage access.
  321. */
  322. EditorUi.prototype.getLocalData = function(key, fn)
  323. {
  324. fn(localStorage.getItem(key));
  325. };
  326. /**
  327. * Abstraction for local storage access.
  328. */
  329. EditorUi.prototype.setLocalData = function(key, data, fn)
  330. {
  331. localStorage.setItem(key, data);
  332. if (fn != null)
  333. {
  334. fn();
  335. }
  336. };
  337. /**
  338. * Abstraction for local storage access.
  339. */
  340. EditorUi.prototype.removeLocalData = function(key, fn)
  341. {
  342. localStorage.removeItem(key)
  343. fn();
  344. };
  345. EditorUi.prototype.setMathEnabled = function(value)
  346. {
  347. this.editor.graph.mathEnabled = value;
  348. this.editor.updateGraphComponents();
  349. this.editor.graph.refresh();
  350. this.fireEvent(new mxEventObject('mathEnabledChanged'));
  351. };
  352. EditorUi.prototype.isMathEnabled = function(value)
  353. {
  354. return this.editor.graph.mathEnabled;
  355. };
  356. /**
  357. * Returns true if using application cache
  358. */
  359. EditorUi.prototype.isAppCache = function()
  360. {
  361. return (urlParams['appcache'] == '1' || this.isOfflineApp());
  362. };
  363. /**
  364. * Returns true if offline app, which isn't a defined thing
  365. */
  366. EditorUi.prototype.isOfflineApp = function()
  367. {
  368. return (urlParams['offline'] == '1');
  369. };
  370. /**
  371. * Returns true if no external comms allowed or possible
  372. */
  373. EditorUi.prototype.isOffline = function()
  374. {
  375. return this.isOfflineApp() || !navigator.onLine || urlParams['stealth'] == '1';
  376. };
  377. /**
  378. * Translates this point by the given vector.
  379. *
  380. * @param {number} dx X-coordinate of the translation.
  381. * @param {number} dy Y-coordinate of the translation.
  382. */
  383. EditorUi.prototype.createSpinner = function(x, y, size)
  384. {
  385. size = (size != null) ? size : 24;
  386. var spinner = new Spinner({
  387. lines: 12, // The number of lines to draw
  388. length: size, // The length of each line
  389. width: Math.round(size / 3), // The line thickness
  390. radius: Math.round(size / 2), // The radius of the inner circle
  391. rotate: 0, // The rotation offset
  392. color: (uiTheme == 'dark') ? '#c0c0c0' : '#000', // #rgb or #rrggbb
  393. speed: 1.5, // Rounds per second
  394. trail: 60, // Afterglow percentage
  395. shadow: false, // Whether to render a shadow
  396. hwaccel: false, // Whether to use hardware acceleration
  397. zIndex: 2e9 // The z-index (defaults to 2000000000)
  398. });
  399. // Extends spin method to include an optional label
  400. var oldSpin = spinner.spin;
  401. spinner.spin = function(container, label)
  402. {
  403. var result = false;
  404. if (!this.active)
  405. {
  406. oldSpin.call(this, container);
  407. this.active = true;
  408. if (label != null)
  409. {
  410. var status = document.createElement('div');
  411. status.style.position = 'absolute';
  412. status.style.whiteSpace = 'nowrap';
  413. status.style.background = '#4B4243';
  414. status.style.color = 'white';
  415. status.style.fontFamily = 'Helvetica, Arial';
  416. status.style.fontSize = '9pt';
  417. status.style.padding = '6px';
  418. status.style.paddingLeft = '10px';
  419. status.style.paddingRight = '10px';
  420. status.style.zIndex = 2e9;
  421. status.style.left = Math.max(0, x) + 'px';
  422. status.style.top = Math.max(0, y + 70) + 'px';
  423. mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
  424. mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
  425. if (uiTheme != 'dark')
  426. {
  427. mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
  428. }
  429. if (label.substring(label.length - 3, label.length) != '...' &&
  430. label.charAt(label.length - 1) != '!')
  431. {
  432. label = label + '...';
  433. }
  434. status.innerHTML = label;
  435. container.appendChild(status);
  436. spinner.status = status;
  437. // Centers the label in older IE versions
  438. if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
  439. {
  440. status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
  441. status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
  442. }
  443. }
  444. // Pause returns a function to resume the spinner
  445. this.pause = mxUtils.bind(this, function()
  446. {
  447. var fn = function() { };
  448. if (this.active)
  449. {
  450. fn = mxUtils.bind(this, function()
  451. {
  452. this.spin(container, label);
  453. });
  454. }
  455. this.stop();
  456. return fn;
  457. });
  458. result = true;
  459. }
  460. return result;
  461. };
  462. // Extends stop method to remove the optional label
  463. var oldStop = spinner.stop;
  464. spinner.stop = function()
  465. {
  466. oldStop.call(this);
  467. this.active = false;
  468. if (spinner.status != null)
  469. {
  470. spinner.status.parentNode.removeChild(spinner.status);
  471. spinner.status = null;
  472. }
  473. };
  474. spinner.pause = function()
  475. {
  476. return function() {};
  477. };
  478. return spinner;
  479. };
  480. /**
  481. * Static method for pasing PNG files.
  482. */
  483. EditorUi.parsePng = function(f, fn, error)
  484. {
  485. var pos = 0;
  486. function fread(d, count)
  487. {
  488. var start = pos;
  489. pos += count;
  490. return d.substring(start, pos);
  491. };
  492. // Reads unsigned long 32 bit big endian
  493. function _freadint(d)
  494. {
  495. var bytes = fread(d, 4);
  496. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  497. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  498. };
  499. // Checks signature
  500. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  501. {
  502. if (error != null)
  503. {
  504. error();
  505. }
  506. return;
  507. }
  508. // Reads header chunk
  509. fread(f,4);
  510. if (fread(f,4) != 'IHDR')
  511. {
  512. if (error != null)
  513. {
  514. error();
  515. }
  516. return;
  517. }
  518. fread(f, 17);
  519. do
  520. {
  521. var n = _freadint(f);
  522. var type = fread(f,4);
  523. if (fn != null)
  524. {
  525. if (fn(pos - 8, type, n))
  526. {
  527. break;
  528. }
  529. }
  530. value = fread(f,n);
  531. fread(f,4);
  532. if (type == 'IEND')
  533. {
  534. break;
  535. }
  536. }
  537. while (n);
  538. };
  539. /**
  540. * Returns true if the given string contains a compatible graph model.
  541. */
  542. EditorUi.prototype.isCompatibleString = function(data)
  543. {
  544. try
  545. {
  546. var doc = mxUtils.parseXml(data);
  547. var node = this.editor.extractGraphModel(doc.documentElement, true);
  548. return node != null && node.getElementsByTagName('parsererror').length == 0;
  549. }
  550. catch (e)
  551. {
  552. // ignore
  553. }
  554. return false;
  555. };
  556. /**
  557. * Extracts the mxfile from the given HTML data from a data transfer event.
  558. */
  559. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  560. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  561. {
  562. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  563. if (result == null)
  564. {
  565. try
  566. {
  567. var idx = data.indexOf('&lt;mxfile ');
  568. if (idx >= 0)
  569. {
  570. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  571. if (idx2 > idx)
  572. {
  573. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  574. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  575. }
  576. }
  577. else
  578. {
  579. // Gets compressed data from mxgraph element in HTML document
  580. var doc = mxUtils.parseXml(data);
  581. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null ||
  582. this.diagramContainer.style.visibility == 'hidden');
  583. result = (node != null) ? mxUtils.getXml(node) : '';
  584. }
  585. }
  586. catch (e)
  587. {
  588. // ignore
  589. }
  590. }
  591. return result;
  592. };
  593. /**
  594. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  595. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  596. */
  597. EditorUi.prototype.validateFileData = function(data)
  598. {
  599. if (data != null && data.length > 0)
  600. {
  601. var index = data.indexOf('<meta charset="utf-8">');
  602. if (index >= 0)
  603. {
  604. var replaceString = '<meta charset="utf-8"/>';
  605. var replaceStrLen = replaceString.length;
  606. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  607. }
  608. data = Graph.zapGremlins(data);
  609. }
  610. return data;
  611. };
  612. /**
  613. *
  614. */
  615. EditorUi.prototype.replaceFileData = function(data)
  616. {
  617. data = this.validateFileData(data);
  618. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  619. // Some nodes must be extracted here to find the mxfile node
  620. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  621. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  622. if (tmp != null)
  623. {
  624. node = tmp;
  625. }
  626. if (node != null)
  627. {
  628. var graph = this.editor.graph;
  629. graph.model.beginUpdate();
  630. try
  631. {
  632. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  633. var nodes = node.getElementsByTagName('diagram');
  634. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  635. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  636. {
  637. this.fileNode = node;
  638. this.pages = (this.pages != null) ? this.pages : [];
  639. // Wraps page nodes
  640. for (var i = nodes.length - 1; i >= 0; i--)
  641. {
  642. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  643. // Checks for invalid page names
  644. if (page.getName() == null)
  645. {
  646. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  647. }
  648. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  649. }
  650. }
  651. else
  652. {
  653. // Creates tabbed file structure if enforced by URL
  654. if (urlParams['pages'] != '0' && this.fileNode == null)
  655. {
  656. this.fileNode = node.ownerDocument.createElement('mxfile');
  657. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  658. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  659. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  660. }
  661. // Avoids scroll offset when switching page
  662. this.editor.setGraphXml(node);
  663. // Avoids duplicate parsing of the XML stored in the node
  664. if (this.currentPage != null)
  665. {
  666. this.currentPage.root = this.editor.graph.model.root;
  667. }
  668. }
  669. if (oldPages != null)
  670. {
  671. for (var i = 0; i < oldPages.length; i++)
  672. {
  673. graph.model.execute(new ChangePage(this, oldPages[i], null));
  674. }
  675. }
  676. }
  677. finally
  678. {
  679. graph.model.endUpdate();
  680. }
  681. }
  682. };
  683. /**
  684. * Translates this point by the given vector.
  685. *
  686. * @param {number} dx X-coordinate of the translation.
  687. * @param {number} dy Y-coordinate of the translation.
  688. */
  689. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  690. {
  691. graph = (graph != null) ? graph : this.editor.graph;
  692. forceXml = (forceXml != null) ? forceXml : false;
  693. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  694. var editLink = null;
  695. var redirect = null;
  696. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  697. {
  698. editLink = '_blank';
  699. }
  700. else
  701. {
  702. editLink = url;
  703. redirect = editLink;
  704. }
  705. if (node == null)
  706. {
  707. return '';
  708. }
  709. else
  710. {
  711. var fileNode = node;
  712. // Ignores case for possible HTML or XML nodes
  713. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  714. {
  715. // Removes control chars in input for correct roundtrip check
  716. var text = Graph.zapGremlins(mxUtils.getXml(node));
  717. var data = Graph.compress(text);
  718. // Fallback to plain XML for invalid compression
  719. // TODO: Remove this fallback with active pages
  720. if (Graph.decompress(data) != text)
  721. {
  722. return text;
  723. }
  724. else
  725. {
  726. var diagramNode = node.ownerDocument.createElement('diagram');
  727. diagramNode.setAttribute('id', Editor.guid());
  728. mxUtils.setTextContent(diagramNode, data);
  729. fileNode = node.ownerDocument.createElement('mxfile');
  730. fileNode.appendChild(diagramNode);
  731. }
  732. }
  733. if (!compact)
  734. {
  735. // Removes old metadata
  736. fileNode.removeAttribute('userAgent');
  737. fileNode.removeAttribute('version');
  738. fileNode.removeAttribute('editor');
  739. fileNode.removeAttribute('type');
  740. // Adds new metadata
  741. fileNode.setAttribute('modified', new Date().toISOString());
  742. fileNode.setAttribute('host', window.location.hostname);
  743. fileNode.setAttribute('agent', navigator.userAgent);
  744. fileNode.setAttribute('version', EditorUi.VERSION);
  745. fileNode.setAttribute('etag', Editor.guid());
  746. var md = (file != null) ? file.getMode() : this.mode;
  747. if (md != null)
  748. {
  749. fileNode.setAttribute('type', md);
  750. }
  751. }
  752. else
  753. {
  754. fileNode = fileNode.cloneNode(true);
  755. fileNode.removeAttribute('userAgent');
  756. fileNode.removeAttribute('version');
  757. fileNode.removeAttribute('editor');
  758. fileNode.removeAttribute('type');
  759. }
  760. var xml = mxUtils.getXml(fileNode);
  761. // Writes the file as an embedded HTML file
  762. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  763. {
  764. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  765. }
  766. // Maps the XML data to the content attribute in the SVG node
  767. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  768. {
  769. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  770. {
  771. url = null;
  772. }
  773. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  774. }
  775. return xml;
  776. }
  777. };
  778. /**
  779. * Translates this point by the given vector.
  780. *
  781. * @param {number} dx X-coordinate of the translation.
  782. * @param {number} dy Y-coordinate of the translation.
  783. */
  784. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  785. {
  786. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  787. currentPage = (currentPage != null) ? currentPage : false;
  788. var node = this.editor.getGraphXml(ignoreSelection);
  789. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  790. {
  791. var data = Graph.compressNode(node);
  792. mxUtils.setTextContent(this.currentPage.node, data);
  793. node = this.fileNode.cloneNode(false);
  794. if (currentPage)
  795. {
  796. node.appendChild(this.currentPage.node);
  797. }
  798. else
  799. {
  800. // Restores order of pages
  801. for (var i = 0; i < this.pages.length; i++)
  802. {
  803. if (this.currentPage != this.pages[i] && this.pages[i].needsUpdate)
  804. {
  805. var enc = new mxCodec(mxUtils.createXmlDocument());
  806. var temp = enc.encode(new mxGraphModel(this.pages[i].root));
  807. this.editor.graph.saveViewState(this.pages[i].viewState, temp);
  808. mxUtils.setTextContent(this.pages[i].node, Graph.compressNode(temp));
  809. // Marks the page as up-to-date
  810. delete this.pages[i].needsUpdate;
  811. }
  812. node.appendChild(this.pages[i].node);
  813. }
  814. }
  815. }
  816. return node;
  817. };
  818. /**
  819. * Removes any values, styles and geometries from the given XML node.
  820. */
  821. EditorUi.prototype.anonymizeString = function(text, zeros)
  822. {
  823. var result = [];
  824. for (var i = 0; i < text.length; i++)
  825. {
  826. var c = text.charAt(i);
  827. if (EditorUi.ignoredAnonymizedChars.indexOf(c) >= 0)
  828. {
  829. result.push(c);
  830. }
  831. else if (!isNaN(parseInt(c)))
  832. {
  833. result.push((zeros) ? '0' : Math.round(Math.random() * 9));
  834. }
  835. else if (c.toLowerCase() != c)
  836. {
  837. result.push(String.fromCharCode(65 + Math.round(Math.random() * 25)));
  838. }
  839. else if (c.toUpperCase() != c)
  840. {
  841. result.push(String.fromCharCode(97 + Math.round(Math.random() * 25)));
  842. }
  843. else if (/\s/.test(c))
  844. {
  845. /* any whitespace */
  846. result.push(' ');
  847. }
  848. else
  849. {
  850. result.push('?');
  851. }
  852. }
  853. return result.join('');
  854. };
  855. /**
  856. * Removes any values, styles and geometries from the given XML node.
  857. */
  858. EditorUi.prototype.anonymizePatch = function(patch)
  859. {
  860. if (patch[EditorUi.DIFF_INSERT] != null)
  861. {
  862. for (var i = 0; i < patch[EditorUi.DIFF_INSERT].length; i++)
  863. {
  864. try
  865. {
  866. var data = patch[EditorUi.DIFF_INSERT][i].data;
  867. var doc = mxUtils.parseXml(data);
  868. var clone = doc.documentElement.cloneNode(false);
  869. if (clone.getAttribute('name') != null)
  870. {
  871. clone.setAttribute('name', this.anonymizeString(clone.getAttribute('name')));
  872. }
  873. patch[EditorUi.DIFF_INSERT][i].data = mxUtils.getXml(clone);
  874. }
  875. catch (e)
  876. {
  877. patch[EditorUi.DIFF_INSERT][i].data = e.message;
  878. }
  879. }
  880. }
  881. if (patch[EditorUi.DIFF_UPDATE] != null)
  882. {
  883. for (var pageId in patch[EditorUi.DIFF_UPDATE])
  884. {
  885. var diff = patch[EditorUi.DIFF_UPDATE][pageId];
  886. if (diff.name != null)
  887. {
  888. diff.name = this.anonymizeString(diff.name);
  889. }
  890. if (diff.cells != null)
  891. {
  892. var anonymizeCellDiffs = mxUtils.bind(this, function(key)
  893. {
  894. var cellDiffs = diff.cells[key];
  895. if (cellDiffs != null)
  896. {
  897. for (var cellId in cellDiffs)
  898. {
  899. if (cellDiffs[cellId].value != null)
  900. {
  901. cellDiffs[cellId].value = '[' +
  902. cellDiffs[cellId].value.length + ']';
  903. }
  904. if (cellDiffs[cellId].xmlValue != null)
  905. {
  906. cellDiffs[cellId].xmlValue = '[' +
  907. cellDiffs[cellId].xmlValue.length + ']';
  908. }
  909. if (cellDiffs[cellId].style != null)
  910. {
  911. cellDiffs[cellId].style = '[' +
  912. cellDiffs[cellId].style.length + ']';
  913. }
  914. if (Object.keys(cellDiffs[cellId]).length == 0)
  915. {
  916. delete cellDiffs[cellId];
  917. }
  918. }
  919. if (Object.keys(cellDiffs).length == 0)
  920. {
  921. delete diff.cells[key];
  922. }
  923. }
  924. });
  925. anonymizeCellDiffs(EditorUi.DIFF_INSERT);
  926. anonymizeCellDiffs(EditorUi.DIFF_UPDATE);
  927. if (Object.keys(diff.cells).length == 0)
  928. {
  929. delete diff.cells;
  930. }
  931. }
  932. if (Object.keys(diff).length == 0)
  933. {
  934. delete patch[EditorUi.DIFF_UPDATE][pageId];
  935. }
  936. }
  937. if (Object.keys(patch[EditorUi.DIFF_UPDATE]).length == 0)
  938. {
  939. delete patch[EditorUi.DIFF_UPDATE];
  940. }
  941. }
  942. return patch;
  943. };
  944. /**
  945. * Removes any values, styles and geometries from the given XML node.
  946. */
  947. EditorUi.prototype.anonymizeAttributes = function(node, zeros)
  948. {
  949. if (node.attributes != null)
  950. {
  951. for (var i = 0; i < node.attributes.length; i++)
  952. {
  953. if (node.attributes[i].name != 'as')
  954. {
  955. node.setAttribute(node.attributes[i].name,
  956. this.anonymizeString(node.attributes[i].value, zeros));
  957. }
  958. }
  959. }
  960. if (node.childNodes != null)
  961. {
  962. for (var i = 0; i < node.childNodes.length; i++)
  963. {
  964. this.anonymizeAttributes(node.childNodes[i], zeros);
  965. }
  966. }
  967. };
  968. /**
  969. * Removes any values, styles and geometries from the given XML node.
  970. */
  971. EditorUi.prototype.anonymizeNode = function(node, zeros)
  972. {
  973. var nodes = node.getElementsByTagName('mxCell');
  974. for (var i = 0; i < nodes.length; i++)
  975. {
  976. if (nodes[i].getAttribute('value') != null)
  977. {
  978. nodes[i].setAttribute('value', '[' + nodes[i].getAttribute('value').length + ']');
  979. }
  980. if (nodes[i].getAttribute('xmlValue') != null)
  981. {
  982. nodes[i].setAttribute('xmlValue', '[' + nodes[i].getAttribute('xmlValue').length + ']');
  983. }
  984. if (nodes[i].getAttribute('style') != null)
  985. {
  986. nodes[i].setAttribute('style', '[' + nodes[i].getAttribute('style').length + ']');
  987. }
  988. if (nodes[i].parentNode != null && nodes[i].parentNode.nodeName != 'root' &&
  989. nodes[i].parentNode.parentNode != null)
  990. {
  991. nodes[i].setAttribute('id', nodes[i].parentNode.getAttribute('id'));
  992. nodes[i].parentNode.parentNode.replaceChild(nodes[i], nodes[i].parentNode);
  993. }
  994. }
  995. return node;
  996. };
  997. /**
  998. * Translates this point by the given vector.
  999. *
  1000. * @param {number} dx X-coordinate of the translation.
  1001. * @param {number} dy Y-coordinate of the translation.
  1002. */
  1003. EditorUi.prototype.synchronizeCurrentFile = function(forceReload)
  1004. {
  1005. var currentFile = this.getCurrentFile();
  1006. if (currentFile != null)
  1007. {
  1008. if (currentFile.savingFile)
  1009. {
  1010. this.handleError({message: mxResources.get('busy')});
  1011. }
  1012. else if (!forceReload && currentFile.invalidChecksum)
  1013. {
  1014. currentFile.handleFileError(null, true);
  1015. }
  1016. else if (this.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1017. {
  1018. currentFile.clearAutosave();
  1019. this.editor.setStatus('');
  1020. if (forceReload)
  1021. {
  1022. currentFile.reloadFile(mxUtils.bind(this, function()
  1023. {
  1024. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1025. }), mxUtils.bind(this, function(err)
  1026. {
  1027. currentFile.handleFileError(err, true);
  1028. }));
  1029. }
  1030. else
  1031. {
  1032. currentFile.synchronizeFile(mxUtils.bind(this, function()
  1033. {
  1034. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1035. }), mxUtils.bind(this, function(err)
  1036. {
  1037. currentFile.handleFileError(err, true);
  1038. }));
  1039. }
  1040. }
  1041. }
  1042. };
  1043. /**
  1044. * Translates this point by the given vector.
  1045. *
  1046. * @param {number} dx X-coordinate of the translation.
  1047. * @param {number} dy Y-coordinate of the translation.
  1048. */
  1049. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file)
  1050. {
  1051. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1052. currentPage = (currentPage != null) ? currentPage : false;
  1053. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  1054. file = (file != null) ? file : this.getCurrentFile();
  1055. var graph = this.editor.graph;
  1056. // Exports SVG for first page while other page is visible by creating a graph
  1057. // LATER: Add caching for the graph or SVG while not on first page
  1058. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  1059. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  1060. {
  1061. graph = this.createTemporaryGraph(graph.getStylesheet());
  1062. var graphGetGlobalVariable = graph.getGlobalVariable;
  1063. var page = this.pages[0];
  1064. graph.getGlobalVariable = function(name)
  1065. {
  1066. if (name == 'page')
  1067. {
  1068. return page.getName();
  1069. }
  1070. else if (name == 'pagenumber')
  1071. {
  1072. return 1;
  1073. }
  1074. return graphGetGlobalVariable.apply(this, arguments);
  1075. };
  1076. document.body.appendChild(graph.container);
  1077. graph.model.setRoot(page.root);
  1078. }
  1079. var result = this.createFileData(node, graph, file, window.location.href,
  1080. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  1081. // Removes temporary graph from DOM
  1082. if (graph != this.editor.graph)
  1083. {
  1084. graph.container.parentNode.removeChild(graph.container);
  1085. }
  1086. return result;
  1087. };
  1088. /**
  1089. *
  1090. */
  1091. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  1092. {
  1093. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1094. var bg = null;
  1095. var js = EditorUi.drawHost + '/js/embed-static.min.js';
  1096. // LATER: Merge common code with EmbedDialog
  1097. if (graph != null)
  1098. {
  1099. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  1100. var scale = graph.view.scale;
  1101. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  1102. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  1103. bg = graph.background;
  1104. // Embed script only used if no redirect
  1105. if (redirect == null)
  1106. {
  1107. var s = this.getBasenames().join(';');
  1108. if (s.length > 0)
  1109. {
  1110. js = EditorUi.drawHost + '/embed.js?s=' + s;
  1111. }
  1112. }
  1113. // Adds embed attributes
  1114. node.setAttribute('x0', x0);
  1115. node.setAttribute('y0', y0);
  1116. }
  1117. if (node != null)
  1118. {
  1119. node.setAttribute('pan', '1');
  1120. node.setAttribute('zoom', '1');
  1121. node.setAttribute('resize', '0');
  1122. node.setAttribute('fit', '0');
  1123. node.setAttribute('border', '20');
  1124. // Hidden attributes
  1125. node.setAttribute('links', '1');
  1126. if (editLink != null)
  1127. {
  1128. node.setAttribute('edit', editLink);
  1129. }
  1130. }
  1131. // Makes XHTML compatible
  1132. if (redirect != null)
  1133. {
  1134. redirect = redirect.replace(/&/g, '&amp;');
  1135. }
  1136. // Removes control chars in input for correct roundtrip check
  1137. var text = (node != null) ? Graph.zapGremlins(mxUtils.getXml(node)) : '';
  1138. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  1139. // embed clients that rely on this format. HTML files and export use getHtml2.
  1140. var data = Graph.compress(text);
  1141. // Fallback to URI encoded XML for invalid compression
  1142. if (Graph.decompress(data) != text)
  1143. {
  1144. data = encodeURIComponent(text);
  1145. }
  1146. var style = 'position:relative;overflow:auto;width:100%;';
  1147. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1148. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1149. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1150. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1151. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1152. '</head>\n<body' +
  1153. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  1154. '\n<div class="mxgraph" style="' + style + '">\n' +
  1155. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  1156. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1157. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1158. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1159. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1160. '\n</body>\n</html>\n';
  1161. };
  1162. /**
  1163. * Same as above but using the new embed code.
  1164. */
  1165. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  1166. {
  1167. var bg = null;
  1168. var js = EditorUi.drawHost + '/js/viewer.min.js';
  1169. var s = '';
  1170. // Makes XHTML compatible
  1171. if (redirect != null)
  1172. {
  1173. redirect = redirect.replace(/&/g, '&amp;');
  1174. }
  1175. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  1176. xml: Graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  1177. if (this.pages != null && this.currentPage != null)
  1178. {
  1179. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  1180. }
  1181. var style = 'max-width:100%;border:1px solid transparent;';
  1182. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1183. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1184. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1185. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1186. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1187. '<meta charset="utf-8"/>\n</head>\n<body>' +
  1188. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  1189. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1190. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1191. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1192. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1193. '\n</body>\n</html>\n';
  1194. };
  1195. /**
  1196. *
  1197. */
  1198. EditorUi.prototype.setFileData = function(data)
  1199. {
  1200. data = this.validateFileData(data);
  1201. this.currentPage = null;
  1202. this.fileNode = null;
  1203. this.pages = null;
  1204. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  1205. // Checks for parser errors
  1206. var errors = (node != null) ? node.getElementsByTagName('parsererror') : null;
  1207. if (errors != null && errors.length > 0)
  1208. {
  1209. var cause = mxResources.get('invalidOrMissingFile');
  1210. var divs = errors[0].getElementsByTagName('div');
  1211. if (divs.length > 0)
  1212. {
  1213. cause = mxUtils.getTextContent(divs[0]);
  1214. }
  1215. throw new Error(cause);
  1216. }
  1217. else
  1218. {
  1219. // Some nodes must be extracted here to find the mxfile node
  1220. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  1221. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  1222. if (tmp != null)
  1223. {
  1224. node = tmp;
  1225. }
  1226. if (node != null && node.nodeName == 'mxfile')
  1227. {
  1228. var nodes = node.getElementsByTagName('diagram');
  1229. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  1230. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  1231. {
  1232. var selectedPage = null;
  1233. this.fileNode = node;
  1234. this.pages = [];
  1235. // Wraps page nodes
  1236. for (var i = 0; i < nodes.length; i++)
  1237. {
  1238. // Adds page ID based on page order to match
  1239. // remote IDs given if IDs are missing here
  1240. if (nodes[i].getAttribute('id') == null)
  1241. {
  1242. nodes[i].setAttribute('id', i);
  1243. }
  1244. var page = new DiagramPage(nodes[i]);
  1245. // Checks for invalid page names
  1246. if (page.getName() == null)
  1247. {
  1248. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  1249. }
  1250. this.pages.push(page);
  1251. if (urlParams['page-id'] != null && page.getId() == urlParams['page-id'])
  1252. {
  1253. selectedPage = page;
  1254. }
  1255. }
  1256. this.currentPage = (selectedPage != null) ? selectedPage :
  1257. this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  1258. node = this.currentPage.node;
  1259. }
  1260. }
  1261. // Creates tabbed file structure if enforced by URL
  1262. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  1263. {
  1264. this.fileNode = node.ownerDocument.createElement('mxfile');
  1265. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  1266. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  1267. this.pages = [this.currentPage];
  1268. }
  1269. // Avoids scroll offset when switching page
  1270. this.editor.setGraphXml(node);
  1271. // Avoids duplicate parsing of the XML stored in the node
  1272. if (this.currentPage != null)
  1273. {
  1274. this.currentPage.root = this.editor.graph.model.root;
  1275. }
  1276. }
  1277. };
  1278. /**
  1279. * Translates this point by the given vector.
  1280. *
  1281. * @param {number} dx X-coordinate of the translation.
  1282. * @param {number} dy Y-coordinate of the translation.
  1283. */
  1284. EditorUi.prototype.getBaseFilename = function(ignorePageName)
  1285. {
  1286. var file = this.getCurrentFile();
  1287. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  1288. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
  1289. /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename) ||
  1290. /(\.drawio)$/i.test(basename))
  1291. {
  1292. basename = basename.substring(0, basename.lastIndexOf('.'));
  1293. }
  1294. if (!ignorePageName && this.pages != null && this.pages.length > 1 &&
  1295. this.currentPage != null && this.currentPage.node.getAttribute('name') != null &&
  1296. this.currentPage.getName().length > 0)
  1297. {
  1298. basename = basename + '-' + this.currentPage.getName();
  1299. }
  1300. return basename;
  1301. };
  1302. /**
  1303. * Translates this point by the given vector.
  1304. *
  1305. * @param {number} dx X-coordinate of the translation.
  1306. * @param {number} dy Y-coordinate of the translation.
  1307. */
  1308. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible, transparent)
  1309. {
  1310. try
  1311. {
  1312. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  1313. var basename = this.getBaseFilename(!currentPage);
  1314. var filename = basename + '.' + format;
  1315. if (format == 'xml')
  1316. {
  1317. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  1318. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  1319. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  1320. this.saveData(filename, format, data, 'text/xml');
  1321. }
  1322. else if (format == 'html')
  1323. {
  1324. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  1325. this.saveData(filename, format, data, 'text/html');
  1326. }
  1327. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  1328. {
  1329. var svg = null;
  1330. var saveSvg = mxUtils.bind(this, function(data)
  1331. {
  1332. if (data.length <= MAX_REQUEST_SIZE)
  1333. {
  1334. this.saveData(filename, 'svg', data, 'image/svg+xml');
  1335. }
  1336. else
  1337. {
  1338. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  1339. {
  1340. mxUtils.popup(svg);
  1341. }));
  1342. }
  1343. });
  1344. if (format == 'svg')
  1345. {
  1346. var bg = this.editor.graph.background;
  1347. if (transparent || bg == mxConstants.NONE)
  1348. {
  1349. bg = null;
  1350. }
  1351. // Sets or disables alternate text for foreignObjects. Disabling is needed
  1352. // because PhantomJS seems to ignore switch statements and paint all text.
  1353. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  1354. if (addShadow)
  1355. {
  1356. this.editor.graph.addSvgShadow(svgRoot);
  1357. }
  1358. // Embeds the images in the SVG output (async)
  1359. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  1360. {
  1361. this.spinner.stop();
  1362. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  1363. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  1364. mxUtils.getXml(svgRoot2));
  1365. })));
  1366. }
  1367. else
  1368. {
  1369. filename = basename + '.svg';
  1370. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  1371. {
  1372. this.spinner.stop();
  1373. saveSvg(svg);
  1374. }), ignoreSelection);
  1375. }
  1376. }
  1377. else
  1378. {
  1379. if (format == 'xmlpng')
  1380. {
  1381. filename = basename + '.png';
  1382. }
  1383. else if (format == 'jpeg')
  1384. {
  1385. filename = basename + '.jpg';
  1386. }
  1387. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  1388. {
  1389. try
  1390. {
  1391. var prev = this.editor.graph.pageVisible;
  1392. if (pageVisible != null)
  1393. {
  1394. this.editor.graph.pageVisible = pageVisible;
  1395. }
  1396. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64, transparent, currentPage);
  1397. this.editor.graph.pageVisible = prev;
  1398. return req;
  1399. }
  1400. catch (e)
  1401. {
  1402. this.handleError(e);
  1403. }
  1404. }));
  1405. }
  1406. }
  1407. catch (e)
  1408. {
  1409. this.handleError(e);
  1410. }
  1411. };
  1412. /**
  1413. * Translates this point by the given vector.
  1414. *
  1415. * @param {number} dx X-coordinate of the translation.
  1416. * @param {number} dy Y-coordinate of the translation.
  1417. */
  1418. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64, transparent, currentPage)
  1419. {
  1420. var bounds = this.editor.graph.getGraphBounds();
  1421. // Exports only current page for images that does not contain file data, but for
  1422. // the other formats with XML included or pdf with all pages, we need to send the complete data and use
  1423. // the from/to URL parameters to specify the page to be exported.
  1424. var data = this.getFileData(true, null, null, null, ignoreSelection, currentPage == false? false : format != 'xmlpng');
  1425. var range = '';
  1426. var allPages = '';
  1427. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  1428. {
  1429. throw {message: mxResources.get('drawingTooLarge')};
  1430. }
  1431. var embed = '0';
  1432. if (format == 'pdf' && currentPage == false)
  1433. {
  1434. allPages = '&allPages=1';
  1435. }
  1436. if (format == 'xmlpng')
  1437. {
  1438. embed = '1';
  1439. format = 'png';
  1440. // Finds the current page number
  1441. if (this.pages != null && this.currentPage != null)
  1442. {
  1443. for (var i = 0; i < this.pages.length; i++)
  1444. {
  1445. if (this.pages[i] == this.currentPage)
  1446. {
  1447. range = '&from=' + i;
  1448. break;
  1449. }
  1450. }
  1451. }
  1452. }
  1453. var bg = this.editor.graph.background;
  1454. if (format == 'png' && transparent)
  1455. {
  1456. bg = mxConstants.NONE;
  1457. }
  1458. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range + allPages +
  1459. '&bg=' + ((bg != null) ? bg : mxConstants.NONE) +
  1460. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1461. encodeURIComponent(data) + ((filename != null) ?
  1462. '&filename=' + encodeURIComponent(filename) : ''));
  1463. };
  1464. /**
  1465. * Translates this point by the given vector.
  1466. *
  1467. * @param {number} dx X-coordinate of the translation.
  1468. * @param {number} dy Y-coordinate of the translation.
  1469. */
  1470. EditorUi.prototype.setMode = function(mode, remember)
  1471. {
  1472. this.mode = mode;
  1473. };
  1474. /**
  1475. * Loads the given file descriptor. The descriptor may define the following properties:
  1476. *
  1477. * - url: The url to load the data from (proxy is used if CORS is not enabled)
  1478. * - data: The data to be inserted. If both, data and url are defined, then the data
  1479. * is preprendended to the data returned from the given URL.
  1480. * - format: Currently, only 'csv' is supported as an optional value. Default is XML.
  1481. * - update: Optional URL to fetch updates from (POST request with the page XML).
  1482. * - interval: Optional interval for fetching updates. Default is 60000 (60 seconds).
  1483. */
  1484. EditorUi.prototype.loadDescriptor = function(desc, success, error)
  1485. {
  1486. var hash = window.location.hash;
  1487. var loadData = mxUtils.bind(this, function(data)
  1488. {
  1489. var realData = (desc.data != null) ? desc.data : '';
  1490. if (data != null && data.length > 0)
  1491. {
  1492. if (realData.length > 0)
  1493. {
  1494. realData += '\n';
  1495. }
  1496. realData += data;
  1497. }
  1498. var xml = (desc.format != 'csv' && realData.length > 0) ? realData : this.emptyDiagramXml;
  1499. var tempFile = new LocalFile(this, xml, (urlParams['title'] != null) ?
  1500. decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
  1501. tempFile.getHash = function()
  1502. {
  1503. return hash;
  1504. };
  1505. this.fileLoaded(tempFile);
  1506. if (desc.format == 'csv')
  1507. {
  1508. this.importCsv(realData, mxUtils.bind(this, function(cells)
  1509. {
  1510. this.editor.undoManager.clear();
  1511. this.editor.setModified(false);
  1512. this.editor.setStatus('');
  1513. }));
  1514. }
  1515. // Installs updates
  1516. if (desc.update != null)
  1517. {
  1518. var interval = (desc.interval != null) ? parseInt(desc.interval) : 60000;
  1519. var currentThread = null;
  1520. var doUpdate = mxUtils.bind(this, function()
  1521. {
  1522. var page = this.currentPage;
  1523. mxUtils.post(desc.update, 'xml=' + encodeURIComponent(
  1524. mxUtils.getXml(this.editor.getGraphXml())),
  1525. mxUtils.bind(this, function(req)
  1526. {
  1527. if (page === this.currentPage)
  1528. {
  1529. if (req.getStatus() >= 200 && req.getStatus() <= 300)
  1530. {
  1531. var doc = this.updateDiagram(req.getText());
  1532. schedule();
  1533. }
  1534. else
  1535. {
  1536. this.handleError({message: mxResources.get('error') + ' ' + req.getStatus()});
  1537. }
  1538. }
  1539. }), mxUtils.bind(this, function(err)
  1540. {
  1541. this.handleError(err);
  1542. }));
  1543. });
  1544. var schedule = mxUtils.bind(this, function()
  1545. {
  1546. window.clearTimeout(currentThread);
  1547. currentThread = window.setTimeout(doUpdate, interval);
  1548. });
  1549. this.editor.addListener('pageSelected', mxUtils.bind(this, function()
  1550. {
  1551. schedule();
  1552. doUpdate();
  1553. }));
  1554. schedule();
  1555. doUpdate();
  1556. }
  1557. if (success != null)
  1558. {
  1559. success();
  1560. }
  1561. });
  1562. if (desc.url != null && desc.url.length > 0)
  1563. {
  1564. var realUrl = desc.url;
  1565. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  1566. {
  1567. realUrl = PROXY_URL + '?url=' + encodeURIComponent(realUrl);
  1568. }
  1569. // LATER: Remove cache-control header
  1570. this.loadUrl(realUrl, mxUtils.bind(this, function(data)
  1571. {
  1572. loadData(data);
  1573. }), mxUtils.bind(this, function(err)
  1574. {
  1575. if (error != null)
  1576. {
  1577. error(err)
  1578. }
  1579. }));
  1580. }
  1581. else
  1582. {
  1583. loadData('');
  1584. }
  1585. };
  1586. /**
  1587. * Translates this point by the given vector.
  1588. *
  1589. * @param {number} dx X-coordinate of the translation.
  1590. * @param {number} dy Y-coordinate of the translation.
  1591. */
  1592. EditorUi.prototype.updateDiagram = function(xml)
  1593. {
  1594. var doc = null;
  1595. var ui = this;
  1596. function createOverlay(desc)
  1597. {
  1598. var overlay = new mxCellOverlay(desc.image || graph.warningImage,
  1599. desc.tooltip, desc.align, desc.valign, desc.offset);
  1600. // Installs a handler for clicks on the overlay
  1601. overlay.addListener(mxEvent.CLICK, function(sender, evt)
  1602. {
  1603. ui.alert(desc.tooltip);
  1604. });
  1605. return overlay;
  1606. };
  1607. if (xml != null && xml.length > 0)
  1608. {
  1609. doc = mxUtils.parseXml(xml);
  1610. var node = (doc != null) ? doc.documentElement : null;
  1611. if (node != null && node.nodeName == 'updates')
  1612. {
  1613. var graph = this.editor.graph;
  1614. var model = graph.getModel();
  1615. model.beginUpdate();
  1616. var fit = null;
  1617. try
  1618. {
  1619. node = node.firstChild;
  1620. while (node != null)
  1621. {
  1622. if (node.nodeName == 'update')
  1623. {
  1624. // Resolves the cell ID
  1625. var cell = model.getCell(node.getAttribute('id'));
  1626. if (cell != null)
  1627. {
  1628. // Changes the value
  1629. try
  1630. {
  1631. var value = node.getAttribute('value');
  1632. if (value != null)
  1633. {
  1634. var valueNode = mxUtils.parseXml(value).documentElement;
  1635. if (valueNode != null)
  1636. {
  1637. if (valueNode.getAttribute('replace-value') == '1')
  1638. {
  1639. model.setValue(cell, valueNode);
  1640. }
  1641. else
  1642. {
  1643. var attrs = valueNode.attributes;
  1644. for (var j = 0; j < attrs.length; j++)
  1645. {
  1646. graph.setAttributeForCell(cell, attrs[j].nodeName,
  1647. (attrs[j].nodeValue.length > 0) ? attrs[j].nodeValue : null);
  1648. }
  1649. }
  1650. }
  1651. }
  1652. }
  1653. catch (e)
  1654. {
  1655. if (window.console != null)
  1656. {
  1657. console.log('Error in value for ' + cell.id + ': ' + e);
  1658. }
  1659. }
  1660. // Changes the style
  1661. try
  1662. {
  1663. var style = node.getAttribute('style');
  1664. if (style != null)
  1665. {
  1666. graph.model.setStyle(cell, style);
  1667. }
  1668. }
  1669. catch (e)
  1670. {
  1671. if (window.console != null)
  1672. {
  1673. console.log('Error in style for ' + cell.id + ': ' + e);
  1674. }
  1675. }
  1676. // Adds or removes an overlay icon
  1677. try
  1678. {
  1679. var icon = node.getAttribute('icon');
  1680. if (icon != null)
  1681. {
  1682. var desc = (icon.length > 0) ? JSON.parse(icon) : null;
  1683. if (desc == null || !desc.append)
  1684. {
  1685. graph.removeCellOverlays(cell);
  1686. }
  1687. if (desc != null)
  1688. {
  1689. graph.addCellOverlay(cell, createOverlay(desc));
  1690. }
  1691. }
  1692. }
  1693. catch (e)
  1694. {
  1695. if (window.console != null)
  1696. {
  1697. console.log('Error in icon for ' + cell.id + ': ' + e);
  1698. }
  1699. }
  1700. // Replaces the geometry
  1701. try
  1702. {
  1703. var geo = node.getAttribute('geometry');
  1704. if (geo != null)
  1705. {
  1706. geo = JSON.parse(geo);
  1707. var curr = graph.getCellGeometry(cell);
  1708. if (curr != null)
  1709. {
  1710. curr = curr.clone();
  1711. // Partially overwrites geometry
  1712. for (key in geo)
  1713. {
  1714. var val = parseFloat(geo[key]);
  1715. if (key == 'dx')
  1716. {
  1717. curr.x += val;
  1718. }
  1719. else if (key == 'dy')
  1720. {
  1721. curr.y += val;
  1722. }
  1723. else if (key == 'dw')
  1724. {
  1725. curr.width += val;
  1726. }
  1727. else if (key == 'dh')
  1728. {
  1729. curr.height += val;
  1730. }
  1731. else
  1732. {
  1733. curr[key] = parseFloat(geo[key]);
  1734. }
  1735. }
  1736. graph.model.setGeometry(cell, curr);
  1737. }
  1738. }
  1739. }
  1740. catch (e)
  1741. {
  1742. if (window.console != null)
  1743. {
  1744. console.log('Error in icon for ' + cell.id + ': ' + e);
  1745. }
  1746. }
  1747. } // if cell != null
  1748. } // if node.nodeName == 'update
  1749. else if (node.nodeName == 'model')
  1750. {
  1751. // Finds first child element
  1752. var dataNode = node.firstChild;
  1753. while (dataNode != null && dataNode.nodeType != mxConstants.NODETYPE_ELEMENT)
  1754. {
  1755. dataNode = dataNode.nextSibling;
  1756. }
  1757. if (dataNode != null)
  1758. {
  1759. var dec = new mxCodec(node.firstChild);
  1760. dec.decode(dataNode, model);
  1761. }
  1762. }
  1763. else if (node.nodeName == 'view')
  1764. {
  1765. if (node.hasAttribute('scale'))
  1766. {
  1767. graph.view.scale = parseFloat(node.getAttribute('scale'));
  1768. }
  1769. if (node.hasAttribute('dx') || node.hasAttribute('dy'))
  1770. {
  1771. graph.view.translate = new mxPoint(parseFloat(node.getAttribute('dx') || 0),
  1772. parseFloat(node.getAttribute('dy') || 0));
  1773. }
  1774. }
  1775. else if (node.nodeName == 'fit')
  1776. {
  1777. if (node.hasAttribute('max-scale'))
  1778. {
  1779. fit = parseFloat(node.getAttribute('max-scale'));
  1780. }
  1781. else
  1782. {
  1783. fit = 1;
  1784. }
  1785. }
  1786. node = node.nextSibling;
  1787. } // end of while
  1788. }
  1789. finally
  1790. {
  1791. model.endUpdate();
  1792. }
  1793. if (fit != null && this.chromelessResize)
  1794. {
  1795. this.chromelessResize(true, fit);
  1796. }
  1797. }
  1798. }
  1799. return doc;
  1800. };
  1801. /**
  1802. * Constructs a filename for a copy of the given file.
  1803. */
  1804. EditorUi.prototype.getCopyFilename = function(file, timestamp)
  1805. {
  1806. var title = (file != null && file.getTitle() != null) ?
  1807. file.getTitle() : this.defaultFilename;
  1808. // Handles extension
  1809. var extension = '';
  1810. var dot = title.lastIndexOf('.');
  1811. if (dot >= 0)
  1812. {
  1813. extension = title.substring(dot);
  1814. title = title.substring(0, dot);
  1815. }
  1816. if (timestamp)
  1817. {
  1818. function getFormattedTime()
  1819. {
  1820. var today = new Date();
  1821. var y = today.getFullYear();
  1822. // JavaScript months are 0-based.
  1823. var m = today.getMonth() + 1;
  1824. var d = today.getDate();
  1825. var h = today.getHours();
  1826. var mi = today.getMinutes();
  1827. var s = today.getSeconds();
  1828. return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
  1829. }
  1830. var ts = new Date();
  1831. title += ' ' + getFormattedTime();
  1832. }
  1833. title = mxResources.get('copyOf', [title]) + extension;
  1834. return title;
  1835. };
  1836. /**
  1837. * Translates this point by the given vector.
  1838. *
  1839. * @param {number} dx X-coordinate of the translation.
  1840. * @param {number} dy Y-coordinate of the translation.
  1841. */
  1842. EditorUi.prototype.fileLoaded = function(file, noDialogs)
  1843. {
  1844. var oldFile = this.getCurrentFile();
  1845. this.fileLoadedError = null;
  1846. this.setCurrentFile(null);
  1847. var result = false;
  1848. this.hideDialog();
  1849. if (oldFile != null)
  1850. {
  1851. oldFile.removeListener(this.descriptorChangedListener);
  1852. oldFile.close();
  1853. }
  1854. this.editor.graph.model.clear();
  1855. this.editor.undoManager.clear();
  1856. var noFile = mxUtils.bind(this, function()
  1857. {
  1858. this.setGraphEnabled(false);
  1859. this.setCurrentFile(null);
  1860. // Keeps initial title if no file existed before
  1861. if (oldFile != null)
  1862. {
  1863. this.updateDocumentTitle();
  1864. }
  1865. // File might have been loaded halfway
  1866. this.editor.graph.model.clear();
  1867. this.editor.undoManager.clear();
  1868. this.setBackgroundImage(null);
  1869. // Avoids empty hash with no value
  1870. if (!noDialogs && window.location.hash != null && window.location.hash.length > 0)
  1871. {
  1872. window.location.hash = '';
  1873. }
  1874. if (this.fname != null)
  1875. {
  1876. this.fnameWrapper.style.display = 'none';
  1877. this.fname.innerHTML = '';
  1878. this.fname.setAttribute('title', mxResources.get('rename'));
  1879. }
  1880. this.editor.setStatus('');
  1881. this.updateUi();
  1882. if (!noDialogs)
  1883. {
  1884. this.showSplash();
  1885. }
  1886. });
  1887. if (file != null)
  1888. {
  1889. try
  1890. {
  1891. // Workaround for delayed scroll repaint with min UI in Safari
  1892. if (mxClient.IS_SF && uiTheme == 'min')
  1893. {
  1894. this.diagramContainer.style.visibility = '';
  1895. }
  1896. // Order is significant, current file needed for correct
  1897. // file format for initial save after starting realtime
  1898. this.openingFile = true;
  1899. this.setCurrentFile(file);
  1900. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1901. file.addListener('contentChanged', this.descriptorChangedListener);
  1902. file.open();
  1903. delete this.openingFile;
  1904. // DescriptorChanged updates the enabled state of the graph
  1905. this.setGraphEnabled(true);
  1906. this.setMode(file.getMode());
  1907. this.editor.graph.model.prefix = Editor.guid() + '-';
  1908. this.editor.undoManager.clear();
  1909. this.descriptorChanged();
  1910. this.updateUi();
  1911. // Realtime files have a valid status message
  1912. if (!file.isEditable())
  1913. {
  1914. this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
  1915. mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
  1916. }
  1917. // Handles modified state after error of loading new file
  1918. else if (file.isModified())
  1919. {
  1920. file.addUnsavedStatus();
  1921. // Restores unsaved data
  1922. if (file.backupPatch != null)
  1923. {
  1924. file.patch([file.backupPatch]);
  1925. }
  1926. }
  1927. else
  1928. {
  1929. this.editor.setStatus('');
  1930. }
  1931. if (!this.editor.isChromelessView() || this.editor.editable)
  1932. {
  1933. this.editor.graph.selectUnlockedLayer();
  1934. this.showLayersDialog();
  1935. this.restoreLibraries();
  1936. // Workaround for no initial focus in FF
  1937. if (window.self !== window.top)
  1938. {
  1939. window.focus();
  1940. }
  1941. }
  1942. else if (this.editor.graph.isLightboxView())
  1943. {
  1944. this.lightboxFit();
  1945. }
  1946. if (this.chromelessResize)
  1947. {
  1948. this.chromelessResize();
  1949. }
  1950. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1951. result = true;
  1952. if (!this.isOffline() && file.getMode() != null)
  1953. {
  1954. EditorUi.logEvent({category: 'File', action: 'open', label:
  1955. file.getMode() + '.' + file.getSize()})
  1956. }
  1957. if (this.editor.editable && this.mode == file.getMode() &&
  1958. file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1959. {
  1960. try
  1961. {
  1962. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1963. }
  1964. catch (e)
  1965. {
  1966. // ignore
  1967. }
  1968. }
  1969. try
  1970. {
  1971. mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
  1972. mxSettings.save();
  1973. }
  1974. catch (e)
  1975. {
  1976. // ignore
  1977. }
  1978. }
  1979. catch (e)
  1980. {
  1981. this.fileLoadedError = e;
  1982. // Makes sure the file does not save the invalid UI model and overwrites anything important
  1983. if (window.console != null)
  1984. {
  1985. console.log('error in fileLoaded:', file, e);
  1986. }
  1987. if (EditorUi.enableLogging && !this.isOffline())
  1988. {
  1989. try
  1990. {
  1991. var img = new Image();
  1992. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  1993. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  1994. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  1995. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  1996. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  1997. }
  1998. catch (e)
  1999. {
  2000. // ignore
  2001. }
  2002. }
  2003. // Asynchronous handling of errors
  2004. var fn = mxUtils.bind(this, function()
  2005. {
  2006. // Removes URL parameter and reloads the page
  2007. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  2008. {
  2009. window.location.search = this.getSearch(['url']);
  2010. }
  2011. else if (oldFile != null)
  2012. {
  2013. this.fileLoaded(oldFile);
  2014. }
  2015. else
  2016. {
  2017. noFile();
  2018. }
  2019. });
  2020. if (!noDialogs)
  2021. {
  2022. this.handleError(e, mxResources.get('errorLoadingFile'), fn, true);
  2023. }
  2024. else
  2025. {
  2026. fn();
  2027. }
  2028. }
  2029. }
  2030. else
  2031. {
  2032. noFile();
  2033. }
  2034. return result;
  2035. };
  2036. /**
  2037. * Creates a hash value for the current file.
  2038. */
  2039. EditorUi.prototype.getHashValueForPages = function(pages, details)
  2040. {
  2041. // TODO: Avoid encoding to XML to make it faster
  2042. var hash = 0;
  2043. var model = new mxGraphModel();
  2044. var codec = new mxCodec();
  2045. if (details != null)
  2046. {
  2047. details.byteCount = 0;
  2048. details.attrCount = 0;
  2049. details.eltCount = 0;
  2050. details.nodeCount = 0;
  2051. }
  2052. for (var i = 0; i < pages.length; i++)
  2053. {
  2054. this.updatePageRoot(pages[i]);
  2055. var diagram = pages[i].node.cloneNode(false);
  2056. // FIXME: Check why names can be null in newer files
  2057. // ignore in hash and do not diff null names for now
  2058. diagram.removeAttribute('name');
  2059. // Model is only a holder for the root
  2060. model.root = pages[i].root;
  2061. var xmlNode = codec.encode(model);
  2062. this.editor.graph.saveViewState(pages[i].viewState, xmlNode, true);
  2063. // Local defaults may be different in files so ignore
  2064. xmlNode.removeAttribute('pageWidth');
  2065. xmlNode.removeAttribute('pageHeight');
  2066. diagram.appendChild(xmlNode);
  2067. if (details != null)
  2068. {
  2069. details.eltCount += diagram.getElementsByTagName('*').length;
  2070. details.nodeCount += diagram.getElementsByTagName('mxCell').length;
  2071. }
  2072. hash = ((hash << 5) - hash + this.hashValue(diagram, function(obj, key, value, isXml)
  2073. {
  2074. // Ignores JS machine rounding errors in known numeric attributes
  2075. // eg. 412.33333333333326 (Webkit/FF) == 412.33333333333325 (Edge/IE11)
  2076. if (isXml && (obj.nodeName == 'mxGeometry' || obj.nodeName == 'mxPoint') &&
  2077. (key == 'x' || key == 'y' || key == 'width' || key == 'height'))
  2078. {
  2079. return Math.round(value);
  2080. }
  2081. // Workaround for previous in patch written to mxCell in 10.0.23
  2082. else if (isXml && obj.nodeName == 'mxCell' && key == 'previous')
  2083. {
  2084. return null;
  2085. }
  2086. else
  2087. {
  2088. return value;
  2089. }
  2090. }, details)) << 0;
  2091. }
  2092. return hash;
  2093. };
  2094. /**
  2095. * Creates a hash value for the given object. Replacer returns the value of the
  2096. * property or attribute for the given object or XML node.
  2097. */
  2098. EditorUi.prototype.hashValue = function(obj, replacer, details)
  2099. {
  2100. var hash = 0;
  2101. // Checks for XML nodes
  2102. if (obj != null && typeof obj === 'object' && typeof obj.nodeType === 'number' &&
  2103. typeof obj.nodeName === 'string' && typeof obj.getAttribute === 'function')
  2104. {
  2105. if (obj.nodeName != null)
  2106. {
  2107. hash = hash ^ this.hashValue(obj.nodeName, replacer, details);
  2108. }
  2109. if (obj.attributes != null)
  2110. {
  2111. if (details != null)
  2112. {
  2113. details.attrCount += obj.attributes.length;
  2114. }
  2115. for (var i = 0; i < obj.attributes.length; i++)
  2116. {
  2117. var key = obj.attributes[i].name;
  2118. var value = (replacer != null) ? replacer(obj, key, obj.attributes[i].value, true) : obj.attributes[i].value;
  2119. if (value != null)
  2120. {
  2121. hash = hash ^ (this.hashValue(key, replacer, details) +
  2122. this.hashValue(value, replacer, details));
  2123. }
  2124. }
  2125. }
  2126. if (obj.childNodes != null)
  2127. {
  2128. for (var i = 0; i < obj.childNodes.length; i++)
  2129. {
  2130. hash = ((hash << 5) - hash + this.hashValue(
  2131. obj.childNodes[i], replacer, details)) << 0;
  2132. }
  2133. }
  2134. }
  2135. else if (obj != null && typeof obj !== 'function')
  2136. {
  2137. var str = String(obj);
  2138. var temp = 0;
  2139. if (details != null)
  2140. {
  2141. details.byteCount += str.length;
  2142. }
  2143. for (var i = 0; i < str.length; i++)
  2144. {
  2145. temp = ((temp << 5) - temp + str.charCodeAt(i)) << 0;
  2146. }
  2147. hash = hash ^ temp;
  2148. }
  2149. return hash;
  2150. };
  2151. /**
  2152. * Adds empty implementation
  2153. */
  2154. EditorUi.prototype.descriptorChanged = function()
  2155. {
  2156. // empty
  2157. };
  2158. /**
  2159. * Hook for subclassers.
  2160. */
  2161. EditorUi.prototype.restoreLibraries = function() { };
  2162. /**
  2163. * Hook for subclassers.
  2164. */
  2165. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn) { };
  2166. /**
  2167. *
  2168. */
  2169. EditorUi.prototype.isScratchpadEnabled = function()
  2170. {
  2171. return isLocalStorage || mxClient.IS_CHROMEAPP;
  2172. };
  2173. /**
  2174. * Shows or hides the scratchpad library.
  2175. */
  2176. EditorUi.prototype.toggleScratchpad = function()
  2177. {
  2178. if (this.isScratchpadEnabled())
  2179. {
  2180. if (this.scratchpad == null)
  2181. {
  2182. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  2183. {
  2184. if (xml == null)
  2185. {
  2186. xml = this.emptyLibraryXml;
  2187. }
  2188. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  2189. }));
  2190. }
  2191. else
  2192. {
  2193. this.closeLibrary(this.scratchpad);
  2194. }
  2195. }
  2196. };
  2197. /**
  2198. * Translates this point by the given vector.
  2199. *
  2200. * @param {number} dx X-coordinate of the translation.
  2201. * @param {number} dy Y-coordinate of the translation.
  2202. */
  2203. EditorUi.prototype.createLibraryDataFromImages = function(images)
  2204. {
  2205. var doc = mxUtils.createXmlDocument();
  2206. var library = doc.createElement('mxlibrary');
  2207. mxUtils.setTextContent(library, JSON.stringify(images));
  2208. doc.appendChild(library);
  2209. return mxUtils.getXml(doc);
  2210. };
  2211. /**
  2212. * Translates this point by the given vector.
  2213. *
  2214. * @param {number} dx X-coordinate of the translation.
  2215. * @param {number} dy Y-coordinate of the translation.
  2216. */
  2217. EditorUi.prototype.closeLibrary = function(file)
  2218. {
  2219. if (file != null)
  2220. {
  2221. this.removeLibrarySidebar(file.getHash());
  2222. if (file.constructor != LocalLibrary)
  2223. {
  2224. mxSettings.removeCustomLibrary(file.getHash());
  2225. }
  2226. if (file.title == '.scratchpad')
  2227. {
  2228. this.scratchpad = null;
  2229. }
  2230. }
  2231. };
  2232. /**
  2233. * Translates this point by the given vector.
  2234. *
  2235. * @param {number} dx X-coordinate of the translation.
  2236. * @param {number} dy Y-coordinate of the translation.
  2237. */
  2238. EditorUi.prototype.removeLibrarySidebar = function(id)
  2239. {
  2240. var elts = this.sidebar.palettes[id];
  2241. if (elts != null)
  2242. {
  2243. for (var i = 0; i < elts.length; i++)
  2244. {
  2245. elts[i].parentNode.removeChild(elts[i]);
  2246. }
  2247. delete this.sidebar.palettes[id];
  2248. }
  2249. };
  2250. /**
  2251. * Changes the position of the library in the sidebar
  2252. */
  2253. EditorUi.prototype.repositionLibrary = function(nextChild)
  2254. {
  2255. var c = this.sidebar.container;
  2256. if (nextChild == null)
  2257. {
  2258. var elts = this.sidebar.palettes['L.scratchpad'];
  2259. if (elts == null)
  2260. {
  2261. elts = this.sidebar.palettes['search'];
  2262. }
  2263. if (elts != null)
  2264. {
  2265. nextChild = elts[elts.length - 1].nextSibling;
  2266. }
  2267. }
  2268. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  2269. var content = c.lastChild;
  2270. var title = content.previousSibling;
  2271. c.insertBefore(content, nextChild);
  2272. c.insertBefore(title, content);
  2273. }
  2274. /**
  2275. * Translates this point by the given vector.
  2276. *
  2277. * @param {number} dx X-coordinate of the translation.
  2278. * @param {number} dy Y-coordinate of the translation.
  2279. */
  2280. EditorUi.prototype.loadLibrary = function(file)
  2281. {
  2282. var doc = mxUtils.parseXml(file.getData());
  2283. if (doc.documentElement.nodeName == 'mxlibrary')
  2284. {
  2285. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2286. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  2287. }
  2288. else
  2289. {
  2290. throw {message: mxResources.get('notALibraryFile')};
  2291. }
  2292. };
  2293. /**
  2294. * Translates this point by the given vector.
  2295. *
  2296. * @param {number} dx X-coordinate of the translation.
  2297. * @param {number} dy Y-coordinate of the translation.
  2298. */
  2299. EditorUi.prototype.getLibraryStorageHint = function(file)
  2300. {
  2301. return '';
  2302. };
  2303. /**
  2304. * Translates this point by the given vector.
  2305. *
  2306. * @param {number} dx X-coordinate of the translation.
  2307. * @param {number} dy Y-coordinate of the translation.
  2308. */
  2309. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  2310. {
  2311. if (this.sidebar == null)
  2312. {
  2313. return;
  2314. }
  2315. if (file.constructor != LocalLibrary)
  2316. {
  2317. mxSettings.addCustomLibrary(file.getHash());
  2318. }
  2319. if (file.title == '.scratchpad')
  2320. {
  2321. this.scratchpad = file;
  2322. }
  2323. var elts = this.sidebar.palettes[file.getHash()];
  2324. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  2325. // Removes existing sidebar entry for this library
  2326. this.removeLibrarySidebar(file.getHash());
  2327. var dropTarget = null;
  2328. var addImages = mxUtils.bind(this, function(imgs, content)
  2329. {
  2330. if (imgs.length == 0 && file.isEditable())
  2331. {
  2332. if (dropTarget == null)
  2333. {
  2334. dropTarget = document.createElement('div');
  2335. dropTarget.className = 'geDropTarget';
  2336. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  2337. }
  2338. content.appendChild(dropTarget);
  2339. }
  2340. else
  2341. {
  2342. this.addLibraryEntries(imgs, content);
  2343. }
  2344. });
  2345. // Adds entries to search index
  2346. // KNOWN: Existing entries are not replaced after edit of custom library
  2347. if (this.sidebar != null && images != null)
  2348. {
  2349. for (var i = 0; i < images.length; i++)
  2350. {
  2351. (mxUtils.bind(this, function(img)
  2352. {
  2353. var data = img.data;
  2354. if (data != null && img.title != null)
  2355. {
  2356. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2357. {
  2358. data = this.convertDataUri(data);
  2359. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2360. if (img.aspect == 'fixed')
  2361. {
  2362. s += 'aspect=fixed;'
  2363. }
  2364. return this.sidebar.createVertexTemplate(s + 'image=' +
  2365. data, img.w, img.h, '', img.title || '', false, false, true)
  2366. }));
  2367. }
  2368. else if (img.xml != null && img.title != null)
  2369. {
  2370. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2371. {
  2372. var cells = this.stringToCells(Graph.decompress(img.xml));
  2373. return this.sidebar.createVertexTemplateFromCells(
  2374. cells, img.w, img.h, img.title || '', true, false, true);
  2375. }));
  2376. }
  2377. }))(images[i]);
  2378. }
  2379. }
  2380. // Adds new sidebar entry for this library
  2381. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  2382. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  2383. {
  2384. addImages(images, content);
  2385. }));
  2386. this.repositionLibrary(nextSibling);
  2387. // Adds tooltip for backend
  2388. var title = contentDiv.parentNode.previousSibling;
  2389. var tip = title.getAttribute('title');
  2390. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  2391. {
  2392. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  2393. }
  2394. var buttons = document.createElement('div');
  2395. buttons.style.position = 'absolute';
  2396. buttons.style.right = '0px';
  2397. buttons.style.top = '0px';
  2398. buttons.style.padding = '8px'
  2399. // Workaround for CSS error in IE8 (standards and quirks)
  2400. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  2401. {
  2402. buttons.style.backgroundColor = 'inherit';
  2403. }
  2404. title.style.position = 'relative';
  2405. var btnWidth = 18;
  2406. var btn = document.createElement('img');
  2407. btn.setAttribute('src', Dialog.prototype.closeImage);
  2408. btn.setAttribute('title', mxResources.get('close'));
  2409. btn.setAttribute('valign', 'absmiddle');
  2410. btn.setAttribute('border', '0');
  2411. btn.style.margin = '0 3px';
  2412. var saveBtn = null;
  2413. if (file.title != '.scratchpad' || this.closableScratchpad)
  2414. {
  2415. buttons.appendChild(btn);
  2416. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  2417. {
  2418. // Workaround for close after any button click in IE8/quirks
  2419. if (!mxEvent.isConsumed(evt))
  2420. {
  2421. var fn = mxUtils.bind(this, function()
  2422. {
  2423. this.closeLibrary(file);
  2424. });
  2425. if (saveBtn != null)
  2426. {
  2427. this.confirm(mxResources.get('allChangesLost'), null, fn,
  2428. mxResources.get('cancel'), mxResources.get('discardChanges'));
  2429. }
  2430. else
  2431. {
  2432. fn();
  2433. }
  2434. mxEvent.consume(evt);
  2435. }
  2436. }));
  2437. }
  2438. if (file.isEditable())
  2439. {
  2440. var graph = this.editor.graph;
  2441. var spinBtn = null;
  2442. var editLibrary = mxUtils.bind(this, function(evt)
  2443. {
  2444. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  2445. mxEvent.consume(evt);
  2446. });
  2447. var saveLibrary = mxUtils.bind(this, function(evt)
  2448. {
  2449. file.setModified(true);
  2450. if (file.isAutosave())
  2451. {
  2452. if (spinBtn != null && spinBtn.parentNode != null)
  2453. {
  2454. spinBtn.parentNode.removeChild(spinBtn);
  2455. }
  2456. spinBtn = btn.cloneNode(false);
  2457. spinBtn.setAttribute('src', Editor.spinImage);
  2458. spinBtn.setAttribute('title', mxResources.get('saving'));
  2459. spinBtn.style.cursor = 'default';
  2460. spinBtn.style.marginRight = '2px';
  2461. spinBtn.style.marginTop = '-2px';
  2462. buttons.insertBefore(spinBtn, buttons.firstChild);
  2463. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2464. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  2465. {
  2466. if (spinBtn != null && spinBtn.parentNode != null)
  2467. {
  2468. spinBtn.parentNode.removeChild(spinBtn);
  2469. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2470. }
  2471. });
  2472. }
  2473. else if (saveBtn == null)
  2474. {
  2475. saveBtn = btn.cloneNode(false);
  2476. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  2477. saveBtn.setAttribute('title', mxResources.get('save'));
  2478. buttons.insertBefore(saveBtn, buttons.firstChild);
  2479. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  2480. {
  2481. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  2482. file.constructor == LocalLibrary, true, function()
  2483. {
  2484. if (saveBtn != null && !file.isModified())
  2485. {
  2486. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2487. saveBtn.parentNode.removeChild(saveBtn);
  2488. saveBtn = null;
  2489. }
  2490. });
  2491. mxEvent.consume(evt);
  2492. }));
  2493. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2494. }
  2495. });
  2496. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  2497. {
  2498. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  2499. // Translates cells to origin
  2500. for (var i = 0; i < cells.length; i++)
  2501. {
  2502. var geo = graph.getCellGeometry(cells[i]);
  2503. if (geo != null)
  2504. {
  2505. geo.translate(-bounds.x, -bounds.y);
  2506. }
  2507. }
  2508. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  2509. cells, bounds.width, bounds.height, title || '', true, false, false));
  2510. var xml = Graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  2511. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  2512. if (title != null)
  2513. {
  2514. entry.title = title;
  2515. }
  2516. images.push(entry);
  2517. saveLibrary(evt);
  2518. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2519. {
  2520. dropTarget.parentNode.removeChild(dropTarget);
  2521. dropTarget = null;
  2522. }
  2523. });
  2524. var addSelection = mxUtils.bind(this, function(evt)
  2525. {
  2526. if (!graph.isSelectionEmpty())
  2527. {
  2528. var cells = graph.getSelectionCells();
  2529. var bounds = graph.view.getBounds(cells);
  2530. var s = graph.view.scale;
  2531. bounds.x /= s;
  2532. bounds.y /= s;
  2533. bounds.width /= s;
  2534. bounds.height /= s;
  2535. bounds.x -= graph.view.translate.x;
  2536. bounds.y -= graph.view.translate.y;
  2537. addCells(cells, bounds);
  2538. }
  2539. else if (graph.getRubberband().isActive())
  2540. {
  2541. graph.getRubberband().execute(evt);
  2542. graph.getRubberband().reset();
  2543. }
  2544. else
  2545. {
  2546. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  2547. }
  2548. mxEvent.consume(evt);
  2549. });
  2550. // Adds drop handler from graph
  2551. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  2552. {
  2553. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  2554. {
  2555. graph.graphHandler.shape.node.style.visibility = 'hidden';
  2556. contentDiv.style.backgroundColor = '#f1f3f4';
  2557. contentDiv.style.cursor = 'copy';
  2558. graph.panningManager.stop();
  2559. graph.autoScroll = false;
  2560. if (graph.graphHandler.guide != null)
  2561. {
  2562. graph.graphHandler.guide.setVisible(false);
  2563. }
  2564. if (graph.graphHandler.hint != null)
  2565. {
  2566. graph.graphHandler.hint.style.visibility = 'hidden';
  2567. }
  2568. mxEvent.consume(evt);
  2569. }
  2570. }), mxUtils.bind(this, function(evt)
  2571. {
  2572. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  2573. {
  2574. contentDiv.style.backgroundColor = '';
  2575. contentDiv.style.cursor = 'default';
  2576. this.sidebar.showTooltips = true;
  2577. graph.panningManager.stop();
  2578. graph.graphHandler.reset();
  2579. graph.isMouseDown = false;
  2580. graph.autoScroll = true;
  2581. addSelection(evt);
  2582. mxEvent.consume(evt);
  2583. }
  2584. }));
  2585. // Handles mouse leaving the library and restoring move
  2586. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  2587. {
  2588. if (graph.isMouseDown && graph.graphHandler.shape != null)
  2589. {
  2590. graph.graphHandler.shape.node.style.visibility = 'visible';
  2591. contentDiv.style.backgroundColor = '';
  2592. contentDiv.style.cursor = '';
  2593. graph.autoScroll = true;
  2594. if (graph.graphHandler.guide != null)
  2595. {
  2596. graph.graphHandler.guide.setVisible(true);
  2597. }
  2598. if (graph.graphHandler.hint != null)
  2599. {
  2600. graph.graphHandler.hint.style.visibility = 'visible';
  2601. }
  2602. }
  2603. }));
  2604. // Adds drop handler from filesystem
  2605. if (Graph.fileSupport)
  2606. {
  2607. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  2608. {
  2609. contentDiv.style.backgroundColor = '#f1f3f4';
  2610. evt.dataTransfer.dropEffect = 'copy';
  2611. contentDiv.style.cursor = 'copy';
  2612. this.sidebar.hideTooltip();
  2613. evt.stopPropagation();
  2614. evt.preventDefault();
  2615. }));
  2616. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  2617. {
  2618. contentDiv.style.cursor = '';
  2619. contentDiv.style.backgroundColor = '';
  2620. if (evt.dataTransfer.files.length > 0)
  2621. {
  2622. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  2623. {
  2624. if (data != null && mimeType.substring(0, 6) == 'image/')
  2625. {
  2626. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  2627. this.convertDataUri(data);
  2628. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  2629. cells[0].vertex = true;
  2630. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  2631. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2632. {
  2633. dropTarget.parentNode.removeChild(dropTarget);
  2634. dropTarget = null;
  2635. }
  2636. }
  2637. else
  2638. {
  2639. var done = false;
  2640. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  2641. {
  2642. if (theData != null && theMimeType == 'text/xml')
  2643. {
  2644. var doc = mxUtils.parseXml(theData);
  2645. if (doc.documentElement.nodeName == 'mxlibrary')
  2646. {
  2647. try
  2648. {
  2649. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2650. addImages(temp, contentDiv);
  2651. images = images.concat(temp);
  2652. saveLibrary(evt);
  2653. this.spinner.stop();
  2654. done = true;
  2655. }
  2656. catch (e)
  2657. {
  2658. // ignore
  2659. }
  2660. }
  2661. else if (doc.documentElement.nodeName == 'mxfile')
  2662. {
  2663. try
  2664. {
  2665. var pages = doc.documentElement.getElementsByTagName('diagram');
  2666. for (var i = 0; i < pages.length; i++)
  2667. {
  2668. var temp = mxUtils.getTextContent(pages[i]);
  2669. var cells = this.stringToCells(Graph.decompress(temp));
  2670. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  2671. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  2672. }
  2673. done = true;
  2674. }
  2675. catch (e)
  2676. {
  2677. if (window.console != null)
  2678. {
  2679. console.log('error in drop handler:', e);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. if (!done)
  2685. {
  2686. this.spinner.stop();
  2687. this.handleError({message: mxResources.get('errorLoadingFile')})
  2688. }
  2689. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2690. {
  2691. dropTarget.parentNode.removeChild(dropTarget);
  2692. dropTarget = null;
  2693. }
  2694. });
  2695. if (file != null && img != null && ((/(\.v(dx|sdx?))($|\?)/i.test(img)) || /(\.vs(x|sx?))($|\?)/i.test(img)))
  2696. {
  2697. this.importVisio(file, function(xml)
  2698. {
  2699. doImport(xml, 'text/xml');
  2700. }, null, img);
  2701. }
  2702. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  2703. {
  2704. this.parseFile(file, mxUtils.bind(this, function(xhr)
  2705. {
  2706. if (xhr.readyState == 4)
  2707. {
  2708. this.spinner.stop();
  2709. if (xhr.status >= 200 && xhr.status <= 299)
  2710. {
  2711. doImport(xhr.responseText, 'text/xml');
  2712. }
  2713. else
  2714. {
  2715. this.handleError({message: mxResources.get((xhr.status == 413) ?
  2716. 'drawingTooLarge' : 'invalidOrMissingFile')},
  2717. mxResources.get('errorLoadingFile'));
  2718. }
  2719. }
  2720. }));
  2721. }
  2722. else
  2723. {
  2724. doImport(data, mimeType);
  2725. }
  2726. }
  2727. }));
  2728. }
  2729. evt.stopPropagation();
  2730. evt.preventDefault();
  2731. }));
  2732. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  2733. {
  2734. contentDiv.style.cursor = '';
  2735. contentDiv.style.backgroundColor = '';
  2736. evt.stopPropagation();
  2737. evt.preventDefault();
  2738. });
  2739. }
  2740. btn = btn.cloneNode(false);
  2741. btn.setAttribute('src', Editor.editImage);
  2742. btn.setAttribute('title', mxResources.get('edit'));
  2743. buttons.insertBefore(btn, buttons.firstChild);
  2744. mxEvent.addListener(btn, 'click', editLibrary);
  2745. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  2746. {
  2747. if (mxEvent.getSource(evt) == contentDiv)
  2748. {
  2749. editLibrary(evt);
  2750. }
  2751. });
  2752. var btn2 = btn.cloneNode(false);
  2753. btn2.setAttribute('src', Editor.plusImage);
  2754. btn2.setAttribute('title', mxResources.get('add'));
  2755. buttons.insertBefore(btn2, buttons.firstChild);
  2756. mxEvent.addListener(btn2, 'click', addSelection);
  2757. if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
  2758. {
  2759. var link = document.createElement('span');
  2760. link.setAttribute('title', mxResources.get('help'));
  2761. link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
  2762. mxUtils.write(link, '?');
  2763. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  2764. {
  2765. this.openLink(EditorUi.scratchpadHelpLink);
  2766. mxEvent.consume(evt);
  2767. }));
  2768. buttons.insertBefore(link, buttons.firstChild);
  2769. }
  2770. }
  2771. title.appendChild(buttons);
  2772. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2773. };
  2774. /**
  2775. * Adds the library entries to the given DOM node.
  2776. */
  2777. EditorUi.prototype.addLibraryEntries = function(imgs, content)
  2778. {
  2779. for (var i = 0; i < imgs.length; i++)
  2780. {
  2781. var img = imgs[i];
  2782. var data = img.data;
  2783. if (data != null)
  2784. {
  2785. data = this.convertDataUri(data);
  2786. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2787. if (img.aspect == 'fixed')
  2788. {
  2789. s += 'aspect=fixed;'
  2790. }
  2791. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  2792. data, img.w, img.h, '', img.title || '', false, false, true));
  2793. }
  2794. else if (img.xml != null)
  2795. {
  2796. var cells = this.stringToCells(Graph.decompress(img.xml));
  2797. if (cells.length > 0)
  2798. {
  2799. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  2800. cells, img.w, img.h, img.title || '', true, false, true));
  2801. }
  2802. }
  2803. }
  2804. };
  2805. /**
  2806. * Extracts the resource for the current language from the given multi language
  2807. * resource object of the form {es: "...", de: "...", main: "..."} where the keys
  2808. * are country codes and main defines the fallback if no resource for the current
  2809. * country code exists.
  2810. */
  2811. EditorUi.prototype.getResource = function(obj)
  2812. {
  2813. return (obj != null) ? (obj[mxLanguage] || obj.main) : null;
  2814. };
  2815. /**
  2816. * EditorUi Overrides
  2817. */
  2818. EditorUi.prototype.footerHeight = 0;
  2819. if (urlParams['offline'] == '1' || EditorUi.isElectronApp)
  2820. {
  2821. //EditorUi.prototype.footerHeight = 4;
  2822. }
  2823. else
  2824. {
  2825. if (urlParams['savesidebar'] == '1')
  2826. {
  2827. Sidebar.prototype.thumbWidth = 64;
  2828. Sidebar.prototype.thumbHeight = 64;
  2829. }
  2830. //EditorUi.prototype.footerHeight = (screen.width >= 760 && screen.height >= 240) ? 46 : 0;
  2831. // Fetches footer from page
  2832. EditorUi.prototype.createFooter = function()
  2833. {
  2834. var footer = document.getElementById('geFooter');
  2835. if (footer != null)
  2836. {
  2837. // footer.style.visibility = 'hidden';
  2838. //
  2839. // // Adds button to hide the footer
  2840. // var img = document.createElement('img');
  2841. // img.setAttribute('border', '0');
  2842. // img.setAttribute('src', Dialog.prototype.closeImage);
  2843. // img.setAttribute('title', mxResources.get('hide'));
  2844. // footer.appendChild(img)
  2845. //
  2846. // if (mxClient.IS_QUIRKS)
  2847. // {
  2848. // img.style.position = 'relative';
  2849. // img.style.styleFloat = 'right';
  2850. // img.style.top = '-30px';
  2851. // img.style.left = '164px';
  2852. // img.style.cursor = 'pointer';
  2853. // }
  2854. //
  2855. // mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  2856. // {
  2857. // this.hideFooter();
  2858. // }));
  2859. }
  2860. return footer;
  2861. };
  2862. }
  2863. EditorUi.initTheme = function()
  2864. {
  2865. if (uiTheme == 'atlas')
  2866. {
  2867. mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
  2868. if (typeof Toolbar !== 'undefined')
  2869. {
  2870. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  2871. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  2872. }
  2873. Editor.prototype.initialTopSpacing = 3;
  2874. EditorUi.prototype.menubarHeight = 41;
  2875. EditorUi.prototype.toolbarHeight = 38;
  2876. }
  2877. else if (uiTheme == 'dark')
  2878. {
  2879. mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
  2880. Dialog.backdropColor = '#2a2a2a';
  2881. Graph.prototype.defaultThemeName = 'darkTheme';
  2882. Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
  2883. Graph.prototype.defaultPageBorderColor = '#505759';
  2884. Graph.prototype.svgShadowColor = '#e0e0e0';
  2885. Graph.prototype.svgShadowOpacity = '0.6';
  2886. Graph.prototype.svgShadowSize = '0.8';
  2887. Graph.prototype.svgShadowBlur = '1.4';
  2888. Format.prototype.inactiveTabBackgroundColor = 'black';
  2889. BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
  2890. Sidebar.prototype.dragPreviewBorder = '1px dashed #cccccc';
  2891. mxGraphHandler.prototype.previewColor = '#cccccc';
  2892. StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
  2893. if (mxClient.IS_SVG)
  2894. {
  2895. Editor.helpImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAP1BMVEUAAAD///////////////////////////////////////////////////////////////////////////////9Du/pqAAAAFXRSTlMAT30qCJRBboyDZyCgRzUUdF46MJlgXETgAAAAeklEQVQY022O2w4DIQhEQUURda/9/28tUO2+7CQS5sgQ4F1RapX78YUwRqQjTU8ILqQfKerTKTvACJ4nLX3krt+8aS82oI8aQC4KavRgtvEW/mDvsICgA03PSGRr79MqX1YPNIxzjyqtw8ZnnRo4t5a5undtJYRywau+ds4Cyza3E6YAAAAASUVORK5CYII=';
  2896. Editor.checkmarkImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAARVBMVEUAAACZmZkICAgEBASNjY2Dg4MYGBiTk5N5eXl1dXVmZmZQUFBCQkI3NzceHh4MDAykpKSJiYl+fn5sbGxaWlo/Pz8SEhK96uPlAAAAAXRSTlMAQObYZgAAAE5JREFUGNPFzTcSgDAQQ1HJGUfy/Y9K7V1qeOUfzQifCQZai1XHaz11LFysbDbzgDSSWMZiETz3+b8yNUc/MMsktxuC8XQBSncdLwz+8gCCggGXzBcozAAAAABJRU5ErkJggg==';
  2897. }
  2898. }
  2899. };
  2900. EditorUi.initTheme();
  2901. /**
  2902. * Hides the footer.
  2903. */
  2904. EditorUi.prototype.hideFooter = function()
  2905. {
  2906. var footer = document.getElementById('geFooter');
  2907. if (footer != null)
  2908. {
  2909. this.footerHeight = 0;
  2910. footer.style.display = 'none';
  2911. this.refresh();
  2912. }
  2913. };
  2914. /**
  2915. * Shows the footer.
  2916. */
  2917. EditorUi.prototype.showFooter = function(height)
  2918. {
  2919. var footer = document.getElementById('geFooter');
  2920. if (footer != null)
  2921. {
  2922. this.footerHeight = height;
  2923. footer.style.display = 'inline';
  2924. this.refresh();
  2925. }
  2926. };
  2927. /**
  2928. * Overrides image dialog to add image search and Google+.
  2929. */
  2930. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  2931. {
  2932. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  2933. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  2934. this.showDialog(dlg.container, (Graph.fileSupport) ? 440 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
  2935. dlg.init();
  2936. };
  2937. /**
  2938. * Hides the current menu.
  2939. */
  2940. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  2941. {
  2942. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  2943. {
  2944. var change = new ChangePageSetup(this, null, image);
  2945. change.ignoreColor = true;
  2946. this.editor.graph.model.execute(change);
  2947. });
  2948. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  2949. {
  2950. apply(image);
  2951. }));
  2952. this.showDialog(dlg.container, 360, 200, true, true);
  2953. dlg.init();
  2954. };
  2955. /**
  2956. * Hides the current menu.
  2957. */
  2958. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  2959. {
  2960. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  2961. this.showDialog(dlg.container, 640, 440, true, false, mxUtils.bind(this, function(cancel)
  2962. {
  2963. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  2964. {
  2965. this.showSplash();
  2966. }
  2967. }));
  2968. dlg.init();
  2969. };
  2970. /**
  2971. * Overridden to update after view state changes.
  2972. */
  2973. var editorUiCreateFormat = EditorUi.prototype.createFormat;
  2974. EditorUi.prototype.createFormat = function(container)
  2975. {
  2976. var format = editorUiCreateFormat.apply(this, arguments);
  2977. this.editor.graph.addListener('viewStateChanged', mxUtils.bind(this, function(evt)
  2978. {
  2979. if (this.editor.graph.isSelectionEmpty())
  2980. {
  2981. format.refresh();
  2982. }
  2983. }));
  2984. return format;
  2985. };
  2986. /**
  2987. * Hook for sidebar footer container.
  2988. */
  2989. EditorUi.prototype.createSidebarFooterContainer = function()
  2990. {
  2991. var div = this.createDiv('geSidebarContainer geSidebarFooter');
  2992. div.style.position = 'absolute';
  2993. div.style.overflow = 'hidden';
  2994. var elt2 = document.createElement('a');
  2995. elt2.className = 'geTitle';
  2996. elt2.style.color = '#188038';
  2997. elt2.style.height = '100%';
  2998. elt2.style.paddingTop = '9px';
  2999. elt2.innerHTML = '<span style="font-size:18px;margin-right:5px;">+</span>';
  3000. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  3001. // Prevents focus
  3002. mxEvent.addListener(elt2, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
  3003. mxUtils.bind(this, function(evt)
  3004. {
  3005. evt.preventDefault();
  3006. }));
  3007. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  3008. {
  3009. this.actions.get('shapes').funct();
  3010. mxEvent.consume(evt);
  3011. }));
  3012. div.appendChild(elt2);
  3013. return div;
  3014. };
  3015. /**
  3016. * Translates this point by the given vector.
  3017. *
  3018. * @param {number} dx X-coordinate of the translation.
  3019. * @param {number} dy Y-coordinate of the translation.
  3020. */
  3021. EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose)
  3022. {
  3023. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3024. var e = (resp != null && resp.error != null) ? resp.error : resp;
  3025. if (e != null || title != null)
  3026. {
  3027. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  3028. var btn = mxResources.get('ok');
  3029. var retry = null;
  3030. title = (title != null) ? title : mxResources.get('error');
  3031. if (e != null)
  3032. {
  3033. if (e.retry != null)
  3034. {
  3035. btn = mxResources.get('cancel');
  3036. retry = function()
  3037. {
  3038. resume();
  3039. e.retry();
  3040. };
  3041. }
  3042. if (e.code == 404 || e.status == 404 || e.code == 403)
  3043. {
  3044. if (e.code == 403)
  3045. {
  3046. if (e.message != null)
  3047. {
  3048. msg = mxUtils.htmlEntities(e.message);
  3049. }
  3050. else
  3051. {
  3052. msg = mxUtils.htmlEntities(mxResources.get('accessDenied'));
  3053. }
  3054. }
  3055. else
  3056. {
  3057. msg = mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied'));
  3058. }
  3059. var id = window.location.hash;
  3060. if (id != null && id.substring(0, 2) == '#G' && resp != null && resp.error != null &&
  3061. resp.error.errors != null && resp.error.errors.length > 0 &&
  3062. resp.error.errors[0].reason == 'fileAccess')
  3063. {
  3064. id = id.substring(2);
  3065. // Special case where the button must have a different label and function
  3066. this.showError(title, msg, mxResources.get('cancel'), null, retry,
  3067. mxResources.get('tryOpeningViaThisPage'), mxUtils.bind(this, function()
  3068. {
  3069. this.editor.graph.openLink('https://drive.google.com/open?id=' + id);
  3070. }), null, null, 380);
  3071. return;
  3072. }
  3073. }
  3074. else if (e.message != null)
  3075. {
  3076. msg = mxUtils.htmlEntities(e.message);
  3077. }
  3078. else if (e.response != null && e.response.error != null)
  3079. {
  3080. msg = mxUtils.htmlEntities(e.response.error);
  3081. }
  3082. else if (window.App !== 'undefined')
  3083. {
  3084. if (e.code == App.ERROR_TIMEOUT)
  3085. {
  3086. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  3087. }
  3088. else if (e.code == App.ERROR_BUSY)
  3089. {
  3090. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  3091. }
  3092. }
  3093. }
  3094. this.showError(title, msg, btn, fn, retry, null, null, null, null,
  3095. null, null, null, (invokeFnOnClose) ? fn : null);
  3096. }
  3097. else if (fn != null)
  3098. {
  3099. fn();
  3100. }
  3101. };
  3102. /**
  3103. * Translates this point by the given vector.
  3104. *
  3105. * @param {number} dx X-coordinate of the translation.
  3106. * @param {number} dy Y-coordinate of the translation.
  3107. */
  3108. EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose)
  3109. {
  3110. var height = (msg != null && msg.length > 120) ? 180 : 150;
  3111. var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
  3112. fn, retry, btn2, fn2, hide, btn3, fn3);
  3113. this.showDialog(dlg.container, w || 340, h || ((msg != null && msg.length > 120) ?
  3114. 180 : 150), true, false, onClose);
  3115. dlg.init();
  3116. };
  3117. /**
  3118. * Translates this point by the given vector.
  3119. *
  3120. * @param {number} dx X-coordinate of the translation.
  3121. * @param {number} dy Y-coordinate of the translation.
  3122. */
  3123. EditorUi.prototype.alert = function(msg, fn)
  3124. {
  3125. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  3126. this.showDialog(dlg.container, 340, 100, true, false);
  3127. dlg.init();
  3128. };
  3129. /**
  3130. * Translates this point by the given vector.
  3131. *
  3132. * @param {number} dx X-coordinate of the translation.
  3133. * @param {number} dy Y-coordinate of the translation.
  3134. */
  3135. EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel, closable)
  3136. {
  3137. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3138. var dlg = new ConfirmDialog(this, msg, function()
  3139. {
  3140. resume();
  3141. if (okFn != null)
  3142. {
  3143. okFn();
  3144. }
  3145. }, function()
  3146. {
  3147. resume();
  3148. if (cancelFn != null)
  3149. {
  3150. cancelFn();
  3151. }
  3152. }, okLabel, cancelLabel);
  3153. this.showDialog(dlg.container, 340, 90, true, closable);
  3154. dlg.init();
  3155. };
  3156. /**
  3157. * Translates this point by the given vector.
  3158. *
  3159. * @param {number} dx X-coordinate of the translation.
  3160. * @param {number} dy Y-coordinate of the translation.
  3161. */
  3162. EditorUi.prototype.setCurrentFile = function(file)
  3163. {
  3164. this.currentFile = file;
  3165. };
  3166. /**
  3167. * Translates this point by the given vector.
  3168. *
  3169. * @param {number} dx X-coordinate of the translation.
  3170. * @param {number} dy Y-coordinate of the translation.
  3171. */
  3172. EditorUi.prototype.getCurrentFile = function()
  3173. {
  3174. return this.currentFile;
  3175. };
  3176. /**
  3177. * Handling for canvas export.
  3178. */
  3179. /**
  3180. * See fixme in convertMath for client-side image generation with math.
  3181. */
  3182. EditorUi.prototype.isExportToCanvas = function()
  3183. {
  3184. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  3185. };
  3186. /**
  3187. * Translates this point by the given vector.
  3188. *
  3189. * @param {number} dx X-coordinate of the translation.
  3190. * @param {number} dy Y-coordinate of the translation.
  3191. */
  3192. EditorUi.prototype.createSvgDataUri = function(svg)
  3193. {
  3194. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  3195. };
  3196. /**
  3197. *
  3198. */
  3199. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  3200. {
  3201. var data = canvas.toDataURL('image/' + format);
  3202. // Checks if output is invalid or empty
  3203. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  3204. {
  3205. throw {message: 'Invalid image'};
  3206. }
  3207. if (xml != null)
  3208. {
  3209. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(Graph.compress(xml)));
  3210. }
  3211. return data;
  3212. };
  3213. /**
  3214. *
  3215. */
  3216. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  3217. {
  3218. var ext = ((format == 'jpeg') ? 'jpg' : format);
  3219. var filename = this.getBaseFilename() + '.' + ext;
  3220. var data = this.createImageDataUri(canvas, xml, format);
  3221. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  3222. };
  3223. /**
  3224. * Returns true if files should be saved using <saveLocalFile>.
  3225. */
  3226. EditorUi.prototype.isLocalFileSave = function()
  3227. {
  3228. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  3229. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  3230. document.documentMode != 9 && document.documentMode != 8 &&
  3231. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  3232. this.isOfflineApp() || mxClient.IS_IOS);
  3233. };
  3234. /**
  3235. * Translates this point by the given vector.
  3236. *
  3237. * @param {number} dx X-coordinate of the translation.
  3238. * @param {number} dy Y-coordinate of the translation.
  3239. */
  3240. EditorUi.prototype.showTextDialog = function(title, text)
  3241. {
  3242. var dlg = new TextareaDialog(this, title, text, null, null, mxResources.get('close'));
  3243. dlg.textarea.style.width = '600px';
  3244. dlg.textarea.style.height = '380px';
  3245. this.showDialog(dlg.container, 620, 460, true, true);
  3246. dlg.init();
  3247. document.execCommand('selectall', false, null);
  3248. };
  3249. /**
  3250. * Translates this point by the given vector.
  3251. *
  3252. * @param {number} dx X-coordinate of the translation.
  3253. * @param {number} dy Y-coordinate of the translation.
  3254. */
  3255. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  3256. {
  3257. // Newer versions of IE
  3258. if (window.Blob && navigator.msSaveOrOpenBlob)
  3259. {
  3260. var blob = (base64Encoded) ?
  3261. this.base64ToBlob(data, mimeType) :
  3262. new Blob([data], {type: mimeType})
  3263. navigator.msSaveOrOpenBlob(blob, filename);
  3264. }
  3265. // Older versions of IE (binary not supported)
  3266. else if (mxClient.IS_IE)
  3267. {
  3268. var win = window.open('about:blank', '_blank');
  3269. if (win == null)
  3270. {
  3271. mxUtils.popup(data, true);
  3272. }
  3273. else
  3274. {
  3275. win.document.write(data);
  3276. win.document.close();
  3277. win.document.execCommand('SaveAs', true, filename);
  3278. win.close();
  3279. }
  3280. }
  3281. // else if (mxClient.IS_IOS)
  3282. // {
  3283. // this.showTextDialog(filename + ':', data);
  3284. // }
  3285. else
  3286. {
  3287. var a = document.createElement('a');
  3288. // Workaround for mxXmlRequest.simulate no longer working in Safari/PaleMoon
  3289. // if this is used (ie PNG export broken after XML export in Safari/PaleMoon).
  3290. var useDownload = !mxClient.IS_SF && navigator.userAgent.indexOf("PaleMoon/") < 0 &&
  3291. typeof a.download !== 'undefined';
  3292. // Workaround for Chromium 65 cross-domain anchor download issue
  3293. if (mxClient.IS_GC)
  3294. {
  3295. var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
  3296. var vers = raw ? parseInt(raw[2], 10) : false;
  3297. useDownload = vers == 65 ? false : useDownload;
  3298. }
  3299. if (useDownload || this.isOffline())
  3300. {
  3301. a.href = URL.createObjectURL((base64Encoded) ?
  3302. this.base64ToBlob(data, mimeType) :
  3303. new Blob([data], {type: mimeType}));
  3304. if (useDownload)
  3305. {
  3306. a.download = filename;
  3307. }
  3308. else
  3309. {
  3310. // Workaround for same window in Safari
  3311. a.setAttribute('target', '_blank');
  3312. }
  3313. document.body.appendChild(a);
  3314. try
  3315. {
  3316. window.setTimeout(function()
  3317. {
  3318. URL.revokeObjectURL(a.href);
  3319. }, 0);
  3320. a.click();
  3321. a.parentNode.removeChild(a);
  3322. }
  3323. catch (e)
  3324. {
  3325. // ignore
  3326. }
  3327. }
  3328. else
  3329. {
  3330. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  3331. req.simulate(document, '_blank');
  3332. }
  3333. }
  3334. };
  3335. /**
  3336. * Translates this point by the given vector.
  3337. *
  3338. * @param {number} dx X-coordinate of the translation.
  3339. * @param {number} dy Y-coordinate of the translation.
  3340. */
  3341. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  3342. {
  3343. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  3344. 'data=' + encodeURIComponent(Graph.compress(data));
  3345. return new mxXmlRequest(SAVE_URL, param +
  3346. ((mimeType != null) ? '&mime=' + mimeType : '') +
  3347. ((format != null) ? '&format=' + format : '') +
  3348. ((base64Response != null) ? '&base64=' + base64Response : '') +
  3349. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  3350. ((base64Encoded) ? '&binary=1' : ''));
  3351. };
  3352. /**
  3353. * Translates this point by the given vector.
  3354. *
  3355. * @param {number} dx X-coordinate of the translation.
  3356. * @param {number} dy Y-coordinate of the translation.
  3357. */
  3358. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  3359. {
  3360. contentType = contentType || '';
  3361. var sliceSize = 1024;
  3362. var byteCharacters = atob(base64Data);
  3363. var bytesLength = byteCharacters.length;
  3364. var slicesCount = Math.ceil(bytesLength / sliceSize);
  3365. var byteArrays = new Array(slicesCount);
  3366. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  3367. {
  3368. var begin = sliceIndex * sliceSize;
  3369. var end = Math.min(begin + sliceSize, bytesLength);
  3370. var bytes = new Array(end - begin);
  3371. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  3372. {
  3373. bytes[i] = byteCharacters[offset].charCodeAt(0);
  3374. }
  3375. byteArrays[sliceIndex] = new Uint8Array(bytes);
  3376. }
  3377. return new Blob(byteArrays, {type: contentType});
  3378. };
  3379. /**
  3380. * Translates this point by the given vector.
  3381. *
  3382. * @param {number} dx X-coordinate of the translation.
  3383. * @param {number} dy Y-coordinate of the translation.
  3384. */
  3385. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab)
  3386. {
  3387. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  3388. allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  3389. var count = this.getServiceCount(allowBrowser);
  3390. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3391. {
  3392. try
  3393. {
  3394. // Opens a new window
  3395. if (mode == '_blank')
  3396. {
  3397. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  3398. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  3399. {
  3400. this.openInNewWindow(data, mimeType, base64Encoded);
  3401. }
  3402. else
  3403. {
  3404. var win = window.open('about:blank');
  3405. if (win == null)
  3406. {
  3407. mxUtils.popup(data, true);
  3408. }
  3409. else
  3410. {
  3411. win.document.write(mxUtils.htmlEntities(data, false));
  3412. win.document.close();
  3413. }
  3414. }
  3415. }
  3416. else if (mode == App.MODE_DEVICE || mode == 'download')
  3417. {
  3418. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  3419. }
  3420. else if (newTitle != null && newTitle.length > 0)
  3421. {
  3422. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3423. {
  3424. try
  3425. {
  3426. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  3427. }
  3428. catch (e)
  3429. {
  3430. this.handleError(e);
  3431. }
  3432. }));
  3433. }
  3434. }
  3435. catch (e)
  3436. {
  3437. this.handleError(e);
  3438. }
  3439. }), mxUtils.bind(this, function()
  3440. {
  3441. this.hideDialog();
  3442. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
  3443. null, count > 1, (count > 4 && (!allowBrowser || count < 6)) ? 3 : 4, data, mimeType, base64Encoded);
  3444. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3445. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3446. this.showDialog(dlg.container, 420, height, true, true);
  3447. dlg.init();
  3448. };
  3449. /**
  3450. *
  3451. */
  3452. EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
  3453. {
  3454. // In Google Chrome 60 the code from below produces a blank window
  3455. if (mxClient.IS_GC || mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  3456. {
  3457. var win = window.open('about:blank');
  3458. if (win == null || win.document == null)
  3459. {
  3460. mxUtils.popup(data, true);
  3461. }
  3462. else
  3463. {
  3464. // Workaround for broken images in SVG output in Chrome
  3465. if (mimeType == 'image/svg+xml')
  3466. {
  3467. win.document.write('<html>' + data + '</html>');
  3468. }
  3469. else
  3470. {
  3471. win.document.write('<html><img src="data:' +
  3472. mimeType + ((base64Encoded) ? ';base64,' +
  3473. data : ';charset=utf8,' + encodeURIComponent(data)) +
  3474. '"/></html>');
  3475. }
  3476. win.document.close();
  3477. }
  3478. }
  3479. else
  3480. {
  3481. // win.open is workaround for cleared contents in Chrome after delay
  3482. // when using location.replace
  3483. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  3484. data : ';charset=utf8,' + encodeURIComponent(data)));
  3485. if (win == null || win.document == null)
  3486. {
  3487. mxUtils.popup(data, true);
  3488. }
  3489. }
  3490. };
  3491. var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
  3492. /**
  3493. * Creates a temporary graph instance for rendering off-screen content.
  3494. */
  3495. EditorUi.prototype.addChromelessToolbarItems = function(addButton)
  3496. {
  3497. if (this.isExportToCanvas())
  3498. {
  3499. this.exportDialog = null;
  3500. var exportButton = addButton(mxUtils.bind(this, function(evt)
  3501. {
  3502. var clickHandler = mxUtils.bind(this, function()
  3503. {
  3504. mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
  3505. if (this.exportDialog != null)
  3506. {
  3507. this.exportDialog.parentNode.removeChild(this.exportDialog);
  3508. this.exportDialog = null;
  3509. }
  3510. });
  3511. if (this.exportDialog != null)
  3512. {
  3513. clickHandler.apply(this);
  3514. }
  3515. else
  3516. {
  3517. this.exportDialog = document.createElement('div');
  3518. var r = exportButton.getBoundingClientRect();
  3519. mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
  3520. this.exportDialog.style.position = 'fixed';
  3521. this.exportDialog.style.textAlign = 'center';
  3522. this.exportDialog.style.fontFamily = 'Helvetica,Arial';
  3523. this.exportDialog.style.backgroundColor = '#000000';
  3524. this.exportDialog.style.width = '50px';
  3525. this.exportDialog.style.height = '50px';
  3526. this.exportDialog.style.padding = '4px 2px 4px 2px';
  3527. this.exportDialog.style.color = '#ffffff';
  3528. mxUtils.setOpacity(this.exportDialog, 70);
  3529. this.exportDialog.style.left = r.left + 'px';
  3530. this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  3531. this.chromelessToolbar.offsetHeight + 4 + 'px';
  3532. // Puts the dialog on top of the container z-index
  3533. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  3534. this.exportDialog.style.zIndex = style.zIndex;
  3535. var spinner = new Spinner({
  3536. lines: 8, // The number of lines to draw
  3537. length: 6, // The length of each line
  3538. width: 5, // The line thickness
  3539. radius: 6, // The radius of the inner circle
  3540. rotate: 0, // The rotation offset
  3541. color: '#fff', // #rgb or #rrggbb
  3542. speed: 1.5, // Rounds per second
  3543. trail: 60, // Afterglow percentage
  3544. shadow: false, // Whether to render a shadow
  3545. hwaccel: false, // Whether to use hardware acceleration
  3546. top: '28px',
  3547. zIndex: 2e9 // The z-index (defaults to 2000000000)
  3548. });
  3549. spinner.spin(this.exportDialog);
  3550. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3551. {
  3552. spinner.stop();
  3553. this.exportDialog.style.width = 'auto';
  3554. this.exportDialog.style.height = 'auto';
  3555. this.exportDialog.style.padding = '10px';
  3556. var data = this.createImageDataUri(canvas, null, 'png');
  3557. var img = document.createElement('img');
  3558. img.style.maxWidth = '140px';
  3559. img.style.maxHeight = '140px';
  3560. img.style.cursor = 'pointer';
  3561. img.style.backgroundColor = 'white';
  3562. img.setAttribute('title', mxResources.get('openInNewWindow'));
  3563. img.setAttribute('border', '0');
  3564. img.setAttribute('src', data);
  3565. this.exportDialog.appendChild(img);
  3566. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  3567. {
  3568. this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
  3569. clickHandler.apply(this, arguments);
  3570. }));
  3571. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3572. {
  3573. this.spinner.stop();
  3574. this.handleError(e);
  3575. }));
  3576. mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
  3577. document.body.appendChild(this.exportDialog);
  3578. }
  3579. mxEvent.consume(evt);
  3580. }), Editor.cameraLargeImage, mxResources.get('export'));
  3581. }
  3582. editoUiAddChromelessToolbarItems.apply(this, arguments);
  3583. };
  3584. /**
  3585. * Translates this point by the given vector.
  3586. *
  3587. * @param {number} dx X-coordinate of the translation.
  3588. * @param {number} dy Y-coordinate of the translation.
  3589. */
  3590. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  3591. {
  3592. if (this.isLocalFileSave())
  3593. {
  3594. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  3595. }
  3596. else
  3597. {
  3598. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  3599. {
  3600. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  3601. }), data, base64Encoded, mime);
  3602. }
  3603. };
  3604. /**
  3605. * Translates this point by the given vector.
  3606. *
  3607. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  3608. * side without requiring a server roundtrip.
  3609. *
  3610. * @param {number} dx X-coordinate of the translation.
  3611. * @param {number} dy Y-coordinate of the translation.
  3612. */
  3613. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
  3614. {
  3615. allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
  3616. var count = this.getServiceCount(false);
  3617. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3618. {
  3619. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  3620. {
  3621. var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
  3622. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  3623. if (xhr != null)
  3624. {
  3625. if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
  3626. {
  3627. xhr.simulate(document, '_blank');
  3628. }
  3629. else
  3630. {
  3631. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3632. {
  3633. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  3634. 'application/pdf' : 'image/' + format);
  3635. // Workaround for no roundtrip required if data is available on client-side
  3636. // TODO: Refactor the saveData/saveRequest call chain for local data
  3637. if (data != null)
  3638. {
  3639. try
  3640. {
  3641. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  3642. }
  3643. catch (e)
  3644. {
  3645. this.handleError(e);
  3646. }
  3647. }
  3648. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  3649. {
  3650. // LATER: Catch possible mixed content error
  3651. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  3652. xhr.send(mxUtils.bind(this, function()
  3653. {
  3654. this.spinner.stop();
  3655. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  3656. {
  3657. try
  3658. {
  3659. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  3660. }
  3661. catch (e)
  3662. {
  3663. this.handleError(e);
  3664. }
  3665. }
  3666. else
  3667. {
  3668. this.handleError({message: mxResources.get('errorSavingFile')});
  3669. }
  3670. }), function(resp)
  3671. {
  3672. this.spinner.stop();
  3673. this.handleError(resp);
  3674. });
  3675. }
  3676. }));
  3677. }
  3678. }
  3679. }
  3680. }), mxUtils.bind(this, function()
  3681. {
  3682. this.hideDialog();
  3683. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
  3684. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  3685. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3686. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3687. this.showDialog(dlg.container, 380, height, true, true);
  3688. dlg.init();
  3689. };
  3690. /**
  3691. *
  3692. */
  3693. EditorUi.prototype.getEditBlankXml = function()
  3694. {
  3695. return this.getFileData(true);
  3696. };
  3697. /**
  3698. * Hook for subclassers.
  3699. */
  3700. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  3701. {
  3702. // do nothing
  3703. };
  3704. /**
  3705. * Hook for subclassers.
  3706. */
  3707. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  3708. {
  3709. fn(null);
  3710. };
  3711. /**
  3712. *
  3713. */
  3714. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow,
  3715. editable, embedImages, border, noCrop, currentPage, linkTarget)
  3716. {
  3717. if (this.spinner.spin(document.body, mxResources.get('export')))
  3718. {
  3719. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3720. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3721. var bg = (transparentBackground) ? null : this.editor.graph.background;
  3722. if (bg == mxConstants.NONE)
  3723. {
  3724. bg = null;
  3725. }
  3726. // Handles special case where background is null but transparent is false
  3727. if (bg == null && transparentBackground == false)
  3728. {
  3729. bg = '#ffffff';
  3730. }
  3731. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3732. // because PhantomJS seems to ignore switch statements and paint all text.
  3733. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null,
  3734. ignoreSelection, null, null, (linkTarget == 'blank') ? '_blank' :
  3735. ((linkTarget == 'self') ? '_top' : null));
  3736. if (addShadow)
  3737. {
  3738. this.editor.graph.addSvgShadow(svgRoot);
  3739. }
  3740. var filename = this.getBaseFilename() + '.svg';
  3741. var doSave = mxUtils.bind(this, function(svgRoot)
  3742. {
  3743. this.spinner.stop();
  3744. if (editable)
  3745. {
  3746. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  3747. }
  3748. if (this.editor.fontCss != null)
  3749. {
  3750. var svgDoc = svgRoot.ownerDocument;
  3751. var style = (svgDoc.createElementNS != null) ?
  3752. svgDoc.createElementNS(mxConstants.NS_SVG, 'style') : svgDoc.createElement('style');
  3753. style.setAttribute('type', 'text/css');
  3754. mxUtils.setTextContent(style, this.editor.fontCss);
  3755. svgRoot.getElementsByTagName('defs')[0].appendChild(style);
  3756. }
  3757. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  3758. mxUtils.getXml(svgRoot);
  3759. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  3760. {
  3761. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  3762. }
  3763. else
  3764. {
  3765. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  3766. {
  3767. mxUtils.popup(svg);
  3768. }));
  3769. }
  3770. });
  3771. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  3772. {
  3773. if (embedImages)
  3774. {
  3775. // Caches images
  3776. if (this.thumbImageCache == null)
  3777. {
  3778. this.thumbImageCache = new Object();
  3779. }
  3780. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  3781. }
  3782. else
  3783. {
  3784. doSave(svgRoot);
  3785. }
  3786. }));
  3787. }
  3788. };
  3789. EditorUi.prototype.addRadiobox = function(div, radioGroupName, label, checked, disabled, disableNewline, visible)
  3790. {
  3791. return this.addCheckbox(div, label, checked, disabled, disableNewline, visible, true, radioGroupName);
  3792. }
  3793. /**
  3794. *
  3795. */
  3796. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible, asRadio, radioGroupName)
  3797. {
  3798. visible = (visible != null) ? visible : true;
  3799. var cb = document.createElement('input');
  3800. cb.style.marginRight = '8px';
  3801. cb.style.marginTop = '16px';
  3802. cb.setAttribute('type', asRadio? 'radio' : 'checkbox');
  3803. var id = 'geCheckbox-' + Editor.guid();
  3804. cb.id = id;
  3805. if (radioGroupName != null)
  3806. {
  3807. cb.setAttribute('name', radioGroupName);
  3808. }
  3809. if (checked)
  3810. {
  3811. cb.setAttribute('checked', 'checked');
  3812. cb.defaultChecked = true;
  3813. }
  3814. if (disabled)
  3815. {
  3816. cb.setAttribute('disabled', 'disabled');
  3817. }
  3818. if (visible)
  3819. {
  3820. div.appendChild(cb);
  3821. var lbl = document.createElement('label');
  3822. mxUtils.write(lbl, label);
  3823. lbl.setAttribute('for', id);
  3824. div.appendChild(lbl);
  3825. if (!disableNewline)
  3826. {
  3827. mxUtils.br(div);
  3828. }
  3829. }
  3830. return cb;
  3831. };
  3832. /**
  3833. *
  3834. */
  3835. EditorUi.prototype.addEditButton = function(div, lightbox)
  3836. {
  3837. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  3838. edit.style.marginLeft = '24px';
  3839. var file = this.getCurrentFile();
  3840. var editUrl = '';
  3841. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  3842. {
  3843. editUrl = window.location.href;
  3844. }
  3845. var editSelect = document.createElement('select');
  3846. editSelect.style.width = '120px';
  3847. editSelect.style.marginLeft = '8px';
  3848. editSelect.style.marginRight = '10px';
  3849. editSelect.className = 'geBtn';
  3850. var blankOption = document.createElement('option');
  3851. blankOption.setAttribute('value', 'blank');
  3852. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  3853. editSelect.appendChild(blankOption);
  3854. var customOption = document.createElement('option');
  3855. customOption.setAttribute('value', 'custom');
  3856. mxUtils.write(customOption, mxResources.get('custom') + '...');
  3857. editSelect.appendChild(customOption);
  3858. div.appendChild(editSelect);
  3859. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  3860. {
  3861. if (editSelect.value == 'custom')
  3862. {
  3863. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  3864. {
  3865. if (value != null)
  3866. {
  3867. editUrl = value;
  3868. }
  3869. else
  3870. {
  3871. editSelect.value = 'blank';
  3872. }
  3873. }, mxResources.get('url'), null, null, null, null, function()
  3874. {
  3875. editSelect.value = 'blank';
  3876. });
  3877. this.showDialog(dlg2.container, 300, 80, true, false);
  3878. dlg2.init();
  3879. }
  3880. }));
  3881. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  3882. {
  3883. if (edit.checked && (lightbox == null || lightbox.checked))
  3884. {
  3885. editSelect.removeAttribute('disabled');
  3886. }
  3887. else
  3888. {
  3889. editSelect.setAttribute('disabled', 'disabled');
  3890. }
  3891. }));
  3892. mxUtils.br(div);
  3893. return {
  3894. getLink: function()
  3895. {
  3896. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  3897. },
  3898. getEditInput: function()
  3899. {
  3900. return edit;
  3901. },
  3902. getEditSelect: function()
  3903. {
  3904. return editSelect;
  3905. }
  3906. };
  3907. }
  3908. /**
  3909. *
  3910. */
  3911. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  3912. {
  3913. mxUtils.write(div, mxResources.get('links') + ':');
  3914. var linkSelect = document.createElement('select');
  3915. linkSelect.style.width = '100px';
  3916. linkSelect.style.marginLeft = '8px';
  3917. linkSelect.style.marginRight = '10px';
  3918. linkSelect.className = 'geBtn';
  3919. var autoOption = document.createElement('option');
  3920. autoOption.setAttribute('value', 'auto');
  3921. mxUtils.write(autoOption, mxResources.get('automatic'));
  3922. linkSelect.appendChild(autoOption);
  3923. var blankOption = document.createElement('option');
  3924. blankOption.setAttribute('value', 'blank');
  3925. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  3926. linkSelect.appendChild(blankOption);
  3927. var selfOption = document.createElement('option');
  3928. selfOption.setAttribute('value', 'self');
  3929. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  3930. linkSelect.appendChild(selfOption);
  3931. if (showFrameOption)
  3932. {
  3933. var frameOption = document.createElement('option');
  3934. frameOption.setAttribute('value', 'frame');
  3935. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  3936. ' (' + mxResources.get('iframe') + ')');
  3937. linkSelect.appendChild(frameOption);
  3938. }
  3939. div.appendChild(linkSelect);
  3940. mxUtils.write(div, mxResources.get('borderColor') + ':');
  3941. var linkColor = '#0000ff';
  3942. var linkButton = null;
  3943. function updateLinkColor()
  3944. {
  3945. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  3946. ((linkColor != null && linkColor != mxConstants.NONE) ?
  3947. 'border:1px solid black;background-color:' + linkColor :
  3948. 'background-position:center center;background-repeat:no-repeat;' +
  3949. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  3950. };
  3951. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  3952. {
  3953. this.pickColor(linkColor || 'none', function(color)
  3954. {
  3955. linkColor = color;
  3956. updateLinkColor();
  3957. });
  3958. mxEvent.consume(evt);
  3959. }));
  3960. updateLinkColor();
  3961. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  3962. linkButton.style.marginLeft = '4px';
  3963. linkButton.style.height = '22px';
  3964. linkButton.style.width = '22px';
  3965. linkButton.style.position = 'relative';
  3966. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  3967. linkButton.className = 'geColorBtn';
  3968. div.appendChild(linkButton);
  3969. mxUtils.br(div);
  3970. return {
  3971. getColor: function()
  3972. {
  3973. return linkColor;
  3974. },
  3975. getTarget: function()
  3976. {
  3977. return linkSelect.value;
  3978. },
  3979. focus: function()
  3980. {
  3981. linkSelect.focus();
  3982. }
  3983. };
  3984. }
  3985. /**
  3986. *
  3987. */
  3988. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  3989. {
  3990. var file = this.getCurrentFile();
  3991. var params = [];
  3992. if (lightbox)
  3993. {
  3994. params.push('lightbox=1');
  3995. if (linkTarget != 'auto')
  3996. {
  3997. params.push('target=' + linkTarget);
  3998. }
  3999. if (linkColor != null && linkColor != mxConstants.NONE)
  4000. {
  4001. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  4002. }
  4003. if (editLink != null && editLink.length > 0)
  4004. {
  4005. params.push('edit=' + encodeURIComponent(editLink));
  4006. }
  4007. if (layers)
  4008. {
  4009. params.push('layers=1');
  4010. }
  4011. if (this.editor.graph.foldingEnabled)
  4012. {
  4013. params.push('nav=1');
  4014. }
  4015. }
  4016. if (allPages && this.currentPage != null && this.pages != null &&
  4017. this.currentPage != this.pages[0])
  4018. {
  4019. params.push('page-id=' + this.currentPage.getId());
  4020. }
  4021. var data = '';
  4022. var addTitle = true;
  4023. if (url != null)
  4024. {
  4025. data = '#U' + encodeURIComponent(url);
  4026. }
  4027. else
  4028. {
  4029. var file = this.getCurrentFile();
  4030. // Fallback to non-public URL for Drive files
  4031. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  4032. {
  4033. data = '#' + file.getHash();
  4034. addTitle = false;
  4035. }
  4036. else
  4037. {
  4038. data = '#R' + encodeURIComponent((allPages) ?
  4039. this.getFileData(true, null, null, null, null, null, null, true) :
  4040. Graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  4041. }
  4042. }
  4043. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  4044. {
  4045. params.push('title=' + encodeURIComponent(file.getTitle()));
  4046. }
  4047. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || !(/.*\.draw\.io$/.test(window.location.hostname))) ?
  4048. EditorUi.drawHost : 'https://' + window.location.host + '/') +
  4049. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  4050. };
  4051. /**
  4052. *
  4053. */
  4054. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  4055. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  4056. {
  4057. var s = this.getBasenames();
  4058. var data = {};
  4059. if (linkColor != '' && linkColor != mxConstants.NONE)
  4060. {
  4061. data.highlight = linkColor;
  4062. }
  4063. if (linkTarget !== 'auto')
  4064. {
  4065. data.target = linkTarget;
  4066. }
  4067. if (!lightbox)
  4068. {
  4069. data.lightbox = false;
  4070. }
  4071. data.nav = this.editor.graph.foldingEnabled;
  4072. var zoom = parseInt(initialZoom);
  4073. if (!isNaN(zoom) && zoom != 100)
  4074. {
  4075. data.zoom = zoom / 100;
  4076. }
  4077. var tb = [];
  4078. if (allPages)
  4079. {
  4080. tb.push('pages');
  4081. data.resize = true;
  4082. if (this.pages != null && this.currentPage != null)
  4083. {
  4084. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  4085. }
  4086. }
  4087. if (zoomEnabled)
  4088. {
  4089. tb.push('zoom');
  4090. data.resize = true;
  4091. }
  4092. if (layers)
  4093. {
  4094. tb.push('layers');
  4095. }
  4096. if (tb.length > 0)
  4097. {
  4098. if (lightbox)
  4099. {
  4100. tb.push('lightbox');
  4101. }
  4102. data.toolbar = tb.join(' ');
  4103. }
  4104. if (editLink != null && editLink.length > 0)
  4105. {
  4106. data.edit = editLink;
  4107. }
  4108. if (publicUrl != null)
  4109. {
  4110. data.url = publicUrl;
  4111. }
  4112. else
  4113. {
  4114. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  4115. }
  4116. var value = '<div class="mxgraph" style="' +
  4117. ((fit) ? 'max-width:100%;' : '') +
  4118. ((tb != '') ? 'border:1px solid transparent;' : '') +
  4119. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  4120. var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
  4121. var s2 = (fetchParam.length > 0) ?
  4122. (((urlParams['dev'] == '1') ?
  4123. 'https://test.draw.io/embed2.js?dev=1' :
  4124. EditorUi.drawHost + '/embed2.js?')) + fetchParam :
  4125. (((urlParams['dev'] == '1') ?
  4126. 'https://test.draw.io/js/viewer.min.js' :
  4127. window.VIEWER_URL ? window.VIEWER_URL : EditorUi.drawHost + '/js/viewer.min.js'));
  4128. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  4129. fn(value, scr);
  4130. };
  4131. /**
  4132. *
  4133. */
  4134. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  4135. {
  4136. var div = document.createElement('div');
  4137. div.style.whiteSpace = 'nowrap';
  4138. var graph = this.editor.graph;
  4139. var hd = document.createElement('h3');
  4140. mxUtils.write(hd, mxResources.get('html'));
  4141. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4142. div.appendChild(hd);
  4143. var radioSection = document.createElement('div');
  4144. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  4145. var publicUrlRadio = document.createElement('input');
  4146. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  4147. publicUrlRadio.setAttribute('value', 'url');
  4148. publicUrlRadio.setAttribute('type', 'radio');
  4149. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  4150. var copyRadio = publicUrlRadio.cloneNode(true);
  4151. copyRadio.setAttribute('value', 'copy');
  4152. radioSection.appendChild(copyRadio);
  4153. var span = document.createElement('span');
  4154. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  4155. radioSection.appendChild(span);
  4156. mxUtils.br(radioSection);
  4157. radioSection.appendChild(publicUrlRadio);
  4158. var span = document.createElement('span');
  4159. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  4160. radioSection.appendChild(span);
  4161. var file = this.getCurrentFile();
  4162. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  4163. {
  4164. var testLink = document.createElement('a');
  4165. testLink.style.paddingLeft = '12px';
  4166. testLink.style.color = 'gray';
  4167. testLink.setAttribute('href', 'javascript:void(0);');
  4168. mxUtils.write(testLink, mxResources.get('share'));
  4169. radioSection.appendChild(testLink);
  4170. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4171. {
  4172. this.hideDialog();
  4173. this.drive.showPermissions(file.getId());
  4174. }));
  4175. }
  4176. copyRadio.setAttribute('checked', 'checked');
  4177. if (publicUrl == null)
  4178. {
  4179. publicUrlRadio.setAttribute('disabled', 'disabled');
  4180. }
  4181. div.appendChild(radioSection);
  4182. var linkSection = this.addLinkSection(div);
  4183. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  4184. mxUtils.write(div, ':');
  4185. var zoomInput = document.createElement('input');
  4186. zoomInput.setAttribute('type', 'text');
  4187. zoomInput.style.marginRight = '16px';
  4188. zoomInput.style.width = '60px';
  4189. zoomInput.style.marginLeft = '4px';
  4190. zoomInput.style.marginRight = '12px';
  4191. zoomInput.value = '100%';
  4192. div.appendChild(zoomInput);
  4193. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4194. var hasPages = this.pages != null && this.pages.length > 1;
  4195. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4196. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4197. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4198. var editSection = this.addEditButton(div, lightbox);
  4199. var edit = editSection.getEditInput();
  4200. edit.style.marginBottom = '16px';
  4201. mxEvent.addListener(lightbox, 'change', function()
  4202. {
  4203. if (lightbox.checked)
  4204. {
  4205. edit.removeAttribute('disabled');
  4206. }
  4207. else
  4208. {
  4209. edit.setAttribute('disabled', 'disabled');
  4210. }
  4211. if (edit.checked && lightbox.checked)
  4212. {
  4213. editSection.getEditSelect().removeAttribute('disabled');
  4214. }
  4215. else
  4216. {
  4217. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4218. }
  4219. });
  4220. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4221. {
  4222. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  4223. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  4224. editSection.getLink());
  4225. }), null, btnLabel, helpLink);
  4226. this.showDialog(dlg.container, 340, 384, true, true);
  4227. copyRadio.focus();
  4228. };
  4229. /**
  4230. *
  4231. */
  4232. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  4233. {
  4234. var div = document.createElement('div');
  4235. div.style.whiteSpace = 'nowrap';
  4236. var graph = this.editor.graph;
  4237. var hd = document.createElement('h3');
  4238. mxUtils.write(hd, title || mxResources.get('link'));
  4239. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4240. div.appendChild(hd);
  4241. var file = this.getCurrentFile();
  4242. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  4243. var dy = 0;
  4244. if (file != null && file.constructor == window.DriveFile && !hideShare)
  4245. {
  4246. dy = 80;
  4247. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  4248. var hintSection = document.createElement('div');
  4249. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  4250. var text = document.createElement('div');
  4251. text.style.whiteSpace = 'normal';
  4252. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  4253. hintSection.appendChild(text);
  4254. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  4255. {
  4256. this.drive.showPermissions(file.getId());
  4257. }));
  4258. shareBtn.style.marginTop = '12px';
  4259. shareBtn.className = 'geBtn';
  4260. hintSection.appendChild(shareBtn);
  4261. div.appendChild(hintSection);
  4262. var testLink = document.createElement('a');
  4263. testLink.style.paddingLeft = '12px';
  4264. testLink.style.color = 'gray';
  4265. testLink.style.fontSize = '11px';
  4266. testLink.setAttribute('href', 'javascript:void(0);');
  4267. mxUtils.write(testLink, mxResources.get('check'));
  4268. hintSection.appendChild(testLink);
  4269. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4270. {
  4271. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4272. {
  4273. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  4274. {
  4275. this.spinner.stop();
  4276. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  4277. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  4278. this.showDialog(dlg.container, 300, 80, true, false);
  4279. dlg.init();
  4280. }));
  4281. }
  4282. }));
  4283. }
  4284. var widthInput = null;
  4285. var heightInput = null;
  4286. if (width != null || height != null)
  4287. {
  4288. dy += 30;
  4289. mxUtils.write(div, mxResources.get('width') + ':');
  4290. widthInput = document.createElement('input');
  4291. widthInput.setAttribute('type', 'text');
  4292. widthInput.style.marginRight = '16px';
  4293. widthInput.style.width = '50px';
  4294. widthInput.style.marginLeft = '6px';
  4295. widthInput.style.marginRight = '16px';
  4296. widthInput.style.marginBottom = '10px';
  4297. widthInput.value = '100%';
  4298. div.appendChild(widthInput);
  4299. mxUtils.write(div, mxResources.get('height') + ':');
  4300. heightInput = document.createElement('input');
  4301. heightInput.setAttribute('type', 'text');
  4302. heightInput.style.width = '50px';
  4303. heightInput.style.marginLeft = '6px';
  4304. heightInput.style.marginBottom = '10px';
  4305. heightInput.value = height + 'px';
  4306. div.appendChild(heightInput);
  4307. mxUtils.br(div);
  4308. }
  4309. var linkSection = this.addLinkSection(div, showFrameOption);
  4310. var hasPages = this.pages != null && this.pages.length > 1;
  4311. var allPages = null;
  4312. if (file == null || file.constructor != window.DriveFile || hideShare)
  4313. {
  4314. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4315. }
  4316. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4317. var editSection = this.addEditButton(div, lightbox);
  4318. var edit = editSection.getEditInput();
  4319. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4320. layers.style.marginLeft = edit.style.marginLeft;
  4321. layers.style.marginBottom = '16px';
  4322. layers.style.marginTop = '8px';
  4323. mxEvent.addListener(lightbox, 'change', function()
  4324. {
  4325. if (lightbox.checked)
  4326. {
  4327. layers.removeAttribute('disabled');
  4328. edit.removeAttribute('disabled');
  4329. }
  4330. else
  4331. {
  4332. layers.setAttribute('disabled', 'disabled');
  4333. edit.setAttribute('disabled', 'disabled');
  4334. }
  4335. if (edit.checked && lightbox.checked)
  4336. {
  4337. editSection.getEditSelect().removeAttribute('disabled');
  4338. }
  4339. else
  4340. {
  4341. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4342. }
  4343. });
  4344. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4345. {
  4346. fn(linkSection.getTarget(), linkSection.getColor(),
  4347. (allPages == null) ? true : allPages.checked,
  4348. lightbox.checked, editSection.getLink(),
  4349. layers.checked, (widthInput != null) ? widthInput.value : null,
  4350. (heightInput != null) ? heightInput.value : null);
  4351. }), null, mxResources.get('create'), helpLink);
  4352. this.showDialog(dlg.container, 340, 254 + dy, true, true);
  4353. if (widthInput != null)
  4354. {
  4355. widthInput.focus();
  4356. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4357. {
  4358. widthInput.select();
  4359. }
  4360. else
  4361. {
  4362. document.execCommand('selectAll', false, null);
  4363. }
  4364. }
  4365. else
  4366. {
  4367. linkSection.focus();
  4368. }
  4369. };
  4370. /**
  4371. *
  4372. */
  4373. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  4374. {
  4375. var div = document.createElement('div');
  4376. div.style.whiteSpace = 'nowrap';
  4377. var hd = document.createElement('h3');
  4378. mxUtils.write(hd, mxResources.get('image'));
  4379. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4380. div.appendChild(hd);
  4381. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  4382. this.editor.graph.isSelectionEmpty());
  4383. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  4384. var graph = this.editor.graph;
  4385. var transparent = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('transparentBackground'),
  4386. graph.background == mxConstants.NONE || graph.background == null);
  4387. if (transparent != null)
  4388. {
  4389. transparent.style.marginBottom = '16px';
  4390. }
  4391. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4392. {
  4393. callback(!selection.checked, (include != null) ? include.checked : false,
  4394. (transparent != null) ? transparent.checked : false);
  4395. }), null, btnLabel, helpLink);
  4396. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 186, true, true);
  4397. };
  4398. /**
  4399. *
  4400. */
  4401. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  4402. cropOption, defaultInclude, format)
  4403. {
  4404. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  4405. var div = document.createElement('div');
  4406. div.style.whiteSpace = 'nowrap';
  4407. var graph = this.editor.graph;
  4408. var height = (format == 'jpeg') ? 196 : 300;
  4409. var hd = document.createElement('h3');
  4410. mxUtils.write(hd, title);
  4411. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  4412. div.appendChild(hd);
  4413. mxUtils.write(div, mxResources.get('zoom') + ':');
  4414. var zoomInput = document.createElement('input');
  4415. zoomInput.setAttribute('type', 'text');
  4416. zoomInput.style.marginRight = '16px';
  4417. zoomInput.style.width = '60px';
  4418. zoomInput.style.marginLeft = '4px';
  4419. zoomInput.style.marginRight = '12px';
  4420. zoomInput.value = this.lastExportZoom || '100%';
  4421. div.appendChild(zoomInput);
  4422. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  4423. var borderInput = document.createElement('input');
  4424. borderInput.setAttribute('type', 'text');
  4425. borderInput.style.marginRight = '16px';
  4426. borderInput.style.width = '60px';
  4427. borderInput.style.marginLeft = '4px';
  4428. borderInput.value = this.lastExportBorder || '0';
  4429. div.appendChild(borderInput);
  4430. mxUtils.br(div);
  4431. var defaultTransparent = false; /*graph.background == mxConstants.NONE || graph.background == null*/;
  4432. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  4433. defaultTransparent, null, null, format != 'jpeg');
  4434. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  4435. false, graph.isSelectionEmpty());
  4436. var cb6 = document.createElement('input');
  4437. cb6.style.marginTop = '16px';
  4438. cb6.style.marginRight = '8px';
  4439. cb6.style.marginLeft = '24px';
  4440. cb6.setAttribute('disabled', 'disabled');
  4441. cb6.setAttribute('type', 'checkbox');
  4442. if (cropOption)
  4443. {
  4444. div.appendChild(cb6);
  4445. mxUtils.write(div, mxResources.get('crop'));
  4446. mxUtils.br(div);
  4447. height += 26;
  4448. mxEvent.addListener(selection, 'change', function()
  4449. {
  4450. if (selection.checked)
  4451. {
  4452. cb6.removeAttribute('disabled');
  4453. }
  4454. else
  4455. {
  4456. cb6.setAttribute('disabled', 'disabled');
  4457. }
  4458. });
  4459. }
  4460. if (!graph.isSelectionEmpty())
  4461. {
  4462. cb6.setAttribute('checked', 'checked');
  4463. cb6.defaultChecked = true;
  4464. }
  4465. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  4466. var cb5 = document.createElement('input');
  4467. cb5.style.marginTop = '16px';
  4468. cb5.style.marginRight = '8px';
  4469. cb5.setAttribute('type', 'checkbox');
  4470. if (this.isOffline() || !this.canvasSupported)
  4471. {
  4472. cb5.setAttribute('disabled', 'disabled');
  4473. }
  4474. if (embedOption)
  4475. {
  4476. div.appendChild(cb5);
  4477. mxUtils.write(div, mxResources.get('embedImages'));
  4478. mxUtils.br(div);
  4479. height += 26;
  4480. }
  4481. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  4482. var hasPages = this.pages != null && this.pages.length > 1;
  4483. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  4484. allPages.style.marginLeft = '24px';
  4485. allPages.style.marginBottom = '16px';
  4486. if (!hasPages)
  4487. {
  4488. allPages.style.display = 'none';
  4489. }
  4490. mxEvent.addListener(include, 'change', function()
  4491. {
  4492. if (include.checked && hasPages)
  4493. {
  4494. allPages.removeAttribute('disabled');
  4495. }
  4496. else
  4497. {
  4498. allPages.setAttribute('disabled', 'disabled');
  4499. }
  4500. });
  4501. if (!defaultInclude || !hasPages)
  4502. {
  4503. allPages.setAttribute('disabled', 'disabled');
  4504. }
  4505. var linkSelect = document.createElement('select');
  4506. linkSelect.style.maxWidth = '260px';
  4507. linkSelect.style.marginLeft = '8px';
  4508. linkSelect.style.marginRight = '10px';
  4509. linkSelect.className = 'geBtn';
  4510. var autoOption = document.createElement('option');
  4511. autoOption.setAttribute('value', 'auto');
  4512. mxUtils.write(autoOption, mxResources.get('automatic'));
  4513. linkSelect.appendChild(autoOption);
  4514. var blankOption = document.createElement('option');
  4515. blankOption.setAttribute('value', 'blank');
  4516. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  4517. linkSelect.appendChild(blankOption);
  4518. var selfOption = document.createElement('option');
  4519. selfOption.setAttribute('value', 'self');
  4520. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  4521. linkSelect.appendChild(selfOption);
  4522. if (format == 'svg')
  4523. {
  4524. mxUtils.write(div, mxResources.get('links') + ':');
  4525. div.appendChild(linkSelect);
  4526. mxUtils.br(div);
  4527. mxUtils.br(div);
  4528. height += 26;
  4529. }
  4530. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4531. {
  4532. this.lastExportBorder = borderInput.value;
  4533. this.lastExportZoom = zoomInput.value;
  4534. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  4535. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked,
  4536. linkSelect.value);
  4537. }), null, btnLabel, helpLink);
  4538. this.showDialog(dlg.container, 340, height, true, true);
  4539. zoomInput.focus();
  4540. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4541. {
  4542. zoomInput.select();
  4543. }
  4544. else
  4545. {
  4546. document.execCommand('selectAll', false, null);
  4547. }
  4548. };
  4549. /**
  4550. *
  4551. */
  4552. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  4553. {
  4554. var div = document.createElement('div');
  4555. div.style.whiteSpace = 'nowrap';
  4556. var graph = this.editor.graph;
  4557. if (title != null)
  4558. {
  4559. var hd = document.createElement('h3');
  4560. mxUtils.write(hd, title);
  4561. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4562. div.appendChild(hd);
  4563. }
  4564. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4565. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  4566. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  4567. var image = this.addCheckbox(div, imageLabel);
  4568. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4569. var editSection = this.addEditButton(div, lightbox);
  4570. var edit = editSection.getEditInput();
  4571. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  4572. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  4573. layers.style.marginLeft = edit.style.marginLeft;
  4574. layers.style.marginBottom = '12px';
  4575. layers.style.marginTop = '8px';
  4576. mxEvent.addListener(lightbox, 'change', function()
  4577. {
  4578. if (lightbox.checked)
  4579. {
  4580. if (hasLayers)
  4581. {
  4582. layers.removeAttribute('disabled');
  4583. }
  4584. edit.removeAttribute('disabled');
  4585. }
  4586. else
  4587. {
  4588. layers.setAttribute('disabled', 'disabled');
  4589. edit.setAttribute('disabled', 'disabled');
  4590. }
  4591. if (edit.checked && lightbox.checked)
  4592. {
  4593. editSection.getEditSelect().removeAttribute('disabled');
  4594. }
  4595. else
  4596. {
  4597. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4598. }
  4599. });
  4600. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4601. {
  4602. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  4603. editSection.getLink(), layers.checked);
  4604. }), null, mxResources.get('embed'), helpLink);
  4605. this.showDialog(dlg.container, 280, 280, true, true);
  4606. };
  4607. /**
  4608. *
  4609. */
  4610. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  4611. {
  4612. var bounds = this.editor.graph.getGraphBounds();
  4613. function doUpdate(dataUri)
  4614. {
  4615. var onclick = ' ';
  4616. var css = '';
  4617. // Adds double click handling
  4618. if (lightbox)
  4619. {
  4620. // KNOWN: Message passing does not seem to work in IE11
  4621. 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(" +
  4622. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4623. ((edit) ? "&edit=_blank" : "") +
  4624. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4625. css += 'cursor:pointer;';
  4626. }
  4627. if (fit)
  4628. {
  4629. css += 'max-width:100%;';
  4630. }
  4631. var atts = '';
  4632. if (retina)
  4633. {
  4634. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  4635. }
  4636. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4637. };
  4638. if (this.isExportToCanvas())
  4639. {
  4640. var scale = 1;
  4641. var ignoreSelection = true;
  4642. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4643. {
  4644. var xml = (lightbox) ? this.getFileData(true) : null;
  4645. var data = this.createImageDataUri(canvas, xml, 'png');
  4646. doUpdate(data);
  4647. }), null, null, null, mxUtils.bind(this, function(e)
  4648. {
  4649. err({message: mxResources.get('unknownError')});
  4650. }), null, true, (retina) ? 2 : 1, null, shadow);
  4651. }
  4652. else
  4653. {
  4654. var data = this.getFileData(true);
  4655. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  4656. {
  4657. var size = '';
  4658. if (retina)
  4659. {
  4660. size = '&w=' + Math.round(2 * bounds.width) +
  4661. '&h=' + Math.round(2 * bounds.height);
  4662. }
  4663. var embed = (lightbox) ? '1' : '0';
  4664. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  4665. '&base64=1&embedXml=' + embed + size + '&xml=' +
  4666. encodeURIComponent(data));
  4667. // LATER: Updates on each change, add a delay
  4668. req.send(mxUtils.bind(this, function()
  4669. {
  4670. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4671. {
  4672. // Fixes possible "incorrect function" for select() on
  4673. // DOM node which is no longer in document with IE11
  4674. doUpdate('data:image/png;base64,' + req.getText());
  4675. }
  4676. else
  4677. {
  4678. err({message: mxResources.get('unknownError')});
  4679. }
  4680. }));
  4681. }
  4682. else
  4683. {
  4684. err({message: mxResources.get('drawingTooLarge')});
  4685. }
  4686. }
  4687. };
  4688. /**
  4689. *
  4690. */
  4691. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  4692. {
  4693. var svgRoot = this.editor.graph.getSvg();
  4694. // Keeps hashtag links on same page
  4695. var links = svgRoot.getElementsByTagName('a');
  4696. if (links != null)
  4697. {
  4698. for (var i = 0; i < links.length; i++)
  4699. {
  4700. var href = links[i].getAttribute('href');
  4701. if (href != null && href.charAt(0) == '#' &&
  4702. links[i].getAttribute('target') == '_blank')
  4703. {
  4704. links[i].removeAttribute('target');
  4705. }
  4706. }
  4707. }
  4708. if (lightbox)
  4709. {
  4710. svgRoot.setAttribute('content', this.getFileData(true));
  4711. }
  4712. // Adds shadow filter
  4713. if (shadow)
  4714. {
  4715. this.editor.graph.addSvgShadow(svgRoot);
  4716. }
  4717. // SVG inside image tag
  4718. if (image)
  4719. {
  4720. var onclick = ' ';
  4721. var css = '';
  4722. // Adds double click handling
  4723. if (lightbox)
  4724. {
  4725. // KNOWN: Message passing does not seem to work in IE11
  4726. 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(" +
  4727. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4728. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4729. css += 'cursor:pointer;';
  4730. }
  4731. if (fit)
  4732. {
  4733. css += 'max-width:100%;';
  4734. }
  4735. // Images inside IMG don't seem to work so embed them all
  4736. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  4737. {
  4738. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  4739. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4740. }));
  4741. }
  4742. else
  4743. {
  4744. var css = '';
  4745. // Adds double click handling
  4746. if (lightbox)
  4747. {
  4748. // KNOWN: Message passing does not seem to work in IE11
  4749. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  4750. // Ignores link events
  4751. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  4752. // Focus existing lightbox
  4753. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  4754. // Message handling
  4755. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  4756. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  4757. "window.addEventListener('message',r);" +
  4758. // Opens lightbox window
  4759. "svg.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4760. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  4761. svgRoot.setAttribute('onclick', js);
  4762. css += 'cursor:pointer;';
  4763. }
  4764. // Adds responsive size
  4765. if (fit)
  4766. {
  4767. var w = parseInt(svgRoot.getAttribute('width'));
  4768. var h = parseInt(svgRoot.getAttribute('height'));
  4769. svgRoot.setAttribute('viewBox', '-0.5 -0.5 ' + w + ' ' + h);
  4770. css += 'max-width:100%;max-height:' + h + 'px;';
  4771. svgRoot.removeAttribute('height');
  4772. }
  4773. if (css != '')
  4774. {
  4775. svgRoot.setAttribute('style', css);
  4776. }
  4777. fn(mxUtils.getXml(svgRoot));
  4778. }
  4779. };
  4780. /**
  4781. * Translates this point by the given vector.
  4782. *
  4783. * @param {number} dx X-coordinate of the translation.
  4784. * @param {number} dy Y-coordinate of the translation.
  4785. */
  4786. EditorUi.prototype.timeSince = function(date)
  4787. {
  4788. var seconds = Math.floor((new Date() - date) / 1000);
  4789. var interval = Math.floor(seconds / 31536000);
  4790. if (interval > 1)
  4791. {
  4792. return interval + ' ' + mxResources.get('years');
  4793. }
  4794. interval = Math.floor(seconds / 2592000);
  4795. if (interval > 1)
  4796. {
  4797. return interval + ' ' + mxResources.get('months');
  4798. }
  4799. interval = Math.floor(seconds / 86400);
  4800. if (interval > 1)
  4801. {
  4802. return interval + ' ' + mxResources.get('days');
  4803. }
  4804. interval = Math.floor(seconds / 3600);
  4805. if (interval > 1)
  4806. {
  4807. return interval + ' ' + mxResources.get('hours');
  4808. }
  4809. interval = Math.floor(seconds / 60);
  4810. if (interval > 1)
  4811. {
  4812. return interval + ' ' + mxResources.get('minutes');
  4813. }
  4814. if (interval == 1)
  4815. {
  4816. return interval + ' ' + mxResources.get('minute');
  4817. }
  4818. return null;
  4819. };
  4820. /**
  4821. * Converts math in the given SVG
  4822. */
  4823. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  4824. {
  4825. if (graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  4826. {
  4827. // Temporarily attaches to DOM for rendering
  4828. // FIXME: If adding svgRoot to body, the text
  4829. // value of the math is appended, if not
  4830. // added to DOM then LaTeX does not work.
  4831. // This must be fixed to enable client-side export
  4832. // if math is enabled.
  4833. // document.body.appendChild(svgRoot);
  4834. Editor.MathJaxRender(svgRoot);
  4835. window.setTimeout(mxUtils.bind(this, function()
  4836. {
  4837. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  4838. {
  4839. // Removes from DOM
  4840. // svgRoot.parentNode.removeChild(svgRoot);
  4841. callback();
  4842. }));
  4843. }), 0);
  4844. }
  4845. else
  4846. {
  4847. callback();
  4848. }
  4849. };
  4850. /**
  4851. *
  4852. */
  4853. EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
  4854. {
  4855. if (node != null)
  4856. {
  4857. var diagramNode = null;
  4858. if (node.nodeName == 'diagram')
  4859. {
  4860. diagramNode = node;
  4861. }
  4862. else if (node.nodeName == 'mxfile')
  4863. {
  4864. var diagrams = node.getElementsByTagName('diagram');
  4865. if (diagrams.length > 0)
  4866. {
  4867. diagramNode = diagrams[0];
  4868. var graphGetGlobalVariable = graph.getGlobalVariable;
  4869. graph.getGlobalVariable = function(name)
  4870. {
  4871. if (name == 'page')
  4872. {
  4873. return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
  4874. }
  4875. else if (name == 'pagenumber')
  4876. {
  4877. return 1;
  4878. }
  4879. return graphGetGlobalVariable.apply(this, arguments);
  4880. };
  4881. }
  4882. }
  4883. if (diagramNode != null)
  4884. {
  4885. var tmp = Graph.decompress(mxUtils.getTextContent(diagramNode));
  4886. if (tmp != null && tmp.length > 0)
  4887. {
  4888. node = mxUtils.parseXml(tmp).documentElement;
  4889. }
  4890. }
  4891. }
  4892. // Hack to decode XML into temp graph via editor
  4893. var prev = this.editor.graph;
  4894. try
  4895. {
  4896. this.editor.graph = graph;
  4897. this.editor.setGraphXml(node);
  4898. }
  4899. catch (e)
  4900. {
  4901. // ignore
  4902. }
  4903. finally
  4904. {
  4905. this.editor.graph = prev;
  4906. }
  4907. return node;
  4908. };
  4909. /**
  4910. *
  4911. */
  4912. EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData)
  4913. {
  4914. try
  4915. {
  4916. var graph = this.editor.graph;
  4917. var diagramData = null;
  4918. // Exports PNG for given optional data
  4919. if (optionalData != null && optionalData.length > 0)
  4920. {
  4921. graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
  4922. document.body.appendChild(graph.container);
  4923. this.decodeNodeIntoGraph(this.editor.extractGraphModel(
  4924. mxUtils.parseXml(optionalData).documentElement, true), graph);
  4925. diagramData = optionalData;
  4926. }
  4927. // Exports PNG for first page while other page is showing
  4928. else if (this.pages != null && this.currentPage != this.pages[0])
  4929. {
  4930. graph = this.createTemporaryGraph(graph.getStylesheet());
  4931. var graphGetGlobalVariable = graph.getGlobalVariable;
  4932. var page = this.pages[0];
  4933. graph.getGlobalVariable = function(name)
  4934. {
  4935. if (name == 'page')
  4936. {
  4937. return page.getName();
  4938. }
  4939. else if (name == 'pagenumber')
  4940. {
  4941. return 1;
  4942. }
  4943. return graphGetGlobalVariable.apply(this, arguments);
  4944. };
  4945. document.body.appendChild(graph.container);
  4946. graph.model.setRoot(page.root);
  4947. }
  4948. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4949. {
  4950. try
  4951. {
  4952. if (diagramData == null)
  4953. {
  4954. diagramData = this.getFileData(true);
  4955. }
  4956. var data = canvas.toDataURL('image/png');
  4957. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel',
  4958. atob(Graph.compress(diagramData)));
  4959. success(data.substring(data.lastIndexOf(',') + 1));
  4960. // Removes temporary graph from DOM
  4961. if (graph != this.editor.graph)
  4962. {
  4963. graph.container.parentNode.removeChild(graph.container);
  4964. }
  4965. }
  4966. catch (e)
  4967. {
  4968. if (error != null)
  4969. {
  4970. error(e);
  4971. }
  4972. }
  4973. }), null, null, null, mxUtils.bind(this, function(e)
  4974. {
  4975. if (error != null)
  4976. {
  4977. error(e);
  4978. }
  4979. }), null, null, null, null, graph.shadowVisible, null, graph);
  4980. }
  4981. catch (e)
  4982. {
  4983. if (error != null)
  4984. {
  4985. error(e);
  4986. }
  4987. }
  4988. }
  4989. /**
  4990. * Returns the SVG of the diagram with embedded XML. If a callback function is
  4991. * used, the images are converted to data URIs.
  4992. */
  4993. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  4994. {
  4995. var bg = graph.background;
  4996. if (bg == mxConstants.NONE)
  4997. {
  4998. bg = null;
  4999. }
  5000. // Sets or disables alternate text for foreignObjects. Disabling is needed
  5001. // because PhantomJS seems to ignore switch statements and paint all text.
  5002. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  5003. if (graph.shadowVisible)
  5004. {
  5005. graph.addSvgShadow(svgRoot);
  5006. }
  5007. if (xml != null)
  5008. {
  5009. svgRoot.setAttribute('content', xml);
  5010. }
  5011. if (url != null)
  5012. {
  5013. svgRoot.setAttribute('resource', url);
  5014. }
  5015. // LATER: Click on SVG content to start editing
  5016. // if (redirect != null)
  5017. // {
  5018. // // TODO: Ignore anchor tag source for click event
  5019. // svgRoot.setAttribute('style', 'cursor:pointer;');
  5020. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  5021. // }
  5022. if (callback != null)
  5023. {
  5024. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  5025. {
  5026. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5027. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5028. mxUtils.getXml(svgRoot));
  5029. }));
  5030. }
  5031. else
  5032. {
  5033. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5034. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5035. mxUtils.getXml(svgRoot);
  5036. }
  5037. };
  5038. /**
  5039. *
  5040. */
  5041. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  5042. {
  5043. format = (format != null) ? format : 'png';
  5044. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  5045. {
  5046. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  5047. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  5048. // Caches images
  5049. if (this.thumbImageCache == null)
  5050. {
  5051. this.thumbImageCache = new Object();
  5052. }
  5053. try
  5054. {
  5055. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  5056. {
  5057. this.spinner.stop();
  5058. try
  5059. {
  5060. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  5061. null, null, ignoreSelection, currentPage) : null, format);
  5062. }
  5063. catch (e)
  5064. {
  5065. // Fallback to server-side image export
  5066. if (e.message == 'Invalid image')
  5067. {
  5068. this.downloadFile(format);
  5069. }
  5070. else
  5071. {
  5072. this.handleError(e);
  5073. }
  5074. }
  5075. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  5076. {
  5077. this.spinner.stop();
  5078. this.handleError(e);
  5079. }), null, ignoreSelection, scale || 1, transparentBackground,
  5080. addShadow, null, null, border, noCrop);
  5081. }
  5082. catch (e)
  5083. {
  5084. this.spinner.stop();
  5085. this.handleError(e);
  5086. }
  5087. }
  5088. };
  5089. /**
  5090. * For the fontCSS to be applied when rendering images on canvas, the actual
  5091. * font data must be made available via a data URI encoding of the file.
  5092. */
  5093. EditorUi.prototype.loadFonts = function(then)
  5094. {
  5095. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  5096. {
  5097. var parts = this.editor.fontCss.split('url(');
  5098. var waiting = 0;
  5099. var fonts = {};
  5100. // Strips leading and trailing quotes and spaces
  5101. function trimString(str)
  5102. {
  5103. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  5104. };
  5105. var finish = mxUtils.bind(this, function()
  5106. {
  5107. if (waiting == 0)
  5108. {
  5109. // Constructs string
  5110. var result = [parts[0]];
  5111. for (var j = 1; j < parts.length; j++)
  5112. {
  5113. var idx = parts[j].indexOf(')');
  5114. result.push('url("');
  5115. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  5116. result.push('"' + parts[j].substring(idx));
  5117. }
  5118. this.editor.resolvedFontCss = result.join('');
  5119. then();
  5120. }
  5121. });
  5122. if (parts.length > 0)
  5123. {
  5124. for (var i = 1; i < parts.length; i++)
  5125. {
  5126. var idx = parts[i].indexOf(')');
  5127. var format = null;
  5128. // Checks if there is a format directive
  5129. var fmtIdx = parts[i].indexOf('format(', idx);
  5130. if (fmtIdx > 0)
  5131. {
  5132. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  5133. }
  5134. (mxUtils.bind(this, function(url)
  5135. {
  5136. if (fonts[url] == null)
  5137. {
  5138. // Mark font es being fetched and fetch it
  5139. fonts[url] = url;
  5140. waiting++;
  5141. var mime = 'application/x-font-ttf';
  5142. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  5143. if (format == 'svg' || /(\.svg)($|\?)/i.test(url))
  5144. {
  5145. mime = 'image/svg+xml';
  5146. }
  5147. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url))
  5148. {
  5149. mime = 'application/x-font-opentype';
  5150. }
  5151. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url))
  5152. {
  5153. mime = 'application/font-woff';
  5154. }
  5155. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url))
  5156. {
  5157. mime = 'application/font-woff2';
  5158. }
  5159. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url))
  5160. {
  5161. mime = 'application/vnd.ms-fontobject';
  5162. }
  5163. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url))
  5164. {
  5165. mime = 'application/font-sfnt';
  5166. }
  5167. var realUrl = url;
  5168. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  5169. {
  5170. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  5171. }
  5172. // LATER: Remove cache-control header
  5173. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  5174. {
  5175. fonts[url] = uri;
  5176. waiting--;
  5177. finish();
  5178. }), mxUtils.bind(this, function(err)
  5179. {
  5180. // LATER: handle error
  5181. waiting--;
  5182. finish();
  5183. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  5184. }
  5185. }))(trimString(parts[i].substring(0, idx)), format);
  5186. }
  5187. }
  5188. }
  5189. else
  5190. {
  5191. then();
  5192. }
  5193. };
  5194. /**
  5195. *
  5196. */
  5197. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  5198. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  5199. {
  5200. limitHeight = (limitHeight != null) ? limitHeight : true;
  5201. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  5202. graph = (graph != null) ? graph : this.editor.graph;
  5203. border = (border != null) ? border : 0;
  5204. var bg = (transparentBackground) ? null : graph.background;
  5205. if (bg == mxConstants.NONE)
  5206. {
  5207. bg = null;
  5208. }
  5209. if (bg == null)
  5210. {
  5211. bg = background;
  5212. }
  5213. // Handles special case where background is null but transparent is false
  5214. if (bg == null && transparentBackground == false)
  5215. {
  5216. bg = '#ffffff';
  5217. }
  5218. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection, null, null, null, addShadow),
  5219. mxUtils.bind(this, function(svgRoot)
  5220. {
  5221. var img = new Image();
  5222. img.onload = mxUtils.bind(this, function()
  5223. {
  5224. try
  5225. {
  5226. var canvas = document.createElement('canvas');
  5227. var w = parseInt(svgRoot.getAttribute('width'));
  5228. var h = parseInt(svgRoot.getAttribute('height'));
  5229. scale = (scale != null) ? scale : 1;
  5230. if (width != null)
  5231. {
  5232. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  5233. }
  5234. w = Math.ceil(scale * w) + 2 * border;
  5235. h = Math.ceil(scale * h) + 2 * border;
  5236. canvas.setAttribute('width', w);
  5237. canvas.setAttribute('height', h);
  5238. var ctx = canvas.getContext('2d');
  5239. if (bg != null)
  5240. {
  5241. ctx.beginPath();
  5242. ctx.rect(0, 0, w, h);
  5243. ctx.fillStyle = bg;
  5244. ctx.fill();
  5245. }
  5246. ctx.scale(scale, scale);
  5247. // Workaround for broken data URI images in Safari on first export
  5248. if (mxClient.IS_SF)
  5249. {
  5250. window.setTimeout(function()
  5251. {
  5252. ctx.drawImage(img, border / scale, border / scale);
  5253. callback(canvas);
  5254. }, 0);
  5255. }
  5256. else
  5257. {
  5258. ctx.drawImage(img, border / scale, border / scale);
  5259. callback(canvas);
  5260. }
  5261. }
  5262. catch (e)
  5263. {
  5264. if (error != null)
  5265. {
  5266. error(e);
  5267. }
  5268. }
  5269. });
  5270. img.onerror = function(e)
  5271. {
  5272. //console.log('img', e, img.src);
  5273. if (error != null)
  5274. {
  5275. error(e);
  5276. }
  5277. };
  5278. try
  5279. {
  5280. if (addShadow)
  5281. {
  5282. this.editor.graph.addSvgShadow(svgRoot);
  5283. }
  5284. var done = mxUtils.bind(this, function()
  5285. {
  5286. if (this.editor.resolvedFontCss != null)
  5287. {
  5288. var st = document.createElement('style');
  5289. st.setAttribute('type', 'text/css');
  5290. st.innerHTML = this.editor.resolvedFontCss;
  5291. // Must be in defs section for FF to work
  5292. var defs = svgRoot.getElementsByTagName('defs');
  5293. defs[0].appendChild(st);
  5294. }
  5295. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  5296. {
  5297. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5298. }));
  5299. });
  5300. this.loadFonts(done);
  5301. }
  5302. catch (e)
  5303. {
  5304. //console.log('src', e, img.src);
  5305. if (error != null)
  5306. {
  5307. error(e);
  5308. }
  5309. }
  5310. }), imageCache, converter);
  5311. };
  5312. /**
  5313. * Converts all images in the SVG output to data URIs for immediate rendering
  5314. */
  5315. EditorUi.prototype.createImageUrlConverter = function()
  5316. {
  5317. var converter = new mxUrlConverter();
  5318. converter.updateBaseUrl();
  5319. // Extends convert to avoid CORS using an image proxy server where needed
  5320. var convert = converter.convert;
  5321. var self = this;
  5322. converter.convert = function(src)
  5323. {
  5324. if (src != null)
  5325. {
  5326. var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  5327. if (remote && !navigator.onLine)
  5328. {
  5329. src = self.svgBrokenImage.src;
  5330. }
  5331. else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  5332. (!self.crossOriginImages || !self.editor.isCorsEnabledForUrl(src)))
  5333. {
  5334. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  5335. }
  5336. else if (src.substring(0, 19) != 'chrome-extension://')
  5337. {
  5338. src = convert.apply(this, arguments);
  5339. }
  5340. }
  5341. return src;
  5342. };
  5343. return converter;
  5344. };
  5345. /**
  5346. * Converts all images in the SVG output to data URIs for immediate rendering
  5347. */
  5348. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  5349. {
  5350. // Converts images to data URLs for immediate painting
  5351. if (converter == null)
  5352. {
  5353. converter = this.createImageUrlConverter();
  5354. }
  5355. // Barrier for asynchronous image loading
  5356. var counter = 0;
  5357. function inc()
  5358. {
  5359. counter++;
  5360. };
  5361. function dec()
  5362. {
  5363. counter--;
  5364. if (counter == 0)
  5365. {
  5366. callback(svgRoot);
  5367. }
  5368. };
  5369. var cache = imageCache || new Object();
  5370. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  5371. {
  5372. var images = svgRoot.getElementsByTagName(tagName);
  5373. for (var i = 0; i < images.length; i++)
  5374. {
  5375. (mxUtils.bind(this, function(img)
  5376. {
  5377. var src = converter.convert(img.getAttribute(srcAttr));
  5378. // Data URIs are pass-through
  5379. if (src != null && src.substring(0, 5) != 'data:')
  5380. {
  5381. var tmp = cache[src];
  5382. if (tmp == null)
  5383. {
  5384. inc();
  5385. this.convertImageToDataUri(src, function(uri)
  5386. {
  5387. if (uri != null)
  5388. {
  5389. cache[src] = uri;
  5390. img.setAttribute(srcAttr, uri);
  5391. }
  5392. dec();
  5393. });
  5394. }
  5395. else
  5396. {
  5397. img.setAttribute(srcAttr, tmp);
  5398. }
  5399. }
  5400. else if (src != null)
  5401. {
  5402. img.setAttribute(srcAttr, src);
  5403. }
  5404. }))(images[i]);
  5405. }
  5406. });
  5407. // Converts all known image tags in output
  5408. // LATER: Add support for images in CSS
  5409. convertImages('image', 'xlink:href');
  5410. convertImages('img', 'src');
  5411. // All from cache or no images
  5412. if (counter == 0)
  5413. {
  5414. callback(svgRoot);
  5415. }
  5416. };
  5417. /**
  5418. * Checks if the client is authorized and calls the next step.
  5419. */
  5420. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix, noBinary)
  5421. {
  5422. try
  5423. {
  5424. var binary = !noBinary && (forceBinary || /(\.png)($|\?)/i.test(url) ||
  5425. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url));
  5426. retry = (retry != null) ? retry : true;
  5427. var fn = mxUtils.bind(this, function()
  5428. {
  5429. mxUtils.get(url, mxUtils.bind(this, function(req)
  5430. {
  5431. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  5432. {
  5433. if (success != null)
  5434. {
  5435. var data = req.getText();
  5436. // Returns PNG as base64 encoded data URI
  5437. if (binary)
  5438. {
  5439. // NOTE: This requires BinaryToArray VB script in the page
  5440. if ((document.documentMode == 9 || document.documentMode == 10) &&
  5441. typeof window.mxUtilsBinaryToArray !== 'undefined')
  5442. {
  5443. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  5444. var tmp = new Array(bin.length);
  5445. for (var i = 0; i < bin.length; i++)
  5446. {
  5447. tmp[i] = String.fromCharCode(bin[i]);
  5448. }
  5449. data = tmp.join('');
  5450. }
  5451. // LATER: Could be JPG but modern browsers
  5452. // ignore the mime type in the data URI
  5453. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  5454. data = dataUriPrefix + this.base64Encode(data);
  5455. }
  5456. success(data);
  5457. }
  5458. }
  5459. else if (error != null)
  5460. {
  5461. error({message: mxResources.get('error') + ' ' + req.getStatus()}, req);
  5462. }
  5463. }), function(req)
  5464. {
  5465. if (error != null)
  5466. {
  5467. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  5468. }
  5469. }, binary, this.timeout, function()
  5470. {
  5471. if (retry && error != null)
  5472. {
  5473. error({code: App.ERROR_TIMEOUT, retry: fn});
  5474. }
  5475. });
  5476. });
  5477. fn();
  5478. }
  5479. catch (e)
  5480. {
  5481. if (error != null)
  5482. {
  5483. error(e);
  5484. }
  5485. }
  5486. };
  5487. /**
  5488. * Returns true if the given URL is known to have CORS headers.
  5489. */
  5490. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  5491. {
  5492. return this.editor.isCorsEnabledForUrl(url);
  5493. };
  5494. /**
  5495. * Translates this point by the given vector.
  5496. *
  5497. * @param {number} dx X-coordinate of the translation.
  5498. * @param {number} dy Y-coordinate of the translation.
  5499. */
  5500. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  5501. {
  5502. if (/(\.svg)$/i.test(url))
  5503. {
  5504. mxUtils.get(url, mxUtils.bind(this, function(req)
  5505. {
  5506. callback(this.createSvgDataUri(req.getText()));
  5507. }),
  5508. function()
  5509. {
  5510. callback(this.svgBrokenImage.src);
  5511. });
  5512. }
  5513. else
  5514. {
  5515. var img = new Image();
  5516. var self = this;
  5517. if (this.crossOriginImages)
  5518. {
  5519. img.crossOrigin = 'anonymous';
  5520. }
  5521. img.onload = function()
  5522. {
  5523. var canvas = document.createElement('canvas');
  5524. var ctx = canvas.getContext('2d');
  5525. canvas.height = img.height;
  5526. canvas.width = img.width;
  5527. ctx.drawImage(img, 0, 0);
  5528. try
  5529. {
  5530. callback(canvas.toDataURL());
  5531. }
  5532. catch (e)
  5533. {
  5534. callback(self.svgBrokenImage.src);
  5535. }
  5536. };
  5537. img.onerror = function()
  5538. {
  5539. callback(self.svgBrokenImage.src);
  5540. };
  5541. img.src = url;
  5542. }
  5543. };
  5544. /**
  5545. * Handling drag and drop and import.
  5546. */
  5547. /**
  5548. * Imports the given XML into the existing diagram.
  5549. */
  5550. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  5551. {
  5552. dx = (dx != null) ? dx : 0;
  5553. dy = (dy != null) ? dy : 0;
  5554. var cells = []
  5555. try
  5556. {
  5557. var graph = this.editor.graph;
  5558. if (xml != null && xml.length > 0)
  5559. {
  5560. // Adds pages
  5561. graph.model.beginUpdate();
  5562. try
  5563. {
  5564. var doc = mxUtils.parseXml(xml);
  5565. // Checks for mxfile with multiple pages
  5566. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  5567. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  5568. {
  5569. var diagrams = node.getElementsByTagName('diagram');
  5570. if (diagrams.length == 1)
  5571. {
  5572. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5573. }
  5574. else if (diagrams.length > 1)
  5575. {
  5576. var i0 = 0;
  5577. // Adds first page to current page if current page is only page and empty
  5578. if (this.pages != null && this.pages.length == 1 && this.isDiagramEmpty())
  5579. {
  5580. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5581. crop = false;
  5582. i0 = 1;
  5583. }
  5584. for (var i = i0; i < diagrams.length; i++)
  5585. {
  5586. // Imported pages must obtain a new ID
  5587. diagrams[i].removeAttribute('id');
  5588. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  5589. var index = this.pages.length;
  5590. // Checks for invalid page names
  5591. if (page.getName() == null)
  5592. {
  5593. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  5594. }
  5595. graph.model.execute(new ChangePage(this, page, page, index, true));
  5596. }
  5597. }
  5598. }
  5599. if (node != null && node.nodeName === 'mxGraphModel')
  5600. {
  5601. cells = graph.importGraphModel(node, dx, dy, crop);
  5602. }
  5603. }
  5604. finally
  5605. {
  5606. graph.model.endUpdate();
  5607. }
  5608. }
  5609. }
  5610. catch (e)
  5611. {
  5612. if (!noErrorHandling)
  5613. {
  5614. this.handleError(e);
  5615. }
  5616. else
  5617. {
  5618. throw e;
  5619. }
  5620. }
  5621. return cells;
  5622. };
  5623. /**
  5624. * Returns true for VSD, VDX and VSS, VSX files.
  5625. */
  5626. EditorUi.prototype.isRemoteVisioFormat = function(filename)
  5627. {
  5628. return /(\.v(sd|dx))($|\?)/i.test(filename) || /(\.vs(s|x))($|\?)/i.test(filename);
  5629. };
  5630. /**
  5631. * Imports the given Visio file
  5632. */
  5633. EditorUi.prototype.importVisio = function(file, done, onerror, filename)
  5634. {
  5635. filename = (filename != null) ? filename : file.name;
  5636. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5637. {
  5638. this.handleError(e);
  5639. });
  5640. var delayed = mxUtils.bind(this, function()
  5641. {
  5642. this.loadingExtensions = false;
  5643. if (this.doImportVisio)
  5644. {
  5645. if (this.isRemoteVisioFormat(filename) && VSD_CONVERT_URL != null)
  5646. {
  5647. var formData = new FormData();
  5648. formData.append('file1', file, filename);
  5649. var xhr = new XMLHttpRequest();
  5650. xhr.open('POST', VSD_CONVERT_URL);
  5651. xhr.responseType = 'blob';
  5652. xhr.onreadystatechange = mxUtils.bind(this, function()
  5653. {
  5654. if (xhr.readyState == 4)
  5655. {
  5656. if (xhr.status >= 200 && xhr.status <= 299)
  5657. {
  5658. try
  5659. {
  5660. //add back the file name
  5661. xhr.response.name = filename;
  5662. this.doImportVisio(xhr.response, done, onerror);
  5663. }
  5664. catch (e)
  5665. {
  5666. onerror(e);
  5667. }
  5668. }
  5669. else
  5670. {
  5671. onerror({});
  5672. }
  5673. }
  5674. });
  5675. xhr.send(formData);
  5676. }
  5677. else
  5678. {
  5679. try
  5680. {
  5681. this.doImportVisio(file, done, onerror);
  5682. }
  5683. catch (e)
  5684. {
  5685. onerror(e);
  5686. }
  5687. }
  5688. }
  5689. });
  5690. if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline())
  5691. {
  5692. this.loadingExtensions = true;
  5693. mxscript('js/extensions.min.js', delayed);
  5694. }
  5695. else
  5696. {
  5697. delayed();
  5698. }
  5699. };
  5700. /**
  5701. * Imports the given GraphML (yEd) file
  5702. */
  5703. EditorUi.prototype.importGraphML = function(xmlData, done, onerror)
  5704. {
  5705. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5706. {
  5707. this.handleError(e);
  5708. });
  5709. var delayed = mxUtils.bind(this, function()
  5710. {
  5711. this.loadingExtensions = false;
  5712. if (this.doImportGraphML)
  5713. {
  5714. try
  5715. {
  5716. this.doImportGraphML(xmlData, done, onerror);
  5717. }
  5718. catch (e)
  5719. {
  5720. onerror(e);
  5721. }
  5722. }
  5723. });
  5724. if (!this.doImportGraphML && !this.loadingExtensions && !this.isOffline())
  5725. {
  5726. this.loadingExtensions = true;
  5727. mxscript('js/extensions.min.js', delayed);
  5728. }
  5729. else
  5730. {
  5731. delayed();
  5732. }
  5733. };
  5734. /**
  5735. * Export the diagram to VSDX
  5736. */
  5737. EditorUi.prototype.exportVisio = function()
  5738. {
  5739. var delayed = mxUtils.bind(this, function()
  5740. {
  5741. this.loadingExtensions = false;
  5742. if (typeof VsdxExport !== 'undefined')
  5743. {
  5744. try
  5745. {
  5746. var expSuccess = new VsdxExport(this).exportCurrentDiagrams();
  5747. if (!expSuccess)
  5748. {
  5749. this.handleError({message: mxResources.get('unknownError')});
  5750. }
  5751. }
  5752. catch (e)
  5753. {
  5754. this.handleError(e);
  5755. }
  5756. }
  5757. });
  5758. if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline())
  5759. {
  5760. this.loadingExtensions = true;
  5761. mxscript('js/extensions.min.js', delayed);
  5762. }
  5763. else
  5764. {
  5765. delayed();
  5766. }
  5767. };
  5768. /**
  5769. * Imports the given Lucidchart data.
  5770. */
  5771. EditorUi.prototype.convertLucidChart = function(data, success, error)
  5772. {
  5773. var delayed = mxUtils.bind(this, function()
  5774. {
  5775. this.loadingExtensions = false;
  5776. // Checks for signature method
  5777. if (typeof window.LucidImporter !== 'undefined')
  5778. {
  5779. try
  5780. {
  5781. success(LucidImporter.importState(JSON.parse(data)));
  5782. }
  5783. catch (e)
  5784. {
  5785. error(e);
  5786. }
  5787. }
  5788. else
  5789. {
  5790. error({message: mxResources.get('serviceUnavailableOrBlocked')});
  5791. }
  5792. });
  5793. if (typeof window.LucidImporter === 'undefined' &&
  5794. !this.loadingExtensions && !this.isOffline())
  5795. {
  5796. this.loadingExtensions = true;
  5797. if (urlParams['dev'] == '1')
  5798. {
  5799. mxscript('js/diagramly/Extensions.js', delayed);
  5800. }
  5801. else
  5802. {
  5803. mxscript('js/extensions.min.js', delayed);
  5804. }
  5805. }
  5806. else
  5807. {
  5808. // Async needed for selection
  5809. window.setTimeout(delayed, 0);
  5810. }
  5811. };
  5812. /**
  5813. * Inserts the given text as a preformatted HTML text.
  5814. */
  5815. EditorUi.prototype.insertAsPreText = function(text, x, y)
  5816. {
  5817. var graph = this.editor.graph;
  5818. var cell = null;
  5819. graph.getModel().beginUpdate();
  5820. try
  5821. {
  5822. cell = graph.insertVertex(null, null, '<pre>' + text + '</pre>',
  5823. x, y, 1, 1, 'text;html=1;align=center;verticalAlign=middle;');
  5824. graph.updateCellSize(cell, true);
  5825. }
  5826. finally
  5827. {
  5828. graph.getModel().endUpdate();
  5829. }
  5830. return cell;
  5831. };
  5832. /**
  5833. * Imports the given XML into the existing diagram.
  5834. * TODO: Make this function asynchronous
  5835. */
  5836. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages)
  5837. {
  5838. crop = (crop != null) ? crop : true;
  5839. resizeImages = (resizeImages != null) ? resizeImages : true;
  5840. // Handles special case for Gliffy data which requires async server-side for parsing
  5841. if (text != null)
  5842. {
  5843. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  5844. {
  5845. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  5846. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  5847. {
  5848. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  5849. {
  5850. this.editor.graph.setSelectionCells(this.insertTextAt(
  5851. xhr.responseText, dx, dy, true));
  5852. }
  5853. }));
  5854. // Returns empty cells array as it is aysynchronous
  5855. return [];
  5856. }
  5857. // Handles special case of data URI which requires async loading for finding size
  5858. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() &&
  5859. (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  5860. {
  5861. var graph = this.editor.graph;
  5862. // Checks for embedded XML in PNG
  5863. if (text.substring(0, 22) == 'data:image/png;base64,')
  5864. {
  5865. var xml = this.extractGraphModelFromPng(text);
  5866. var result = this.importXml(xml, dx, dy, crop, true);
  5867. if (result.length > 0)
  5868. {
  5869. return result;
  5870. }
  5871. }
  5872. // Tries to extract embedded XML from SVG data URI
  5873. if (text.substring(0, 19) == 'data:image/svg+xml;')
  5874. {
  5875. try
  5876. {
  5877. var xml = null;
  5878. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  5879. {
  5880. xml = text.substring(text.indexOf(',') + 1);
  5881. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  5882. }
  5883. else
  5884. {
  5885. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  5886. }
  5887. var result = this.importXml(xml, dx, dy, crop, true);
  5888. if (result.length > 0)
  5889. {
  5890. return result;
  5891. }
  5892. }
  5893. catch (e)
  5894. {
  5895. // Ignore
  5896. }
  5897. }
  5898. this.loadImage(text, mxUtils.bind(this, function(img)
  5899. {
  5900. if (text.substring(0, 5) == 'data:')
  5901. {
  5902. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  5903. {
  5904. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5905. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5906. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  5907. }), resizeImages, this.maxImageSize);
  5908. }
  5909. else
  5910. {
  5911. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  5912. var w = Math.round(img.width * s);
  5913. var h = Math.round(img.height * s);
  5914. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5915. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5916. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  5917. }
  5918. }), mxUtils.bind(this, function()
  5919. {
  5920. var cell = null;
  5921. // Inserts invalid data URIs as text
  5922. graph.getModel().beginUpdate();
  5923. try
  5924. {
  5925. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  5926. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  5927. graph.updateCellSize(cell);
  5928. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  5929. }
  5930. finally
  5931. {
  5932. graph.getModel().endUpdate();
  5933. }
  5934. graph.setSelectionCell(cell);
  5935. }));
  5936. return [];
  5937. }
  5938. else
  5939. {
  5940. text = Graph.zapGremlins(mxUtils.trim(text));
  5941. if (this.isCompatibleString(text))
  5942. {
  5943. return this.importXml(text, dx, dy, crop);
  5944. }
  5945. else if (text.length > 0)
  5946. {
  5947. if (this.isLucidChartData(text))
  5948. {
  5949. this.convertLucidChart(text, mxUtils.bind(this, function(xml)
  5950. {
  5951. this.editor.graph.setSelectionCells(
  5952. this.importXml(xml, dx, dy, crop));
  5953. }), mxUtils.bind(this, function(e)
  5954. {
  5955. this.handleError(e);
  5956. }));
  5957. }
  5958. else
  5959. {
  5960. var graph = this.editor.graph;
  5961. var cell = null;
  5962. graph.getModel().beginUpdate();
  5963. try
  5964. {
  5965. // Fires cellsInserted to apply the current style to the inserted text.
  5966. // This requires the value to be empty when the event is fired.
  5967. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  5968. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  5969. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  5970. // Single tag is converted
  5971. if (text.charAt(0) == '<' && text.indexOf('>') == text.length - 1)
  5972. {
  5973. text = mxUtils.htmlEntities(text);
  5974. }
  5975. // Apply value and updates the cell size to fit the text block
  5976. cell.value = text;
  5977. graph.updateCellSize(cell);
  5978. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  5979. 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;
  5980. if (regexp.test(cell.value))
  5981. {
  5982. graph.setLinkForCell(cell, cell.value);
  5983. }
  5984. // Adds spacing
  5985. cell.geometry.width += graph.gridSize;
  5986. cell.geometry.height += graph.gridSize;
  5987. }
  5988. finally
  5989. {
  5990. graph.getModel().endUpdate();
  5991. }
  5992. return [cell];
  5993. }
  5994. }
  5995. }
  5996. }
  5997. return [];
  5998. };
  5999. /**
  6000. * Formats the given file size.
  6001. */
  6002. EditorUi.prototype.formatFileSize = function(size)
  6003. {
  6004. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  6005. var i = -1;
  6006. do
  6007. {
  6008. size = size / 1024;
  6009. i++;
  6010. } while (size > 1024);
  6011. return Math.max(size, 0.1).toFixed(1) + units[i];
  6012. };
  6013. /**
  6014. * Imports the given XML into the existing diagram.
  6015. */
  6016. EditorUi.prototype.convertDataUri = function(uri)
  6017. {
  6018. // Handles special case of data URI which needs to be rewritten
  6019. // to be used in a cell style to remove the semicolon
  6020. if (uri.substring(0, 5) == 'data:')
  6021. {
  6022. var semi = uri.indexOf(';');
  6023. if (semi > 0)
  6024. {
  6025. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  6026. }
  6027. }
  6028. return uri;
  6029. };
  6030. /**
  6031. * Returns true for Gliffy data.
  6032. */
  6033. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  6034. {
  6035. return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
  6036. };
  6037. /**
  6038. * Returns true for Gliffy
  6039. */
  6040. EditorUi.prototype.isLucidChartData = function(data)
  6041. {
  6042. return data != null && data.substring(0, 26) == '{"state":"{\\"Properties\\":';
  6043. };
  6044. /**
  6045. * Imports a local file from the device or local storage.
  6046. */
  6047. EditorUi.prototype.importLocalFile = function(device, noSplash)
  6048. {
  6049. // input.click does not work in IE on Windows 7
  6050. if (device && Graph.fileSupport && ((!mxClient.IS_IE && !mxClient.IS_IE11) ||
  6051. navigator.appVersion.indexOf('Windows NT 6.1') < 0))
  6052. {
  6053. var input = document.createElement('input');
  6054. input.setAttribute('type', 'file');
  6055. mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
  6056. {
  6057. if (input.files != null)
  6058. {
  6059. // Using null for position will disable crop of input file
  6060. this.importFiles(input.files, null, null, this.maxImageSize);
  6061. }
  6062. }));
  6063. input.click();
  6064. }
  6065. else
  6066. {
  6067. window.openNew = false;
  6068. window.openKey = 'import';
  6069. if (!noSplash)
  6070. {
  6071. var prevValue = Editor.useLocalStorage;
  6072. Editor.useLocalStorage = !device;
  6073. }
  6074. // Closes dialog after open
  6075. window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
  6076. {
  6077. this.hideDialog(cancel);
  6078. }));
  6079. window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
  6080. {
  6081. if (filename != null && Graph.fileSupport && /(\.v(dx|sdx?))($|\?)/i.test(filename))
  6082. {
  6083. // "Not a UTF 8 file" when opening VSDX in IE so this is never called
  6084. var file = new Blob([xml], {type: 'application/octet-stream'})
  6085. this.importVisio(file, mxUtils.bind(this, function(xml)
  6086. {
  6087. this.importXml(xml, 0, 0, true);
  6088. }), null, filename);
  6089. }
  6090. else
  6091. {
  6092. this.editor.graph.setSelectionCells(this.importXml(xml, 0, 0, true));
  6093. }
  6094. }));
  6095. // Removes openFile if dialog is closed
  6096. this.showDialog(new OpenDialog(this).container, 360, 220, true, true, function()
  6097. {
  6098. window.openFile = null;
  6099. });
  6100. // Extends dialog close to show splash screen
  6101. if (!noSplash)
  6102. {
  6103. var dlg = this.dialog;
  6104. var dlgClose = dlg.close;
  6105. this.dialog.close = mxUtils.bind(this, function(cancel)
  6106. {
  6107. Editor.useLocalStorage = prevValue;
  6108. dlgClose.apply(dlg, arguments);
  6109. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  6110. {
  6111. this.showSplash();
  6112. }
  6113. });
  6114. }
  6115. }
  6116. };
  6117. /**
  6118. * Imports the given XML into the existing diagram.
  6119. */
  6120. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  6121. {
  6122. crop = (crop != null) ? crop : true;
  6123. var async = false;
  6124. var cells = null;
  6125. var handleResult = mxUtils.bind(this, function(xml)
  6126. {
  6127. var importedCells = null;
  6128. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  6129. {
  6130. this.loadLibrary(new LocalLibrary(this, xml, filename));
  6131. }
  6132. else
  6133. {
  6134. importedCells = this.importXml(xml, dx, dy, crop);
  6135. }
  6136. if (done != null)
  6137. {
  6138. done(importedCells);
  6139. }
  6140. });
  6141. if (mimeType.substring(0, 5) == 'image')
  6142. {
  6143. var containsModel = false;
  6144. if (mimeType.substring(0, 9) == 'image/png')
  6145. {
  6146. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  6147. if (xml != null && xml.length > 0)
  6148. {
  6149. cells = this.importXml(xml, dx, dy, crop);
  6150. containsModel = true;
  6151. }
  6152. }
  6153. if (!containsModel)
  6154. {
  6155. var graph = this.editor.graph;
  6156. // Strips encoding bit (eg. ;base64,) for cell style
  6157. var semi = data.indexOf(';');
  6158. if (semi > 0)
  6159. {
  6160. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6161. }
  6162. if (crop && graph.isGridEnabled())
  6163. {
  6164. dx = graph.snap(dx);
  6165. dy = graph.snap(dy);
  6166. }
  6167. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  6168. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6169. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  6170. }
  6171. }
  6172. else if (/(\.*<graphml )/.test(data))
  6173. {
  6174. async = true;
  6175. this.importGraphML(data, handleResult);
  6176. }
  6177. else if (file != null && filename != null && ((/(\.v(dx|sdx?))($|\?)/i.test(filename)) || /(\.vs(x|sx?))($|\?)/i.test(filename)))
  6178. {
  6179. // LATER: done and async are a hack before making this asynchronous
  6180. async = true;
  6181. this.importVisio(file, handleResult);
  6182. }
  6183. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  6184. {
  6185. // LATER: done and async are a hack before making this asynchronous
  6186. async = true;
  6187. // Returns empty cells array as it is aysynchronous
  6188. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  6189. {
  6190. if (xhr.readyState == 4)
  6191. {
  6192. if (xhr.status >= 200 && xhr.status <= 299)
  6193. {
  6194. handleResult(xhr.responseText);
  6195. }
  6196. else if (done != null)
  6197. {
  6198. done(null);
  6199. }
  6200. }
  6201. }), filename);
  6202. }
  6203. else if (!/(\.v(sd|dx))($|\?)/i.test(filename) && !/(\.vs(s|x))($|\?)/i.test(filename))
  6204. {
  6205. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  6206. }
  6207. if (!async && done != null)
  6208. {
  6209. done(cells);
  6210. }
  6211. return cells;
  6212. };
  6213. /**
  6214. * Base64 encodes the given string. This method seems to be more
  6215. * robust for encoding PNG from binary AJAX responses.
  6216. */
  6217. EditorUi.prototype.base64Encode = function(str)
  6218. {
  6219. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6220. var out = "", i = 0, len = str.length, c1, c2, c3;
  6221. while (i < len)
  6222. {
  6223. c1 = str.charCodeAt(i++) & 0xff;
  6224. if (i == len)
  6225. {
  6226. out += CHARS.charAt(c1 >> 2);
  6227. out += CHARS.charAt((c1 & 0x3) << 4);
  6228. out += "==";
  6229. break;
  6230. }
  6231. c2 = str.charCodeAt(i++);
  6232. if (i == len)
  6233. {
  6234. out += CHARS.charAt(c1 >> 2);
  6235. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  6236. out += CHARS.charAt((c2 & 0xF) << 2);
  6237. out += "=";
  6238. break;
  6239. }
  6240. c3 = str.charCodeAt(i++);
  6241. out += CHARS.charAt(c1 >> 2);
  6242. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  6243. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  6244. out += CHARS.charAt(c3 & 0x3F);
  6245. }
  6246. return out;
  6247. };
  6248. /**
  6249. *
  6250. */
  6251. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  6252. {
  6253. x = (x != null) ? x : 0;
  6254. y = (y != null) ? y : 0;
  6255. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6256. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  6257. var crop = x != null && y != null;
  6258. var resizeImages = true;
  6259. // Checks if large images are imported
  6260. var largeImages = false;
  6261. if (!mxClient.IS_CHROMEAPP && files != null)
  6262. {
  6263. var thresh = resampleThreshold || this.resampleThreshold;
  6264. for (var i = 0; i < files.length; i++)
  6265. {
  6266. if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
  6267. {
  6268. largeImages = true;
  6269. break;
  6270. }
  6271. }
  6272. }
  6273. var doImportFiles = mxUtils.bind(this, function()
  6274. {
  6275. var graph = this.editor.graph;
  6276. var gs = graph.gridSize;
  6277. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  6278. {
  6279. if (data != null && data.substring(0, 10) == '<mxlibrary')
  6280. {
  6281. this.spinner.stop();
  6282. this.loadLibrary(new LocalLibrary(this, data, filename));
  6283. return null;
  6284. }
  6285. else
  6286. {
  6287. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  6288. }
  6289. });
  6290. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  6291. {
  6292. graph.setSelectionCells(cells);
  6293. });
  6294. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6295. {
  6296. var count = files.length;
  6297. var remain = count;
  6298. var queue = [];
  6299. // Barrier waits for all files to be loaded asynchronously
  6300. var barrier = mxUtils.bind(this, function(index, fnc)
  6301. {
  6302. queue[index] = fnc;
  6303. if (--remain == 0)
  6304. {
  6305. this.spinner.stop();
  6306. if (barrierFn != null)
  6307. {
  6308. barrierFn(queue);
  6309. }
  6310. else
  6311. {
  6312. var cells = [];
  6313. graph.getModel().beginUpdate();
  6314. try
  6315. {
  6316. for (var j = 0; j < queue.length; j++)
  6317. {
  6318. var tmp = queue[j]();
  6319. if (tmp != null)
  6320. {
  6321. cells = cells.concat(tmp);
  6322. }
  6323. }
  6324. }
  6325. finally
  6326. {
  6327. graph.getModel().endUpdate();
  6328. }
  6329. }
  6330. resultFn(cells);
  6331. }
  6332. });
  6333. for (var i = 0; i < count; i++)
  6334. {
  6335. (mxUtils.bind(this, function(index)
  6336. {
  6337. var file = files[index];
  6338. if (file != null)
  6339. {
  6340. var reader = new FileReader();
  6341. reader.onload = mxUtils.bind(this, function(e)
  6342. {
  6343. if (filterFn == null || filterFn(file))
  6344. {
  6345. if (file.type.substring(0, 6) == 'image/')
  6346. {
  6347. if (file.type.substring(0, 9) == 'image/svg')
  6348. {
  6349. // Checks if SVG contains content attribute
  6350. var data = e.target.result;
  6351. var comma = data.indexOf(',');
  6352. var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
  6353. var root = mxUtils.parseXml(svgText);
  6354. var svgs = root.getElementsByTagName('svg');
  6355. if (svgs.length > 0)
  6356. {
  6357. var svgRoot = svgs[0];
  6358. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  6359. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  6360. {
  6361. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  6362. }
  6363. if (cont != null && cont.charAt(0) == '%')
  6364. {
  6365. cont = decodeURIComponent(cont);
  6366. }
  6367. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  6368. cont.substring(0, 14) === '<mxGraphModel '))
  6369. {
  6370. barrier(index, mxUtils.bind(this, function()
  6371. {
  6372. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  6373. }));
  6374. }
  6375. else
  6376. {
  6377. // SVG needs special handling to add viewbox if missing and
  6378. // find initial size from SVG attributes (only for IE11)
  6379. barrier(index, mxUtils.bind(this, function()
  6380. {
  6381. try
  6382. {
  6383. var prefix = data.substring(0, comma + 1);
  6384. // Parses SVG and find width and height
  6385. if (root != null)
  6386. {
  6387. var svgs = root.getElementsByTagName('svg');
  6388. if (svgs.length > 0)
  6389. {
  6390. var svgRoot = svgs[0];
  6391. var w = parseFloat(svgRoot.getAttribute('width'));
  6392. var h = parseFloat(svgRoot.getAttribute('height'));
  6393. // Check if viewBox attribute already exists
  6394. var vb = svgRoot.getAttribute('viewBox');
  6395. if (vb == null || vb.length == 0)
  6396. {
  6397. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6398. }
  6399. // Uses width and height from viewbox for
  6400. // missing width and height attributes
  6401. else if (isNaN(w) || isNaN(h))
  6402. {
  6403. var tokens = vb.split(' ');
  6404. if (tokens.length > 3)
  6405. {
  6406. w = parseFloat(tokens[2]);
  6407. h = parseFloat(tokens[3]);
  6408. }
  6409. }
  6410. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6411. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6412. var cells = fn(data, file.type, x + index * gs, y + index * gs, Math.max(
  6413. 1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  6414. // Hack to fix width and height asynchronously
  6415. if (isNaN(w) || isNaN(h))
  6416. {
  6417. var img = new Image();
  6418. img.onload = mxUtils.bind(this, function()
  6419. {
  6420. w = Math.max(1, img.width);
  6421. h = Math.max(1, img.height);
  6422. cells[0].geometry.width = w;
  6423. cells[0].geometry.height = h;
  6424. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6425. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6426. var semi = data.indexOf(';');
  6427. if (semi > 0)
  6428. {
  6429. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6430. }
  6431. graph.setCellStyles('image', data, [cells[0]]);
  6432. });
  6433. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6434. }
  6435. return cells;
  6436. }
  6437. }
  6438. }
  6439. catch (e)
  6440. {
  6441. // ignores any SVG parsing errors
  6442. }
  6443. return null;
  6444. }));
  6445. }
  6446. }
  6447. else
  6448. {
  6449. barrier(index, mxUtils.bind(this, function()
  6450. {
  6451. return null;
  6452. }));
  6453. }
  6454. }
  6455. else
  6456. {
  6457. // Checks if PNG+XML is available to bypass code below
  6458. var containsModel = false;
  6459. if (file.type == 'image/png')
  6460. {
  6461. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  6462. if (xml != null && xml.length > 0)
  6463. {
  6464. var img = new Image();
  6465. img.src = e.target.result;
  6466. barrier(index, mxUtils.bind(this, function()
  6467. {
  6468. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  6469. img.width, img.height, file.name);
  6470. }));
  6471. containsModel = true;
  6472. }
  6473. }
  6474. // Additional asynchronous step for finding image size
  6475. if (!containsModel)
  6476. {
  6477. // Cannot load local files in Chrome App
  6478. if (mxClient.IS_CHROMEAPP)
  6479. {
  6480. this.spinner.stop();
  6481. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  6482. mxResources.get('cancel'), mxUtils.bind(this, function()
  6483. {
  6484. // Hides the dialog
  6485. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  6486. {
  6487. // Redirects to import function
  6488. this.actions.get('import').funct();
  6489. })
  6490. );
  6491. }
  6492. else
  6493. {
  6494. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  6495. {
  6496. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  6497. {
  6498. barrier(index, mxUtils.bind(this, function()
  6499. {
  6500. // Refuses to insert images above a certain size as they kill the app
  6501. if (data2 != null && data2.length < maxBytes)
  6502. {
  6503. var s = (!resizeImages || !this.isResampleImage(e.target.result, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  6504. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  6505. }
  6506. else
  6507. {
  6508. this.handleError({message: mxResources.get('imageTooBig')});
  6509. return null;
  6510. }
  6511. }));
  6512. }), resizeImages, maxSize, resampleThreshold);
  6513. }), mxUtils.bind(this, function()
  6514. {
  6515. this.handleError({message: mxResources.get('invalidOrMissingFile')});
  6516. }));
  6517. }
  6518. }
  6519. }
  6520. }
  6521. else
  6522. {
  6523. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6524. {
  6525. barrier(index, function()
  6526. {
  6527. return cells;
  6528. });
  6529. });
  6530. }
  6531. }
  6532. });
  6533. // Handles special cases
  6534. if (/(\.v(dx|sdx?))($|\?)/i.test(file.name) || /(\.vs(x|sx?))($|\?)/i.test(file.name))
  6535. {
  6536. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6537. {
  6538. barrier(index, function()
  6539. {
  6540. return cells;
  6541. });
  6542. }, file);
  6543. }
  6544. else if (file.type.substring(0, 5) == 'image')
  6545. {
  6546. reader.readAsDataURL(file);
  6547. }
  6548. else
  6549. {
  6550. reader.readAsText(file);
  6551. }
  6552. }
  6553. }))(i);
  6554. }
  6555. }
  6556. });
  6557. if (largeImages)
  6558. {
  6559. this.confirmImageResize(function(doResize)
  6560. {
  6561. resizeImages = doResize;
  6562. doImportFiles();
  6563. }, resizeDialog);
  6564. }
  6565. else
  6566. {
  6567. doImportFiles();
  6568. }
  6569. };
  6570. /**
  6571. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6572. * Filename is an optional parameter for blobs (that do not have a filename).
  6573. */
  6574. EditorUi.prototype.confirmImageResize = function(fn, force)
  6575. {
  6576. force = (force != null) ? force : false;
  6577. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  6578. var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
  6579. var wrapper = function(remember, resize)
  6580. {
  6581. if (remember || force)
  6582. {
  6583. mxSettings.setResizeImages((remember) ? resize : null);
  6584. mxSettings.save();
  6585. }
  6586. resume();
  6587. fn(resize);
  6588. };
  6589. if (resizeImages != null && !force)
  6590. {
  6591. wrapper(false, resizeImages);
  6592. }
  6593. else
  6594. {
  6595. this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
  6596. function(remember)
  6597. {
  6598. wrapper(remember, true);
  6599. },
  6600. function(remember)
  6601. {
  6602. wrapper(remember, false);
  6603. }, mxResources.get('resize'), mxResources.get('actualSize'),
  6604. '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
  6605. '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
  6606. isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
  6607. (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
  6608. }
  6609. };
  6610. /**
  6611. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6612. * Filename is an optional parameter for blobs (that do not have a filename).
  6613. */
  6614. EditorUi.prototype.parseFile = function(file, fn, filename)
  6615. {
  6616. filename = (filename != null) ? filename : file.name;
  6617. var formData = new FormData();
  6618. formData.append('format', 'xml');
  6619. formData.append('upfile', file, filename);
  6620. var xhr = new XMLHttpRequest();
  6621. xhr.open('POST', OPEN_URL);
  6622. xhr.onreadystatechange = function()
  6623. {
  6624. fn(xhr);
  6625. };
  6626. xhr.send(formData);
  6627. };
  6628. /**
  6629. *
  6630. */
  6631. EditorUi.prototype.isResampleImage = function(data, thresh)
  6632. {
  6633. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  6634. return data.length > thresh;
  6635. };
  6636. /**
  6637. * Resizes the given image if <maxImageBytes> is not null.
  6638. */
  6639. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  6640. {
  6641. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6642. var w = Math.max(1, img.width);
  6643. var h = Math.max(1, img.height);
  6644. if (enabled && this.isResampleImage(data, thresh))
  6645. {
  6646. try
  6647. {
  6648. var factor = Math.max(w / maxSize, h / maxSize);
  6649. if (factor > 1)
  6650. {
  6651. var w2 = Math.round(w / factor);
  6652. var h2 = Math.round(h / factor);
  6653. var canvas = document.createElement('canvas');
  6654. canvas.width = w2;
  6655. canvas.height = h2;
  6656. var ctx = canvas.getContext('2d');
  6657. ctx.drawImage(img, 0, 0, w2, h2);
  6658. var tmp = canvas.toDataURL();
  6659. // Uses new image if smaller
  6660. if (tmp.length < data.length)
  6661. {
  6662. // Checks if the image is empty by comparing
  6663. // with an empty image of the same size
  6664. var canvas2 = document.createElement('canvas');
  6665. canvas2.width = w2;
  6666. canvas2.height = h2;
  6667. var tmp2 = canvas2.toDataURL();
  6668. if (tmp !== tmp2)
  6669. {
  6670. data = tmp;
  6671. w = w2;
  6672. h = h2;
  6673. }
  6674. }
  6675. }
  6676. }
  6677. catch (e)
  6678. {
  6679. // ignores image scaling errors
  6680. }
  6681. }
  6682. fn(data, w, h);
  6683. };
  6684. EditorUi.prototype.crcTable = [];
  6685. for (var n = 0; n < 256; n++)
  6686. {
  6687. var c = n;
  6688. for (var k = 0; k < 8; k++)
  6689. {
  6690. if ((c & 1) == 1)
  6691. {
  6692. c = 0xedb88320 ^ (c >>> 1);
  6693. }
  6694. else
  6695. {
  6696. c >>>= 1;
  6697. }
  6698. EditorUi.prototype.crcTable[n] = c;
  6699. }
  6700. }
  6701. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  6702. {
  6703. var c = crc;
  6704. for (var n = 0; n < len; n++)
  6705. {
  6706. c = EditorUi.prototype.crcTable[(c ^ data.charCodeAt(off + n)) & 0xff] ^ (c >>> 8);
  6707. }
  6708. return c;
  6709. };
  6710. EditorUi.prototype.crc32 = function(str)
  6711. {
  6712. this.crcTable = this.crcTable || this.createCrcTable();
  6713. var crc = 0 ^ (-1);
  6714. for (var i = 0; i < str.length; i++ )
  6715. {
  6716. crc = (crc >>> 8) ^ this.crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
  6717. }
  6718. return (crc ^ (-1)) >>> 0;
  6719. };
  6720. /**
  6721. * Adds the given text to the compressed or non-compressed text chunk.
  6722. */
  6723. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  6724. {
  6725. var base64 = data.substring(data.indexOf(',') + 1);
  6726. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  6727. var pos = 0;
  6728. function fread(d, count)
  6729. {
  6730. var start = pos;
  6731. pos += count;
  6732. return d.substring(start, pos);
  6733. };
  6734. // Reads unsigned long 32 bit big endian
  6735. function _freadint(d)
  6736. {
  6737. var bytes = fread(d, 4);
  6738. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  6739. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  6740. };
  6741. function writeInt(num)
  6742. {
  6743. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  6744. (num >> 8) & 0x000000ff, num & 0x000000ff);
  6745. };
  6746. // Checks signature
  6747. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  6748. {
  6749. if (error != null)
  6750. {
  6751. error();
  6752. }
  6753. return;
  6754. }
  6755. // Reads header chunk
  6756. fread(f,4);
  6757. if (fread(f,4) != 'IHDR')
  6758. {
  6759. if (error != null)
  6760. {
  6761. error();
  6762. }
  6763. return;
  6764. }
  6765. fread(f, 17);
  6766. var result = f.substring(0, pos);
  6767. do
  6768. {
  6769. var n = _freadint(f);
  6770. var chunk = fread(f,4);
  6771. if (chunk == 'IDAT')
  6772. {
  6773. result = f.substring(0, pos - 8);
  6774. var chunkData = key + String.fromCharCode(0) +
  6775. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  6776. value;
  6777. var crc = 0xffffffff;
  6778. crc = this.updateCRC(crc, type, 0, 4);
  6779. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  6780. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  6781. result += f.substring(pos - 8, f.length);
  6782. break;
  6783. }
  6784. result += f.substring(pos - 8, pos - 4 + n);
  6785. fread(f,n);
  6786. fread(f,4);
  6787. }
  6788. while (n);
  6789. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  6790. }
  6791. /**
  6792. * Extracts the XML from the compressed or non-compressed text chunk.
  6793. */
  6794. EditorUi.prototype.extractGraphModelFromPng = function(data)
  6795. {
  6796. var result = null;
  6797. try
  6798. {
  6799. var base64 = data.substring(data.indexOf(',') + 1);
  6800. // Workaround for invalid character error in Safari
  6801. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  6802. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  6803. {
  6804. var value = binary.substring(pos + 8, pos + 8 + length);
  6805. if (type == 'zTXt')
  6806. {
  6807. var idx = value.indexOf(String.fromCharCode(0));
  6808. if (value.substring(0, idx) == 'mxGraphModel')
  6809. {
  6810. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  6811. var xmlData = Graph.bytesToString(pako.inflateRaw(
  6812. value.substring(idx + 2))).replace(/\+/g,' ');
  6813. if (xmlData != null && xmlData.length > 0)
  6814. {
  6815. result = xmlData;
  6816. }
  6817. }
  6818. }
  6819. // Uncompressed section is normally not used
  6820. else if (type == 'tEXt')
  6821. {
  6822. var vals = value.split(String.fromCharCode(0));
  6823. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  6824. {
  6825. result = vals[1];
  6826. }
  6827. }
  6828. if (result != null || type == 'IDAT')
  6829. {
  6830. // Stops processing the file as our text chunks
  6831. // are always placed before the data section
  6832. return true;
  6833. }
  6834. }));
  6835. }
  6836. catch (e)
  6837. {
  6838. // ignores decoding errors
  6839. }
  6840. if (result != null && result.charAt(0) == '%')
  6841. {
  6842. result = decodeURIComponent(result);
  6843. }
  6844. // Workaround for double encoded content
  6845. if (result != null && result.charAt(0) == '%')
  6846. {
  6847. result = decodeURIComponent(result);
  6848. }
  6849. return result;
  6850. };
  6851. /**
  6852. * Loads the image from the given URI.
  6853. *
  6854. * @param {number} dx X-coordinate of the translation.
  6855. * @param {number} dy Y-coordinate of the translation.
  6856. */
  6857. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  6858. {
  6859. var img = new Image();
  6860. img.onload = function()
  6861. {
  6862. onload(img);
  6863. }
  6864. if (onerror != null)
  6865. {
  6866. img.onerror = onerror;
  6867. }
  6868. img.src = uri;
  6869. };
  6870. // Initializes the user interface
  6871. var editorUiInit = EditorUi.prototype.init;
  6872. EditorUi.prototype.init = function()
  6873. {
  6874. mxStencilRegistry.allowEval = mxStencilRegistry.allowEval && !this.isOfflineApp();
  6875. // Must be set before UI is created in superclass
  6876. if (typeof window.mxSettings !== 'undefined')
  6877. {
  6878. this.formatWidth = mxSettings.getFormatWidth();
  6879. }
  6880. var ui = this;
  6881. var graph = this.editor.graph;
  6882. // Redirects custom link title via UI for page links
  6883. graph.getLinkTitle = function(href)
  6884. {
  6885. return ui.getLinkTitle(href);
  6886. };
  6887. // Redirects custom link via UI for page link handling
  6888. graph.customLinkClicked = function(link)
  6889. {
  6890. var done = false;
  6891. try
  6892. {
  6893. ui.handleCustomLink(link);
  6894. done = true;
  6895. }
  6896. catch (e)
  6897. {
  6898. ui.handleError(e);
  6899. }
  6900. return done;
  6901. };
  6902. // Extends clear default style to clear persisted settings
  6903. var clearDefaultStyle = this.clearDefaultStyle;
  6904. this.clearDefaultStyle = function()
  6905. {
  6906. clearDefaultStyle.apply(this, arguments);
  6907. };
  6908. // Sets help link for placeholders
  6909. if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
  6910. {
  6911. EditDataDialog.placeholderHelpLink = 'https://desk.draw.io/support/solutions/articles/16000051979';
  6912. }
  6913. // Passes current page to editor window
  6914. var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
  6915. this.editor.getEditBlankUrl = function(params)
  6916. {
  6917. params = (params != null) ? params : '';
  6918. if (ui.pages != null && ui.currentPage != null)
  6919. {
  6920. for (var i = 0; i < ui.pages.length; i++)
  6921. {
  6922. if (ui.pages[i] == ui.currentPage)
  6923. {
  6924. if (i > 0)
  6925. {
  6926. params += ((params.length > 0) ? '&' : '?') + 'page=' + i;
  6927. }
  6928. break;
  6929. }
  6930. }
  6931. }
  6932. if (urlParams['dev'] == '1')
  6933. {
  6934. params += ((params.length > 0) ? '&' : '?') + 'dev=1&drawdev=1';
  6935. }
  6936. return editorGetEditBlankUrl.apply(this, arguments);
  6937. };
  6938. // For chromeless mode and lightbox mode in viewer
  6939. // Must be overridden before supercall to be applied
  6940. // in case of chromeless initialization
  6941. var graphAddClickHandler = graph.addClickHandler;
  6942. graph.addClickHandler = function(highlight, beforeClick, onClick)
  6943. {
  6944. var tmp = beforeClick;
  6945. beforeClick = function(evt, href)
  6946. {
  6947. if (href == null)
  6948. {
  6949. var source = mxEvent.getSource(evt);
  6950. if (source.nodeName.toLowerCase() == 'a')
  6951. {
  6952. href = source.getAttribute('href');
  6953. }
  6954. }
  6955. if (href != null && graph.isCustomLink(href) &&
  6956. (mxEvent.isTouchEvent(evt) ||
  6957. !mxEvent.isPopupTrigger(evt)) &&
  6958. graph.customLinkClicked(href))
  6959. {
  6960. mxEvent.consume(evt);
  6961. }
  6962. if (tmp != null)
  6963. {
  6964. tmp(evt, href);
  6965. }
  6966. };
  6967. // For some reason, local argument override is not enough in this case...
  6968. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  6969. };
  6970. editorUiInit.apply(this, arguments);
  6971. if (mxClient.IS_SVG)
  6972. {
  6973. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  6974. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  6975. }
  6976. // Overrides print dialog size
  6977. ui.actions.get('print').funct = function()
  6978. {
  6979. ui.showDialog(new PrintDialog(ui).container, 360,
  6980. (ui.pages != null && ui.pages.length > 1) ?
  6981. 420 : 360, true, true);
  6982. };
  6983. // Specifies the default filename
  6984. this.defaultFilename = mxResources.get('untitledDiagram');
  6985. // Adds placeholder for %page% and %pagenumber%
  6986. var graphGetGlobalVariable = graph.getGlobalVariable;
  6987. graph.getGlobalVariable = function(name)
  6988. {
  6989. if (name == 'page' && ui.currentPage != null)
  6990. {
  6991. return ui.currentPage.getName();
  6992. }
  6993. else if (name == 'pagenumber')
  6994. {
  6995. if (ui.currentPage != null && ui.pages != null)
  6996. {
  6997. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  6998. }
  6999. else
  7000. {
  7001. return 1;
  7002. }
  7003. }
  7004. return graphGetGlobalVariable.apply(this, arguments);
  7005. };
  7006. var graphLabelLinkClicked = graph.labelLinkClicked;
  7007. graph.labelLinkClicked = function(state, elt, evt)
  7008. {
  7009. var href = elt.getAttribute('href');
  7010. if (href != null && graph.isCustomLink(href) &&
  7011. (mxEvent.isTouchEvent(evt) ||
  7012. !mxEvent.isPopupTrigger(evt)))
  7013. {
  7014. // Active links are moved to the hint
  7015. if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
  7016. {
  7017. graph.customLinkClicked(href);
  7018. // Resets rubberband after click on locked cell
  7019. graph.getRubberband().reset();
  7020. }
  7021. mxEvent.consume(evt);
  7022. }
  7023. else
  7024. {
  7025. graphLabelLinkClicked.apply(this, arguments);
  7026. }
  7027. };
  7028. // Overrides editor filename
  7029. this.editor.getOrCreateFilename = function()
  7030. {
  7031. var filename = ui.defaultFilename;
  7032. var file = ui.getCurrentFile();
  7033. if (file != null)
  7034. {
  7035. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  7036. }
  7037. return filename;
  7038. };
  7039. // Disables print action for standalone apps on iOS
  7040. // because there is no way to close the new window
  7041. // LATER: Use iframe for print, disable preview
  7042. var printAction = this.actions.get('print');
  7043. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  7044. printAction.visible = printAction.isEnabled();
  7045. // Scales pages/graph to fit available size
  7046. if (!this.editor.chromeless || this.editor.editable)
  7047. {
  7048. // Defines additional hotkeys
  7049. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  7050. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  7051. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  7052. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  7053. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  7054. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  7055. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  7056. if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp)
  7057. {
  7058. this.altShiftActions[83] = 'synchronize'; // Alt+Shift+S
  7059. }
  7060. // Handles copy paste of images from clipboard
  7061. if (!mxClient.IS_IE)
  7062. {
  7063. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  7064. {
  7065. var graph = this.editor.graph;
  7066. if (!mxEvent.isConsumed(evt))
  7067. {
  7068. try
  7069. {
  7070. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  7071. var containsText = false;
  7072. // Workaround for asynchronous paste event processing in textInput
  7073. // is to ignore this event if it contains text/html/rtf (see below).
  7074. // NOTE: Image is not pasted into textInput so can't listen there.
  7075. for (var i = 0; i < data.types.length; i++)
  7076. {
  7077. if (data.types[i].substring(0, 5) === 'text/')
  7078. {
  7079. containsText = true;
  7080. break;
  7081. }
  7082. }
  7083. if (!containsText)
  7084. {
  7085. var items = data.items;
  7086. for (index in items)
  7087. {
  7088. var item = items[index];
  7089. if (item.kind === 'file')
  7090. {
  7091. if (graph.isEditing())
  7092. {
  7093. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7094. {
  7095. // Inserts image into current text box
  7096. graph.insertImage(data, w, h);
  7097. }, function()
  7098. {
  7099. // No post processing
  7100. }, function(file)
  7101. {
  7102. // Handles only images
  7103. return file.type.substring(0, 6) == 'image/';
  7104. }, function(queue)
  7105. {
  7106. // Invokes elements of queue in order
  7107. for (var i = 0; i < queue.length; i++)
  7108. {
  7109. queue[i]();
  7110. }
  7111. });
  7112. }
  7113. else
  7114. {
  7115. var pt = this.editor.graph.getInsertPoint();
  7116. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  7117. mxEvent.consume(evt);
  7118. }
  7119. break;
  7120. }
  7121. }
  7122. }
  7123. }
  7124. catch (e)
  7125. {
  7126. // ignore
  7127. }
  7128. }
  7129. }), false);
  7130. }
  7131. // Focused but invisible textarea during control or meta key events
  7132. var textInput = document.createElement('div');
  7133. textInput.style.position = 'absolute';
  7134. textInput.style.whiteSpace = 'nowrap';
  7135. textInput.style.overflow = 'hidden';
  7136. textInput.style.display = 'block';
  7137. textInput.contentEditable = true;
  7138. mxUtils.setOpacity(textInput, 0);
  7139. textInput.style.width = '1px';
  7140. textInput.style.height = '1px';
  7141. textInput.innerHTML = '&nbsp;';
  7142. var restoreFocus = false;
  7143. // Disables built-in cut, copy and paste shortcuts
  7144. this.keyHandler.bindControlKey(88, null);
  7145. this.keyHandler.bindControlKey(67, null);
  7146. this.keyHandler.bindControlKey(86, null);
  7147. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  7148. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  7149. {
  7150. // No dialog visible
  7151. var source = mxEvent.getSource(evt);
  7152. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  7153. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  7154. {
  7155. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  7156. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  7157. {
  7158. // Cannot use parentNode for check in IE
  7159. if (!restoreFocus)
  7160. {
  7161. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  7162. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  7163. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  7164. graph.container.appendChild(textInput);
  7165. restoreFocus = true;
  7166. // Workaround for selected document content in quirks mode
  7167. if (mxClient.IS_QUIRKS)
  7168. {
  7169. window.setTimeout(function()
  7170. {
  7171. textInput.focus();
  7172. document.execCommand('selectAll', false, null);
  7173. }, 0);
  7174. }
  7175. else
  7176. {
  7177. textInput.focus();
  7178. document.execCommand('selectAll', false, null);
  7179. }
  7180. }
  7181. }
  7182. }
  7183. }));
  7184. // Clears input and restores focus and selection
  7185. function clearInput()
  7186. {
  7187. window.setTimeout(function()
  7188. {
  7189. textInput.innerHTML = '&nbsp;';
  7190. textInput.focus();
  7191. document.execCommand('selectAll', false, null);
  7192. }, 0);
  7193. };
  7194. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  7195. {
  7196. // Workaround for asynchronous event read invalid in IE quirks mode
  7197. var keyCode = evt.keyCode;
  7198. // Asynchronous workaround for scroll to origin after paste if the
  7199. // Ctrl-key is not pressed for long enough in FF on Windows
  7200. window.setTimeout(mxUtils.bind(this, function()
  7201. {
  7202. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  7203. keyCode == 91 /* Meta */))
  7204. {
  7205. restoreFocus = false;
  7206. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  7207. {
  7208. graph.container.focus();
  7209. }
  7210. textInput.parentNode.removeChild(textInput);
  7211. // Workaround for lost cursor in focused element
  7212. if (this.dialog == null)
  7213. {
  7214. mxUtils.clearSelection();
  7215. }
  7216. }
  7217. }), 0);
  7218. }));
  7219. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  7220. {
  7221. if (graph.isEnabled())
  7222. {
  7223. mxClipboard.copy(graph);
  7224. this.copyCells(textInput);
  7225. clearInput();
  7226. }
  7227. }));
  7228. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  7229. {
  7230. if (graph.isEnabled())
  7231. {
  7232. mxClipboard.copy(graph);
  7233. this.copyCells(textInput, true);
  7234. clearInput();
  7235. }
  7236. }));
  7237. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  7238. {
  7239. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  7240. {
  7241. textInput.innerHTML = '&nbsp;';
  7242. textInput.focus();
  7243. window.setTimeout(mxUtils.bind(this, function()
  7244. {
  7245. this.pasteCells(evt, textInput);
  7246. textInput.innerHTML = '&nbsp;';
  7247. }), 0);
  7248. }
  7249. }), true);
  7250. // Needed for IE11
  7251. var isSelectionAllowed2 = this.isSelectionAllowed;
  7252. this.isSelectionAllowed = function(evt)
  7253. {
  7254. if (mxEvent.getSource(evt) == textInput)
  7255. {
  7256. return true;
  7257. }
  7258. return isSelectionAllowed2.apply(this, arguments);
  7259. };
  7260. };
  7261. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  7262. var x = document.body.clientWidth / 2 - 2;
  7263. // Holds the x-coordinate of the point
  7264. this.spinner = this.createSpinner(x, y, 24);
  7265. // Installs drag and drop handler for rich text editor
  7266. if (Graph.fileSupport)
  7267. {
  7268. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  7269. {
  7270. // Setup the dnd listeners
  7271. var graph = this.editor.graph;
  7272. var textElt = graph.cellEditor.text2;
  7273. var dropElt = null;
  7274. if (textElt != null)
  7275. {
  7276. mxEvent.addListener(textElt, 'dragleave', function(evt)
  7277. {
  7278. if (dropElt != null)
  7279. {
  7280. dropElt.parentNode.removeChild(dropElt);
  7281. dropElt = null;
  7282. }
  7283. evt.stopPropagation();
  7284. evt.preventDefault();
  7285. });
  7286. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  7287. {
  7288. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7289. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7290. {
  7291. dropElt = this.highlightElement(textElt);
  7292. }
  7293. evt.stopPropagation();
  7294. evt.preventDefault();
  7295. }));
  7296. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  7297. {
  7298. if (dropElt != null)
  7299. {
  7300. dropElt.parentNode.removeChild(dropElt);
  7301. dropElt = null;
  7302. }
  7303. if (evt.dataTransfer.files.length > 0)
  7304. {
  7305. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7306. {
  7307. // Inserts image into current text box
  7308. graph.insertImage(data, w, h);
  7309. }, function()
  7310. {
  7311. // No post processing
  7312. }, function(file)
  7313. {
  7314. // Handles only images
  7315. return file.type.substring(0, 6) == 'image/';
  7316. }, function(queue)
  7317. {
  7318. // Invokes elements of queue in order
  7319. for (var i = 0; i < queue.length; i++)
  7320. {
  7321. queue[i]();
  7322. }
  7323. }, mxEvent.isControlDown(evt));
  7324. }
  7325. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  7326. {
  7327. var uri = evt.dataTransfer.getData('text/uri-list');
  7328. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7329. {
  7330. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7331. {
  7332. var w = Math.max(1, img.width);
  7333. var h = Math.max(1, img.height);
  7334. var maxSize = this.maxImageSize;
  7335. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7336. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  7337. }));
  7338. }
  7339. else
  7340. {
  7341. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7342. }
  7343. }
  7344. else
  7345. {
  7346. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7347. {
  7348. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  7349. }
  7350. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7351. {
  7352. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7353. }
  7354. }
  7355. evt.stopPropagation();
  7356. evt.preventDefault();
  7357. }));
  7358. }
  7359. }));
  7360. }
  7361. //Add ruler in test mode only
  7362. //TODO add the ruler containers correctly and make the vertical one dynamic as the side panel size can change
  7363. if (urlParams['ruler'] == '1' && typeof mxRuler !== 'undefined')
  7364. {
  7365. var hRulerDiv = document.createElement('div');
  7366. hRulerDiv.style.position = 'absolute';
  7367. hRulerDiv.style.top = '95px';
  7368. hRulerDiv.style.left = '250px';
  7369. hRulerDiv.style.width = '2000px';
  7370. hRulerDiv.style.height = '30px';
  7371. hRulerDiv.style.background = 'whiteSmoke';
  7372. document.body.appendChild(hRulerDiv);
  7373. var vRulerDiv = document.createElement('div');
  7374. vRulerDiv.style.position = 'absolute';
  7375. vRulerDiv.style.top = '125px';
  7376. vRulerDiv.style.left = '220px';
  7377. vRulerDiv.style.width = '30px';
  7378. vRulerDiv.style.height = '1000px';
  7379. vRulerDiv.style.background = 'whiteSmoke';
  7380. document.body.appendChild(vRulerDiv);
  7381. var square = document.createElement('div');
  7382. square.style.position = 'absolute';
  7383. square.style.top = '95px';
  7384. square.style.left = '220px';
  7385. square.style.width = '30px';
  7386. square.style.height = '30px';
  7387. square.style.background = 'whiteSmoke';
  7388. document.body.appendChild(square);
  7389. this.vRuler = new mxRuler(this.editor.graph, vRulerDiv, true);
  7390. this.hRuler = new mxRuler(this.editor.graph, hRulerDiv, false);
  7391. }
  7392. // Adds an element to edit the style in the footer in test mode
  7393. if (urlParams['styledev'] == '1')
  7394. {
  7395. var footer = document.getElementById('geFooter');
  7396. if (footer != null)
  7397. {
  7398. this.styleInput = document.createElement('input');
  7399. this.styleInput.setAttribute('type', 'text');
  7400. this.styleInput.style.position = 'absolute';
  7401. this.styleInput.style.top = '14px';
  7402. this.styleInput.style.left = '2px';
  7403. // Workaround for ignore right CSS property in FF
  7404. this.styleInput.style.width = '98%';
  7405. this.styleInput.style.visibility = 'hidden';
  7406. this.styleInput.style.opacity = '0.9';
  7407. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  7408. {
  7409. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  7410. }));
  7411. footer.appendChild(this.styleInput);
  7412. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  7413. {
  7414. if (this.editor.graph.getSelectionCount() > 0)
  7415. {
  7416. var cell = this.editor.graph.getSelectionCell();
  7417. var style = this.editor.graph.getModel().getStyle(cell);
  7418. this.styleInput.value = style || '';
  7419. this.styleInput.style.visibility = 'visible';
  7420. } else
  7421. {
  7422. this.styleInput.style.visibility = 'hidden';
  7423. }
  7424. }));
  7425. }
  7426. var isSelectionAllowed = this.isSelectionAllowed;
  7427. this.isSelectionAllowed = function(evt)
  7428. {
  7429. if (mxEvent.getSource(evt) == this.styleInput)
  7430. {
  7431. return true;
  7432. }
  7433. return isSelectionAllowed.apply(this, arguments);
  7434. };
  7435. }
  7436. // Removes info text in page
  7437. var info = document.getElementById('geInfo');
  7438. if (info != null)
  7439. {
  7440. info.parentNode.removeChild(info);
  7441. }
  7442. // Installs drag and drop handler for files
  7443. // Enables dropping files
  7444. if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
  7445. {
  7446. // Setup the dnd listeners
  7447. var dropElt = null;
  7448. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  7449. {
  7450. if (graph.isEnabled())
  7451. {
  7452. if (dropElt != null)
  7453. {
  7454. dropElt.parentNode.removeChild(dropElt);
  7455. dropElt = null;
  7456. }
  7457. evt.stopPropagation();
  7458. evt.preventDefault();
  7459. }
  7460. });
  7461. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  7462. {
  7463. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7464. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7465. {
  7466. dropElt = this.highlightElement(graph.container);
  7467. }
  7468. if (this.sidebar != null)
  7469. {
  7470. this.sidebar.hideTooltip();
  7471. }
  7472. evt.stopPropagation();
  7473. evt.preventDefault();
  7474. }));
  7475. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  7476. {
  7477. if (dropElt != null)
  7478. {
  7479. dropElt.parentNode.removeChild(dropElt);
  7480. dropElt = null;
  7481. }
  7482. if (graph.isEnabled())
  7483. {
  7484. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  7485. var tr = graph.view.translate;
  7486. var scale = graph.view.scale;
  7487. var x = pt.x / scale - tr.x;
  7488. var y = pt.y / scale - tr.y;
  7489. if (mxEvent.isAltDown(evt))
  7490. {
  7491. x = 0;
  7492. y = 0;
  7493. }
  7494. if (evt.dataTransfer.files.length > 0)
  7495. {
  7496. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  7497. mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  7498. }
  7499. else
  7500. {
  7501. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  7502. evt.dataTransfer.getData('text/uri-list') : null;
  7503. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  7504. if (data != null)
  7505. {
  7506. graph.setSelectionCells(this.importXml(data, x, y, true));
  7507. }
  7508. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7509. {
  7510. var html = evt.dataTransfer.getData('text/html');
  7511. var div = document.createElement('div');
  7512. div.innerHTML = html;
  7513. // The default is based on the extension
  7514. var asImage = null;
  7515. // Extracts single image
  7516. var imgs = div.getElementsByTagName('img');
  7517. if (imgs != null && imgs.length == 1)
  7518. {
  7519. html = imgs[0].getAttribute('src');
  7520. // Handles special case where the src attribute has no valid extension
  7521. // in which case the text would be inserted as text with a link
  7522. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  7523. {
  7524. asImage = true;
  7525. }
  7526. }
  7527. else
  7528. {
  7529. // Extracts single link
  7530. var a = div.getElementsByTagName('a');
  7531. if (a != null && a.length == 1)
  7532. {
  7533. html = a[0].getAttribute('href');
  7534. }
  7535. }
  7536. var resizeImages = true;
  7537. var doInsert = mxUtils.bind(this, function()
  7538. {
  7539. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage, null, resizeImages));
  7540. });
  7541. if (asImage && html.length > this.resampleThreshold)
  7542. {
  7543. this.confirmImageResize(function(doResize)
  7544. {
  7545. resizeImages = doResize;
  7546. doInsert();
  7547. }, mxEvent.isControlDown(evt));
  7548. }
  7549. else
  7550. {
  7551. doInsert();
  7552. }
  7553. }
  7554. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7555. {
  7556. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7557. {
  7558. var w = Math.max(1, img.width);
  7559. var h = Math.max(1, img.height);
  7560. var maxSize = this.maxImageSize;
  7561. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7562. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  7563. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  7564. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  7565. }), mxUtils.bind(this, function(img)
  7566. {
  7567. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  7568. }));
  7569. }
  7570. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7571. {
  7572. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  7573. }
  7574. }
  7575. }
  7576. evt.stopPropagation();
  7577. evt.preventDefault();
  7578. }), false);
  7579. }
  7580. this.initPages();
  7581. // Installs listener for fixing references in undo history in
  7582. // collaborative editing where terminals may have vanished
  7583. // Undo/Redo listener to update edit's references before executing undo/redo
  7584. this.editUpdateListener = mxUtils.bind(this, function(sender, evt)
  7585. {
  7586. var edit = evt.getProperty('edit');
  7587. if (edit != null)
  7588. {
  7589. this.updateEditReferences(edit);
  7590. }
  7591. });
  7592. this.editor.undoManager.addListener(mxEvent.BEFORE_UNDO, this.editUpdateListener);
  7593. this.editor.undoManager.addListener(mxEvent.BEFORE_REDO, this.editUpdateListener);
  7594. // Embedded mode
  7595. if (urlParams['embed'] == '1')
  7596. {
  7597. this.initializeEmbedMode();
  7598. }
  7599. this.installSettings();
  7600. };
  7601. /**
  7602. *
  7603. */
  7604. EditorUi.prototype.getLinkTitle = function(href)
  7605. {
  7606. var title = Graph.prototype.getLinkTitle.apply(this, arguments);
  7607. if (href.substring(0, 13) == 'data:page/id,')
  7608. {
  7609. var comma = href.indexOf(',');
  7610. if (comma > 0)
  7611. {
  7612. var page = this.getPageById(href.substring(comma + 1));
  7613. if (page != null)
  7614. {
  7615. title = page.getName();
  7616. }
  7617. else
  7618. {
  7619. title = mxResources.get('pageNotFound');
  7620. }
  7621. }
  7622. }
  7623. else if (href.substring(0, 5) == 'data:')
  7624. {
  7625. title = mxResources.get('action');
  7626. }
  7627. return title;
  7628. };
  7629. /**
  7630. *
  7631. */
  7632. EditorUi.prototype.handleCustomLink = function(href)
  7633. {
  7634. if (href.substring(0, 13) == 'data:page/id,')
  7635. {
  7636. var comma = href.indexOf(',');
  7637. var page = this.getPageById(href.substring(comma + 1));
  7638. if (page)
  7639. {
  7640. this.selectPage(page)
  7641. }
  7642. else
  7643. {
  7644. // Needs fallback for missing resource in case of viewer lightbox
  7645. throw new Error(mxResources.get('pageNotFound') || 'Page not found');
  7646. }
  7647. }
  7648. else
  7649. {
  7650. this.editor.graph.handleCustomLink(href);
  7651. }
  7652. };
  7653. /**
  7654. *
  7655. */
  7656. EditorUi.prototype.isSettingsEnabled = function()
  7657. {
  7658. return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
  7659. };
  7660. /**
  7661. * Creates the format panel and adds overrides.
  7662. */
  7663. EditorUi.prototype.installSettings = function()
  7664. {
  7665. if (this.isSettingsEnabled())
  7666. {
  7667. // Gets recent colors from settings
  7668. ColorDialog.recentColors = mxSettings.getRecentColors();
  7669. // Updates UI to reflect current edge style
  7670. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  7671. /**
  7672. * Persists copy on connect switch.
  7673. */
  7674. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  7675. this.fireEvent(new mxEventObject('copyConnectChanged'));
  7676. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  7677. {
  7678. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  7679. mxSettings.save();
  7680. }));
  7681. /**
  7682. * Persists default page format.
  7683. */
  7684. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  7685. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  7686. {
  7687. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  7688. mxSettings.save();
  7689. }));
  7690. /**
  7691. * Persists default grid color.
  7692. */
  7693. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  7694. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  7695. {
  7696. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  7697. mxSettings.save();
  7698. }));
  7699. /**
  7700. * Persists autosave switch in Chrome app.
  7701. */
  7702. if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
  7703. {
  7704. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  7705. {
  7706. mxSettings.setAutosave(this.editor.autosave);
  7707. mxSettings.save();
  7708. }));
  7709. this.editor.autosave = mxSettings.getAutosave();
  7710. }
  7711. /**
  7712. *
  7713. */
  7714. if (this.sidebar != null)
  7715. {
  7716. this.sidebar.showPalette('search', mxSettings.settings.search);
  7717. }
  7718. /**
  7719. * Shows scratchpad if never shown.
  7720. */
  7721. if ((!this.editor.chromeless || this.editor.editable) &&
  7722. this.sidebar != null && (mxSettings.settings.isNew ||
  7723. parseInt(mxSettings.settings.version || 0) <= 8))
  7724. {
  7725. this.toggleScratchpad();
  7726. mxSettings.save();
  7727. }
  7728. // Saves app defaults for UI
  7729. this.addListener('formatWidthChanged', function()
  7730. {
  7731. mxSettings.setFormatWidth(this.formatWidth);
  7732. mxSettings.save();
  7733. });
  7734. }
  7735. };
  7736. /**
  7737. * Creates the format panel and adds overrides.
  7738. */
  7739. EditorUi.prototype.copyCells = function(elt, removeCells)
  7740. {
  7741. var graph = this.editor.graph;
  7742. if (!graph.isSelectionEmpty())
  7743. {
  7744. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  7745. // LATER: Add span with XML in data attribute
  7746. // var span = document.createElement('span');
  7747. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  7748. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  7749. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  7750. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  7751. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  7752. if (removeCells)
  7753. {
  7754. graph.removeCells(cells, false);
  7755. graph.lastPasteXml = null;
  7756. }
  7757. else
  7758. {
  7759. graph.lastPasteXml = xml;
  7760. graph.pasteCounter = 0;
  7761. }
  7762. elt.focus();
  7763. document.execCommand('selectAll', false, null);
  7764. }
  7765. else
  7766. {
  7767. // Disables copy on focused element
  7768. elt.innerHTML = '';
  7769. }
  7770. };
  7771. /**
  7772. * Creates the format panel and adds overrides.
  7773. */
  7774. EditorUi.prototype.pasteCells = function(evt, elt)
  7775. {
  7776. if (!mxEvent.isConsumed(evt))
  7777. {
  7778. var spans = elt.getElementsByTagName('span');
  7779. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  7780. 'application/vnd.lucid.chart.objects')
  7781. {
  7782. var content = spans[0].getAttribute('data-lucid-content');
  7783. if (content != null && content.length > 0)
  7784. {
  7785. this.convertLucidChart(content, mxUtils.bind(this, function(xml)
  7786. {
  7787. var graph = this.editor.graph;
  7788. graph.setSelectionCells(this.importXml(xml, 0, 0));
  7789. graph.scrollCellToVisible(graph.getSelectionCell());
  7790. }), mxUtils.bind(this, function(e)
  7791. {
  7792. this.handleError(e);
  7793. }));
  7794. mxEvent.consume(evt);
  7795. }
  7796. }
  7797. else
  7798. {
  7799. var graph = this.editor.graph;
  7800. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  7801. mxUtils.getTextContent(elt) : elt.textContent);
  7802. var compat = false;
  7803. // Workaround for junk after XML in VM
  7804. try
  7805. {
  7806. var idx = xml.lastIndexOf('%3E');
  7807. if (idx >= 0 && idx < xml.length - 3)
  7808. {
  7809. xml = xml.substring(0, idx + 3);
  7810. }
  7811. }
  7812. catch (e)
  7813. {
  7814. // ignore
  7815. }
  7816. // Checks for embedded XML content
  7817. try
  7818. {
  7819. var spans = elt.getElementsByTagName('span');
  7820. var tmp = (spans != null && spans.length > 0) ?
  7821. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  7822. decodeURIComponent(xml);
  7823. if (this.isCompatibleString(tmp))
  7824. {
  7825. compat = true;
  7826. xml = tmp;
  7827. }
  7828. }
  7829. catch (e)
  7830. {
  7831. // ignore
  7832. }
  7833. if (graph.lastPasteXml == xml)
  7834. {
  7835. graph.pasteCounter++;
  7836. }
  7837. else
  7838. {
  7839. graph.lastPasteXml = xml;
  7840. graph.pasteCounter = 0;
  7841. }
  7842. var dx = graph.pasteCounter * graph.gridSize;
  7843. if (xml != null && xml.length > 0)
  7844. {
  7845. if (compat || this.isCompatibleString(xml))
  7846. {
  7847. graph.setSelectionCells(this.importXml(xml, dx, dx));
  7848. }
  7849. else
  7850. {
  7851. var pt = graph.getInsertPoint();
  7852. if (graph.isMouseInsertPoint())
  7853. {
  7854. dx = 0;
  7855. // No offset for insert at mouse position
  7856. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  7857. {
  7858. graph.pasteCounter--;
  7859. }
  7860. }
  7861. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  7862. }
  7863. if (!graph.isSelectionEmpty())
  7864. {
  7865. graph.scrollCellToVisible(graph.getSelectionCell());
  7866. if (this.hoverIcons != null)
  7867. {
  7868. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  7869. }
  7870. try
  7871. {
  7872. mxEvent.consume(evt);
  7873. }
  7874. catch (e)
  7875. {
  7876. // ignore event no longer exists in async handler in IE8-
  7877. }
  7878. }
  7879. }
  7880. }
  7881. }
  7882. };
  7883. /**
  7884. * Adds a file drop handler for opening local files.
  7885. */
  7886. EditorUi.prototype.addFileDropHandler = function(elts)
  7887. {
  7888. // Installs drag and drop handler for files
  7889. if (Graph.fileSupport)
  7890. {
  7891. var dropElt = null;
  7892. for (var i = 0; i < elts.length; i++)
  7893. {
  7894. // Setup the dnd listeners
  7895. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  7896. {
  7897. if (dropElt != null)
  7898. {
  7899. dropElt.parentNode.removeChild(dropElt);
  7900. dropElt = null;
  7901. }
  7902. evt.stopPropagation();
  7903. evt.preventDefault();
  7904. });
  7905. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  7906. {
  7907. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7908. {
  7909. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7910. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  7911. {
  7912. dropElt = this.highlightElement();
  7913. }
  7914. }
  7915. evt.stopPropagation();
  7916. evt.preventDefault();
  7917. }));
  7918. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  7919. {
  7920. if (dropElt != null)
  7921. {
  7922. dropElt.parentNode.removeChild(dropElt);
  7923. dropElt = null;
  7924. }
  7925. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7926. {
  7927. if (evt.dataTransfer.files.length > 0)
  7928. {
  7929. this.hideDialog();
  7930. // Never open files in embed mode
  7931. if (urlParams['embed'] == '1')
  7932. {
  7933. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  7934. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  7935. }
  7936. else
  7937. {
  7938. this.openFiles(evt.dataTransfer.files, true);
  7939. }
  7940. }
  7941. else
  7942. {
  7943. // Handles open special files via text drag and drop
  7944. var data = this.extractGraphModelFromEvent(evt);
  7945. // Tries additional and async parsing of text content such as HTML, Gliffy data
  7946. if (data == null)
  7947. {
  7948. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  7949. if (provider != null)
  7950. {
  7951. if (document.documentMode == 10 || document.documentMode == 11)
  7952. {
  7953. data = provider.getData('Text');
  7954. }
  7955. else
  7956. {
  7957. var data = null;
  7958. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  7959. {
  7960. var data = evt.dataTransfer.getData('text/uri-list');
  7961. }
  7962. else
  7963. {
  7964. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  7965. }
  7966. if (data != null && data.length > 0)
  7967. {
  7968. var div = document.createElement('div');
  7969. div.innerHTML = data;
  7970. // Extracts single image
  7971. var imgs = div.getElementsByTagName('img');
  7972. if (imgs.length > 0)
  7973. {
  7974. data = imgs[0].getAttribute('src');
  7975. }
  7976. }
  7977. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  7978. {
  7979. data = provider.getData('text/plain');
  7980. }
  7981. }
  7982. if (data != null)
  7983. {
  7984. // Checks for embedded XML in PNG
  7985. if (data.substring(0, 22) == 'data:image/png;base64,')
  7986. {
  7987. var xml = this.extractGraphModelFromPng(data);
  7988. if (xml != null && xml.length > 0)
  7989. {
  7990. this.openLocalFile(xml, null, true);
  7991. }
  7992. }
  7993. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  7994. {
  7995. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  7996. {
  7997. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  7998. {
  7999. this.openLocalFile(req.getText(), null, true);
  8000. }
  8001. }));
  8002. }
  8003. else if (/^https?:\/\//.test(data))
  8004. {
  8005. if (this.getCurrentFile() == null)
  8006. {
  8007. window.location.hash = '#U' + encodeURIComponent(data);
  8008. }
  8009. else
  8010. {
  8011. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  8012. (EditorUi.drawHost + '/') : 'https://' + location.host + '/') +
  8013. window.location.search + '#U' + encodeURIComponent(data));
  8014. }
  8015. }
  8016. }
  8017. }
  8018. }
  8019. else
  8020. {
  8021. this.openLocalFile(data, null, true);
  8022. }
  8023. }
  8024. }
  8025. evt.stopPropagation();
  8026. evt.preventDefault();
  8027. }));
  8028. }
  8029. }
  8030. };
  8031. /**
  8032. * Highlights the given element
  8033. */
  8034. EditorUi.prototype.highlightElement = function(elt)
  8035. {
  8036. var x = 0;
  8037. var y = 0;
  8038. var w = 0;
  8039. var h = 0;
  8040. if (elt == null)
  8041. {
  8042. var b = document.body;
  8043. var d = document.documentElement;
  8044. w = (b.clientWidth || d.clientWidth) - 3;
  8045. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  8046. }
  8047. else
  8048. {
  8049. x = elt.offsetTop;
  8050. y = elt.offsetLeft;
  8051. w = elt.clientWidth;
  8052. h = elt.clientHeight;
  8053. }
  8054. var hl = document.createElement('div');
  8055. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  8056. hl.style.border = '3px dotted rgb(254, 137, 12)';
  8057. hl.style.pointerEvents = 'none';
  8058. hl.style.position = 'absolute';
  8059. hl.style.top = x + 'px';
  8060. hl.style.left = y + 'px';
  8061. hl.style.width = Math.max(0, w - 3) + 'px';
  8062. hl.style.height = Math.max(0, h - 3) + 'px';
  8063. if (elt != null && elt.parentNode == this.editor.graph.container)
  8064. {
  8065. this.editor.graph.container.appendChild(hl);
  8066. }
  8067. else
  8068. {
  8069. document.body.appendChild(hl);
  8070. }
  8071. return hl;
  8072. };
  8073. /**
  8074. * Highlights the given element
  8075. */
  8076. EditorUi.prototype.stringToCells = function(xml)
  8077. {
  8078. var doc = mxUtils.parseXml(xml);
  8079. var node = this.editor.extractGraphModel(doc.documentElement);
  8080. var cells = [];
  8081. if (node != null)
  8082. {
  8083. var codec = new mxCodec(node.ownerDocument);
  8084. var model = new mxGraphModel();
  8085. codec.decode(node, model);
  8086. var parent = model.getChildAt(model.getRoot(), 0);
  8087. for (var j = 0; j < model.getChildCount(parent); j++)
  8088. {
  8089. cells.push(model.getChildAt(parent, j));
  8090. }
  8091. }
  8092. return cells;
  8093. };
  8094. /**
  8095. * Opens the given files in the editor.
  8096. */
  8097. EditorUi.prototype.openFiles = function(files, temp)
  8098. {
  8099. if (this.spinner.spin(document.body, mxResources.get('loading')))
  8100. {
  8101. for (var i = 0; i < files.length; i++)
  8102. {
  8103. (mxUtils.bind(this, function(file)
  8104. {
  8105. var reader = new FileReader();
  8106. reader.onload = mxUtils.bind(this, function(e)
  8107. {
  8108. try
  8109. {
  8110. var data = e.target.result;
  8111. var name = file.name;
  8112. if (name != null && name.length > 0)
  8113. {
  8114. if (!this.useCanvasForExport && /(\.png)$/i.test(name))
  8115. {
  8116. name = name.substring(0, name.length - 4) + '.xml';
  8117. }
  8118. var handleResult = mxUtils.bind(this, function(xml)
  8119. {
  8120. var dot = name.lastIndexOf('.');
  8121. if (dot >= 0)
  8122. {
  8123. name = name.substring(0, name.lastIndexOf('.')) + '.xml';
  8124. }
  8125. else
  8126. {
  8127. name = name + '.xml';
  8128. }
  8129. if (xml.substring(0, 10) == '<mxlibrary')
  8130. {
  8131. // Creates new temporary file if library is dropped in splash screen
  8132. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8133. {
  8134. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8135. }
  8136. try
  8137. {
  8138. this.loadLibrary(new LocalLibrary(this, xml, name));
  8139. }
  8140. catch (e)
  8141. {
  8142. this.handleError(e, mxResources.get('errorLoadingFile'));
  8143. }
  8144. }
  8145. else
  8146. {
  8147. this.openLocalFile(xml, name, temp);
  8148. }
  8149. });
  8150. if (/(\.v(dx|sdx?))($|\?)/i.test(name) || /(\.vs(x|sx?))($|\?)/i.test(name))
  8151. {
  8152. this.importVisio(file, mxUtils.bind(this, function(xml)
  8153. {
  8154. this.spinner.stop();
  8155. handleResult(xml);
  8156. }));
  8157. }
  8158. else if (/(\.*<graphml )/.test(data))
  8159. {
  8160. this.importGraphML(data, mxUtils.bind(this, function(xml)
  8161. {
  8162. this.spinner.stop();
  8163. handleResult(xml);
  8164. }));
  8165. }
  8166. else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  8167. this.isRemoteFileFormat(data, name))
  8168. {
  8169. this.parseFile(file, mxUtils.bind(this, function(xhr)
  8170. {
  8171. if (xhr.readyState == 4)
  8172. {
  8173. this.spinner.stop();
  8174. if (xhr.status >= 200 && xhr.status <= 299)
  8175. {
  8176. handleResult(xhr.responseText);
  8177. }
  8178. else
  8179. {
  8180. this.handleError({message: mxResources.get((xhr.status == 413) ?
  8181. 'drawingTooLarge' : 'invalidOrMissingFile')},
  8182. mxResources.get('errorLoadingFile'));
  8183. }
  8184. }
  8185. }));
  8186. }
  8187. else if (this.isLucidChartData(data))
  8188. {
  8189. if (/(\.json)$/i.test(name))
  8190. {
  8191. name = name.substring(0, name.length - 5) + '.xml';
  8192. }
  8193. // LATER: Add import step that produces cells and use callback
  8194. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  8195. {
  8196. this.spinner.stop();
  8197. this.openLocalFile(xml, name, temp);
  8198. }), mxUtils.bind(this, function(e)
  8199. {
  8200. this.spinner.stop();
  8201. this.handleError(e);
  8202. }));
  8203. }
  8204. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  8205. {
  8206. this.spinner.stop();
  8207. // Creates new temporary file if library is dropped in splash screen
  8208. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8209. {
  8210. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8211. }
  8212. try
  8213. {
  8214. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  8215. }
  8216. catch (e)
  8217. {
  8218. this.handleError(e, mxResources.get('errorLoadingFile'));
  8219. }
  8220. }
  8221. else
  8222. {
  8223. if (file.type.substring(0, 9) == 'image/png')
  8224. {
  8225. data = this.extractGraphModelFromPng(data);
  8226. }
  8227. this.spinner.stop();
  8228. this.openLocalFile(data, name, temp);
  8229. }
  8230. }
  8231. }
  8232. catch (e)
  8233. {
  8234. this.handleError(e);
  8235. }
  8236. });
  8237. reader.onerror = mxUtils.bind(this, function(e)
  8238. {
  8239. this.spinner.stop();
  8240. this.handleError(e);
  8241. window.openFile = null;
  8242. });
  8243. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  8244. {
  8245. reader.readAsDataURL(file);
  8246. }
  8247. else
  8248. {
  8249. reader.readAsText(file);
  8250. }
  8251. }))(files[i]);
  8252. }
  8253. }
  8254. };
  8255. /**
  8256. * Shows the layers dialog if the graph has more than one layer.
  8257. */
  8258. EditorUi.prototype.openLocalFile = function(data, name, temp)
  8259. {
  8260. var currentFile = this.getCurrentFile();
  8261. var fn = mxUtils.bind(this, function()
  8262. {
  8263. window.openFile = null;
  8264. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  8265. {
  8266. var doc = mxUtils.parseXml(data);
  8267. if (doc != null)
  8268. {
  8269. this.editor.setGraphXml(doc.documentElement);
  8270. this.editor.graph.selectAll();
  8271. }
  8272. }
  8273. else
  8274. {
  8275. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  8276. }
  8277. });
  8278. if (data != null && data.length > 0)
  8279. {
  8280. if (currentFile == null || (!currentFile.isModified() &&
  8281. (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)))
  8282. {
  8283. fn();
  8284. }
  8285. else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) &&
  8286. currentFile != null && currentFile.isModified())
  8287. {
  8288. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8289. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8290. }
  8291. else
  8292. {
  8293. window.openFile = new OpenFile(function()
  8294. {
  8295. window.openFile = null;
  8296. });
  8297. window.openFile.setData(data, name);
  8298. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  8299. {
  8300. if (currentFile != null && currentFile.isModified())
  8301. {
  8302. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8303. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8304. }
  8305. else
  8306. {
  8307. fn();
  8308. }
  8309. }));
  8310. }
  8311. }
  8312. else
  8313. {
  8314. throw new Error(mxResources.get('notADiagramFile'));
  8315. }
  8316. };
  8317. /**
  8318. * Returns a list of all shapes used in the current file.
  8319. */
  8320. EditorUi.prototype.getBasenames = function()
  8321. {
  8322. var basenames = {};
  8323. if (this.pages != null)
  8324. {
  8325. for (var i = 0; i < this.pages.length; i++)
  8326. {
  8327. this.updatePageRoot(this.pages[i]);
  8328. this.addBasenamesForCell(this.pages[i].root, basenames);
  8329. }
  8330. }
  8331. else
  8332. {
  8333. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  8334. }
  8335. var result = [];
  8336. for (var key in basenames)
  8337. {
  8338. result.push(key);
  8339. }
  8340. return result;
  8341. };
  8342. /**
  8343. * Returns a list of all shapes used in the current file.
  8344. */
  8345. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  8346. {
  8347. function addName(name)
  8348. {
  8349. if (name != null)
  8350. {
  8351. // LATER: Check if this case exists
  8352. var dot = name.lastIndexOf('.');
  8353. if (dot > 0)
  8354. {
  8355. name = name.substring(dot + 1, name.length);
  8356. }
  8357. if (basenames[name] == null)
  8358. {
  8359. basenames[name] = true;
  8360. }
  8361. }
  8362. };
  8363. var graph = this.editor.graph;
  8364. var style = graph.getCellStyle(cell);
  8365. var shape = style[mxConstants.STYLE_SHAPE];
  8366. addName(mxStencilRegistry.getBasenameForStencil(shape));
  8367. // Adds package names for markers in edges
  8368. if (graph.model.isEdge(cell))
  8369. {
  8370. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  8371. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  8372. }
  8373. var childCount = graph.model.getChildCount(cell);
  8374. for (var i = 0; i < childCount; i++)
  8375. {
  8376. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  8377. }
  8378. };
  8379. /**
  8380. * Shows the layers dialog if the graph has more than one layer.
  8381. */
  8382. EditorUi.prototype.setGraphEnabled = function(enabled)
  8383. {
  8384. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  8385. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  8386. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  8387. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  8388. this.hsplit.style.display = (enabled) ? '' : 'none';
  8389. this.editor.graph.setEnabled(enabled);
  8390. if (this.tabContainer != null)
  8391. {
  8392. this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
  8393. }
  8394. if (!enabled)
  8395. {
  8396. if (this.actions.outlineWindow != null)
  8397. {
  8398. this.actions.outlineWindow.window.setVisible(false);
  8399. }
  8400. if (this.actions.layersWindow != null)
  8401. {
  8402. this.actions.layersWindow.window.setVisible(false);
  8403. }
  8404. if (this.menus.tagsWindow != null)
  8405. {
  8406. this.menus.tagsWindow.window.setVisible(false);
  8407. }
  8408. if (this.menus.findWindow != null)
  8409. {
  8410. this.menus.findWindow.window.setVisible(false);
  8411. }
  8412. }
  8413. };
  8414. /**
  8415. * Shows the layers dialog if the graph has more than one layer.
  8416. */
  8417. EditorUi.prototype.initializeEmbedMode = function()
  8418. {
  8419. this.setGraphEnabled(false);
  8420. var parent = window.opener || window.parent;
  8421. if (parent != window)
  8422. {
  8423. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  8424. {
  8425. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  8426. {
  8427. this.spinner.stop();
  8428. this.addEmbedButtons();
  8429. this.setGraphEnabled(true);
  8430. if (xml != null && xml.length > 0)
  8431. {
  8432. this.setFileData(xml);
  8433. if (!this.editor.isChromelessView())
  8434. {
  8435. this.showLayersDialog();
  8436. }
  8437. else if (this.editor.graph.isLightboxView())
  8438. {
  8439. this.lightboxFit();
  8440. }
  8441. if (this.chromelessResize)
  8442. {
  8443. this.chromelessResize();
  8444. }
  8445. }
  8446. else
  8447. {
  8448. this.editor.graph.model.clear();
  8449. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  8450. }
  8451. this.editor.undoManager.clear();
  8452. this.editor.modified = (modified != null) ? modified : false;
  8453. this.updateUi();
  8454. // Workaround for no initial focus in FF
  8455. // (does not work in Conf Cloud with FF)
  8456. if (window.self !== window.top)
  8457. {
  8458. window.focus();
  8459. }
  8460. if (this.format != null)
  8461. {
  8462. this.format.refresh();
  8463. }
  8464. }));
  8465. }
  8466. }
  8467. };
  8468. /**
  8469. * Shows the layers dialog if the graph has more than one layer.
  8470. */
  8471. EditorUi.prototype.showLayersDialog = function()
  8472. {
  8473. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  8474. {
  8475. if (this.actions.layersWindow == null)
  8476. {
  8477. this.actions.get('layers').funct();
  8478. }
  8479. else
  8480. {
  8481. this.actions.layersWindow.window.setVisible(true);
  8482. }
  8483. }
  8484. };
  8485. /**
  8486. * Tries to find a public URL for the given file.
  8487. */
  8488. EditorUi.prototype.getPublicUrl = function(file, fn)
  8489. {
  8490. if (file != null)
  8491. {
  8492. file.getPublicUrl(fn);
  8493. }
  8494. else
  8495. {
  8496. fn(null);
  8497. }
  8498. };
  8499. /**
  8500. * Adds the buttons for embedded mode.
  8501. */
  8502. EditorUi.prototype.createLoadMessage = function(eventName)
  8503. {
  8504. var graph = this.editor.graph;
  8505. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  8506. bounds: graph.getGraphBounds(), currentPage: this.getSelectedPageIndex(),
  8507. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds()};
  8508. };
  8509. /**
  8510. * Adds the buttons for embedded mode.
  8511. */
  8512. EditorUi.prototype.installMessageHandler = function(fn)
  8513. {
  8514. var changeListener = null;
  8515. var ignoreChange = false;
  8516. var autosave = false;
  8517. var lastData = null;
  8518. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  8519. {
  8520. if (!this.editor.modified || urlParams['modified'] == '0')
  8521. {
  8522. this.editor.setStatus('');
  8523. }
  8524. else if (urlParams['modified'] != null)
  8525. {
  8526. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  8527. }
  8528. });
  8529. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  8530. // Receives XML message from opener and puts it into the graph
  8531. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  8532. {
  8533. var validSource = window.opener || window.parent;
  8534. if (evt.source != validSource)
  8535. {
  8536. return;
  8537. }
  8538. var data = evt.data;
  8539. var extractDiagramXml = mxUtils.bind(this, function(data)
  8540. {
  8541. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  8542. {
  8543. try
  8544. {
  8545. if (data.substring(0, 22) == 'data:image/png;base64,')
  8546. {
  8547. data = this.extractGraphModelFromPng(data);
  8548. }
  8549. else if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  8550. {
  8551. data = atob(data.substring(26));
  8552. }
  8553. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  8554. {
  8555. data = data.substring(24);
  8556. }
  8557. if (data != null)
  8558. {
  8559. if (data.charAt(0) == '%')
  8560. {
  8561. data = decodeURIComponent(data);
  8562. }
  8563. else if (data.charAt(0) != '<')
  8564. {
  8565. data = Graph.decompress(data);
  8566. }
  8567. }
  8568. }
  8569. catch (e)
  8570. {
  8571. // ignore compression errors and use empty data
  8572. }
  8573. }
  8574. return data;
  8575. });
  8576. if (urlParams['proto'] == 'json')
  8577. {
  8578. try
  8579. {
  8580. data = JSON.parse(data);
  8581. }
  8582. catch (e)
  8583. {
  8584. data = null;
  8585. }
  8586. if (data == null)
  8587. {
  8588. // Ignore
  8589. return;
  8590. }
  8591. else if (data.action == 'dialog')
  8592. {
  8593. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  8594. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  8595. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  8596. if (data.modified != null)
  8597. {
  8598. this.editor.modified = data.modified;
  8599. }
  8600. return;
  8601. }
  8602. else if (data.action == 'prompt')
  8603. {
  8604. this.spinner.stop();
  8605. var dlg = new FilenameDialog(this, data.defaultValue || '',
  8606. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  8607. {
  8608. if (value != null)
  8609. {
  8610. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  8611. }
  8612. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  8613. this.showDialog(dlg.container, 300, 80, true, false);
  8614. dlg.init();
  8615. return;
  8616. }
  8617. else if (data.action == 'draft')
  8618. {
  8619. var tmp = extractDiagramXml(data.xml);
  8620. this.spinner.stop();
  8621. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  8622. tmp, mxUtils.bind(this, function()
  8623. {
  8624. this.hideDialog();
  8625. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  8626. }), mxUtils.bind(this, function()
  8627. {
  8628. this.hideDialog();
  8629. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  8630. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  8631. (data.discardKey) ? mxResources.get(data.discardKey) : null,
  8632. (data.ignore) ? mxUtils.bind(this, function()
  8633. {
  8634. this.hideDialog();
  8635. parent.postMessage(JSON.stringify({event: 'draft', result: 'ignore', message: data}), '*');
  8636. }) : null);
  8637. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  8638. {
  8639. if (cancel)
  8640. {
  8641. this.actions.get('exit').funct();
  8642. }
  8643. }));
  8644. try
  8645. {
  8646. dlg.init();
  8647. }
  8648. catch (e)
  8649. {
  8650. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  8651. }
  8652. return;
  8653. }
  8654. else if (data.action == 'template')
  8655. {
  8656. this.spinner.stop();
  8657. var enableRecentDocs = data.enableRecent == 1;
  8658. var enableSearchDocs = data.enableSearch == 1;
  8659. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  8660. {
  8661. xml = xml || this.emptyDiagramXml;
  8662. // LATER: Add autosave option in template message
  8663. if (data.callback != null)
  8664. {
  8665. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  8666. blank: xml == this.emptyDiagramXml, name: name}), '*');
  8667. }
  8668. else
  8669. {
  8670. fn(xml, evt, xml != this.emptyDiagramXml);
  8671. // Workaround for status updated before modified applied
  8672. if (!this.editor.modified)
  8673. {
  8674. this.editor.setStatus('');
  8675. }
  8676. }
  8677. }), null, null, null, null, null, null, null,
  8678. enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
  8679. {
  8680. this.remoteInvoke('getRecentDiagrams', null, null, recentReadyCallback, function()
  8681. {
  8682. recentReadyCallback(null, 'Network Error!');
  8683. });
  8684. }) : null,
  8685. enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
  8686. {
  8687. this.remoteInvoke('searchDiagrams', [searchStr], null, searchReadyCallback, function()
  8688. {
  8689. searchReadyCallback(null, 'Network Error!');
  8690. });
  8691. }) : null,
  8692. function(url, info, name)
  8693. {
  8694. parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
  8695. name: name}), '*');
  8696. });
  8697. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  8698. {
  8699. if (cancel)
  8700. {
  8701. this.actions.get('exit').funct();
  8702. }
  8703. }));
  8704. dlg.init();
  8705. return;
  8706. }
  8707. else if (data.action == 'textContent')
  8708. {
  8709. //TODO Remove this message and use remove invokation instead
  8710. var allPagesTxt = this.getDiagramTextContent();
  8711. parent.postMessage(JSON.stringify({event: 'textContent', data: allPagesTxt, message: data}), '*');
  8712. return;
  8713. }
  8714. else if (data.action == 'status')
  8715. {
  8716. if (data.messageKey != null)
  8717. {
  8718. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  8719. }
  8720. else if (data.message != null)
  8721. {
  8722. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  8723. }
  8724. if (data.modified != null)
  8725. {
  8726. this.editor.modified = data.modified;
  8727. }
  8728. return;
  8729. }
  8730. else if (data.action == 'spinner')
  8731. {
  8732. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  8733. if (data.show != null && !data.show)
  8734. {
  8735. this.spinner.stop();
  8736. }
  8737. else
  8738. {
  8739. this.spinner.spin(document.body, msg)
  8740. }
  8741. return;
  8742. }
  8743. else if (data.action == 'export')
  8744. {
  8745. if (data.format == 'png' || data.format == 'xmlpng')
  8746. {
  8747. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8748. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8749. {
  8750. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  8751. this.editor.graph.setEnabled(false);
  8752. var graph = this.editor.graph;
  8753. var postDataBack = mxUtils.bind(this, function(uri)
  8754. {
  8755. this.editor.graph.setEnabled(true);
  8756. this.spinner.stop();
  8757. var msg = this.createLoadMessage('export');
  8758. msg.format = data.format;
  8759. msg.message = data;
  8760. msg.data = uri;
  8761. msg.xml = encodeURIComponent(xml);
  8762. parent.postMessage(JSON.stringify(msg), '*');
  8763. });
  8764. var processUri = mxUtils.bind(this, function(uri)
  8765. {
  8766. if (uri == null)
  8767. {
  8768. uri = Editor.blankImage;
  8769. }
  8770. if (data.format == 'xmlpng')
  8771. {
  8772. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  8773. atob(Graph.compress(xml)));
  8774. }
  8775. // Removes temporary graph from DOM
  8776. if (graph != this.editor.graph)
  8777. {
  8778. graph.container.parentNode.removeChild(graph.container);
  8779. }
  8780. postDataBack(uri);
  8781. });
  8782. // LATER: Uses external export if current page (not first page) has mathEnabled
  8783. if (this.isExportToCanvas())
  8784. {
  8785. // Exports PNG for first page while other page is visible by creating a graph
  8786. // LATER: Add caching for the graph or SVG while not on first page
  8787. if (this.pages != null && this.currentPage != this.pages[0])
  8788. {
  8789. graph = this.createTemporaryGraph(graph.getStylesheet());
  8790. var graphGetGlobalVariable = graph.getGlobalVariable;
  8791. var page = this.pages[0];
  8792. graph.getGlobalVariable = function(name)
  8793. {
  8794. if (name == 'page')
  8795. {
  8796. return page.getName();
  8797. }
  8798. else if (name == 'pagenumber')
  8799. {
  8800. return 1;
  8801. }
  8802. return graphGetGlobalVariable.apply(this, arguments);
  8803. };
  8804. document.body.appendChild(graph.container);
  8805. graph.model.setRoot(page.root);
  8806. }
  8807. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  8808. {
  8809. processUri(canvas.toDataURL('image/png'));
  8810. }), null, null, null, mxUtils.bind(this, function()
  8811. {
  8812. processUri(null);
  8813. }), null, null, null, null, null, null, graph);
  8814. }
  8815. else
  8816. {
  8817. // Data from server is base64 encoded to avoid binary XHR
  8818. // Double encoding for XML arg is needed for UTF8 encoding
  8819. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  8820. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  8821. encodeURIComponent(encodeURIComponent(xml)));
  8822. req.send(mxUtils.bind(this, function(req)
  8823. {
  8824. // Temp graph was never created at this point so we can
  8825. // skip processUri since it already contains the XML
  8826. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8827. {
  8828. postDataBack('data:image/png;base64,' + req.getText());
  8829. }
  8830. else
  8831. {
  8832. processUri(null);
  8833. }
  8834. }), mxUtils.bind(this, function()
  8835. {
  8836. processUri(null);
  8837. }));
  8838. }
  8839. }
  8840. }
  8841. else
  8842. {
  8843. // SVG is generated from graph so parse optional XML
  8844. if (data.xml != null && data.xml.length > 0)
  8845. {
  8846. this.setFileData(data.xml);
  8847. }
  8848. var msg = this.createLoadMessage('export');
  8849. // Forces new HTML format if pages exists
  8850. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  8851. (this.pages != null && this.pages.length > 1))))
  8852. {
  8853. var node = this.getXmlFileData();
  8854. msg.xml = mxUtils.getXml(node);
  8855. msg.data = this.getFileData(null, null, true, null, null, null, node);
  8856. msg.format = data.format;
  8857. }
  8858. else if (data.format == 'html')
  8859. {
  8860. var xml = this.editor.getGraphXml();
  8861. msg.data = this.getHtml(xml, this.editor.graph);
  8862. msg.xml = mxUtils.getXml(xml);
  8863. msg.format = data.format;
  8864. }
  8865. else
  8866. {
  8867. // Creates a preview with no alt text for unsupported browsers
  8868. mxSvgCanvas2D.prototype.foAltText = null;
  8869. var bg = this.editor.graph.background;
  8870. if (bg == mxConstants.NONE)
  8871. {
  8872. bg = null;
  8873. }
  8874. msg.xml = this.getFileData(true);
  8875. msg.format = 'svg';
  8876. if (data.embedImages || data.embedImages == null)
  8877. {
  8878. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8879. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8880. {
  8881. this.editor.graph.setEnabled(false);
  8882. if (data.format == 'xmlsvg')
  8883. {
  8884. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  8885. {
  8886. this.editor.graph.setEnabled(true);
  8887. this.spinner.stop();
  8888. msg.data = this.createSvgDataUri(svg);
  8889. parent.postMessage(JSON.stringify(msg), '*');
  8890. }));
  8891. }
  8892. else
  8893. {
  8894. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  8895. {
  8896. this.editor.graph.setEnabled(true);
  8897. this.spinner.stop();
  8898. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  8899. parent.postMessage(JSON.stringify(msg), '*');
  8900. }));
  8901. }
  8902. }
  8903. return;
  8904. }
  8905. else
  8906. {
  8907. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  8908. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  8909. msg.data = this.createSvgDataUri(svg);
  8910. }
  8911. }
  8912. parent.postMessage(JSON.stringify(msg), '*');
  8913. }
  8914. return;
  8915. }
  8916. else if (data.action == 'load')
  8917. {
  8918. autosave = data.autosave == 1;
  8919. this.hideDialog();
  8920. if (data.modified != null && urlParams['modified'] == null)
  8921. {
  8922. urlParams['modified'] = data.modified;
  8923. }
  8924. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  8925. {
  8926. urlParams['saveAndExit'] = data.saveAndExit;
  8927. }
  8928. if (data.title != null && this.buttonContainer != null)
  8929. {
  8930. var tmp = document.createElement('span');
  8931. mxUtils.write(tmp, data.title);
  8932. if (uiTheme == 'atlas')
  8933. {
  8934. this.buttonContainer.style.paddingRight = '12px';
  8935. this.buttonContainer.style.paddingTop = '12px';
  8936. this.buttonContainer.style.right = '25px';
  8937. }
  8938. else if (uiTheme != 'min')
  8939. {
  8940. this.buttonContainer.style.paddingRight = '38px';
  8941. this.buttonContainer.style.paddingTop = '6px';
  8942. }
  8943. if (this.embedFilenameSpan != null)
  8944. {
  8945. this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
  8946. }
  8947. this.buttonContainer.appendChild(tmp);
  8948. this.embedFilenameSpan = tmp;
  8949. }
  8950. if (data.xmlpng != null)
  8951. {
  8952. data = this.extractGraphModelFromPng(data.xmlpng);
  8953. }
  8954. else
  8955. {
  8956. data = data.xml;
  8957. }
  8958. }
  8959. else if (data.action == 'remoteInvokeReady')
  8960. {
  8961. this.handleRemoteInvokeReady(parent);
  8962. return;
  8963. }
  8964. else if (data.action == 'remoteInvoke')
  8965. {
  8966. this.handleRemoteInvoke(data);
  8967. return;
  8968. }
  8969. else if (data.action == 'remoteInvokeResponse')
  8970. {
  8971. this.handleRemoteInvokeResponse(data);
  8972. return;
  8973. }
  8974. else
  8975. {
  8976. // Unknown message must stop execution
  8977. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  8978. return;
  8979. }
  8980. }
  8981. var doLoad = mxUtils.bind(this, function(data, evt)
  8982. {
  8983. ignoreChange = true;
  8984. try
  8985. {
  8986. fn(data, evt);
  8987. }
  8988. catch (e)
  8989. {
  8990. this.handleError(e);
  8991. }
  8992. ignoreChange = false;
  8993. if (urlParams['modified'] != null)
  8994. {
  8995. this.editor.setStatus('');
  8996. }
  8997. var getData = mxUtils.bind(this, function()
  8998. {
  8999. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  9000. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  9001. });;
  9002. lastData = getData();
  9003. if (autosave && changeListener == null)
  9004. {
  9005. changeListener = mxUtils.bind(this, function(sender, eventObject)
  9006. {
  9007. var data = getData();
  9008. if (data != lastData && !ignoreChange)
  9009. {
  9010. var msg = this.createLoadMessage('autosave');
  9011. msg.xml = data;
  9012. data = JSON.stringify(msg);
  9013. var parent = window.opener || window.parent;
  9014. parent.postMessage(data, '*');
  9015. }
  9016. lastData = data;
  9017. });
  9018. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  9019. // Some options trigger autosave
  9020. this.editor.graph.addListener('gridSizeChanged', changeListener);
  9021. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  9022. this.addListener('pageFormatChanged', changeListener);
  9023. this.addListener('pageScaleChanged', changeListener);
  9024. this.addListener('backgroundColorChanged', changeListener);
  9025. this.addListener('backgroundImageChanged', changeListener);
  9026. this.addListener('foldingEnabledChanged', changeListener);
  9027. this.addListener('mathEnabledChanged', changeListener);
  9028. this.addListener('gridEnabledChanged', changeListener);
  9029. this.addListener('guidesEnabledChanged', changeListener);
  9030. this.addListener('pageViewChanged', changeListener);
  9031. }
  9032. // Sends the bounds of the graph to the host after parsing
  9033. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  9034. {
  9035. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  9036. }
  9037. });
  9038. if (data != null && typeof data.substring === 'function' && data.substring(0, 34) == 'data:application/vnd.visio;base64,')
  9039. {
  9040. // Checks VND binary magic number in base64
  9041. var filename = (data.substring(34, 45) == '0M8R4KGxGuE') ? 'raw.vsd' : 'raw.vsdx';
  9042. this.importVisio(this.base64ToBlob(data.substring(data.indexOf(',') + 1)), function(xml)
  9043. {
  9044. doLoad(xml, evt);
  9045. }, mxUtils.bind(this, function(e)
  9046. {
  9047. this.handleError(e);
  9048. }), filename);
  9049. }
  9050. else if (data != null && typeof data.substring === 'function' && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, ''))
  9051. {
  9052. // Asynchronous parsing via server
  9053. this.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  9054. {
  9055. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299 &&
  9056. xhr.responseText.substring(0, 13) == '<mxGraphModel')
  9057. {
  9058. doLoad(xhr.responseText, evt);
  9059. }
  9060. }), '');
  9061. }
  9062. else if (data != null && typeof data.substring === 'function' && this.isLucidChartData(data))
  9063. {
  9064. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  9065. {
  9066. doLoad(xml);
  9067. }), mxUtils.bind(this, function(e)
  9068. {
  9069. this.handleError(e);
  9070. }));
  9071. }
  9072. else
  9073. {
  9074. data = extractDiagramXml(data);
  9075. doLoad(data, evt);
  9076. }
  9077. }));
  9078. // Requests data from the sender. This is a workaround for not allowing
  9079. // the opener to listen for the onload event if not in the same origin.
  9080. var parent = window.opener || window.parent;
  9081. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  9082. parent.postMessage(msg, '*');
  9083. };
  9084. /**
  9085. * Adds the buttons for embedded mode.
  9086. */
  9087. EditorUi.prototype.addEmbedButtons = function()
  9088. {
  9089. if (this.menubar != null)
  9090. {
  9091. var div = document.createElement('div');
  9092. div.style.display = 'inline-block';
  9093. div.style.position = 'absolute';
  9094. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  9095. div.style.paddingLeft = '8px';
  9096. div.style.paddingBottom = '2px';
  9097. var button = document.createElement('button');
  9098. mxUtils.write(button, mxResources.get('save'));
  9099. button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
  9100. button.className = 'geBigButton';
  9101. button.style.fontSize = '12px';
  9102. button.style.padding = '4px 6px 4px 6px';
  9103. button.style.borderRadius = '3px';
  9104. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9105. {
  9106. this.actions.get('save').funct();
  9107. }));
  9108. div.appendChild(button);
  9109. if (urlParams['saveAndExit'] == '1')
  9110. {
  9111. button = document.createElement('a');
  9112. mxUtils.write(button, mxResources.get('saveAndExit'));
  9113. button.setAttribute('title', mxResources.get('saveAndExit'));
  9114. button.style.fontSize = '12px';
  9115. button.style.marginLeft = '6px';
  9116. button.style.padding = '4px';
  9117. button.style.cursor = 'pointer';
  9118. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9119. {
  9120. this.actions.get('saveAndExit').funct();
  9121. }));
  9122. div.appendChild(button);
  9123. }
  9124. button = document.createElement('a');
  9125. mxUtils.write(button, mxResources.get('exit'));
  9126. button.setAttribute('title', mxResources.get('exit'));
  9127. button.style.fontSize = '12px';
  9128. button.style.marginLeft = '6px';
  9129. button.style.marginRight = '20px';
  9130. button.style.padding = '4px';
  9131. button.style.cursor = 'pointer';
  9132. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9133. {
  9134. this.actions.get('exit').funct();
  9135. }));
  9136. div.appendChild(button);
  9137. this.toolbar.container.appendChild(div);
  9138. this.toolbar.staticElements.push(div);
  9139. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  9140. }
  9141. };
  9142. /**
  9143. *
  9144. */
  9145. EditorUi.prototype.showImportCsvDialog = function()
  9146. {
  9147. if (this.importCsvDialog == null)
  9148. {
  9149. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  9150. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  9151. {
  9152. this.importCsv(newValue);
  9153. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  9154. }
  9155. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  9156. this.importCsvDialog.init();
  9157. };
  9158. /**
  9159. * TODO: Move to Editor
  9160. */
  9161. EditorUi.prototype.importCsv = function(text, done)
  9162. {
  9163. try
  9164. {
  9165. var lines = text.split('\n');
  9166. var cells = [];
  9167. if (lines.length > 0)
  9168. {
  9169. // Internal lookup table
  9170. var lookups = {};
  9171. // Default values
  9172. var style = null;
  9173. var parentstyle = null;
  9174. var identity = null;
  9175. var parent = null;
  9176. var namespace = '';
  9177. var width = 'auto';
  9178. var height = 'auto';
  9179. var left = null;
  9180. var top = null;
  9181. var edgespacing = 40;
  9182. var nodespacing = 40;
  9183. var levelspacing = 100;
  9184. var padding = 0;
  9185. var graph = this.editor.graph;
  9186. var view = graph.view;
  9187. var bds = graph.getGraphBounds();
  9188. // Delayed after optional layout
  9189. var afterInsert = function()
  9190. {
  9191. if (done != null)
  9192. {
  9193. done(select);
  9194. }
  9195. else
  9196. {
  9197. graph.setSelectionCells(select);
  9198. graph.scrollCellToVisible(graph.getSelectionCell());
  9199. }
  9200. };
  9201. // Computes unscaled, untranslated graph bounds
  9202. var pt = graph.getFreeInsertPoint();
  9203. var x0 = pt.x;
  9204. var y0 = pt.y;
  9205. var y = y0;
  9206. // Default label value depends on column names
  9207. var label = null;
  9208. // Default layout to run.
  9209. var layout = 'auto';
  9210. // Name of the attribute that contains the parent reference
  9211. var parent = null;
  9212. // Name of the attribute that contains the references for creating edges
  9213. var edges = [];
  9214. // Name of the column for hyperlinks
  9215. var link = null;
  9216. // String array of names to remove from metadata
  9217. var ignore = null;
  9218. // Read processing instructions first
  9219. var index = 0;
  9220. while (index < lines.length && lines[index].charAt(0) == '#')
  9221. {
  9222. var text = lines[index];
  9223. index++;
  9224. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  9225. lines[index].charAt(0) == '#')
  9226. {
  9227. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  9228. index++;
  9229. }
  9230. if (text.charAt(1) != '#')
  9231. {
  9232. // Processing instruction
  9233. var idx = text.indexOf(':');
  9234. if (idx > 0)
  9235. {
  9236. var key = mxUtils.trim(text.substring(1, idx));
  9237. var value = mxUtils.trim(text.substring(idx + 1));
  9238. if (key == 'label')
  9239. {
  9240. label = graph.sanitizeHtml(value);
  9241. }
  9242. else if (key == 'style')
  9243. {
  9244. style = value;
  9245. }
  9246. else if (key == 'parentstyle')
  9247. {
  9248. parentstyle = value;
  9249. }
  9250. else if (key == 'identity' && value.length > 0 && value != '-')
  9251. {
  9252. identity = value;
  9253. }
  9254. else if (key == 'parent' && value.length > 0 && value != '-')
  9255. {
  9256. parent = value;
  9257. }
  9258. else if (key == 'namespace' && value.length > 0 && value != '-')
  9259. {
  9260. namespace = value;
  9261. }
  9262. else if (key == 'width')
  9263. {
  9264. width = value;
  9265. }
  9266. else if (key == 'height')
  9267. {
  9268. height = value;
  9269. }
  9270. else if (key == 'left' && value.length > 0)
  9271. {
  9272. left = value;
  9273. }
  9274. else if (key == 'top' && value.length > 0)
  9275. {
  9276. top = value;
  9277. }
  9278. else if (key == 'ignore')
  9279. {
  9280. ignore = value.split(',');
  9281. }
  9282. else if (key == 'connect')
  9283. {
  9284. edges.push(JSON.parse(value));
  9285. }
  9286. else if (key == 'link')
  9287. {
  9288. link = value;
  9289. }
  9290. else if (key == 'padding')
  9291. {
  9292. padding = parseFloat(value);
  9293. }
  9294. else if (key == 'edgespacing')
  9295. {
  9296. edgespacing = parseFloat(value);
  9297. }
  9298. else if (key == 'nodespacing')
  9299. {
  9300. nodespacing = parseFloat(value);
  9301. }
  9302. else if (key == 'levelspacing')
  9303. {
  9304. levelspacing = parseFloat(value);
  9305. }
  9306. else if (key == 'layout')
  9307. {
  9308. layout = value;
  9309. }
  9310. }
  9311. }
  9312. }
  9313. var keys = this.editor.csvToArray(lines[index]);
  9314. // Converts name of identity and parent to indexes of column
  9315. var identityIndex = null;
  9316. var parentIndex = null;
  9317. if (identity != null || parent != null)
  9318. {
  9319. for (var i = 0; i < keys.length; i++)
  9320. {
  9321. if (identity == keys[i])
  9322. {
  9323. identityIndex = i;
  9324. }
  9325. if (parent == keys[i])
  9326. {
  9327. parentIndex = i;
  9328. }
  9329. }
  9330. }
  9331. if (label == null)
  9332. {
  9333. label = '%' + keys[0] + '%';
  9334. }
  9335. if (edges != null)
  9336. {
  9337. for (var e = 0; e < edges.length; e++)
  9338. {
  9339. if (lookups[edges[e].to] == null)
  9340. {
  9341. lookups[edges[e].to] = {};
  9342. }
  9343. }
  9344. }
  9345. graph.model.beginUpdate();
  9346. try
  9347. {
  9348. for (var i = index + 1; i < lines.length; i++)
  9349. {
  9350. var values = this.editor.csvToArray(lines[i]);
  9351. if (values == null)
  9352. {
  9353. var short = (lines[i].length > 40) ? lines[i].substring(0, 40) + '...' : lines[i];
  9354. throw new Error(i + ' (' + short + ') ' + mxResources.get('containsValidationErrors'));
  9355. }
  9356. else if (values.length == keys.length)
  9357. {
  9358. var cell = null;
  9359. var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
  9360. if (id != null)
  9361. {
  9362. cell = graph.model.getCell(id);
  9363. }
  9364. if (cell == null)
  9365. {
  9366. var cell = new mxCell(label, new mxGeometry(x0, y,
  9367. 0, 0), style || 'whiteSpace=wrap;html=1;');
  9368. cell.vertex = true;
  9369. cell.id = id;
  9370. }
  9371. for (var j = 0; j < values.length; j++)
  9372. {
  9373. graph.setAttributeForCell(cell, keys[j], values[j]);
  9374. }
  9375. graph.setAttributeForCell(cell, 'placeholders', '1');
  9376. cell.style = graph.replacePlaceholders(cell, cell.style);
  9377. for (var e = 0; e < edges.length; e++)
  9378. {
  9379. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  9380. }
  9381. if (link != null && link != 'link')
  9382. {
  9383. graph.setLinkForCell(cell, cell.getAttribute(link));
  9384. // Removes attribute
  9385. graph.setAttributeForCell(cell, link, null);
  9386. }
  9387. // Sets the size
  9388. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
  9389. var size = this.editor.graph.getPreferredSizeForCell(cell);
  9390. if (cell.vertex)
  9391. {
  9392. if (left != null && cell.getAttribute(left) != null)
  9393. {
  9394. cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
  9395. }
  9396. if (top != null && cell.getAttribute(top) != null)
  9397. {
  9398. cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
  9399. }
  9400. if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
  9401. {
  9402. cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
  9403. }
  9404. else
  9405. {
  9406. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  9407. }
  9408. if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
  9409. {
  9410. cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
  9411. }
  9412. else
  9413. {
  9414. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  9415. }
  9416. y += cell.geometry.height + nodespacing;
  9417. }
  9418. var parent = (parentIndex != null) ? graph.model.getCell(
  9419. namespace + values[parentIndex]) : null;
  9420. if (parent != null)
  9421. {
  9422. parent.style = graph.replacePlaceholders(parent, parentstyle);
  9423. graph.addCell(cell, parent);
  9424. }
  9425. else
  9426. {
  9427. cells.push(graph.addCell(cell));
  9428. }
  9429. }
  9430. }
  9431. var roots = cells.slice();
  9432. var select = cells.slice();
  9433. for (var e = 0; e < edges.length; e++)
  9434. {
  9435. var edge = edges[e];
  9436. for (var i = 0; i < cells.length; i++)
  9437. {
  9438. var cell = cells[i];
  9439. var tmp = cell.getAttribute(edge.from);
  9440. if (tmp != null)
  9441. {
  9442. // Removes attribute
  9443. graph.setAttributeForCell(cell, edge.from, null);
  9444. var refs = tmp.split(',');
  9445. for (var j = 0; j < refs.length; j++)
  9446. {
  9447. var ref = lookups[edge.to][refs[j]];
  9448. if (ref != null)
  9449. {
  9450. var label = edge.label;
  9451. if (edge.fromlabel != null)
  9452. {
  9453. label = (cell.getAttribute(edge.fromlabel) || '') + (label || '');
  9454. }
  9455. if (edge.tolabel != null)
  9456. {
  9457. label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
  9458. }
  9459. select.push(graph.insertEdge(null, null, label || '',
  9460. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  9461. edge.style || graph.createCurrentEdgeStyle()));
  9462. mxUtils.remove((edge.invert) ? cell : ref, roots);
  9463. }
  9464. }
  9465. }
  9466. }
  9467. }
  9468. // Removes ignored attributes after processing above
  9469. if (ignore != null)
  9470. {
  9471. for (var i = 0; i < cells.length; i++)
  9472. {
  9473. var cell = cells[i];
  9474. for (var j = 0; j < ignore.length; j++)
  9475. {
  9476. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  9477. }
  9478. }
  9479. }
  9480. var edgeLayout = new mxParallelEdgeLayout(graph);
  9481. edgeLayout.spacing = edgespacing;
  9482. var postProcess = function()
  9483. {
  9484. edgeLayout.execute(graph.getDefaultParent());
  9485. // Aligns cells to grid and/or rounds positions
  9486. for (var i = 0; i < cells.length; i++)
  9487. {
  9488. var geo = graph.getCellGeometry(cells[i]);
  9489. geo.x = Math.round(graph.snap(geo.x));
  9490. geo.y = Math.round(graph.snap(geo.y));
  9491. if (width == 'auto')
  9492. {
  9493. geo.width = Math.round(graph.snap(geo.width));
  9494. }
  9495. if (height == 'auto')
  9496. {
  9497. geo.height = Math.round(graph.snap(geo.height));
  9498. }
  9499. }
  9500. };
  9501. if (layout == 'circle')
  9502. {
  9503. var circleLayout = new mxCircleLayout(graph);
  9504. circleLayout.resetEdges = false;
  9505. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  9506. // Ignore other cells
  9507. circleLayout.isVertexIgnored = function(vertex)
  9508. {
  9509. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  9510. mxUtils.indexOf(cells, vertex) < 0;
  9511. };
  9512. this.executeLayout(function()
  9513. {
  9514. circleLayout.execute(graph.getDefaultParent());
  9515. postProcess();
  9516. }, true, afterInsert);
  9517. afterInsert = null;
  9518. }
  9519. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  9520. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  9521. {
  9522. // Required for layouts to work with new cells
  9523. graph.view.validate();
  9524. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  9525. treeLayout.levelDistance = nodespacing;
  9526. treeLayout.edgeRouting = false;
  9527. treeLayout.resetEdges = false;
  9528. this.executeLayout(function()
  9529. {
  9530. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  9531. }, true, afterInsert);
  9532. afterInsert = null;
  9533. }
  9534. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  9535. (layout == 'auto' && roots.length == 1))
  9536. {
  9537. // Required for layouts to work with new cells
  9538. graph.view.validate();
  9539. var flowLayout = new mxHierarchicalLayout(graph,
  9540. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  9541. flowLayout.intraCellSpacing = nodespacing;
  9542. flowLayout.parallelEdgeSpacing = edgespacing;
  9543. flowLayout.interRankCellSpacing = levelspacing;
  9544. flowLayout.disableEdgeStyle = false;
  9545. this.executeLayout(function()
  9546. {
  9547. flowLayout.execute(graph.getDefaultParent(), select);
  9548. // Workaround for flow layout moving cells to origin
  9549. graph.moveCells(select, x0, y0);
  9550. }, true, afterInsert);
  9551. afterInsert = null;
  9552. }
  9553. else if (layout == 'organic' || (layout == 'auto' &&
  9554. select.length > cells.length))
  9555. {
  9556. // Required for layouts to work with new cells
  9557. graph.view.validate();
  9558. var organicLayout = new mxFastOrganicLayout(graph);
  9559. organicLayout.forceConstant = nodespacing * 3;
  9560. organicLayout.resetEdges = false;
  9561. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  9562. // Ignore other cells
  9563. organicLayout.isVertexIgnored = function(vertex)
  9564. {
  9565. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  9566. mxUtils.indexOf(cells, vertex) < 0;
  9567. };
  9568. var edgeLayout = new mxParallelEdgeLayout(graph);
  9569. edgeLayout.spacing = edgespacing;
  9570. this.executeLayout(function()
  9571. {
  9572. organicLayout.execute(graph.getDefaultParent());
  9573. postProcess();
  9574. }, true, afterInsert);
  9575. afterInsert = null;
  9576. }
  9577. this.hideDialog();
  9578. }
  9579. finally
  9580. {
  9581. graph.model.endUpdate();
  9582. }
  9583. if (afterInsert != null)
  9584. {
  9585. afterInsert();
  9586. }
  9587. }
  9588. }
  9589. catch (e)
  9590. {
  9591. this.handleError(e);
  9592. }
  9593. };
  9594. /**
  9595. * Translates this point by the given vector.
  9596. *
  9597. * @param {number} dx X-coordinate of the translation.
  9598. * @param {number} dy Y-coordinate of the translation.
  9599. */
  9600. EditorUi.prototype.getSearch = function(exclude)
  9601. {
  9602. var result = '';
  9603. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  9604. {
  9605. var amp = '?';
  9606. for (var key in urlParams)
  9607. {
  9608. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  9609. {
  9610. result += amp + key + '=' + urlParams[key];
  9611. amp = '&';
  9612. }
  9613. }
  9614. }
  9615. else
  9616. {
  9617. result = window.location.search;
  9618. }
  9619. return result;
  9620. };
  9621. /**
  9622. * Returns the URL for a copy of this editor with no state.
  9623. */
  9624. EditorUi.prototype.getUrl = function(pathname)
  9625. {
  9626. var href = (pathname != null) ? pathname : window.location.pathname;
  9627. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  9628. if (urlParams['offline'] == '1')
  9629. {
  9630. href += window.location.search;
  9631. }
  9632. else
  9633. {
  9634. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  9635. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  9636. // Removes template URL parameter for new blank diagram
  9637. for (var key in urlParams)
  9638. {
  9639. if (mxUtils.indexOf(ignored, key) < 0)
  9640. {
  9641. if (parms == 0)
  9642. {
  9643. href += '?';
  9644. }
  9645. else
  9646. {
  9647. href += '&';
  9648. }
  9649. if (urlParams[key] != null)
  9650. {
  9651. href += key + '=' + urlParams[key];
  9652. parms++;
  9653. }
  9654. }
  9655. }
  9656. }
  9657. return href;
  9658. };
  9659. /**
  9660. * Overrides link dialog.
  9661. */
  9662. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  9663. {
  9664. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  9665. this.showDialog(dlg.container, 480, 130, true, true);
  9666. dlg.init();
  9667. };
  9668. /**
  9669. * Overrides createOutline
  9670. */
  9671. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  9672. EditorUi.prototype.createOutline = function(wnd)
  9673. {
  9674. var outline = editorUiCreateOutline.apply(this, arguments);
  9675. var graph = this.editor.graph;
  9676. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  9677. outline.getSourceGraphBounds = function()
  9678. {
  9679. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  9680. {
  9681. var pb = this.source.getPagePadding();
  9682. var s = this.source.view.scale;
  9683. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  9684. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  9685. return result;
  9686. }
  9687. return outlineGetSourceGraphBounds.apply(this, arguments);
  9688. };
  9689. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  9690. outline.getSourceContainerSize = function()
  9691. {
  9692. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9693. {
  9694. var pad = this.source.getPagePadding();
  9695. var s = this.source.view.scale;
  9696. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  9697. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  9698. }
  9699. return outlineGetSourceContainerSize.apply(this, arguments);
  9700. };
  9701. outline.getOutlineOffset = function(scale)
  9702. {
  9703. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9704. {
  9705. var pb = this.source.getPagePadding();
  9706. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  9707. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  9708. // Why is vertical offset negative relative to dy
  9709. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  9710. }
  9711. return new mxPoint(8 / scale, 8 / scale);
  9712. };
  9713. var outlineInit = outline.init;
  9714. outline.init = function()
  9715. {
  9716. outlineInit.apply(this, arguments);
  9717. // Problem: Need to override a function in the view but the view is created
  9718. // with the graph so a refresh of the page is needed to see this change.
  9719. outline.outline.view.getBackgroundPageBounds = function()
  9720. {
  9721. var layout = graph.getPageLayout();
  9722. var page = graph.getPageSize();
  9723. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  9724. this.scale * (this.translate.y + layout.y * page.height),
  9725. this.scale * layout.width * page.width,
  9726. this.scale * layout.height * page.height);
  9727. };
  9728. outline.outline.view.validateBackgroundPage();
  9729. };
  9730. this.editor.addListener('pageSelected', function(sender, evt)
  9731. {
  9732. var change = evt.getProperty('change');
  9733. var graph = outline.source;
  9734. var g = outline.outline;
  9735. g.pageScale = graph.pageScale;
  9736. g.pageFormat = graph.pageFormat;
  9737. g.background = graph.background;
  9738. g.pageVisible = graph.pageVisible;
  9739. g.background = graph.background;
  9740. var current = mxUtils.getCurrentStyle(graph.container);
  9741. g.container.style.backgroundColor = current.backgroundColor;
  9742. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  9743. {
  9744. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  9745. }
  9746. outline.outline.view.clear(change.previousPage.root, true);
  9747. outline.outline.view.validate();
  9748. });
  9749. return outline;
  9750. };
  9751. /**
  9752. * Returns the number of storage options enabled
  9753. */
  9754. EditorUi.prototype.getServiceCount = function(allowBrowser, splash)
  9755. {
  9756. var serviceCount = 0;
  9757. if (this.drive != null || typeof window.DriveClient === 'function')
  9758. {
  9759. serviceCount++
  9760. }
  9761. if (!splash && (this.dropbox != null || typeof window.DropboxClient === 'function'))
  9762. {
  9763. serviceCount++
  9764. }
  9765. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  9766. {
  9767. serviceCount++
  9768. }
  9769. if (!splash && (this.gitHub != null))
  9770. {
  9771. serviceCount++
  9772. }
  9773. if (!splash && (this.trello != null || typeof window.TrelloClient === 'function'))
  9774. {
  9775. serviceCount++
  9776. }
  9777. if (allowBrowser && isLocalStorage && urlParams['browser'] == '1')
  9778. {
  9779. serviceCount++
  9780. }
  9781. else
  9782. {
  9783. serviceCount++
  9784. }
  9785. return serviceCount;
  9786. }
  9787. /**
  9788. * Updates action and menu states depending on the file.
  9789. */
  9790. EditorUi.prototype.updateUi = function()
  9791. {
  9792. this.updateButtonContainer();
  9793. this.updateActionStates();
  9794. // Action states that only need update for new files
  9795. var file = this.getCurrentFile();
  9796. var active = file != null || (urlParams['embed'] == '1' &&
  9797. this.editor.graph.isEnabled());
  9798. this.menus.get('viewPanels').setEnabled(active);
  9799. this.menus.get('viewZoom').setEnabled(active);
  9800. var restricted = (urlParams['embed'] != '1' ||
  9801. !this.editor.graph.isEnabled()) &&
  9802. (file == null || file.isRestricted());
  9803. this.actions.get('makeCopy').setEnabled(!restricted);
  9804. this.actions.get('print').setEnabled(!restricted);
  9805. this.menus.get('exportAs').setEnabled(!restricted);
  9806. this.menus.get('embed').setEnabled(!restricted);
  9807. // Disables libraries and extras menu in embed mode
  9808. // while waiting for file data
  9809. var libsEnabled = urlParams['embed'] != '1' ||
  9810. this.editor.graph.isEnabled();
  9811. this.menus.get('extras').setEnabled(libsEnabled);
  9812. if (Editor.enableCustomLibraries)
  9813. {
  9814. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  9815. this.menus.get('newLibrary').setEnabled(libsEnabled);
  9816. }
  9817. // Disables actions in the toolbar
  9818. var editable = (urlParams['embed'] == '1' &&
  9819. this.editor.graph.isEnabled()) ||
  9820. (file != null && file.isEditable());
  9821. this.actions.get('image').setEnabled(active);
  9822. this.actions.get('zoomIn').setEnabled(active);
  9823. this.actions.get('zoomOut').setEnabled(active);
  9824. this.actions.get('resetView').setEnabled(active);
  9825. // Updates undo history states
  9826. this.actions.get('undo').setEnabled(this.canUndo() && editable);
  9827. this.actions.get('redo').setEnabled(this.canRedo() && editable);
  9828. // Disables menus
  9829. this.menus.get('edit').setEnabled(active);
  9830. this.menus.get('view').setEnabled(active);
  9831. this.menus.get('importFrom').setEnabled(editable);
  9832. this.menus.get('arrange').setEnabled(editable);
  9833. // Disables connection drop downs in toolbar
  9834. if (this.toolbar != null)
  9835. {
  9836. if (this.toolbar.edgeShapeMenu != null)
  9837. {
  9838. this.toolbar.edgeShapeMenu.setEnabled(editable);
  9839. }
  9840. if (this.toolbar.edgeStyleMenu != null)
  9841. {
  9842. this.toolbar.edgeStyleMenu.setEnabled(editable);
  9843. }
  9844. }
  9845. if (this.isAppCache())
  9846. {
  9847. var appCache = applicationCache;
  9848. // NOTE: HTML5 Cache is deprecated
  9849. if (appCache != null && this.offlineStatus == null)
  9850. {
  9851. this.offlineStatus = document.createElement('div');
  9852. this.offlineStatus.className = 'geItem';
  9853. this.offlineStatus.style.position = 'absolute';
  9854. this.offlineStatus.style.fontSize = '8pt';
  9855. this.offlineStatus.style.top = '2px';
  9856. this.offlineStatus.style.right = '12px';
  9857. this.offlineStatus.style.color = '#666';
  9858. this.offlineStatus.style.margin = '4px';
  9859. this.offlineStatus.style.padding = '2px';
  9860. this.offlineStatus.style.verticalAlign = 'middle';
  9861. this.offlineStatus.innerHTML = '';
  9862. this.menubarContainer.appendChild(this.offlineStatus);
  9863. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  9864. {
  9865. var img = this.offlineStatus.getElementsByTagName('img');
  9866. if (img != null && img.length > 0)
  9867. {
  9868. this.alert(img[0].getAttribute('title'));
  9869. }
  9870. }));
  9871. var appCache = window.applicationCache;
  9872. var lastStatus = null;
  9873. var updateStatus = mxUtils.bind(this, function()
  9874. {
  9875. var newStatus = appCache.status;
  9876. var html = '';
  9877. if (newStatus == appCache.CHECKING)
  9878. {
  9879. newStatus = appCache.DOWNLOADING;
  9880. }
  9881. switch (newStatus)
  9882. {
  9883. case appCache.UNCACHED: // UNCACHED == 0
  9884. html = '';
  9885. break;
  9886. case appCache.IDLE: // IDLE == 1
  9887. html = (uiTheme == 'min') ? '' : '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  9888. break;
  9889. case appCache.DOWNLOADING: // DOWNLOADING == 3
  9890. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  9891. break;
  9892. case appCache.UPDATEREADY: // UPDATEREADY == 4
  9893. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  9894. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  9895. break;
  9896. case appCache.OBSOLETE: // OBSOLETE == 5
  9897. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9898. break;
  9899. default:
  9900. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9901. break;
  9902. }
  9903. if (newStatus != lastStatus)
  9904. {
  9905. this.offlineStatus.innerHTML = html;
  9906. lastStatus = newStatus;
  9907. }
  9908. });
  9909. mxEvent.addListener(appCache, 'checking', updateStatus);
  9910. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  9911. mxEvent.addListener(appCache, 'downloading', updateStatus);
  9912. mxEvent.addListener(appCache, 'progress', updateStatus);
  9913. mxEvent.addListener(appCache, 'cached', updateStatus);
  9914. mxEvent.addListener(appCache, 'updateready', updateStatus);
  9915. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  9916. mxEvent.addListener(appCache, 'error', updateStatus);
  9917. updateStatus();
  9918. }
  9919. }
  9920. else
  9921. {
  9922. this.updateUserElement();
  9923. }
  9924. };
  9925. /**
  9926. * Hook for subclassers
  9927. */
  9928. EditorUi.prototype.updateButtonContainer = function()
  9929. {
  9930. // do nothing
  9931. };
  9932. /**
  9933. * Hook for subclassers
  9934. */
  9935. EditorUi.prototype.updateUserElement = function()
  9936. {
  9937. // do nothing
  9938. };
  9939. /**
  9940. * Returns true if a diagram is cative and editable.
  9941. */
  9942. EditorUi.prototype.isDiagramActive = function()
  9943. {
  9944. var file = this.getCurrentFile();
  9945. return (file != null && file.isEditable()) ||
  9946. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  9947. };
  9948. /**
  9949. * Updates action states depending on the selection.
  9950. */
  9951. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  9952. EditorUi.prototype.updateActionStates = function()
  9953. {
  9954. editorUiUpdateActionStates.apply(this, arguments);
  9955. var graph = this.editor.graph;
  9956. var active = this.isDiagramActive();
  9957. var file = this.getCurrentFile();
  9958. var enabled = file != null || urlParams['embed'] == '1';
  9959. this.actions.get('pageSetup').setEnabled(active);
  9960. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  9961. this.actions.get('guides').setEnabled(active);
  9962. this.actions.get('editData').setEnabled(active);
  9963. this.actions.get('shadowVisible').setEnabled(active);
  9964. this.actions.get('connectionArrows').setEnabled(active);
  9965. this.actions.get('connectionPoints').setEnabled(active);
  9966. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  9967. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  9968. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  9969. this.actions.get('createShape').setEnabled(active);
  9970. this.actions.get('createRevision').setEnabled(active);
  9971. this.actions.get('moveToFolder').setEnabled(file != null);
  9972. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  9973. this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
  9974. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  9975. this.actions.get('tags').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  9976. this.actions.get('find').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  9977. this.actions.get('layers').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  9978. this.actions.get('outline').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  9979. this.actions.get('rename').setEnabled((file != null && file.isRenamable()) || urlParams['embed'] == '1');
  9980. this.actions.get('close').setEnabled(file != null);
  9981. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  9982. var state = graph.view.getState(graph.getSelectionCell());
  9983. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  9984. };
  9985. /**
  9986. * Overridden to remove export dialog in chromeless lightbox.
  9987. */
  9988. var editoUiDestroy = EditorUi.prototype.destroy;
  9989. EditorUi.prototype.destroy = function()
  9990. {
  9991. if (this.editUpdateListener)
  9992. {
  9993. this.editor.undoManager.removeListener(this.editUpdateListener);
  9994. this.editUpdateListener = null;
  9995. }
  9996. if (this.exportDialog != null)
  9997. {
  9998. this.exportDialog.parentNode.removeChild(this.exportDialog);
  9999. this.exportDialog = null;
  10000. }
  10001. editoUiDestroy.apply(this, arguments);
  10002. };
  10003. /**
  10004. * Overrides export dialog for using ui functions for save and setting global switches.
  10005. */
  10006. if (window.ExportDialog != null)
  10007. {
  10008. ExportDialog.showXmlOption = false;
  10009. ExportDialog.showGifOption = false;
  10010. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  10011. {
  10012. var graph = editorUi.editor.graph;
  10013. if (format == 'xml')
  10014. {
  10015. editorUi.hideDialog();
  10016. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  10017. }
  10018. else if (format == 'svg')
  10019. {
  10020. editorUi.hideDialog();
  10021. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  10022. }
  10023. else
  10024. {
  10025. var data = editorUi.getFileData(true, null, null, null, null, true);
  10026. var bounds = graph.getGraphBounds();
  10027. var w = Math.floor(bounds.width * s / graph.view.scale);
  10028. var h = Math.floor(bounds.height * s / graph.view.scale);
  10029. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  10030. {
  10031. editorUi.hideDialog();
  10032. editorUi.saveRequest(name, format,
  10033. function(newTitle, base64)
  10034. {
  10035. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  10036. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  10037. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  10038. '&border=' + b + '&xml=' + encodeURIComponent(data));
  10039. });
  10040. }
  10041. else
  10042. {
  10043. mxUtils.alert(mxResources.get('drawingTooLarge'));
  10044. }
  10045. }
  10046. };
  10047. }
  10048. /*********************************************************************************************
  10049. * This section is a fix for undo/redo edits having stale 1st- and 2nd-order references *
  10050. * The code might be reworked or even thrown out when a conceptually nicer solution is found *
  10051. *********************************************************************************************/
  10052. /**
  10053. * Updates all references in all edits and their changes in order to correspond to current model
  10054. */
  10055. EditorUi.prototype.updateEditReferences = function(edit)
  10056. {
  10057. for (var i = 0; i < edit.changes.length; i++)
  10058. {
  10059. var change = edit.changes[i];
  10060. if (change != null && change.constructor == mxChildChange)
  10061. {
  10062. if (change.child != null)
  10063. {
  10064. var child = change.child;
  10065. if (child.source != null && child.source.id != null)
  10066. {
  10067. var modelSource = this.getFutureCellForEdit(change.model, edit, child.source.id);
  10068. if (modelSource != child.source)
  10069. {
  10070. child.source = modelSource
  10071. }
  10072. }
  10073. if (child.target != null && child.target.id != null)
  10074. {
  10075. var modelTarget = this.getFutureCellForEdit(change.model, edit, child.target.id);
  10076. if (modelTarget != child.target)
  10077. {
  10078. child.target = modelTarget
  10079. }
  10080. }
  10081. }
  10082. }
  10083. }
  10084. };
  10085. /**
  10086. * Looks ahead in edit's changes to see if the last child change containing ID is one that creates a cell, then returns it.
  10087. * If cell already exists in a model, returns it first.
  10088. */
  10089. EditorUi.prototype.getFutureCellForEdit = function(model, edit, id)
  10090. {
  10091. var result = model.getCell(id);
  10092. if (result == null)
  10093. {
  10094. // Scans changes backwards
  10095. for (var i = edit.changes.length - 1; i >= 0; i--)
  10096. {
  10097. var change = edit.changes[i];
  10098. if (change.constructor == mxChildChange)
  10099. {
  10100. // Checks if child is being added in this change
  10101. if (change.child != null && change.child.id == id)
  10102. {
  10103. // Checks if cell is being removed
  10104. if (model.contains(change.previous))
  10105. {
  10106. result = change.child;
  10107. }
  10108. // Stops scan in any case, at the end of the edit
  10109. // the cell will be either added or deleted
  10110. break;
  10111. }
  10112. }
  10113. }
  10114. }
  10115. return result;
  10116. };
  10117. EditorUi.prototype.getDiagramTextContent = function()
  10118. {
  10119. this.editor.graph.setEnabled(false);
  10120. var graph = this.editor.graph;
  10121. var allPagesTxt = '';
  10122. if (this.pages != null)
  10123. {
  10124. for (var i = 0; i < this.pages.length; i++)
  10125. {
  10126. var pageGraph = graph;
  10127. if (this.currentPage != this.pages[i])
  10128. {
  10129. pageGraph = this.createTemporaryGraph(graph.getStylesheet());
  10130. pageGraph.model.setRoot(this.pages[i].root);
  10131. }
  10132. allPagesTxt += this.pages[i].getName() + ' ' + pageGraph.getIndexableText() + ' ';
  10133. }
  10134. }
  10135. else
  10136. {
  10137. allPagesTxt = graph.getIndexableText();
  10138. }
  10139. this.editor.graph.setEnabled(true);
  10140. return allPagesTxt;
  10141. };
  10142. EditorUi.prototype.showRemotelyStoredLibrary = function(title)
  10143. {
  10144. var selectedLibs = {};
  10145. var div = document.createElement('div');
  10146. div.style.whiteSpace = 'nowrap';
  10147. var graph = this.editor.graph;
  10148. var hd = document.createElement('h3');
  10149. mxUtils.write(hd, mxUtils.htmlEntities(title));
  10150. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  10151. div.appendChild(hd);
  10152. var libsSection = document.createElement('div');
  10153. libsSection.style.cssText = 'border:1px solid lightGray;overflow: auto;height:300px';
  10154. libsSection.innerHTML = '<img src="/images/spin.gif">';
  10155. var loadedLibs = {};
  10156. try
  10157. {
  10158. var custLibs = mxSettings.getCustomLibraries();
  10159. for (var j = 0; j < custLibs.length; j++)
  10160. {
  10161. var l = custLibs[j];
  10162. if (l.substring(0, 1) == 'R')
  10163. {
  10164. var libDesc = JSON.parse(decodeURIComponent(l.substring(1)));
  10165. loadedLibs[libDesc[0]] = {
  10166. id: libDesc[0],
  10167. title: libDesc[1],
  10168. downloadUrl: libDesc[2]
  10169. };
  10170. }
  10171. }
  10172. }
  10173. catch(e){}
  10174. this.remoteInvoke('getCustomLibraries', null, null, function(libsList)
  10175. {
  10176. libsSection.innerHTML = '';
  10177. for (var i = 0; i < libsList.length; i++)
  10178. {
  10179. var lib = libsList[i];
  10180. if (loadedLibs[lib.id])
  10181. {
  10182. selectedLibs[lib.id] = lib;
  10183. }
  10184. var libCheck = this.addCheckbox(libsSection, lib.title, loadedLibs[lib.id]);
  10185. (function(lib2, check)
  10186. {
  10187. mxEvent.addListener(check, 'change', function()
  10188. {
  10189. if (this.checked)
  10190. {
  10191. selectedLibs[lib2.id] = lib2;
  10192. }
  10193. else
  10194. {
  10195. delete selectedLibs[lib2.id];
  10196. }
  10197. });
  10198. })(lib, libCheck)
  10199. }
  10200. }, function()
  10201. {
  10202. this.handleError(null, mxResources.get('errorGettingConfLibs', null, 'An error occured while getting Confluence libraries list'));
  10203. });
  10204. div.appendChild(libsSection);
  10205. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  10206. {
  10207. this.spinner.spin(document.body, mxResources.get('loading'));
  10208. var pendingLibs = 0;
  10209. for (var id in selectedLibs)
  10210. {
  10211. if (loadedLibs[id] != null) continue; //already loaded!
  10212. pendingLibs++;
  10213. (mxUtils.bind(this, function(lib)
  10214. {
  10215. this.remoteInvoke('getFileContent', [lib.downloadUrl], null, mxUtils.bind(this, function(libContent)
  10216. {
  10217. pendingLibs--;
  10218. if (pendingLibs == 0) this.spinner.stop();
  10219. try
  10220. {
  10221. this.loadLibrary(new RemoteLibrary(this, libContent, lib));
  10222. }
  10223. catch (e)
  10224. {
  10225. this.handleError(e, mxResources.get('errorLoadingFile'));
  10226. }
  10227. }), mxUtils.bind(this, function()
  10228. {
  10229. pendingLibs--;
  10230. if (pendingLibs == 0) this.spinner.stop();
  10231. this.handleError(null, mxResources.get('errorLoadingFile'));
  10232. }));
  10233. }))(selectedLibs[id]);
  10234. }
  10235. for (var id in loadedLibs)
  10236. {
  10237. if (!selectedLibs[id]) //Removed
  10238. {
  10239. this.closeLibrary(new RemoteLibrary(this, null, loadedLibs[id])); //create a dummy library such that we can call closeLibrary
  10240. }
  10241. }
  10242. if (pendingLibs == 0) this.spinner.stop();
  10243. }));
  10244. this.showDialog(dlg.container, 340, 375, true, true);
  10245. };
  10246. //Remote invokation, currently limited to functions in EditorUi (and its sub objects) for security reasons
  10247. //White-listed functions and some info about it
  10248. EditorUi.prototype.remoteInvokableFns = {
  10249. getDiagramTextContent: {isAsync: false}
  10250. };
  10251. EditorUi.prototype.remoteInvokeCallbacks = [];
  10252. EditorUi.prototype.remoteInvokeQueue = [];
  10253. EditorUi.prototype.handleRemoteInvokeReady = function(remoteWin)
  10254. {
  10255. this.remoteWin = remoteWin;
  10256. for (var i = 0; i < this.remoteInvokeQueue.length; i++)
  10257. {
  10258. remoteWin.postMessage(this.remoteInvokeQueue[i], '*');
  10259. }
  10260. this.remoteInvokeQueue = [];
  10261. };
  10262. EditorUi.prototype.handleRemoteInvokeResponse = function(msg)
  10263. {
  10264. var msgMarkers = msg.msgMarkers;
  10265. var callback = this.remoteInvokeCallbacks[msgMarkers.callbackId];
  10266. if (msg.error)
  10267. {
  10268. if (callback.error) callback.error(msg.error.errResp);
  10269. }
  10270. else if (callback.callback)
  10271. {
  10272. callback.callback.apply(this, msg.resp);
  10273. }
  10274. this.remoteInvokeCallbacks[msgMarkers.callbackId] = null; //set it to null only to keep the index
  10275. };
  10276. EditorUi.prototype.remoteInvoke = function(remoteFn, remoteFnArgs, msgMarkers, callback, error)
  10277. {
  10278. msgMarkers = msgMarkers || {};
  10279. msgMarkers.callbackId = this.remoteInvokeCallbacks.length;
  10280. this.remoteInvokeCallbacks.push({callback: callback, error: error});
  10281. var msg = JSON.stringify({event: 'remoteInvoke', funtionName: remoteFn, functionArgs: remoteFnArgs, msgMarkers: msgMarkers});
  10282. if (this.remoteWin != null) //remote invoke is ready
  10283. {
  10284. this.remoteWin.postMessage(msg, '*');
  10285. }
  10286. else
  10287. {
  10288. this.remoteInvokeQueue.push(msg);
  10289. }
  10290. };
  10291. EditorUi.prototype.handleRemoteInvoke = function(msg)
  10292. {
  10293. var sendResponse = mxUtils.bind(this, function(resp, error)
  10294. {
  10295. var respMsg = {event: 'remoteInvokeResponse', msgMarkers: msg.msgMarkers};
  10296. if (error != null)
  10297. {
  10298. respMsg.error = {errResp: error};
  10299. }
  10300. else if (resp != null)
  10301. {
  10302. respMsg.resp = resp;
  10303. }
  10304. this.remoteWin.postMessage(JSON.stringify(respMsg), '*');
  10305. });
  10306. try
  10307. {
  10308. //Remote invoke are allowed to call functions in AC
  10309. var funtionName = msg.funtionName;
  10310. var functionInfo = this.remoteInvokableFns[funtionName];
  10311. if (functionInfo != null && typeof this[funtionName] === 'function')
  10312. {
  10313. var functionArgs = msg.functionArgs;
  10314. //Confirm functionArgs are not null and is array, otherwise, discard it
  10315. if (!Array.isArray(functionArgs))
  10316. {
  10317. functionArgs = [];
  10318. }
  10319. //for functions with callbacks (async) we assume last two arguments are success, error
  10320. if (functionInfo.isAsync)
  10321. {
  10322. //success
  10323. functionArgs.push(function()
  10324. {
  10325. sendResponse(Array.prototype.slice.apply(arguments));
  10326. });
  10327. //error
  10328. functionArgs.push(function(err)
  10329. {
  10330. sendResponse(null, err || 'Unkown Error');
  10331. });
  10332. this[funtionName].apply(this, functionArgs);
  10333. }
  10334. else
  10335. {
  10336. var resp = this[funtionName].apply(this, functionArgs);
  10337. sendResponse([resp]);
  10338. }
  10339. }
  10340. else
  10341. {
  10342. sendResponse(null, 'Invalid Call: ' + funtionName + ' is not found.');
  10343. }
  10344. }
  10345. catch(e)
  10346. {
  10347. sendResponse(null, 'Invalid Call: An error occured, ' + e.message);
  10348. }
  10349. };
  10350. })();