EditorUi.js 347 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032
  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. * Returns true if the given binary data is a Visio file.
  558. */
  559. EditorUi.prototype.isVisioData = function(data)
  560. {
  561. return data.length > 8 && (data.charCodeAt(0) == 0xD0 && data.charCodeAt(1) == 0xCF &&
  562. data.charCodeAt(2) == 0x11 && data.charCodeAt(3) == 0xE0 && data.charCodeAt(4) == 0xA1 && data.charCodeAt(5) == 0xB1 &&
  563. data.charCodeAt(6) == 0x1A && data.charCodeAt(7) == 0xE1) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  564. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x04) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  565. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x06);
  566. };
  567. /**
  568. * Returns true if the given binary data is a PNG file.
  569. */
  570. EditorUi.prototype.isPngData = function(data)
  571. {
  572. return data.length > 8 && data.charCodeAt(0) == 137 && data.charCodeAt(1) == 80 &&
  573. data.charCodeAt(2) == 78 && data.charCodeAt(3) == 71 && data.charCodeAt(4) == 13 &&
  574. data.charCodeAt(5) == 10 && data.charCodeAt(6) == 26 && data.charCodeAt(7) == 10;
  575. };
  576. /**
  577. * Extracts the mxfile from the given HTML data from a data transfer event.
  578. */
  579. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  580. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  581. {
  582. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  583. if (result == null)
  584. {
  585. try
  586. {
  587. var idx = data.indexOf('&lt;mxfile ');
  588. if (idx >= 0)
  589. {
  590. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  591. if (idx2 > idx)
  592. {
  593. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  594. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  595. }
  596. }
  597. else
  598. {
  599. // Gets compressed data from mxgraph element in HTML document
  600. var doc = mxUtils.parseXml(data);
  601. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null ||
  602. this.diagramContainer.style.visibility == 'hidden');
  603. result = (node != null) ? mxUtils.getXml(node) : '';
  604. }
  605. }
  606. catch (e)
  607. {
  608. // ignore
  609. }
  610. }
  611. return result;
  612. };
  613. /**
  614. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  615. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  616. */
  617. EditorUi.prototype.validateFileData = function(data)
  618. {
  619. if (data != null && data.length > 0)
  620. {
  621. var index = data.indexOf('<meta charset="utf-8">');
  622. if (index >= 0)
  623. {
  624. var replaceString = '<meta charset="utf-8"/>';
  625. var replaceStrLen = replaceString.length;
  626. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  627. }
  628. data = Graph.zapGremlins(data);
  629. }
  630. return data;
  631. };
  632. /**
  633. *
  634. */
  635. EditorUi.prototype.replaceFileData = function(data)
  636. {
  637. data = this.validateFileData(data);
  638. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  639. // Some nodes must be extracted here to find the mxfile node
  640. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  641. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  642. if (tmp != null)
  643. {
  644. node = tmp;
  645. }
  646. if (node != null)
  647. {
  648. var graph = this.editor.graph;
  649. graph.model.beginUpdate();
  650. try
  651. {
  652. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  653. var nodes = node.getElementsByTagName('diagram');
  654. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  655. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  656. {
  657. this.fileNode = node;
  658. this.pages = (this.pages != null) ? this.pages : [];
  659. // Wraps page nodes
  660. for (var i = nodes.length - 1; i >= 0; i--)
  661. {
  662. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  663. // Checks for invalid page names
  664. if (page.getName() == null)
  665. {
  666. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  667. }
  668. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  669. }
  670. }
  671. else
  672. {
  673. // Creates tabbed file structure if enforced by URL
  674. if (urlParams['pages'] != '0' && this.fileNode == null)
  675. {
  676. this.fileNode = node.ownerDocument.createElement('mxfile');
  677. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  678. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  679. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  680. }
  681. // Avoids scroll offset when switching page
  682. this.editor.setGraphXml(node);
  683. // Avoids duplicate parsing of the XML stored in the node
  684. if (this.currentPage != null)
  685. {
  686. this.currentPage.root = this.editor.graph.model.root;
  687. }
  688. }
  689. if (oldPages != null)
  690. {
  691. for (var i = 0; i < oldPages.length; i++)
  692. {
  693. graph.model.execute(new ChangePage(this, oldPages[i], null));
  694. }
  695. }
  696. }
  697. finally
  698. {
  699. graph.model.endUpdate();
  700. }
  701. }
  702. };
  703. /**
  704. * Translates this point by the given vector.
  705. *
  706. * @param {number} dx X-coordinate of the translation.
  707. * @param {number} dy Y-coordinate of the translation.
  708. */
  709. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  710. {
  711. graph = (graph != null) ? graph : this.editor.graph;
  712. forceXml = (forceXml != null) ? forceXml : false;
  713. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  714. var editLink = null;
  715. var redirect = null;
  716. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  717. {
  718. editLink = '_blank';
  719. }
  720. else
  721. {
  722. editLink = url;
  723. redirect = editLink;
  724. }
  725. if (node == null)
  726. {
  727. return '';
  728. }
  729. else
  730. {
  731. var fileNode = node;
  732. // Ignores case for possible HTML or XML nodes
  733. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  734. {
  735. // Removes control chars in input for correct roundtrip check
  736. var text = Graph.zapGremlins(mxUtils.getXml(node));
  737. var data = Graph.compress(text);
  738. // Fallback to plain XML for invalid compression
  739. // TODO: Remove this fallback with active pages
  740. if (Graph.decompress(data) != text)
  741. {
  742. return text;
  743. }
  744. else
  745. {
  746. var diagramNode = node.ownerDocument.createElement('diagram');
  747. diagramNode.setAttribute('id', Editor.guid());
  748. mxUtils.setTextContent(diagramNode, data);
  749. fileNode = node.ownerDocument.createElement('mxfile');
  750. fileNode.appendChild(diagramNode);
  751. }
  752. }
  753. if (!compact)
  754. {
  755. // Removes old metadata
  756. fileNode.removeAttribute('userAgent');
  757. fileNode.removeAttribute('version');
  758. fileNode.removeAttribute('editor');
  759. fileNode.removeAttribute('type');
  760. // Adds new metadata
  761. fileNode.setAttribute('modified', new Date().toISOString());
  762. fileNode.setAttribute('host', window.location.hostname);
  763. fileNode.setAttribute('agent', navigator.userAgent);
  764. fileNode.setAttribute('version', EditorUi.VERSION);
  765. fileNode.setAttribute('etag', Editor.guid());
  766. var md = (file != null) ? file.getMode() : this.mode;
  767. if (md != null)
  768. {
  769. fileNode.setAttribute('type', md);
  770. }
  771. }
  772. else
  773. {
  774. fileNode = fileNode.cloneNode(true);
  775. fileNode.removeAttribute('userAgent');
  776. fileNode.removeAttribute('version');
  777. fileNode.removeAttribute('editor');
  778. fileNode.removeAttribute('type');
  779. }
  780. var xml = mxUtils.getXml(fileNode);
  781. // Writes the file as an embedded HTML file
  782. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  783. {
  784. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  785. }
  786. // Maps the XML data to the content attribute in the SVG node
  787. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  788. {
  789. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  790. {
  791. url = null;
  792. }
  793. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  794. }
  795. return xml;
  796. }
  797. };
  798. /**
  799. * Translates this point by the given vector.
  800. *
  801. * @param {number} dx X-coordinate of the translation.
  802. * @param {number} dy Y-coordinate of the translation.
  803. */
  804. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  805. {
  806. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  807. currentPage = (currentPage != null) ? currentPage : false;
  808. var node = this.editor.getGraphXml(ignoreSelection);
  809. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  810. {
  811. var data = Graph.compressNode(node);
  812. mxUtils.setTextContent(this.currentPage.node, data);
  813. node = this.fileNode.cloneNode(false);
  814. if (currentPage)
  815. {
  816. node.appendChild(this.currentPage.node);
  817. }
  818. else
  819. {
  820. // Restores order of pages
  821. for (var i = 0; i < this.pages.length; i++)
  822. {
  823. if (this.currentPage != this.pages[i] && this.pages[i].needsUpdate)
  824. {
  825. var enc = new mxCodec(mxUtils.createXmlDocument());
  826. var temp = enc.encode(new mxGraphModel(this.pages[i].root));
  827. this.editor.graph.saveViewState(this.pages[i].viewState, temp);
  828. mxUtils.setTextContent(this.pages[i].node, Graph.compressNode(temp));
  829. // Marks the page as up-to-date
  830. delete this.pages[i].needsUpdate;
  831. }
  832. node.appendChild(this.pages[i].node);
  833. }
  834. }
  835. }
  836. return node;
  837. };
  838. /**
  839. * Removes any values, styles and geometries from the given XML node.
  840. */
  841. EditorUi.prototype.anonymizeString = function(text, zeros)
  842. {
  843. var result = [];
  844. for (var i = 0; i < text.length; i++)
  845. {
  846. var c = text.charAt(i);
  847. if (EditorUi.ignoredAnonymizedChars.indexOf(c) >= 0)
  848. {
  849. result.push(c);
  850. }
  851. else if (!isNaN(parseInt(c)))
  852. {
  853. result.push((zeros) ? '0' : Math.round(Math.random() * 9));
  854. }
  855. else if (c.toLowerCase() != c)
  856. {
  857. result.push(String.fromCharCode(65 + Math.round(Math.random() * 25)));
  858. }
  859. else if (c.toUpperCase() != c)
  860. {
  861. result.push(String.fromCharCode(97 + Math.round(Math.random() * 25)));
  862. }
  863. else if (/\s/.test(c))
  864. {
  865. /* any whitespace */
  866. result.push(' ');
  867. }
  868. else
  869. {
  870. result.push('?');
  871. }
  872. }
  873. return result.join('');
  874. };
  875. /**
  876. * Removes any values, styles and geometries from the given XML node.
  877. */
  878. EditorUi.prototype.anonymizePatch = function(patch)
  879. {
  880. if (patch[EditorUi.DIFF_INSERT] != null)
  881. {
  882. for (var i = 0; i < patch[EditorUi.DIFF_INSERT].length; i++)
  883. {
  884. try
  885. {
  886. var data = patch[EditorUi.DIFF_INSERT][i].data;
  887. var doc = mxUtils.parseXml(data);
  888. var clone = doc.documentElement.cloneNode(false);
  889. if (clone.getAttribute('name') != null)
  890. {
  891. clone.setAttribute('name', this.anonymizeString(clone.getAttribute('name')));
  892. }
  893. patch[EditorUi.DIFF_INSERT][i].data = mxUtils.getXml(clone);
  894. }
  895. catch (e)
  896. {
  897. patch[EditorUi.DIFF_INSERT][i].data = e.message;
  898. }
  899. }
  900. }
  901. if (patch[EditorUi.DIFF_UPDATE] != null)
  902. {
  903. for (var pageId in patch[EditorUi.DIFF_UPDATE])
  904. {
  905. var diff = patch[EditorUi.DIFF_UPDATE][pageId];
  906. if (diff.name != null)
  907. {
  908. diff.name = this.anonymizeString(diff.name);
  909. }
  910. if (diff.cells != null)
  911. {
  912. var anonymizeCellDiffs = mxUtils.bind(this, function(key)
  913. {
  914. var cellDiffs = diff.cells[key];
  915. if (cellDiffs != null)
  916. {
  917. for (var cellId in cellDiffs)
  918. {
  919. if (cellDiffs[cellId].value != null)
  920. {
  921. cellDiffs[cellId].value = '[' +
  922. cellDiffs[cellId].value.length + ']';
  923. }
  924. if (cellDiffs[cellId].xmlValue != null)
  925. {
  926. cellDiffs[cellId].xmlValue = '[' +
  927. cellDiffs[cellId].xmlValue.length + ']';
  928. }
  929. if (cellDiffs[cellId].style != null)
  930. {
  931. cellDiffs[cellId].style = '[' +
  932. cellDiffs[cellId].style.length + ']';
  933. }
  934. if (Object.keys(cellDiffs[cellId]).length == 0)
  935. {
  936. delete cellDiffs[cellId];
  937. }
  938. }
  939. if (Object.keys(cellDiffs).length == 0)
  940. {
  941. delete diff.cells[key];
  942. }
  943. }
  944. });
  945. anonymizeCellDiffs(EditorUi.DIFF_INSERT);
  946. anonymizeCellDiffs(EditorUi.DIFF_UPDATE);
  947. if (Object.keys(diff.cells).length == 0)
  948. {
  949. delete diff.cells;
  950. }
  951. }
  952. if (Object.keys(diff).length == 0)
  953. {
  954. delete patch[EditorUi.DIFF_UPDATE][pageId];
  955. }
  956. }
  957. if (Object.keys(patch[EditorUi.DIFF_UPDATE]).length == 0)
  958. {
  959. delete patch[EditorUi.DIFF_UPDATE];
  960. }
  961. }
  962. return patch;
  963. };
  964. /**
  965. * Removes any values, styles and geometries from the given XML node.
  966. */
  967. EditorUi.prototype.anonymizeAttributes = function(node, zeros)
  968. {
  969. if (node.attributes != null)
  970. {
  971. for (var i = 0; i < node.attributes.length; i++)
  972. {
  973. if (node.attributes[i].name != 'as')
  974. {
  975. node.setAttribute(node.attributes[i].name,
  976. this.anonymizeString(node.attributes[i].value, zeros));
  977. }
  978. }
  979. }
  980. if (node.childNodes != null)
  981. {
  982. for (var i = 0; i < node.childNodes.length; i++)
  983. {
  984. this.anonymizeAttributes(node.childNodes[i], zeros);
  985. }
  986. }
  987. };
  988. /**
  989. * Removes any values, styles and geometries from the given XML node.
  990. */
  991. EditorUi.prototype.anonymizeNode = function(node, zeros)
  992. {
  993. var nodes = node.getElementsByTagName('mxCell');
  994. for (var i = 0; i < nodes.length; i++)
  995. {
  996. if (nodes[i].getAttribute('value') != null)
  997. {
  998. nodes[i].setAttribute('value', '[' + nodes[i].getAttribute('value').length + ']');
  999. }
  1000. if (nodes[i].getAttribute('xmlValue') != null)
  1001. {
  1002. nodes[i].setAttribute('xmlValue', '[' + nodes[i].getAttribute('xmlValue').length + ']');
  1003. }
  1004. if (nodes[i].getAttribute('style') != null)
  1005. {
  1006. nodes[i].setAttribute('style', '[' + nodes[i].getAttribute('style').length + ']');
  1007. }
  1008. if (nodes[i].parentNode != null && nodes[i].parentNode.nodeName != 'root' &&
  1009. nodes[i].parentNode.parentNode != null)
  1010. {
  1011. nodes[i].setAttribute('id', nodes[i].parentNode.getAttribute('id'));
  1012. nodes[i].parentNode.parentNode.replaceChild(nodes[i], nodes[i].parentNode);
  1013. }
  1014. }
  1015. return node;
  1016. };
  1017. /**
  1018. * Translates this point by the given vector.
  1019. *
  1020. * @param {number} dx X-coordinate of the translation.
  1021. * @param {number} dy Y-coordinate of the translation.
  1022. */
  1023. EditorUi.prototype.synchronizeCurrentFile = function(forceReload)
  1024. {
  1025. var currentFile = this.getCurrentFile();
  1026. if (currentFile != null)
  1027. {
  1028. if (currentFile.savingFile)
  1029. {
  1030. this.handleError({message: mxResources.get('busy')});
  1031. }
  1032. else if (!forceReload && currentFile.invalidChecksum)
  1033. {
  1034. currentFile.handleFileError(null, true);
  1035. }
  1036. else if (this.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1037. {
  1038. currentFile.clearAutosave();
  1039. this.editor.setStatus('');
  1040. if (forceReload)
  1041. {
  1042. currentFile.reloadFile(mxUtils.bind(this, function()
  1043. {
  1044. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1045. }), mxUtils.bind(this, function(err)
  1046. {
  1047. currentFile.handleFileError(err, true);
  1048. }));
  1049. }
  1050. else
  1051. {
  1052. currentFile.synchronizeFile(mxUtils.bind(this, function()
  1053. {
  1054. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1055. }), mxUtils.bind(this, function(err)
  1056. {
  1057. currentFile.handleFileError(err, true);
  1058. }));
  1059. }
  1060. }
  1061. }
  1062. };
  1063. /**
  1064. * Translates this point by the given vector.
  1065. *
  1066. * @param {number} dx X-coordinate of the translation.
  1067. * @param {number} dy Y-coordinate of the translation.
  1068. */
  1069. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file)
  1070. {
  1071. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1072. currentPage = (currentPage != null) ? currentPage : false;
  1073. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  1074. file = (file != null) ? file : this.getCurrentFile();
  1075. var graph = this.editor.graph;
  1076. // Exports SVG for first page while other page is visible by creating a graph
  1077. // LATER: Add caching for the graph or SVG while not on first page
  1078. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  1079. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  1080. {
  1081. graph = this.createTemporaryGraph(graph.getStylesheet());
  1082. var graphGetGlobalVariable = graph.getGlobalVariable;
  1083. var page = this.pages[0];
  1084. graph.getGlobalVariable = function(name)
  1085. {
  1086. if (name == 'page')
  1087. {
  1088. return page.getName();
  1089. }
  1090. else if (name == 'pagenumber')
  1091. {
  1092. return 1;
  1093. }
  1094. return graphGetGlobalVariable.apply(this, arguments);
  1095. };
  1096. document.body.appendChild(graph.container);
  1097. graph.model.setRoot(page.root);
  1098. }
  1099. var result = this.createFileData(node, graph, file, window.location.href,
  1100. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  1101. // Removes temporary graph from DOM
  1102. if (graph != this.editor.graph)
  1103. {
  1104. graph.container.parentNode.removeChild(graph.container);
  1105. }
  1106. return result;
  1107. };
  1108. /**
  1109. *
  1110. */
  1111. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  1112. {
  1113. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1114. var bg = null;
  1115. var js = EditorUi.drawHost + '/js/embed-static.min.js';
  1116. // LATER: Merge common code with EmbedDialog
  1117. if (graph != null)
  1118. {
  1119. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  1120. var scale = graph.view.scale;
  1121. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  1122. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  1123. bg = graph.background;
  1124. // Embed script only used if no redirect
  1125. if (redirect == null)
  1126. {
  1127. var s = this.getBasenames().join(';');
  1128. if (s.length > 0)
  1129. {
  1130. js = EditorUi.drawHost + '/embed.js?s=' + s;
  1131. }
  1132. }
  1133. // Adds embed attributes
  1134. node.setAttribute('x0', x0);
  1135. node.setAttribute('y0', y0);
  1136. }
  1137. if (node != null)
  1138. {
  1139. node.setAttribute('pan', '1');
  1140. node.setAttribute('zoom', '1');
  1141. node.setAttribute('resize', '0');
  1142. node.setAttribute('fit', '0');
  1143. node.setAttribute('border', '20');
  1144. // Hidden attributes
  1145. node.setAttribute('links', '1');
  1146. if (editLink != null)
  1147. {
  1148. node.setAttribute('edit', editLink);
  1149. }
  1150. }
  1151. // Makes XHTML compatible
  1152. if (redirect != null)
  1153. {
  1154. redirect = redirect.replace(/&/g, '&amp;');
  1155. }
  1156. // Removes control chars in input for correct roundtrip check
  1157. var text = (node != null) ? Graph.zapGremlins(mxUtils.getXml(node)) : '';
  1158. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  1159. // embed clients that rely on this format. HTML files and export use getHtml2.
  1160. var data = Graph.compress(text);
  1161. // Fallback to URI encoded XML for invalid compression
  1162. if (Graph.decompress(data) != text)
  1163. {
  1164. data = encodeURIComponent(text);
  1165. }
  1166. var style = 'position:relative;overflow:auto;width:100%;';
  1167. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1168. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1169. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1170. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1171. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1172. '</head>\n<body' +
  1173. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  1174. '\n<div class="mxgraph" style="' + style + '">\n' +
  1175. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  1176. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1177. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1178. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1179. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1180. '\n</body>\n</html>\n';
  1181. };
  1182. /**
  1183. * Same as above but using the new embed code.
  1184. */
  1185. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  1186. {
  1187. var bg = null;
  1188. var js = EditorUi.drawHost + '/js/viewer.min.js';
  1189. var s = '';
  1190. // Makes XHTML compatible
  1191. if (redirect != null)
  1192. {
  1193. redirect = redirect.replace(/&/g, '&amp;');
  1194. }
  1195. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  1196. xml: Graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  1197. if (this.pages != null && this.currentPage != null)
  1198. {
  1199. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  1200. }
  1201. var style = 'max-width:100%;border:1px solid transparent;';
  1202. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1203. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1204. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1205. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1206. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1207. '<meta charset="utf-8"/>\n</head>\n<body>' +
  1208. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  1209. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1210. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1211. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1212. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1213. '\n</body>\n</html>\n';
  1214. };
  1215. /**
  1216. *
  1217. */
  1218. EditorUi.prototype.setFileData = function(data)
  1219. {
  1220. data = this.validateFileData(data);
  1221. this.currentPage = null;
  1222. this.fileNode = null;
  1223. this.pages = null;
  1224. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  1225. // Checks for parser errors
  1226. var errors = (node != null) ? node.getElementsByTagName('parsererror') : null;
  1227. if (errors != null && errors.length > 0)
  1228. {
  1229. var cause = mxResources.get('invalidOrMissingFile');
  1230. var divs = errors[0].getElementsByTagName('div');
  1231. if (divs.length > 0)
  1232. {
  1233. cause = mxUtils.getTextContent(divs[0]);
  1234. }
  1235. throw new Error(cause);
  1236. }
  1237. else
  1238. {
  1239. // Some nodes must be extracted here to find the mxfile node
  1240. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  1241. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  1242. if (tmp != null)
  1243. {
  1244. node = tmp;
  1245. }
  1246. if (node != null && node.nodeName == 'mxfile')
  1247. {
  1248. var nodes = node.getElementsByTagName('diagram');
  1249. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  1250. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  1251. {
  1252. var selectedPage = null;
  1253. this.fileNode = node;
  1254. this.pages = [];
  1255. // Wraps page nodes
  1256. for (var i = 0; i < nodes.length; i++)
  1257. {
  1258. // Adds page ID based on page order to match
  1259. // remote IDs given if IDs are missing here
  1260. if (nodes[i].getAttribute('id') == null)
  1261. {
  1262. nodes[i].setAttribute('id', i);
  1263. }
  1264. var page = new DiagramPage(nodes[i]);
  1265. // Checks for invalid page names
  1266. if (page.getName() == null)
  1267. {
  1268. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  1269. }
  1270. this.pages.push(page);
  1271. if (urlParams['page-id'] != null && page.getId() == urlParams['page-id'])
  1272. {
  1273. selectedPage = page;
  1274. }
  1275. }
  1276. this.currentPage = (selectedPage != null) ? selectedPage :
  1277. this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  1278. node = this.currentPage.node;
  1279. }
  1280. }
  1281. // Creates tabbed file structure if enforced by URL
  1282. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  1283. {
  1284. this.fileNode = node.ownerDocument.createElement('mxfile');
  1285. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  1286. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  1287. this.pages = [this.currentPage];
  1288. }
  1289. // Avoids scroll offset when switching page
  1290. this.editor.setGraphXml(node);
  1291. // Avoids duplicate parsing of the XML stored in the node
  1292. if (this.currentPage != null)
  1293. {
  1294. this.currentPage.root = this.editor.graph.model.root;
  1295. }
  1296. }
  1297. };
  1298. /**
  1299. * Translates this point by the given vector.
  1300. *
  1301. * @param {number} dx X-coordinate of the translation.
  1302. * @param {number} dy Y-coordinate of the translation.
  1303. */
  1304. EditorUi.prototype.getBaseFilename = function(ignorePageName)
  1305. {
  1306. var file = this.getCurrentFile();
  1307. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  1308. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
  1309. /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename) ||
  1310. /(\.drawio)$/i.test(basename))
  1311. {
  1312. basename = basename.substring(0, basename.lastIndexOf('.'));
  1313. }
  1314. if (!ignorePageName && this.pages != null && this.pages.length > 1 &&
  1315. this.currentPage != null && this.currentPage.node.getAttribute('name') != null &&
  1316. this.currentPage.getName().length > 0)
  1317. {
  1318. basename = basename + '-' + this.currentPage.getName();
  1319. }
  1320. return basename;
  1321. };
  1322. /**
  1323. * Translates this point by the given vector.
  1324. *
  1325. * @param {number} dx X-coordinate of the translation.
  1326. * @param {number} dy Y-coordinate of the translation.
  1327. */
  1328. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible, transparent)
  1329. {
  1330. try
  1331. {
  1332. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  1333. var basename = this.getBaseFilename(!currentPage);
  1334. var filename = basename + '.' + format;
  1335. if (format == 'xml')
  1336. {
  1337. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  1338. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  1339. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  1340. this.saveData(filename, format, data, 'text/xml');
  1341. }
  1342. else if (format == 'html')
  1343. {
  1344. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  1345. this.saveData(filename, format, data, 'text/html');
  1346. }
  1347. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  1348. {
  1349. var svg = null;
  1350. var saveSvg = mxUtils.bind(this, function(data)
  1351. {
  1352. if (data.length <= MAX_REQUEST_SIZE)
  1353. {
  1354. this.saveData(filename, 'svg', data, 'image/svg+xml');
  1355. }
  1356. else
  1357. {
  1358. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  1359. {
  1360. mxUtils.popup(svg);
  1361. }));
  1362. }
  1363. });
  1364. if (format == 'svg')
  1365. {
  1366. var bg = this.editor.graph.background;
  1367. if (transparent || bg == mxConstants.NONE)
  1368. {
  1369. bg = null;
  1370. }
  1371. // Sets or disables alternate text for foreignObjects. Disabling is needed
  1372. // because PhantomJS seems to ignore switch statements and paint all text.
  1373. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  1374. if (addShadow)
  1375. {
  1376. this.editor.graph.addSvgShadow(svgRoot);
  1377. }
  1378. // Embeds the images in the SVG output (async)
  1379. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  1380. {
  1381. this.spinner.stop();
  1382. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  1383. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  1384. mxUtils.getXml(svgRoot2));
  1385. })));
  1386. }
  1387. else
  1388. {
  1389. filename = basename + '.svg';
  1390. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  1391. {
  1392. this.spinner.stop();
  1393. saveSvg(svg);
  1394. }), ignoreSelection);
  1395. }
  1396. }
  1397. else
  1398. {
  1399. if (format == 'xmlpng')
  1400. {
  1401. filename = basename + '.png';
  1402. }
  1403. else if (format == 'jpeg')
  1404. {
  1405. filename = basename + '.jpg';
  1406. }
  1407. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  1408. {
  1409. try
  1410. {
  1411. var prev = this.editor.graph.pageVisible;
  1412. if (pageVisible != null)
  1413. {
  1414. this.editor.graph.pageVisible = pageVisible;
  1415. }
  1416. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64, transparent, currentPage);
  1417. this.editor.graph.pageVisible = prev;
  1418. return req;
  1419. }
  1420. catch (e)
  1421. {
  1422. this.handleError(e);
  1423. }
  1424. }));
  1425. }
  1426. }
  1427. catch (e)
  1428. {
  1429. this.handleError(e);
  1430. }
  1431. };
  1432. /**
  1433. * Translates this point by the given vector.
  1434. *
  1435. * @param {number} dx X-coordinate of the translation.
  1436. * @param {number} dy Y-coordinate of the translation.
  1437. */
  1438. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64, transparent, currentPage)
  1439. {
  1440. var bounds = this.editor.graph.getGraphBounds();
  1441. // Exports only current page for images that does not contain file data, but for
  1442. // the other formats with XML included or pdf with all pages, we need to send the complete data and use
  1443. // the from/to URL parameters to specify the page to be exported.
  1444. var data = this.getFileData(true, null, null, null, ignoreSelection, currentPage == false? false : format != 'xmlpng');
  1445. var range = '';
  1446. var allPages = '';
  1447. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  1448. {
  1449. throw {message: mxResources.get('drawingTooLarge')};
  1450. }
  1451. var embed = '0';
  1452. if (format == 'pdf' && currentPage == false)
  1453. {
  1454. allPages = '&allPages=1';
  1455. }
  1456. if (format == 'xmlpng')
  1457. {
  1458. embed = '1';
  1459. format = 'png';
  1460. // Finds the current page number
  1461. if (this.pages != null && this.currentPage != null)
  1462. {
  1463. for (var i = 0; i < this.pages.length; i++)
  1464. {
  1465. if (this.pages[i] == this.currentPage)
  1466. {
  1467. range = '&from=' + i;
  1468. break;
  1469. }
  1470. }
  1471. }
  1472. }
  1473. var bg = this.editor.graph.background;
  1474. if (format == 'png' && transparent)
  1475. {
  1476. bg = mxConstants.NONE;
  1477. }
  1478. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range + allPages +
  1479. '&bg=' + ((bg != null) ? bg : mxConstants.NONE) +
  1480. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1481. encodeURIComponent(data) + ((filename != null) ?
  1482. '&filename=' + encodeURIComponent(filename) : ''));
  1483. };
  1484. /**
  1485. * Translates this point by the given vector.
  1486. *
  1487. * @param {number} dx X-coordinate of the translation.
  1488. * @param {number} dy Y-coordinate of the translation.
  1489. */
  1490. EditorUi.prototype.setMode = function(mode, remember)
  1491. {
  1492. this.mode = mode;
  1493. };
  1494. /**
  1495. * Loads the given file descriptor. The descriptor may define the following properties:
  1496. *
  1497. * - url: The url to load the data from (proxy is used if CORS is not enabled)
  1498. * - data: The data to be inserted. If both, data and url are defined, then the data
  1499. * is preprendended to the data returned from the given URL.
  1500. * - format: Currently, only 'csv' is supported as an optional value. Default is XML.
  1501. * - update: Optional URL to fetch updates from (POST request with the page XML).
  1502. * - interval: Optional interval for fetching updates. Default is 60000 (60 seconds).
  1503. */
  1504. EditorUi.prototype.loadDescriptor = function(desc, success, error)
  1505. {
  1506. var hash = window.location.hash;
  1507. var loadData = mxUtils.bind(this, function(data)
  1508. {
  1509. var realData = (desc.data != null) ? desc.data : '';
  1510. if (data != null && data.length > 0)
  1511. {
  1512. if (realData.length > 0)
  1513. {
  1514. realData += '\n';
  1515. }
  1516. realData += data;
  1517. }
  1518. var xml = (desc.format != 'csv' && realData.length > 0) ? realData : this.emptyDiagramXml;
  1519. var tempFile = new LocalFile(this, xml, (urlParams['title'] != null) ?
  1520. decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
  1521. tempFile.getHash = function()
  1522. {
  1523. return hash;
  1524. };
  1525. this.fileLoaded(tempFile);
  1526. if (desc.format == 'csv')
  1527. {
  1528. this.importCsv(realData, mxUtils.bind(this, function(cells)
  1529. {
  1530. this.editor.undoManager.clear();
  1531. this.editor.setModified(false);
  1532. this.editor.setStatus('');
  1533. }));
  1534. }
  1535. // Installs updates
  1536. if (desc.update != null)
  1537. {
  1538. var interval = (desc.interval != null) ? parseInt(desc.interval) : 60000;
  1539. var currentThread = null;
  1540. var doUpdate = mxUtils.bind(this, function()
  1541. {
  1542. var page = this.currentPage;
  1543. mxUtils.post(desc.update, 'xml=' + encodeURIComponent(
  1544. mxUtils.getXml(this.editor.getGraphXml())),
  1545. mxUtils.bind(this, function(req)
  1546. {
  1547. if (page === this.currentPage)
  1548. {
  1549. if (req.getStatus() >= 200 && req.getStatus() <= 300)
  1550. {
  1551. var doc = this.updateDiagram(req.getText());
  1552. schedule();
  1553. }
  1554. else
  1555. {
  1556. this.handleError({message: mxResources.get('error') + ' ' + req.getStatus()});
  1557. }
  1558. }
  1559. }), mxUtils.bind(this, function(err)
  1560. {
  1561. this.handleError(err);
  1562. }));
  1563. });
  1564. var schedule = mxUtils.bind(this, function()
  1565. {
  1566. window.clearTimeout(currentThread);
  1567. currentThread = window.setTimeout(doUpdate, interval);
  1568. });
  1569. this.editor.addListener('pageSelected', mxUtils.bind(this, function()
  1570. {
  1571. schedule();
  1572. doUpdate();
  1573. }));
  1574. schedule();
  1575. doUpdate();
  1576. }
  1577. if (success != null)
  1578. {
  1579. success();
  1580. }
  1581. });
  1582. if (desc.url != null && desc.url.length > 0)
  1583. {
  1584. var realUrl = desc.url;
  1585. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  1586. {
  1587. realUrl = PROXY_URL + '?url=' + encodeURIComponent(realUrl);
  1588. }
  1589. // LATER: Remove cache-control header
  1590. this.loadUrl(realUrl, mxUtils.bind(this, function(data)
  1591. {
  1592. loadData(data);
  1593. }), mxUtils.bind(this, function(err)
  1594. {
  1595. if (error != null)
  1596. {
  1597. error(err)
  1598. }
  1599. }));
  1600. }
  1601. else
  1602. {
  1603. loadData('');
  1604. }
  1605. };
  1606. /**
  1607. * Translates this point by the given vector.
  1608. *
  1609. * @param {number} dx X-coordinate of the translation.
  1610. * @param {number} dy Y-coordinate of the translation.
  1611. */
  1612. EditorUi.prototype.updateDiagram = function(xml)
  1613. {
  1614. var doc = null;
  1615. var ui = this;
  1616. function createOverlay(desc)
  1617. {
  1618. var overlay = new mxCellOverlay(desc.image || graph.warningImage,
  1619. desc.tooltip, desc.align, desc.valign, desc.offset);
  1620. // Installs a handler for clicks on the overlay
  1621. overlay.addListener(mxEvent.CLICK, function(sender, evt)
  1622. {
  1623. ui.alert(desc.tooltip);
  1624. });
  1625. return overlay;
  1626. };
  1627. if (xml != null && xml.length > 0)
  1628. {
  1629. doc = mxUtils.parseXml(xml);
  1630. var node = (doc != null) ? doc.documentElement : null;
  1631. if (node != null && node.nodeName == 'updates')
  1632. {
  1633. var graph = this.editor.graph;
  1634. var model = graph.getModel();
  1635. model.beginUpdate();
  1636. var fit = null;
  1637. try
  1638. {
  1639. node = node.firstChild;
  1640. while (node != null)
  1641. {
  1642. if (node.nodeName == 'update')
  1643. {
  1644. // Resolves the cell ID
  1645. var cell = model.getCell(node.getAttribute('id'));
  1646. if (cell != null)
  1647. {
  1648. // Changes the value
  1649. try
  1650. {
  1651. var value = node.getAttribute('value');
  1652. if (value != null)
  1653. {
  1654. var valueNode = mxUtils.parseXml(value).documentElement;
  1655. if (valueNode != null)
  1656. {
  1657. if (valueNode.getAttribute('replace-value') == '1')
  1658. {
  1659. model.setValue(cell, valueNode);
  1660. }
  1661. else
  1662. {
  1663. var attrs = valueNode.attributes;
  1664. for (var j = 0; j < attrs.length; j++)
  1665. {
  1666. graph.setAttributeForCell(cell, attrs[j].nodeName,
  1667. (attrs[j].nodeValue.length > 0) ? attrs[j].nodeValue : null);
  1668. }
  1669. }
  1670. }
  1671. }
  1672. }
  1673. catch (e)
  1674. {
  1675. if (window.console != null)
  1676. {
  1677. console.log('Error in value for ' + cell.id + ': ' + e);
  1678. }
  1679. }
  1680. // Changes the style
  1681. try
  1682. {
  1683. var style = node.getAttribute('style');
  1684. if (style != null)
  1685. {
  1686. graph.model.setStyle(cell, style);
  1687. }
  1688. }
  1689. catch (e)
  1690. {
  1691. if (window.console != null)
  1692. {
  1693. console.log('Error in style for ' + cell.id + ': ' + e);
  1694. }
  1695. }
  1696. // Adds or removes an overlay icon
  1697. try
  1698. {
  1699. var icon = node.getAttribute('icon');
  1700. if (icon != null)
  1701. {
  1702. var desc = (icon.length > 0) ? JSON.parse(icon) : null;
  1703. if (desc == null || !desc.append)
  1704. {
  1705. graph.removeCellOverlays(cell);
  1706. }
  1707. if (desc != null)
  1708. {
  1709. graph.addCellOverlay(cell, createOverlay(desc));
  1710. }
  1711. }
  1712. }
  1713. catch (e)
  1714. {
  1715. if (window.console != null)
  1716. {
  1717. console.log('Error in icon for ' + cell.id + ': ' + e);
  1718. }
  1719. }
  1720. // Replaces the geometry
  1721. try
  1722. {
  1723. var geo = node.getAttribute('geometry');
  1724. if (geo != null)
  1725. {
  1726. geo = JSON.parse(geo);
  1727. var curr = graph.getCellGeometry(cell);
  1728. if (curr != null)
  1729. {
  1730. curr = curr.clone();
  1731. // Partially overwrites geometry
  1732. for (key in geo)
  1733. {
  1734. var val = parseFloat(geo[key]);
  1735. if (key == 'dx')
  1736. {
  1737. curr.x += val;
  1738. }
  1739. else if (key == 'dy')
  1740. {
  1741. curr.y += val;
  1742. }
  1743. else if (key == 'dw')
  1744. {
  1745. curr.width += val;
  1746. }
  1747. else if (key == 'dh')
  1748. {
  1749. curr.height += val;
  1750. }
  1751. else
  1752. {
  1753. curr[key] = parseFloat(geo[key]);
  1754. }
  1755. }
  1756. graph.model.setGeometry(cell, curr);
  1757. }
  1758. }
  1759. }
  1760. catch (e)
  1761. {
  1762. if (window.console != null)
  1763. {
  1764. console.log('Error in icon for ' + cell.id + ': ' + e);
  1765. }
  1766. }
  1767. } // if cell != null
  1768. } // if node.nodeName == 'update
  1769. else if (node.nodeName == 'model')
  1770. {
  1771. // Finds first child element
  1772. var dataNode = node.firstChild;
  1773. while (dataNode != null && dataNode.nodeType != mxConstants.NODETYPE_ELEMENT)
  1774. {
  1775. dataNode = dataNode.nextSibling;
  1776. }
  1777. if (dataNode != null)
  1778. {
  1779. var dec = new mxCodec(node.firstChild);
  1780. dec.decode(dataNode, model);
  1781. }
  1782. }
  1783. else if (node.nodeName == 'view')
  1784. {
  1785. if (node.hasAttribute('scale'))
  1786. {
  1787. graph.view.scale = parseFloat(node.getAttribute('scale'));
  1788. }
  1789. if (node.hasAttribute('dx') || node.hasAttribute('dy'))
  1790. {
  1791. graph.view.translate = new mxPoint(parseFloat(node.getAttribute('dx') || 0),
  1792. parseFloat(node.getAttribute('dy') || 0));
  1793. }
  1794. }
  1795. else if (node.nodeName == 'fit')
  1796. {
  1797. if (node.hasAttribute('max-scale'))
  1798. {
  1799. fit = parseFloat(node.getAttribute('max-scale'));
  1800. }
  1801. else
  1802. {
  1803. fit = 1;
  1804. }
  1805. }
  1806. node = node.nextSibling;
  1807. } // end of while
  1808. }
  1809. finally
  1810. {
  1811. model.endUpdate();
  1812. }
  1813. if (fit != null && this.chromelessResize)
  1814. {
  1815. this.chromelessResize(true, fit);
  1816. }
  1817. }
  1818. }
  1819. return doc;
  1820. };
  1821. /**
  1822. * Constructs a filename for a copy of the given file.
  1823. */
  1824. EditorUi.prototype.getCopyFilename = function(file, timestamp)
  1825. {
  1826. var title = (file != null && file.getTitle() != null) ?
  1827. file.getTitle() : this.defaultFilename;
  1828. // Handles extension
  1829. var extension = '';
  1830. var dot = title.lastIndexOf('.');
  1831. if (dot >= 0)
  1832. {
  1833. extension = title.substring(dot);
  1834. title = title.substring(0, dot);
  1835. }
  1836. if (timestamp)
  1837. {
  1838. function getFormattedTime()
  1839. {
  1840. var today = new Date();
  1841. var y = today.getFullYear();
  1842. // JavaScript months are 0-based.
  1843. var m = today.getMonth() + 1;
  1844. var d = today.getDate();
  1845. var h = today.getHours();
  1846. var mi = today.getMinutes();
  1847. var s = today.getSeconds();
  1848. return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
  1849. }
  1850. var ts = new Date();
  1851. title += ' ' + getFormattedTime();
  1852. }
  1853. title = mxResources.get('copyOf', [title]) + extension;
  1854. return title;
  1855. };
  1856. /**
  1857. * Translates this point by the given vector.
  1858. *
  1859. * @param {number} dx X-coordinate of the translation.
  1860. * @param {number} dy Y-coordinate of the translation.
  1861. */
  1862. EditorUi.prototype.fileLoaded = function(file, noDialogs)
  1863. {
  1864. var oldFile = this.getCurrentFile();
  1865. this.fileLoadedError = null;
  1866. this.setCurrentFile(null);
  1867. var result = false;
  1868. this.hideDialog();
  1869. if (oldFile != null)
  1870. {
  1871. oldFile.removeListener(this.descriptorChangedListener);
  1872. oldFile.close();
  1873. }
  1874. this.editor.graph.model.clear();
  1875. this.editor.undoManager.clear();
  1876. var noFile = mxUtils.bind(this, function()
  1877. {
  1878. this.setGraphEnabled(false);
  1879. this.setCurrentFile(null);
  1880. // Keeps initial title if no file existed before
  1881. if (oldFile != null)
  1882. {
  1883. this.updateDocumentTitle();
  1884. }
  1885. // File might have been loaded halfway
  1886. this.editor.graph.model.clear();
  1887. this.editor.undoManager.clear();
  1888. this.setBackgroundImage(null);
  1889. // Avoids empty hash with no value
  1890. if (!noDialogs && window.location.hash != null && window.location.hash.length > 0)
  1891. {
  1892. window.location.hash = '';
  1893. }
  1894. if (this.fname != null)
  1895. {
  1896. this.fnameWrapper.style.display = 'none';
  1897. this.fname.innerHTML = '';
  1898. this.fname.setAttribute('title', mxResources.get('rename'));
  1899. }
  1900. this.editor.setStatus('');
  1901. this.updateUi();
  1902. if (!noDialogs)
  1903. {
  1904. this.showSplash();
  1905. }
  1906. });
  1907. if (file != null)
  1908. {
  1909. try
  1910. {
  1911. // Workaround for delayed scroll repaint with min UI in Safari
  1912. if (mxClient.IS_SF && uiTheme == 'min')
  1913. {
  1914. this.diagramContainer.style.visibility = '';
  1915. }
  1916. // Order is significant, current file needed for correct
  1917. // file format for initial save after starting realtime
  1918. this.openingFile = true;
  1919. this.setCurrentFile(file);
  1920. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1921. file.addListener('contentChanged', this.descriptorChangedListener);
  1922. file.open();
  1923. delete this.openingFile;
  1924. // DescriptorChanged updates the enabled state of the graph
  1925. this.setGraphEnabled(true);
  1926. this.setMode(file.getMode());
  1927. this.editor.graph.model.prefix = Editor.guid() + '-';
  1928. this.editor.undoManager.clear();
  1929. this.descriptorChanged();
  1930. this.updateUi();
  1931. // Realtime files have a valid status message
  1932. if (!file.isEditable())
  1933. {
  1934. this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
  1935. mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
  1936. }
  1937. // Handles modified state after error of loading new file
  1938. else if (file.isModified())
  1939. {
  1940. file.addUnsavedStatus();
  1941. // Restores unsaved data
  1942. if (file.backupPatch != null)
  1943. {
  1944. file.patch([file.backupPatch]);
  1945. }
  1946. }
  1947. else
  1948. {
  1949. this.editor.setStatus('');
  1950. }
  1951. if (!this.editor.isChromelessView() || this.editor.editable)
  1952. {
  1953. this.editor.graph.selectUnlockedLayer();
  1954. this.showLayersDialog();
  1955. this.restoreLibraries();
  1956. // Workaround for no initial focus in FF
  1957. if (window.self !== window.top)
  1958. {
  1959. window.focus();
  1960. }
  1961. }
  1962. else if (this.editor.graph.isLightboxView())
  1963. {
  1964. this.lightboxFit();
  1965. }
  1966. if (this.chromelessResize)
  1967. {
  1968. this.chromelessResize();
  1969. }
  1970. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1971. result = true;
  1972. if (!this.isOffline() && file.getMode() != null)
  1973. {
  1974. EditorUi.logEvent({category: 'File', action: 'open', label:
  1975. file.getMode() + '.' + file.getSize()})
  1976. }
  1977. if (this.editor.editable && this.mode == file.getMode() &&
  1978. file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1979. {
  1980. try
  1981. {
  1982. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1983. }
  1984. catch (e)
  1985. {
  1986. // ignore
  1987. }
  1988. }
  1989. try
  1990. {
  1991. mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
  1992. mxSettings.save();
  1993. }
  1994. catch (e)
  1995. {
  1996. // ignore
  1997. }
  1998. }
  1999. catch (e)
  2000. {
  2001. this.fileLoadedError = e;
  2002. // Makes sure the file does not save the invalid UI model and overwrites anything important
  2003. if (window.console != null)
  2004. {
  2005. console.log('error in fileLoaded:', file, e);
  2006. }
  2007. if (EditorUi.enableLogging && !this.isOffline())
  2008. {
  2009. try
  2010. {
  2011. var img = new Image();
  2012. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  2013. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  2014. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  2015. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  2016. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  2017. }
  2018. catch (e)
  2019. {
  2020. // ignore
  2021. }
  2022. }
  2023. // Asynchronous handling of errors
  2024. var fn = mxUtils.bind(this, function()
  2025. {
  2026. // Removes URL parameter and reloads the page
  2027. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  2028. {
  2029. window.location.search = this.getSearch(['url']);
  2030. }
  2031. else if (oldFile != null)
  2032. {
  2033. this.fileLoaded(oldFile);
  2034. }
  2035. else
  2036. {
  2037. noFile();
  2038. }
  2039. });
  2040. if (!noDialogs)
  2041. {
  2042. this.handleError(e, mxResources.get('errorLoadingFile'), fn, true);
  2043. }
  2044. else
  2045. {
  2046. fn();
  2047. }
  2048. }
  2049. }
  2050. else
  2051. {
  2052. noFile();
  2053. }
  2054. return result;
  2055. };
  2056. /**
  2057. * Creates a hash value for the current file.
  2058. */
  2059. EditorUi.prototype.getHashValueForPages = function(pages, details)
  2060. {
  2061. // TODO: Avoid encoding to XML to make it faster
  2062. var hash = 0;
  2063. var model = new mxGraphModel();
  2064. var codec = new mxCodec();
  2065. if (details != null)
  2066. {
  2067. details.byteCount = 0;
  2068. details.attrCount = 0;
  2069. details.eltCount = 0;
  2070. details.nodeCount = 0;
  2071. }
  2072. for (var i = 0; i < pages.length; i++)
  2073. {
  2074. this.updatePageRoot(pages[i]);
  2075. var diagram = pages[i].node.cloneNode(false);
  2076. // FIXME: Check why names can be null in newer files
  2077. // ignore in hash and do not diff null names for now
  2078. diagram.removeAttribute('name');
  2079. // Model is only a holder for the root
  2080. model.root = pages[i].root;
  2081. var xmlNode = codec.encode(model);
  2082. this.editor.graph.saveViewState(pages[i].viewState, xmlNode, true);
  2083. // Local defaults may be different in files so ignore
  2084. xmlNode.removeAttribute('pageWidth');
  2085. xmlNode.removeAttribute('pageHeight');
  2086. diagram.appendChild(xmlNode);
  2087. if (details != null)
  2088. {
  2089. details.eltCount += diagram.getElementsByTagName('*').length;
  2090. details.nodeCount += diagram.getElementsByTagName('mxCell').length;
  2091. }
  2092. hash = ((hash << 5) - hash + this.hashValue(diagram, function(obj, key, value, isXml)
  2093. {
  2094. // Ignores JS machine rounding errors in known numeric attributes
  2095. // eg. 412.33333333333326 (Webkit/FF) == 412.33333333333325 (Edge/IE11)
  2096. if (isXml && (obj.nodeName == 'mxGeometry' || obj.nodeName == 'mxPoint') &&
  2097. (key == 'x' || key == 'y' || key == 'width' || key == 'height'))
  2098. {
  2099. return Math.round(value);
  2100. }
  2101. // Workaround for previous in patch written to mxCell in 10.0.23
  2102. else if (isXml && obj.nodeName == 'mxCell' && key == 'previous')
  2103. {
  2104. return null;
  2105. }
  2106. else
  2107. {
  2108. return value;
  2109. }
  2110. }, details)) << 0;
  2111. }
  2112. return hash;
  2113. };
  2114. /**
  2115. * Creates a hash value for the given object. Replacer returns the value of the
  2116. * property or attribute for the given object or XML node.
  2117. */
  2118. EditorUi.prototype.hashValue = function(obj, replacer, details)
  2119. {
  2120. var hash = 0;
  2121. // Checks for XML nodes
  2122. if (obj != null && typeof obj === 'object' && typeof obj.nodeType === 'number' &&
  2123. typeof obj.nodeName === 'string' && typeof obj.getAttribute === 'function')
  2124. {
  2125. if (obj.nodeName != null)
  2126. {
  2127. hash = hash ^ this.hashValue(obj.nodeName, replacer, details);
  2128. }
  2129. if (obj.attributes != null)
  2130. {
  2131. if (details != null)
  2132. {
  2133. details.attrCount += obj.attributes.length;
  2134. }
  2135. for (var i = 0; i < obj.attributes.length; i++)
  2136. {
  2137. var key = obj.attributes[i].name;
  2138. var value = (replacer != null) ? replacer(obj, key, obj.attributes[i].value, true) : obj.attributes[i].value;
  2139. if (value != null)
  2140. {
  2141. hash = hash ^ (this.hashValue(key, replacer, details) +
  2142. this.hashValue(value, replacer, details));
  2143. }
  2144. }
  2145. }
  2146. if (obj.childNodes != null)
  2147. {
  2148. for (var i = 0; i < obj.childNodes.length; i++)
  2149. {
  2150. hash = ((hash << 5) - hash + this.hashValue(
  2151. obj.childNodes[i], replacer, details)) << 0;
  2152. }
  2153. }
  2154. }
  2155. else if (obj != null && typeof obj !== 'function')
  2156. {
  2157. var str = String(obj);
  2158. var temp = 0;
  2159. if (details != null)
  2160. {
  2161. details.byteCount += str.length;
  2162. }
  2163. for (var i = 0; i < str.length; i++)
  2164. {
  2165. temp = ((temp << 5) - temp + str.charCodeAt(i)) << 0;
  2166. }
  2167. hash = hash ^ temp;
  2168. }
  2169. return hash;
  2170. };
  2171. /**
  2172. * Adds empty implementation
  2173. */
  2174. EditorUi.prototype.descriptorChanged = function()
  2175. {
  2176. // empty
  2177. };
  2178. /**
  2179. * Hook for subclassers.
  2180. */
  2181. EditorUi.prototype.restoreLibraries = function() { };
  2182. /**
  2183. * Hook for subclassers.
  2184. */
  2185. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn) { };
  2186. /**
  2187. *
  2188. */
  2189. EditorUi.prototype.isScratchpadEnabled = function()
  2190. {
  2191. return isLocalStorage || mxClient.IS_CHROMEAPP;
  2192. };
  2193. /**
  2194. * Shows or hides the scratchpad library.
  2195. */
  2196. EditorUi.prototype.toggleScratchpad = function()
  2197. {
  2198. if (this.isScratchpadEnabled())
  2199. {
  2200. if (this.scratchpad == null)
  2201. {
  2202. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  2203. {
  2204. if (xml == null)
  2205. {
  2206. xml = this.emptyLibraryXml;
  2207. }
  2208. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  2209. }));
  2210. }
  2211. else
  2212. {
  2213. this.closeLibrary(this.scratchpad);
  2214. }
  2215. }
  2216. };
  2217. /**
  2218. * Translates this point by the given vector.
  2219. *
  2220. * @param {number} dx X-coordinate of the translation.
  2221. * @param {number} dy Y-coordinate of the translation.
  2222. */
  2223. EditorUi.prototype.createLibraryDataFromImages = function(images)
  2224. {
  2225. var doc = mxUtils.createXmlDocument();
  2226. var library = doc.createElement('mxlibrary');
  2227. mxUtils.setTextContent(library, JSON.stringify(images));
  2228. doc.appendChild(library);
  2229. return mxUtils.getXml(doc);
  2230. };
  2231. /**
  2232. * Translates this point by the given vector.
  2233. *
  2234. * @param {number} dx X-coordinate of the translation.
  2235. * @param {number} dy Y-coordinate of the translation.
  2236. */
  2237. EditorUi.prototype.closeLibrary = function(file)
  2238. {
  2239. if (file != null)
  2240. {
  2241. this.removeLibrarySidebar(file.getHash());
  2242. if (file.constructor != LocalLibrary)
  2243. {
  2244. mxSettings.removeCustomLibrary(file.getHash());
  2245. }
  2246. if (file.title == '.scratchpad')
  2247. {
  2248. this.scratchpad = null;
  2249. }
  2250. }
  2251. };
  2252. /**
  2253. * Translates this point by the given vector.
  2254. *
  2255. * @param {number} dx X-coordinate of the translation.
  2256. * @param {number} dy Y-coordinate of the translation.
  2257. */
  2258. EditorUi.prototype.removeLibrarySidebar = function(id)
  2259. {
  2260. var elts = this.sidebar.palettes[id];
  2261. if (elts != null)
  2262. {
  2263. for (var i = 0; i < elts.length; i++)
  2264. {
  2265. elts[i].parentNode.removeChild(elts[i]);
  2266. }
  2267. delete this.sidebar.palettes[id];
  2268. }
  2269. };
  2270. /**
  2271. * Changes the position of the library in the sidebar
  2272. */
  2273. EditorUi.prototype.repositionLibrary = function(nextChild)
  2274. {
  2275. var c = this.sidebar.container;
  2276. if (nextChild == null)
  2277. {
  2278. var elts = this.sidebar.palettes['L.scratchpad'];
  2279. if (elts == null)
  2280. {
  2281. elts = this.sidebar.palettes['search'];
  2282. }
  2283. if (elts != null)
  2284. {
  2285. nextChild = elts[elts.length - 1].nextSibling;
  2286. }
  2287. }
  2288. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  2289. var content = c.lastChild;
  2290. var title = content.previousSibling;
  2291. c.insertBefore(content, nextChild);
  2292. c.insertBefore(title, content);
  2293. }
  2294. /**
  2295. * Translates this point by the given vector.
  2296. *
  2297. * @param {number} dx X-coordinate of the translation.
  2298. * @param {number} dy Y-coordinate of the translation.
  2299. */
  2300. EditorUi.prototype.loadLibrary = function(file)
  2301. {
  2302. var doc = mxUtils.parseXml(file.getData());
  2303. if (doc.documentElement.nodeName == 'mxlibrary')
  2304. {
  2305. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2306. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  2307. }
  2308. else
  2309. {
  2310. throw {message: mxResources.get('notALibraryFile')};
  2311. }
  2312. };
  2313. /**
  2314. * Translates this point by the given vector.
  2315. *
  2316. * @param {number} dx X-coordinate of the translation.
  2317. * @param {number} dy Y-coordinate of the translation.
  2318. */
  2319. EditorUi.prototype.getLibraryStorageHint = function(file)
  2320. {
  2321. return '';
  2322. };
  2323. /**
  2324. * Translates this point by the given vector.
  2325. *
  2326. * @param {number} dx X-coordinate of the translation.
  2327. * @param {number} dy Y-coordinate of the translation.
  2328. */
  2329. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  2330. {
  2331. if (this.sidebar == null)
  2332. {
  2333. return;
  2334. }
  2335. if (file.constructor != LocalLibrary)
  2336. {
  2337. mxSettings.addCustomLibrary(file.getHash());
  2338. }
  2339. if (file.title == '.scratchpad')
  2340. {
  2341. this.scratchpad = file;
  2342. }
  2343. var elts = this.sidebar.palettes[file.getHash()];
  2344. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  2345. // Removes existing sidebar entry for this library
  2346. this.removeLibrarySidebar(file.getHash());
  2347. var dropTarget = null;
  2348. var addImages = mxUtils.bind(this, function(imgs, content)
  2349. {
  2350. if (imgs.length == 0 && file.isEditable())
  2351. {
  2352. if (dropTarget == null)
  2353. {
  2354. dropTarget = document.createElement('div');
  2355. dropTarget.className = 'geDropTarget';
  2356. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  2357. }
  2358. content.appendChild(dropTarget);
  2359. }
  2360. else
  2361. {
  2362. this.addLibraryEntries(imgs, content);
  2363. }
  2364. });
  2365. // Adds entries to search index
  2366. // KNOWN: Existing entries are not replaced after edit of custom library
  2367. if (this.sidebar != null && images != null)
  2368. {
  2369. for (var i = 0; i < images.length; i++)
  2370. {
  2371. (mxUtils.bind(this, function(img)
  2372. {
  2373. var data = img.data;
  2374. if (data != null && img.title != null)
  2375. {
  2376. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2377. {
  2378. data = this.convertDataUri(data);
  2379. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2380. if (img.aspect == 'fixed')
  2381. {
  2382. s += 'aspect=fixed;'
  2383. }
  2384. return this.sidebar.createVertexTemplate(s + 'image=' +
  2385. data, img.w, img.h, '', img.title || '', false, false, true)
  2386. }));
  2387. }
  2388. else if (img.xml != null && img.title != null)
  2389. {
  2390. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2391. {
  2392. var cells = this.stringToCells(Graph.decompress(img.xml));
  2393. return this.sidebar.createVertexTemplateFromCells(
  2394. cells, img.w, img.h, img.title || '', true, false, true);
  2395. }));
  2396. }
  2397. }))(images[i]);
  2398. }
  2399. }
  2400. // Adds new sidebar entry for this library
  2401. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  2402. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  2403. {
  2404. addImages(images, content);
  2405. }));
  2406. this.repositionLibrary(nextSibling);
  2407. // Adds tooltip for backend
  2408. var title = contentDiv.parentNode.previousSibling;
  2409. var tip = title.getAttribute('title');
  2410. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  2411. {
  2412. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  2413. }
  2414. var buttons = document.createElement('div');
  2415. buttons.style.position = 'absolute';
  2416. buttons.style.right = '0px';
  2417. buttons.style.top = '0px';
  2418. buttons.style.padding = '8px'
  2419. // Workaround for CSS error in IE8 (standards and quirks)
  2420. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  2421. {
  2422. buttons.style.backgroundColor = 'inherit';
  2423. }
  2424. title.style.position = 'relative';
  2425. var btnWidth = 18;
  2426. var btn = document.createElement('img');
  2427. btn.setAttribute('src', Dialog.prototype.closeImage);
  2428. btn.setAttribute('title', mxResources.get('close'));
  2429. btn.setAttribute('valign', 'absmiddle');
  2430. btn.setAttribute('border', '0');
  2431. btn.style.margin = '0 3px';
  2432. var saveBtn = null;
  2433. if (file.title != '.scratchpad' || this.closableScratchpad)
  2434. {
  2435. buttons.appendChild(btn);
  2436. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  2437. {
  2438. // Workaround for close after any button click in IE8/quirks
  2439. if (!mxEvent.isConsumed(evt))
  2440. {
  2441. var fn = mxUtils.bind(this, function()
  2442. {
  2443. this.closeLibrary(file);
  2444. });
  2445. if (saveBtn != null)
  2446. {
  2447. this.confirm(mxResources.get('allChangesLost'), null, fn,
  2448. mxResources.get('cancel'), mxResources.get('discardChanges'));
  2449. }
  2450. else
  2451. {
  2452. fn();
  2453. }
  2454. mxEvent.consume(evt);
  2455. }
  2456. }));
  2457. }
  2458. if (file.isEditable())
  2459. {
  2460. var graph = this.editor.graph;
  2461. var spinBtn = null;
  2462. var editLibrary = mxUtils.bind(this, function(evt)
  2463. {
  2464. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  2465. mxEvent.consume(evt);
  2466. });
  2467. var saveLibrary = mxUtils.bind(this, function(evt)
  2468. {
  2469. file.setModified(true);
  2470. if (file.isAutosave())
  2471. {
  2472. if (spinBtn != null && spinBtn.parentNode != null)
  2473. {
  2474. spinBtn.parentNode.removeChild(spinBtn);
  2475. }
  2476. spinBtn = btn.cloneNode(false);
  2477. spinBtn.setAttribute('src', Editor.spinImage);
  2478. spinBtn.setAttribute('title', mxResources.get('saving'));
  2479. spinBtn.style.cursor = 'default';
  2480. spinBtn.style.marginRight = '2px';
  2481. spinBtn.style.marginTop = '-2px';
  2482. buttons.insertBefore(spinBtn, buttons.firstChild);
  2483. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2484. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  2485. {
  2486. if (spinBtn != null && spinBtn.parentNode != null)
  2487. {
  2488. spinBtn.parentNode.removeChild(spinBtn);
  2489. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2490. }
  2491. });
  2492. }
  2493. else if (saveBtn == null)
  2494. {
  2495. saveBtn = btn.cloneNode(false);
  2496. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  2497. saveBtn.setAttribute('title', mxResources.get('save'));
  2498. buttons.insertBefore(saveBtn, buttons.firstChild);
  2499. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  2500. {
  2501. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  2502. file.constructor == LocalLibrary, true, function()
  2503. {
  2504. if (saveBtn != null && !file.isModified())
  2505. {
  2506. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2507. saveBtn.parentNode.removeChild(saveBtn);
  2508. saveBtn = null;
  2509. }
  2510. });
  2511. mxEvent.consume(evt);
  2512. }));
  2513. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2514. }
  2515. });
  2516. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  2517. {
  2518. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  2519. // Translates cells to origin
  2520. for (var i = 0; i < cells.length; i++)
  2521. {
  2522. var geo = graph.getCellGeometry(cells[i]);
  2523. if (geo != null)
  2524. {
  2525. geo.translate(-bounds.x, -bounds.y);
  2526. }
  2527. }
  2528. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  2529. cells, bounds.width, bounds.height, title || '', true, false, false));
  2530. var xml = Graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  2531. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  2532. if (title != null)
  2533. {
  2534. entry.title = title;
  2535. }
  2536. images.push(entry);
  2537. saveLibrary(evt);
  2538. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2539. {
  2540. dropTarget.parentNode.removeChild(dropTarget);
  2541. dropTarget = null;
  2542. }
  2543. });
  2544. var addSelection = mxUtils.bind(this, function(evt)
  2545. {
  2546. if (!graph.isSelectionEmpty())
  2547. {
  2548. var cells = graph.getSelectionCells();
  2549. var bounds = graph.view.getBounds(cells);
  2550. var s = graph.view.scale;
  2551. bounds.x /= s;
  2552. bounds.y /= s;
  2553. bounds.width /= s;
  2554. bounds.height /= s;
  2555. bounds.x -= graph.view.translate.x;
  2556. bounds.y -= graph.view.translate.y;
  2557. addCells(cells, bounds);
  2558. }
  2559. else if (graph.getRubberband().isActive())
  2560. {
  2561. graph.getRubberband().execute(evt);
  2562. graph.getRubberband().reset();
  2563. }
  2564. else
  2565. {
  2566. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  2567. }
  2568. mxEvent.consume(evt);
  2569. });
  2570. // Adds drop handler from graph
  2571. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  2572. {
  2573. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  2574. {
  2575. graph.graphHandler.shape.node.style.visibility = 'hidden';
  2576. contentDiv.style.backgroundColor = '#f1f3f4';
  2577. contentDiv.style.cursor = 'copy';
  2578. graph.panningManager.stop();
  2579. graph.autoScroll = false;
  2580. if (graph.graphHandler.guide != null)
  2581. {
  2582. graph.graphHandler.guide.setVisible(false);
  2583. }
  2584. if (graph.graphHandler.hint != null)
  2585. {
  2586. graph.graphHandler.hint.style.visibility = 'hidden';
  2587. }
  2588. mxEvent.consume(evt);
  2589. }
  2590. }), mxUtils.bind(this, function(evt)
  2591. {
  2592. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  2593. {
  2594. contentDiv.style.backgroundColor = '';
  2595. contentDiv.style.cursor = 'default';
  2596. this.sidebar.showTooltips = true;
  2597. graph.panningManager.stop();
  2598. graph.graphHandler.reset();
  2599. graph.isMouseDown = false;
  2600. graph.autoScroll = true;
  2601. addSelection(evt);
  2602. mxEvent.consume(evt);
  2603. }
  2604. }));
  2605. // Handles mouse leaving the library and restoring move
  2606. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  2607. {
  2608. if (graph.isMouseDown && graph.graphHandler.shape != null)
  2609. {
  2610. graph.graphHandler.shape.node.style.visibility = 'visible';
  2611. contentDiv.style.backgroundColor = '';
  2612. contentDiv.style.cursor = '';
  2613. graph.autoScroll = true;
  2614. if (graph.graphHandler.guide != null)
  2615. {
  2616. graph.graphHandler.guide.setVisible(true);
  2617. }
  2618. if (graph.graphHandler.hint != null)
  2619. {
  2620. graph.graphHandler.hint.style.visibility = 'visible';
  2621. }
  2622. }
  2623. }));
  2624. // Adds drop handler from filesystem
  2625. if (Graph.fileSupport)
  2626. {
  2627. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  2628. {
  2629. contentDiv.style.backgroundColor = '#f1f3f4';
  2630. evt.dataTransfer.dropEffect = 'copy';
  2631. contentDiv.style.cursor = 'copy';
  2632. this.sidebar.hideTooltip();
  2633. evt.stopPropagation();
  2634. evt.preventDefault();
  2635. }));
  2636. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  2637. {
  2638. contentDiv.style.cursor = '';
  2639. contentDiv.style.backgroundColor = '';
  2640. if (evt.dataTransfer.files.length > 0)
  2641. {
  2642. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  2643. {
  2644. if (data != null && mimeType.substring(0, 6) == 'image/')
  2645. {
  2646. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  2647. this.convertDataUri(data);
  2648. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  2649. cells[0].vertex = true;
  2650. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  2651. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2652. {
  2653. dropTarget.parentNode.removeChild(dropTarget);
  2654. dropTarget = null;
  2655. }
  2656. }
  2657. else
  2658. {
  2659. var done = false;
  2660. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  2661. {
  2662. if (theData != null && theMimeType == 'text/xml')
  2663. {
  2664. var doc = mxUtils.parseXml(theData);
  2665. if (doc.documentElement.nodeName == 'mxlibrary')
  2666. {
  2667. try
  2668. {
  2669. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2670. addImages(temp, contentDiv);
  2671. images = images.concat(temp);
  2672. saveLibrary(evt);
  2673. this.spinner.stop();
  2674. done = true;
  2675. }
  2676. catch (e)
  2677. {
  2678. // ignore
  2679. }
  2680. }
  2681. else if (doc.documentElement.nodeName == 'mxfile')
  2682. {
  2683. try
  2684. {
  2685. var pages = doc.documentElement.getElementsByTagName('diagram');
  2686. for (var i = 0; i < pages.length; i++)
  2687. {
  2688. var temp = mxUtils.getTextContent(pages[i]);
  2689. var cells = this.stringToCells(Graph.decompress(temp));
  2690. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  2691. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  2692. }
  2693. done = true;
  2694. }
  2695. catch (e)
  2696. {
  2697. if (window.console != null)
  2698. {
  2699. console.log('error in drop handler:', e);
  2700. }
  2701. }
  2702. }
  2703. }
  2704. if (!done)
  2705. {
  2706. this.spinner.stop();
  2707. this.handleError({message: mxResources.get('errorLoadingFile')})
  2708. }
  2709. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2710. {
  2711. dropTarget.parentNode.removeChild(dropTarget);
  2712. dropTarget = null;
  2713. }
  2714. });
  2715. if (file != null && img != null && ((/(\.v(dx|sdx?))($|\?)/i.test(img)) || /(\.vs(x|sx?))($|\?)/i.test(img)))
  2716. {
  2717. this.importVisio(file, function(xml)
  2718. {
  2719. doImport(xml, 'text/xml');
  2720. }, null, img);
  2721. }
  2722. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  2723. {
  2724. this.parseFile(file, mxUtils.bind(this, function(xhr)
  2725. {
  2726. if (xhr.readyState == 4)
  2727. {
  2728. this.spinner.stop();
  2729. if (xhr.status >= 200 && xhr.status <= 299)
  2730. {
  2731. doImport(xhr.responseText, 'text/xml');
  2732. }
  2733. else
  2734. {
  2735. this.handleError({message: mxResources.get((xhr.status == 413) ?
  2736. 'drawingTooLarge' : 'invalidOrMissingFile')},
  2737. mxResources.get('errorLoadingFile'));
  2738. }
  2739. }
  2740. }));
  2741. }
  2742. else
  2743. {
  2744. doImport(data, mimeType);
  2745. }
  2746. }
  2747. }));
  2748. }
  2749. evt.stopPropagation();
  2750. evt.preventDefault();
  2751. }));
  2752. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  2753. {
  2754. contentDiv.style.cursor = '';
  2755. contentDiv.style.backgroundColor = '';
  2756. evt.stopPropagation();
  2757. evt.preventDefault();
  2758. });
  2759. }
  2760. btn = btn.cloneNode(false);
  2761. btn.setAttribute('src', Editor.editImage);
  2762. btn.setAttribute('title', mxResources.get('edit'));
  2763. buttons.insertBefore(btn, buttons.firstChild);
  2764. mxEvent.addListener(btn, 'click', editLibrary);
  2765. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  2766. {
  2767. if (mxEvent.getSource(evt) == contentDiv)
  2768. {
  2769. editLibrary(evt);
  2770. }
  2771. });
  2772. var btn2 = btn.cloneNode(false);
  2773. btn2.setAttribute('src', Editor.plusImage);
  2774. btn2.setAttribute('title', mxResources.get('add'));
  2775. buttons.insertBefore(btn2, buttons.firstChild);
  2776. mxEvent.addListener(btn2, 'click', addSelection);
  2777. if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
  2778. {
  2779. var link = document.createElement('span');
  2780. link.setAttribute('title', mxResources.get('help'));
  2781. link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
  2782. mxUtils.write(link, '?');
  2783. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  2784. {
  2785. this.openLink(EditorUi.scratchpadHelpLink);
  2786. mxEvent.consume(evt);
  2787. }));
  2788. buttons.insertBefore(link, buttons.firstChild);
  2789. }
  2790. }
  2791. title.appendChild(buttons);
  2792. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2793. };
  2794. /**
  2795. * Adds the library entries to the given DOM node.
  2796. */
  2797. EditorUi.prototype.addLibraryEntries = function(imgs, content)
  2798. {
  2799. for (var i = 0; i < imgs.length; i++)
  2800. {
  2801. var img = imgs[i];
  2802. var data = img.data;
  2803. if (data != null)
  2804. {
  2805. data = this.convertDataUri(data);
  2806. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2807. if (img.aspect == 'fixed')
  2808. {
  2809. s += 'aspect=fixed;'
  2810. }
  2811. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  2812. data, img.w, img.h, '', img.title || '', false, false, true));
  2813. }
  2814. else if (img.xml != null)
  2815. {
  2816. var cells = this.stringToCells(Graph.decompress(img.xml));
  2817. if (cells.length > 0)
  2818. {
  2819. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  2820. cells, img.w, img.h, img.title || '', true, false, true));
  2821. }
  2822. }
  2823. }
  2824. };
  2825. /**
  2826. * Extracts the resource for the current language from the given multi language
  2827. * resource object of the form {es: "...", de: "...", main: "..."} where the keys
  2828. * are country codes and main defines the fallback if no resource for the current
  2829. * country code exists.
  2830. */
  2831. EditorUi.prototype.getResource = function(obj)
  2832. {
  2833. return (obj != null) ? (obj[mxLanguage] || obj.main) : null;
  2834. };
  2835. /**
  2836. * EditorUi Overrides
  2837. */
  2838. EditorUi.prototype.footerHeight = 0;
  2839. if (urlParams['offline'] == '1' || EditorUi.isElectronApp)
  2840. {
  2841. //EditorUi.prototype.footerHeight = 4;
  2842. }
  2843. else
  2844. {
  2845. if (urlParams['savesidebar'] == '1')
  2846. {
  2847. Sidebar.prototype.thumbWidth = 64;
  2848. Sidebar.prototype.thumbHeight = 64;
  2849. }
  2850. //EditorUi.prototype.footerHeight = (screen.width >= 760 && screen.height >= 240) ? 46 : 0;
  2851. // Fetches footer from page
  2852. EditorUi.prototype.createFooter = function()
  2853. {
  2854. var footer = document.getElementById('geFooter');
  2855. if (footer != null)
  2856. {
  2857. // footer.style.visibility = 'hidden';
  2858. //
  2859. // // Adds button to hide the footer
  2860. // var img = document.createElement('img');
  2861. // img.setAttribute('border', '0');
  2862. // img.setAttribute('src', Dialog.prototype.closeImage);
  2863. // img.setAttribute('title', mxResources.get('hide'));
  2864. // footer.appendChild(img)
  2865. //
  2866. // if (mxClient.IS_QUIRKS)
  2867. // {
  2868. // img.style.position = 'relative';
  2869. // img.style.styleFloat = 'right';
  2870. // img.style.top = '-30px';
  2871. // img.style.left = '164px';
  2872. // img.style.cursor = 'pointer';
  2873. // }
  2874. //
  2875. // mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  2876. // {
  2877. // this.hideFooter();
  2878. // }));
  2879. }
  2880. return footer;
  2881. };
  2882. }
  2883. EditorUi.initTheme = function()
  2884. {
  2885. if (uiTheme == 'atlas')
  2886. {
  2887. mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
  2888. if (typeof Toolbar !== 'undefined')
  2889. {
  2890. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  2891. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  2892. }
  2893. Editor.prototype.initialTopSpacing = 3;
  2894. EditorUi.prototype.menubarHeight = 41;
  2895. EditorUi.prototype.toolbarHeight = 38;
  2896. }
  2897. else if (uiTheme == 'dark')
  2898. {
  2899. mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
  2900. Dialog.backdropColor = '#2a2a2a';
  2901. Graph.prototype.defaultThemeName = 'darkTheme';
  2902. Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
  2903. Graph.prototype.defaultPageBorderColor = '#505759';
  2904. Format.prototype.inactiveTabBackgroundColor = 'black';
  2905. BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
  2906. Sidebar.prototype.dragPreviewBorder = '1px dashed #cccccc';
  2907. mxGraphHandler.prototype.previewColor = '#cccccc';
  2908. StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
  2909. if (mxClient.IS_SVG)
  2910. {
  2911. Editor.helpImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAP1BMVEUAAAD///////////////////////////////////////////////////////////////////////////////9Du/pqAAAAFXRSTlMAT30qCJRBboyDZyCgRzUUdF46MJlgXETgAAAAeklEQVQY022O2w4DIQhEQUURda/9/28tUO2+7CQS5sgQ4F1RapX78YUwRqQjTU8ILqQfKerTKTvACJ4nLX3krt+8aS82oI8aQC4KavRgtvEW/mDvsICgA03PSGRr79MqX1YPNIxzjyqtw8ZnnRo4t5a5undtJYRywau+ds4Cyza3E6YAAAAASUVORK5CYII=';
  2912. Editor.checkmarkImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAARVBMVEUAAACZmZkICAgEBASNjY2Dg4MYGBiTk5N5eXl1dXVmZmZQUFBCQkI3NzceHh4MDAykpKSJiYl+fn5sbGxaWlo/Pz8SEhK96uPlAAAAAXRSTlMAQObYZgAAAE5JREFUGNPFzTcSgDAQQ1HJGUfy/Y9K7V1qeOUfzQifCQZai1XHaz11LFysbDbzgDSSWMZiETz3+b8yNUc/MMsktxuC8XQBSncdLwz+8gCCggGXzBcozAAAAABJRU5ErkJggg==';
  2913. }
  2914. }
  2915. };
  2916. EditorUi.initTheme();
  2917. /**
  2918. * Hides the footer.
  2919. */
  2920. EditorUi.prototype.hideFooter = function()
  2921. {
  2922. var footer = document.getElementById('geFooter');
  2923. if (footer != null)
  2924. {
  2925. this.footerHeight = 0;
  2926. footer.style.display = 'none';
  2927. this.refresh();
  2928. }
  2929. };
  2930. /**
  2931. * Shows the footer.
  2932. */
  2933. EditorUi.prototype.showFooter = function(height)
  2934. {
  2935. var footer = document.getElementById('geFooter');
  2936. if (footer != null)
  2937. {
  2938. this.footerHeight = height;
  2939. footer.style.display = 'inline';
  2940. this.refresh();
  2941. }
  2942. };
  2943. /**
  2944. * Overrides image dialog to add image search and Google+.
  2945. */
  2946. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  2947. {
  2948. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  2949. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  2950. this.showDialog(dlg.container, (Graph.fileSupport) ? 440 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
  2951. dlg.init();
  2952. };
  2953. /**
  2954. * Hides the current menu.
  2955. */
  2956. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  2957. {
  2958. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  2959. {
  2960. var change = new ChangePageSetup(this, null, image);
  2961. change.ignoreColor = true;
  2962. this.editor.graph.model.execute(change);
  2963. });
  2964. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  2965. {
  2966. apply(image);
  2967. }));
  2968. this.showDialog(dlg.container, 360, 200, true, true);
  2969. dlg.init();
  2970. };
  2971. /**
  2972. * Hides the current menu.
  2973. */
  2974. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  2975. {
  2976. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  2977. this.showDialog(dlg.container, 640, 440, true, false, mxUtils.bind(this, function(cancel)
  2978. {
  2979. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  2980. {
  2981. this.showSplash();
  2982. }
  2983. }));
  2984. dlg.init();
  2985. };
  2986. /**
  2987. * Overridden to update after view state changes.
  2988. */
  2989. var editorUiCreateFormat = EditorUi.prototype.createFormat;
  2990. EditorUi.prototype.createFormat = function(container)
  2991. {
  2992. var format = editorUiCreateFormat.apply(this, arguments);
  2993. this.editor.graph.addListener('viewStateChanged', mxUtils.bind(this, function(evt)
  2994. {
  2995. if (this.editor.graph.isSelectionEmpty())
  2996. {
  2997. format.refresh();
  2998. }
  2999. }));
  3000. return format;
  3001. };
  3002. /**
  3003. * Hook for sidebar footer container.
  3004. */
  3005. EditorUi.prototype.createSidebarFooterContainer = function()
  3006. {
  3007. var div = this.createDiv('geSidebarContainer geSidebarFooter');
  3008. div.style.position = 'absolute';
  3009. div.style.overflow = 'hidden';
  3010. var elt2 = document.createElement('a');
  3011. elt2.className = 'geTitle';
  3012. elt2.style.color = '#188038';
  3013. elt2.style.height = '100%';
  3014. elt2.style.paddingTop = '9px';
  3015. elt2.innerHTML = '<span style="font-size:18px;margin-right:5px;">+</span>';
  3016. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  3017. // Prevents focus
  3018. mxEvent.addListener(elt2, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
  3019. mxUtils.bind(this, function(evt)
  3020. {
  3021. evt.preventDefault();
  3022. }));
  3023. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  3024. {
  3025. this.actions.get('shapes').funct();
  3026. mxEvent.consume(evt);
  3027. }));
  3028. div.appendChild(elt2);
  3029. return div;
  3030. };
  3031. /**
  3032. * Translates this point by the given vector.
  3033. *
  3034. * @param {number} dx X-coordinate of the translation.
  3035. * @param {number} dy Y-coordinate of the translation.
  3036. */
  3037. EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose, notFoundMessage)
  3038. {
  3039. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3040. var e = (resp != null && resp.error != null) ? resp.error : resp;
  3041. if (e != null || title != null)
  3042. {
  3043. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  3044. var btn = mxResources.get('ok');
  3045. var retry = null;
  3046. title = (title != null) ? title : mxResources.get('error');
  3047. if (e != null)
  3048. {
  3049. if (e.retry != null)
  3050. {
  3051. btn = mxResources.get('cancel');
  3052. retry = function()
  3053. {
  3054. resume();
  3055. e.retry();
  3056. };
  3057. }
  3058. if (e.code == 404 || e.status == 404 || e.code == 403)
  3059. {
  3060. if (e.code == 403)
  3061. {
  3062. if (e.message != null)
  3063. {
  3064. msg = mxUtils.htmlEntities(e.message);
  3065. }
  3066. else
  3067. {
  3068. msg = mxUtils.htmlEntities(mxResources.get('accessDenied'));
  3069. }
  3070. }
  3071. else
  3072. {
  3073. msg = (notFoundMessage != null) ? notFoundMessage :
  3074. mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied') +
  3075. ((this.drive != null && this.drive.user != null) ? ' (' + this.drive.user.displayName +
  3076. ', ' + this.drive.user.email+ ')' : ''));
  3077. }
  3078. var id = window.location.hash;
  3079. // #U handles case where we tried to fallback to Google File and
  3080. // hash property still shows the public URL we tried to load
  3081. if (id != null && (id.substring(0, 2) == '#G' ||
  3082. id.substring(0, 45) == '#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D') &&
  3083. ((resp != null && resp.error != null && ((resp.error.errors != null &&
  3084. resp.error.errors.length > 0 && resp.error.errors[0].reason == 'fileAccess') ||
  3085. (resp.error.data != null && resp.error.data.length > 0 &&
  3086. resp.error.data[0].reason == 'fileAccess'))) ||
  3087. e.code == 404 || e.status == 404))
  3088. {
  3089. id = (id.substring(0, 2) == '#U') ? id.substring(45, id.lastIndexOf('%26ex')) : id.substring(2);
  3090. // Special case where the button must have a different label and function
  3091. this.showError(title, msg, mxResources.get('openInNewWindow'), mxUtils.bind(this, function()
  3092. {
  3093. this.editor.graph.openLink('https://drive.google.com/open?id=' + id);
  3094. this.handleError(resp, title, fn, invokeFnOnClose, notFoundMessage)
  3095. }), retry, mxResources.get('changeUser'), mxUtils.bind(this, function()
  3096. {
  3097. if (this.spinner.spin(document.body, mxResources.get('loading')))
  3098. {
  3099. this.drive.clearUserId();
  3100. gapi.auth.signOut();
  3101. // Reload page to reset client auth
  3102. window.location.reload();
  3103. }
  3104. }), mxResources.get('cancel'), mxUtils.bind(this, function()
  3105. {
  3106. window.location.hash = '';
  3107. }), 480, 150);
  3108. return;
  3109. }
  3110. }
  3111. else if (e.message != null)
  3112. {
  3113. msg = mxUtils.htmlEntities(e.message);
  3114. }
  3115. else if (e.response != null && e.response.error != null)
  3116. {
  3117. msg = mxUtils.htmlEntities(e.response.error);
  3118. }
  3119. else if (window.App !== 'undefined')
  3120. {
  3121. if (e.code == App.ERROR_TIMEOUT)
  3122. {
  3123. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  3124. }
  3125. else if (e.code == App.ERROR_BUSY)
  3126. {
  3127. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  3128. }
  3129. }
  3130. }
  3131. this.showError(title, msg, btn, fn, retry, null, null, null, null,
  3132. null, null, null, (invokeFnOnClose) ? fn : null);
  3133. }
  3134. else if (fn != null)
  3135. {
  3136. fn();
  3137. }
  3138. };
  3139. /**
  3140. * Translates this point by the given vector.
  3141. *
  3142. * @param {number} dx X-coordinate of the translation.
  3143. * @param {number} dy Y-coordinate of the translation.
  3144. */
  3145. EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose)
  3146. {
  3147. var height = (msg != null && msg.length > 120) ? 180 : 150;
  3148. var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
  3149. fn, retry, btn2, fn2, hide, btn3, fn3);
  3150. this.showDialog(dlg.container, w || 340, h || ((msg != null && msg.length > 120) ?
  3151. 180 : 150), true, false, onClose);
  3152. dlg.init();
  3153. };
  3154. /**
  3155. * Translates this point by the given vector.
  3156. *
  3157. * @param {number} dx X-coordinate of the translation.
  3158. * @param {number} dy Y-coordinate of the translation.
  3159. */
  3160. EditorUi.prototype.alert = function(msg, fn)
  3161. {
  3162. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  3163. this.showDialog(dlg.container, 340, 100, true, false);
  3164. dlg.init();
  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.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel, closable)
  3173. {
  3174. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3175. var dlg = new ConfirmDialog(this, msg, function()
  3176. {
  3177. resume();
  3178. if (okFn != null)
  3179. {
  3180. okFn();
  3181. }
  3182. }, function()
  3183. {
  3184. resume();
  3185. if (cancelFn != null)
  3186. {
  3187. cancelFn();
  3188. }
  3189. }, okLabel, cancelLabel);
  3190. this.showDialog(dlg.container, 340, 90, true, closable);
  3191. dlg.init();
  3192. };
  3193. /**
  3194. * Translates this point by the given vector.
  3195. *
  3196. * @param {number} dx X-coordinate of the translation.
  3197. * @param {number} dy Y-coordinate of the translation.
  3198. */
  3199. EditorUi.prototype.setCurrentFile = function(file)
  3200. {
  3201. this.currentFile = file;
  3202. };
  3203. /**
  3204. * Translates this point by the given vector.
  3205. *
  3206. * @param {number} dx X-coordinate of the translation.
  3207. * @param {number} dy Y-coordinate of the translation.
  3208. */
  3209. EditorUi.prototype.getCurrentFile = function()
  3210. {
  3211. return this.currentFile;
  3212. };
  3213. /**
  3214. * Handling for canvas export.
  3215. */
  3216. /**
  3217. * See fixme in convertMath for client-side image generation with math.
  3218. */
  3219. EditorUi.prototype.isExportToCanvas = function()
  3220. {
  3221. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  3222. };
  3223. /**
  3224. * Translates this point by the given vector.
  3225. *
  3226. * @param {number} dx X-coordinate of the translation.
  3227. * @param {number} dy Y-coordinate of the translation.
  3228. */
  3229. EditorUi.prototype.createSvgDataUri = function(svg)
  3230. {
  3231. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  3232. };
  3233. /**
  3234. *
  3235. */
  3236. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  3237. {
  3238. var data = canvas.toDataURL('image/' + format);
  3239. // Checks if output is invalid or empty
  3240. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  3241. {
  3242. throw {message: 'Invalid image'};
  3243. }
  3244. if (xml != null)
  3245. {
  3246. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(Graph.compress(xml)));
  3247. }
  3248. return data;
  3249. };
  3250. /**
  3251. *
  3252. */
  3253. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  3254. {
  3255. var ext = ((format == 'jpeg') ? 'jpg' : format);
  3256. var filename = this.getBaseFilename() + '.' + ext;
  3257. var data = this.createImageDataUri(canvas, xml, format);
  3258. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  3259. };
  3260. /**
  3261. * Returns true if files should be saved using <saveLocalFile>.
  3262. */
  3263. EditorUi.prototype.isLocalFileSave = function()
  3264. {
  3265. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  3266. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  3267. document.documentMode != 9 && document.documentMode != 8 &&
  3268. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  3269. this.isOfflineApp() || mxClient.IS_IOS);
  3270. };
  3271. /**
  3272. * Translates this point by the given vector.
  3273. *
  3274. * @param {number} dx X-coordinate of the translation.
  3275. * @param {number} dy Y-coordinate of the translation.
  3276. */
  3277. EditorUi.prototype.showTextDialog = function(title, text)
  3278. {
  3279. var dlg = new TextareaDialog(this, title, text, null, null, mxResources.get('close'));
  3280. dlg.textarea.style.width = '600px';
  3281. dlg.textarea.style.height = '380px';
  3282. this.showDialog(dlg.container, 620, 460, true, true);
  3283. dlg.init();
  3284. document.execCommand('selectall', false, null);
  3285. };
  3286. /**
  3287. * Translates this point by the given vector.
  3288. *
  3289. * @param {number} dx X-coordinate of the translation.
  3290. * @param {number} dy Y-coordinate of the translation.
  3291. */
  3292. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  3293. {
  3294. // Newer versions of IE
  3295. if (window.Blob && navigator.msSaveOrOpenBlob)
  3296. {
  3297. var blob = (base64Encoded) ?
  3298. this.base64ToBlob(data, mimeType) :
  3299. new Blob([data], {type: mimeType})
  3300. navigator.msSaveOrOpenBlob(blob, filename);
  3301. }
  3302. // Older versions of IE (binary not supported)
  3303. else if (mxClient.IS_IE)
  3304. {
  3305. var win = window.open('about:blank', '_blank');
  3306. if (win == null)
  3307. {
  3308. mxUtils.popup(data, true);
  3309. }
  3310. else
  3311. {
  3312. win.document.write(data);
  3313. win.document.close();
  3314. win.document.execCommand('SaveAs', true, filename);
  3315. win.close();
  3316. }
  3317. }
  3318. // else if (mxClient.IS_IOS)
  3319. // {
  3320. // this.showTextDialog(filename + ':', data);
  3321. // }
  3322. else
  3323. {
  3324. var a = document.createElement('a');
  3325. // Workaround for mxXmlRequest.simulate no longer working in Safari/PaleMoon
  3326. // if this is used (ie PNG export broken after XML export in Safari/PaleMoon).
  3327. var useDownload = !mxClient.IS_SF && navigator.userAgent.indexOf("PaleMoon/") < 0 &&
  3328. typeof a.download !== 'undefined';
  3329. // Workaround for Chromium 65 cross-domain anchor download issue
  3330. if (mxClient.IS_GC)
  3331. {
  3332. var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
  3333. var vers = raw ? parseInt(raw[2], 10) : false;
  3334. useDownload = vers == 65 ? false : useDownload;
  3335. }
  3336. if (useDownload || this.isOffline())
  3337. {
  3338. a.href = URL.createObjectURL((base64Encoded) ?
  3339. this.base64ToBlob(data, mimeType) :
  3340. new Blob([data], {type: mimeType}));
  3341. if (useDownload)
  3342. {
  3343. a.download = filename;
  3344. }
  3345. else
  3346. {
  3347. // Workaround for same window in Safari
  3348. a.setAttribute('target', '_blank');
  3349. }
  3350. document.body.appendChild(a);
  3351. try
  3352. {
  3353. window.setTimeout(function()
  3354. {
  3355. URL.revokeObjectURL(a.href);
  3356. }, 0);
  3357. a.click();
  3358. a.parentNode.removeChild(a);
  3359. }
  3360. catch (e)
  3361. {
  3362. // ignore
  3363. }
  3364. }
  3365. else
  3366. {
  3367. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  3368. req.simulate(document, '_blank');
  3369. }
  3370. }
  3371. };
  3372. /**
  3373. * Translates this point by the given vector.
  3374. *
  3375. * @param {number} dx X-coordinate of the translation.
  3376. * @param {number} dy Y-coordinate of the translation.
  3377. */
  3378. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  3379. {
  3380. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  3381. 'data=' + encodeURIComponent(Graph.compress(data));
  3382. return new mxXmlRequest(SAVE_URL, param +
  3383. ((mimeType != null) ? '&mime=' + mimeType : '') +
  3384. ((format != null) ? '&format=' + format : '') +
  3385. ((base64Response != null) ? '&base64=' + base64Response : '') +
  3386. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  3387. ((base64Encoded) ? '&binary=1' : ''));
  3388. };
  3389. /**
  3390. * Translates this point by the given vector.
  3391. *
  3392. * @param {number} dx X-coordinate of the translation.
  3393. * @param {number} dy Y-coordinate of the translation.
  3394. */
  3395. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  3396. {
  3397. contentType = contentType || '';
  3398. var sliceSize = 1024;
  3399. var byteCharacters = atob(base64Data);
  3400. var bytesLength = byteCharacters.length;
  3401. var slicesCount = Math.ceil(bytesLength / sliceSize);
  3402. var byteArrays = new Array(slicesCount);
  3403. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  3404. {
  3405. var begin = sliceIndex * sliceSize;
  3406. var end = Math.min(begin + sliceSize, bytesLength);
  3407. var bytes = new Array(end - begin);
  3408. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  3409. {
  3410. bytes[i] = byteCharacters[offset].charCodeAt(0);
  3411. }
  3412. byteArrays[sliceIndex] = new Uint8Array(bytes);
  3413. }
  3414. return new Blob(byteArrays, {type: contentType});
  3415. };
  3416. /**
  3417. * Translates this point by the given vector.
  3418. *
  3419. * @param {number} dx X-coordinate of the translation.
  3420. * @param {number} dy Y-coordinate of the translation.
  3421. */
  3422. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab)
  3423. {
  3424. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  3425. allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  3426. var count = this.getServiceCount(allowBrowser);
  3427. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3428. {
  3429. try
  3430. {
  3431. // Opens a new window
  3432. if (mode == '_blank')
  3433. {
  3434. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  3435. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  3436. {
  3437. this.openInNewWindow(data, mimeType, base64Encoded);
  3438. }
  3439. else
  3440. {
  3441. var win = window.open('about:blank');
  3442. if (win == null)
  3443. {
  3444. mxUtils.popup(data, true);
  3445. }
  3446. else
  3447. {
  3448. win.document.write(mxUtils.htmlEntities(data, false));
  3449. win.document.close();
  3450. }
  3451. }
  3452. }
  3453. else if (mode == App.MODE_DEVICE || mode == 'download')
  3454. {
  3455. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  3456. }
  3457. else if (newTitle != null && newTitle.length > 0)
  3458. {
  3459. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3460. {
  3461. try
  3462. {
  3463. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  3464. }
  3465. catch (e)
  3466. {
  3467. this.handleError(e);
  3468. }
  3469. }));
  3470. }
  3471. }
  3472. catch (e)
  3473. {
  3474. this.handleError(e);
  3475. }
  3476. }), mxUtils.bind(this, function()
  3477. {
  3478. this.hideDialog();
  3479. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
  3480. null, count > 1, (count > 4 && (!allowBrowser || count < 6)) ? 3 : 4, data, mimeType, base64Encoded);
  3481. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3482. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3483. this.showDialog(dlg.container, 420, height, true, true);
  3484. dlg.init();
  3485. };
  3486. /**
  3487. *
  3488. */
  3489. EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
  3490. {
  3491. // In Google Chrome 60 the code from below produces a blank window
  3492. if (mxClient.IS_GC || mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  3493. {
  3494. var win = window.open('about:blank');
  3495. if (win == null || win.document == null)
  3496. {
  3497. mxUtils.popup(data, true);
  3498. }
  3499. else
  3500. {
  3501. // Workaround for broken images in SVG output in Chrome
  3502. if (mimeType == 'image/svg+xml')
  3503. {
  3504. win.document.write('<html>' + data + '</html>');
  3505. }
  3506. else
  3507. {
  3508. win.document.write('<html><img src="data:' +
  3509. mimeType + ((base64Encoded) ? ';base64,' +
  3510. data : ';charset=utf8,' + encodeURIComponent(data)) +
  3511. '"/></html>');
  3512. }
  3513. win.document.close();
  3514. }
  3515. }
  3516. else
  3517. {
  3518. // win.open is workaround for cleared contents in Chrome after delay
  3519. // when using location.replace
  3520. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  3521. data : ';charset=utf8,' + encodeURIComponent(data)));
  3522. if (win == null || win.document == null)
  3523. {
  3524. mxUtils.popup(data, true);
  3525. }
  3526. }
  3527. };
  3528. var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
  3529. /**
  3530. * Creates a temporary graph instance for rendering off-screen content.
  3531. */
  3532. EditorUi.prototype.addChromelessToolbarItems = function(addButton)
  3533. {
  3534. if (this.isExportToCanvas())
  3535. {
  3536. this.exportDialog = null;
  3537. var exportButton = addButton(mxUtils.bind(this, function(evt)
  3538. {
  3539. var clickHandler = mxUtils.bind(this, function()
  3540. {
  3541. mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
  3542. if (this.exportDialog != null)
  3543. {
  3544. this.exportDialog.parentNode.removeChild(this.exportDialog);
  3545. this.exportDialog = null;
  3546. }
  3547. });
  3548. if (this.exportDialog != null)
  3549. {
  3550. clickHandler.apply(this);
  3551. }
  3552. else
  3553. {
  3554. this.exportDialog = document.createElement('div');
  3555. var r = exportButton.getBoundingClientRect();
  3556. mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
  3557. this.exportDialog.style.position = 'fixed';
  3558. this.exportDialog.style.textAlign = 'center';
  3559. this.exportDialog.style.fontFamily = 'Helvetica,Arial';
  3560. this.exportDialog.style.backgroundColor = '#000000';
  3561. this.exportDialog.style.width = '50px';
  3562. this.exportDialog.style.height = '50px';
  3563. this.exportDialog.style.padding = '4px 2px 4px 2px';
  3564. this.exportDialog.style.color = '#ffffff';
  3565. mxUtils.setOpacity(this.exportDialog, 70);
  3566. this.exportDialog.style.left = r.left + 'px';
  3567. this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  3568. this.chromelessToolbar.offsetHeight + 4 + 'px';
  3569. // Puts the dialog on top of the container z-index
  3570. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  3571. this.exportDialog.style.zIndex = style.zIndex;
  3572. var spinner = new Spinner({
  3573. lines: 8, // The number of lines to draw
  3574. length: 6, // The length of each line
  3575. width: 5, // The line thickness
  3576. radius: 6, // The radius of the inner circle
  3577. rotate: 0, // The rotation offset
  3578. color: '#fff', // #rgb or #rrggbb
  3579. speed: 1.5, // Rounds per second
  3580. trail: 60, // Afterglow percentage
  3581. shadow: false, // Whether to render a shadow
  3582. hwaccel: false, // Whether to use hardware acceleration
  3583. top: '28px',
  3584. zIndex: 2e9 // The z-index (defaults to 2000000000)
  3585. });
  3586. spinner.spin(this.exportDialog);
  3587. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3588. {
  3589. spinner.stop();
  3590. this.exportDialog.style.width = 'auto';
  3591. this.exportDialog.style.height = 'auto';
  3592. this.exportDialog.style.padding = '10px';
  3593. var data = this.createImageDataUri(canvas, null, 'png');
  3594. var img = document.createElement('img');
  3595. img.style.maxWidth = '140px';
  3596. img.style.maxHeight = '140px';
  3597. img.style.cursor = 'pointer';
  3598. img.style.backgroundColor = 'white';
  3599. img.setAttribute('title', mxResources.get('openInNewWindow'));
  3600. img.setAttribute('border', '0');
  3601. img.setAttribute('src', data);
  3602. this.exportDialog.appendChild(img);
  3603. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  3604. {
  3605. this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
  3606. clickHandler.apply(this, arguments);
  3607. }));
  3608. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3609. {
  3610. this.spinner.stop();
  3611. this.handleError(e);
  3612. }));
  3613. mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
  3614. document.body.appendChild(this.exportDialog);
  3615. }
  3616. mxEvent.consume(evt);
  3617. }), Editor.cameraLargeImage, mxResources.get('export'));
  3618. }
  3619. editoUiAddChromelessToolbarItems.apply(this, arguments);
  3620. };
  3621. /**
  3622. * Translates this point by the given vector.
  3623. *
  3624. * @param {number} dx X-coordinate of the translation.
  3625. * @param {number} dy Y-coordinate of the translation.
  3626. */
  3627. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  3628. {
  3629. if (this.isLocalFileSave())
  3630. {
  3631. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  3632. }
  3633. else
  3634. {
  3635. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  3636. {
  3637. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  3638. }), data, base64Encoded, mime);
  3639. }
  3640. };
  3641. /**
  3642. * Translates this point by the given vector.
  3643. *
  3644. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  3645. * side without requiring a server roundtrip.
  3646. *
  3647. * @param {number} dx X-coordinate of the translation.
  3648. * @param {number} dy Y-coordinate of the translation.
  3649. */
  3650. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
  3651. {
  3652. allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
  3653. var count = this.getServiceCount(false);
  3654. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3655. {
  3656. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  3657. {
  3658. var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
  3659. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  3660. if (xhr != null)
  3661. {
  3662. if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
  3663. {
  3664. xhr.simulate(document, '_blank');
  3665. }
  3666. else
  3667. {
  3668. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3669. {
  3670. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  3671. 'application/pdf' : 'image/' + format);
  3672. // Workaround for no roundtrip required if data is available on client-side
  3673. // TODO: Refactor the saveData/saveRequest call chain for local data
  3674. if (data != null)
  3675. {
  3676. try
  3677. {
  3678. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  3679. }
  3680. catch (e)
  3681. {
  3682. this.handleError(e);
  3683. }
  3684. }
  3685. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  3686. {
  3687. // LATER: Catch possible mixed content error
  3688. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  3689. xhr.send(mxUtils.bind(this, function()
  3690. {
  3691. this.spinner.stop();
  3692. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  3693. {
  3694. try
  3695. {
  3696. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  3697. }
  3698. catch (e)
  3699. {
  3700. this.handleError(e);
  3701. }
  3702. }
  3703. else
  3704. {
  3705. this.handleError({message: mxResources.get('errorSavingFile')});
  3706. }
  3707. }), function(resp)
  3708. {
  3709. this.spinner.stop();
  3710. this.handleError(resp);
  3711. });
  3712. }
  3713. }));
  3714. }
  3715. }
  3716. }
  3717. }), mxUtils.bind(this, function()
  3718. {
  3719. this.hideDialog();
  3720. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
  3721. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  3722. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3723. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3724. this.showDialog(dlg.container, 380, height, true, true);
  3725. dlg.init();
  3726. };
  3727. /**
  3728. *
  3729. */
  3730. EditorUi.prototype.getEditBlankXml = function()
  3731. {
  3732. return this.getFileData(true);
  3733. };
  3734. /**
  3735. * Hook for subclassers.
  3736. */
  3737. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  3738. {
  3739. // do nothing
  3740. };
  3741. /**
  3742. * Hook for subclassers.
  3743. */
  3744. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  3745. {
  3746. fn(null);
  3747. };
  3748. /**
  3749. *
  3750. */
  3751. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow,
  3752. editable, embedImages, border, noCrop, currentPage, linkTarget)
  3753. {
  3754. if (this.spinner.spin(document.body, mxResources.get('export')))
  3755. {
  3756. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3757. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3758. var bg = (transparentBackground) ? null : this.editor.graph.background;
  3759. if (bg == mxConstants.NONE)
  3760. {
  3761. bg = null;
  3762. }
  3763. // Handles special case where background is null but transparent is false
  3764. if (bg == null && transparentBackground == false)
  3765. {
  3766. bg = '#ffffff';
  3767. }
  3768. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3769. // because PhantomJS seems to ignore switch statements and paint all text.
  3770. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null,
  3771. ignoreSelection, null, null, (linkTarget == 'blank') ? '_blank' :
  3772. ((linkTarget == 'self') ? '_top' : null));
  3773. if (addShadow)
  3774. {
  3775. this.editor.graph.addSvgShadow(svgRoot);
  3776. }
  3777. var filename = this.getBaseFilename() + '.svg';
  3778. var doSave = mxUtils.bind(this, function(svgRoot)
  3779. {
  3780. this.spinner.stop();
  3781. if (editable)
  3782. {
  3783. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  3784. }
  3785. if (this.editor.fontCss != null)
  3786. {
  3787. var svgDoc = svgRoot.ownerDocument;
  3788. var style = (svgDoc.createElementNS != null) ?
  3789. svgDoc.createElementNS(mxConstants.NS_SVG, 'style') : svgDoc.createElement('style');
  3790. style.setAttribute('type', 'text/css');
  3791. mxUtils.setTextContent(style, this.editor.fontCss);
  3792. svgRoot.getElementsByTagName('defs')[0].appendChild(style);
  3793. }
  3794. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  3795. mxUtils.getXml(svgRoot);
  3796. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  3797. {
  3798. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  3799. }
  3800. else
  3801. {
  3802. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  3803. {
  3804. mxUtils.popup(svg);
  3805. }));
  3806. }
  3807. });
  3808. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  3809. {
  3810. if (embedImages)
  3811. {
  3812. // Caches images
  3813. if (this.thumbImageCache == null)
  3814. {
  3815. this.thumbImageCache = new Object();
  3816. }
  3817. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  3818. }
  3819. else
  3820. {
  3821. doSave(svgRoot);
  3822. }
  3823. }));
  3824. }
  3825. };
  3826. EditorUi.prototype.addRadiobox = function(div, radioGroupName, label, checked, disabled, disableNewline, visible)
  3827. {
  3828. return this.addCheckbox(div, label, checked, disabled, disableNewline, visible, true, radioGroupName);
  3829. }
  3830. /**
  3831. *
  3832. */
  3833. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible, asRadio, radioGroupName)
  3834. {
  3835. visible = (visible != null) ? visible : true;
  3836. var cb = document.createElement('input');
  3837. cb.style.marginRight = '8px';
  3838. cb.style.marginTop = '16px';
  3839. cb.setAttribute('type', asRadio? 'radio' : 'checkbox');
  3840. var id = 'geCheckbox-' + Editor.guid();
  3841. cb.id = id;
  3842. if (radioGroupName != null)
  3843. {
  3844. cb.setAttribute('name', radioGroupName);
  3845. }
  3846. if (checked)
  3847. {
  3848. cb.setAttribute('checked', 'checked');
  3849. cb.defaultChecked = true;
  3850. }
  3851. if (disabled)
  3852. {
  3853. cb.setAttribute('disabled', 'disabled');
  3854. }
  3855. if (visible)
  3856. {
  3857. div.appendChild(cb);
  3858. var lbl = document.createElement('label');
  3859. mxUtils.write(lbl, label);
  3860. lbl.setAttribute('for', id);
  3861. div.appendChild(lbl);
  3862. if (!disableNewline)
  3863. {
  3864. mxUtils.br(div);
  3865. }
  3866. }
  3867. return cb;
  3868. };
  3869. /**
  3870. *
  3871. */
  3872. EditorUi.prototype.addEditButton = function(div, lightbox)
  3873. {
  3874. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  3875. edit.style.marginLeft = '24px';
  3876. var file = this.getCurrentFile();
  3877. var editUrl = '';
  3878. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  3879. {
  3880. editUrl = window.location.href;
  3881. }
  3882. var editSelect = document.createElement('select');
  3883. editSelect.style.width = '120px';
  3884. editSelect.style.marginLeft = '8px';
  3885. editSelect.style.marginRight = '10px';
  3886. editSelect.className = 'geBtn';
  3887. var blankOption = document.createElement('option');
  3888. blankOption.setAttribute('value', 'blank');
  3889. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  3890. editSelect.appendChild(blankOption);
  3891. var customOption = document.createElement('option');
  3892. customOption.setAttribute('value', 'custom');
  3893. mxUtils.write(customOption, mxResources.get('custom') + '...');
  3894. editSelect.appendChild(customOption);
  3895. div.appendChild(editSelect);
  3896. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  3897. {
  3898. if (editSelect.value == 'custom')
  3899. {
  3900. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  3901. {
  3902. if (value != null)
  3903. {
  3904. editUrl = value;
  3905. }
  3906. else
  3907. {
  3908. editSelect.value = 'blank';
  3909. }
  3910. }, mxResources.get('url'), null, null, null, null, function()
  3911. {
  3912. editSelect.value = 'blank';
  3913. });
  3914. this.showDialog(dlg2.container, 300, 80, true, false);
  3915. dlg2.init();
  3916. }
  3917. }));
  3918. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  3919. {
  3920. if (edit.checked && (lightbox == null || lightbox.checked))
  3921. {
  3922. editSelect.removeAttribute('disabled');
  3923. }
  3924. else
  3925. {
  3926. editSelect.setAttribute('disabled', 'disabled');
  3927. }
  3928. }));
  3929. mxUtils.br(div);
  3930. return {
  3931. getLink: function()
  3932. {
  3933. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  3934. },
  3935. getEditInput: function()
  3936. {
  3937. return edit;
  3938. },
  3939. getEditSelect: function()
  3940. {
  3941. return editSelect;
  3942. }
  3943. };
  3944. }
  3945. /**
  3946. *
  3947. */
  3948. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  3949. {
  3950. mxUtils.write(div, mxResources.get('links') + ':');
  3951. var linkSelect = document.createElement('select');
  3952. linkSelect.style.width = '100px';
  3953. linkSelect.style.marginLeft = '8px';
  3954. linkSelect.style.marginRight = '10px';
  3955. linkSelect.className = 'geBtn';
  3956. var autoOption = document.createElement('option');
  3957. autoOption.setAttribute('value', 'auto');
  3958. mxUtils.write(autoOption, mxResources.get('automatic'));
  3959. linkSelect.appendChild(autoOption);
  3960. var blankOption = document.createElement('option');
  3961. blankOption.setAttribute('value', 'blank');
  3962. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  3963. linkSelect.appendChild(blankOption);
  3964. var selfOption = document.createElement('option');
  3965. selfOption.setAttribute('value', 'self');
  3966. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  3967. linkSelect.appendChild(selfOption);
  3968. if (showFrameOption)
  3969. {
  3970. var frameOption = document.createElement('option');
  3971. frameOption.setAttribute('value', 'frame');
  3972. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  3973. ' (' + mxResources.get('iframe') + ')');
  3974. linkSelect.appendChild(frameOption);
  3975. }
  3976. div.appendChild(linkSelect);
  3977. mxUtils.write(div, mxResources.get('borderColor') + ':');
  3978. var linkColor = '#0000ff';
  3979. var linkButton = null;
  3980. function updateLinkColor()
  3981. {
  3982. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  3983. ((linkColor != null && linkColor != mxConstants.NONE) ?
  3984. 'border:1px solid black;background-color:' + linkColor :
  3985. 'background-position:center center;background-repeat:no-repeat;' +
  3986. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  3987. };
  3988. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  3989. {
  3990. this.pickColor(linkColor || 'none', function(color)
  3991. {
  3992. linkColor = color;
  3993. updateLinkColor();
  3994. });
  3995. mxEvent.consume(evt);
  3996. }));
  3997. updateLinkColor();
  3998. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  3999. linkButton.style.marginLeft = '4px';
  4000. linkButton.style.height = '22px';
  4001. linkButton.style.width = '22px';
  4002. linkButton.style.position = 'relative';
  4003. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  4004. linkButton.className = 'geColorBtn';
  4005. div.appendChild(linkButton);
  4006. mxUtils.br(div);
  4007. return {
  4008. getColor: function()
  4009. {
  4010. return linkColor;
  4011. },
  4012. getTarget: function()
  4013. {
  4014. return linkSelect.value;
  4015. },
  4016. focus: function()
  4017. {
  4018. linkSelect.focus();
  4019. }
  4020. };
  4021. }
  4022. /**
  4023. *
  4024. */
  4025. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  4026. {
  4027. var file = this.getCurrentFile();
  4028. var params = [];
  4029. if (lightbox)
  4030. {
  4031. params.push('lightbox=1');
  4032. if (linkTarget != 'auto')
  4033. {
  4034. params.push('target=' + linkTarget);
  4035. }
  4036. if (linkColor != null && linkColor != mxConstants.NONE)
  4037. {
  4038. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  4039. }
  4040. if (editLink != null && editLink.length > 0)
  4041. {
  4042. params.push('edit=' + encodeURIComponent(editLink));
  4043. }
  4044. if (layers)
  4045. {
  4046. params.push('layers=1');
  4047. }
  4048. if (this.editor.graph.foldingEnabled)
  4049. {
  4050. params.push('nav=1');
  4051. }
  4052. }
  4053. if (allPages && this.currentPage != null && this.pages != null &&
  4054. this.currentPage != this.pages[0])
  4055. {
  4056. params.push('page-id=' + this.currentPage.getId());
  4057. }
  4058. var data = '';
  4059. var addTitle = true;
  4060. if (url != null)
  4061. {
  4062. data = '#U' + encodeURIComponent(url);
  4063. }
  4064. else
  4065. {
  4066. var file = this.getCurrentFile();
  4067. // Fallback to non-public URL for Drive files
  4068. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  4069. {
  4070. data = '#' + file.getHash();
  4071. addTitle = false;
  4072. }
  4073. else
  4074. {
  4075. data = '#R' + encodeURIComponent((allPages) ?
  4076. this.getFileData(true, null, null, null, null, null, null, true) :
  4077. Graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  4078. }
  4079. }
  4080. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  4081. {
  4082. params.push('title=' + encodeURIComponent(file.getTitle()));
  4083. }
  4084. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || !(/.*\.draw\.io$/.test(window.location.hostname))) ?
  4085. EditorUi.drawHost : 'https://' + window.location.host + '/') +
  4086. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  4087. };
  4088. /**
  4089. *
  4090. */
  4091. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  4092. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  4093. {
  4094. var s = this.getBasenames();
  4095. var data = {};
  4096. if (linkColor != '' && linkColor != mxConstants.NONE)
  4097. {
  4098. data.highlight = linkColor;
  4099. }
  4100. if (linkTarget !== 'auto')
  4101. {
  4102. data.target = linkTarget;
  4103. }
  4104. if (!lightbox)
  4105. {
  4106. data.lightbox = false;
  4107. }
  4108. data.nav = this.editor.graph.foldingEnabled;
  4109. var zoom = parseInt(initialZoom);
  4110. if (!isNaN(zoom) && zoom != 100)
  4111. {
  4112. data.zoom = zoom / 100;
  4113. }
  4114. var tb = [];
  4115. if (allPages)
  4116. {
  4117. tb.push('pages');
  4118. data.resize = true;
  4119. if (this.pages != null && this.currentPage != null)
  4120. {
  4121. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  4122. }
  4123. }
  4124. if (zoomEnabled)
  4125. {
  4126. tb.push('zoom');
  4127. data.resize = true;
  4128. }
  4129. if (layers)
  4130. {
  4131. tb.push('layers');
  4132. }
  4133. if (tb.length > 0)
  4134. {
  4135. if (lightbox)
  4136. {
  4137. tb.push('lightbox');
  4138. }
  4139. data.toolbar = tb.join(' ');
  4140. }
  4141. if (editLink != null && editLink.length > 0)
  4142. {
  4143. data.edit = editLink;
  4144. }
  4145. if (publicUrl != null)
  4146. {
  4147. data.url = publicUrl;
  4148. }
  4149. else
  4150. {
  4151. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  4152. }
  4153. var value = '<div class="mxgraph" style="' +
  4154. ((fit) ? 'max-width:100%;' : '') +
  4155. ((tb != '') ? 'border:1px solid transparent;' : '') +
  4156. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  4157. var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
  4158. var s2 = (fetchParam.length > 0) ?
  4159. (((urlParams['dev'] == '1') ?
  4160. 'https://test.draw.io/embed2.js?dev=1' :
  4161. EditorUi.drawHost + '/embed2.js?')) + fetchParam :
  4162. (((urlParams['dev'] == '1') ?
  4163. 'https://test.draw.io/js/viewer.min.js' :
  4164. window.VIEWER_URL ? window.VIEWER_URL : EditorUi.drawHost + '/js/viewer.min.js'));
  4165. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  4166. fn(value, scr);
  4167. };
  4168. /**
  4169. *
  4170. */
  4171. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  4172. {
  4173. var div = document.createElement('div');
  4174. div.style.whiteSpace = 'nowrap';
  4175. var graph = this.editor.graph;
  4176. var hd = document.createElement('h3');
  4177. mxUtils.write(hd, mxResources.get('html'));
  4178. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4179. div.appendChild(hd);
  4180. var radioSection = document.createElement('div');
  4181. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  4182. var publicUrlRadio = document.createElement('input');
  4183. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  4184. publicUrlRadio.setAttribute('value', 'url');
  4185. publicUrlRadio.setAttribute('type', 'radio');
  4186. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  4187. var copyRadio = publicUrlRadio.cloneNode(true);
  4188. copyRadio.setAttribute('value', 'copy');
  4189. radioSection.appendChild(copyRadio);
  4190. var span = document.createElement('span');
  4191. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  4192. radioSection.appendChild(span);
  4193. mxUtils.br(radioSection);
  4194. radioSection.appendChild(publicUrlRadio);
  4195. var span = document.createElement('span');
  4196. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  4197. radioSection.appendChild(span);
  4198. var file = this.getCurrentFile();
  4199. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  4200. {
  4201. var testLink = document.createElement('a');
  4202. testLink.style.paddingLeft = '12px';
  4203. testLink.style.color = 'gray';
  4204. testLink.setAttribute('href', 'javascript:void(0);');
  4205. mxUtils.write(testLink, mxResources.get('share'));
  4206. radioSection.appendChild(testLink);
  4207. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4208. {
  4209. this.hideDialog();
  4210. this.drive.showPermissions(file.getId());
  4211. }));
  4212. }
  4213. copyRadio.setAttribute('checked', 'checked');
  4214. if (publicUrl == null)
  4215. {
  4216. publicUrlRadio.setAttribute('disabled', 'disabled');
  4217. }
  4218. div.appendChild(radioSection);
  4219. var linkSection = this.addLinkSection(div);
  4220. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  4221. mxUtils.write(div, ':');
  4222. var zoomInput = document.createElement('input');
  4223. zoomInput.setAttribute('type', 'text');
  4224. zoomInput.style.marginRight = '16px';
  4225. zoomInput.style.width = '60px';
  4226. zoomInput.style.marginLeft = '4px';
  4227. zoomInput.style.marginRight = '12px';
  4228. zoomInput.value = '100%';
  4229. div.appendChild(zoomInput);
  4230. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4231. var hasPages = this.pages != null && this.pages.length > 1;
  4232. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4233. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4234. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4235. var editSection = this.addEditButton(div, lightbox);
  4236. var edit = editSection.getEditInput();
  4237. edit.style.marginBottom = '16px';
  4238. mxEvent.addListener(lightbox, 'change', function()
  4239. {
  4240. if (lightbox.checked)
  4241. {
  4242. edit.removeAttribute('disabled');
  4243. }
  4244. else
  4245. {
  4246. edit.setAttribute('disabled', 'disabled');
  4247. }
  4248. if (edit.checked && lightbox.checked)
  4249. {
  4250. editSection.getEditSelect().removeAttribute('disabled');
  4251. }
  4252. else
  4253. {
  4254. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4255. }
  4256. });
  4257. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4258. {
  4259. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  4260. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  4261. editSection.getLink());
  4262. }), null, btnLabel, helpLink);
  4263. this.showDialog(dlg.container, 340, 384, true, true);
  4264. copyRadio.focus();
  4265. };
  4266. /**
  4267. *
  4268. */
  4269. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  4270. {
  4271. var div = document.createElement('div');
  4272. div.style.whiteSpace = 'nowrap';
  4273. var graph = this.editor.graph;
  4274. var hd = document.createElement('h3');
  4275. mxUtils.write(hd, title || mxResources.get('link'));
  4276. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4277. div.appendChild(hd);
  4278. var file = this.getCurrentFile();
  4279. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  4280. var dy = 0;
  4281. if (file != null && file.constructor == window.DriveFile && !hideShare)
  4282. {
  4283. dy = 80;
  4284. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  4285. var hintSection = document.createElement('div');
  4286. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  4287. var text = document.createElement('div');
  4288. text.style.whiteSpace = 'normal';
  4289. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  4290. hintSection.appendChild(text);
  4291. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  4292. {
  4293. this.drive.showPermissions(file.getId());
  4294. }));
  4295. shareBtn.style.marginTop = '12px';
  4296. shareBtn.className = 'geBtn';
  4297. hintSection.appendChild(shareBtn);
  4298. div.appendChild(hintSection);
  4299. var testLink = document.createElement('a');
  4300. testLink.style.paddingLeft = '12px';
  4301. testLink.style.color = 'gray';
  4302. testLink.style.fontSize = '11px';
  4303. testLink.setAttribute('href', 'javascript:void(0);');
  4304. mxUtils.write(testLink, mxResources.get('check'));
  4305. hintSection.appendChild(testLink);
  4306. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4307. {
  4308. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4309. {
  4310. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  4311. {
  4312. this.spinner.stop();
  4313. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  4314. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  4315. this.showDialog(dlg.container, 300, 80, true, false);
  4316. dlg.init();
  4317. }));
  4318. }
  4319. }));
  4320. }
  4321. var widthInput = null;
  4322. var heightInput = null;
  4323. if (width != null || height != null)
  4324. {
  4325. dy += 30;
  4326. mxUtils.write(div, mxResources.get('width') + ':');
  4327. widthInput = document.createElement('input');
  4328. widthInput.setAttribute('type', 'text');
  4329. widthInput.style.marginRight = '16px';
  4330. widthInput.style.width = '50px';
  4331. widthInput.style.marginLeft = '6px';
  4332. widthInput.style.marginRight = '16px';
  4333. widthInput.style.marginBottom = '10px';
  4334. widthInput.value = '100%';
  4335. div.appendChild(widthInput);
  4336. mxUtils.write(div, mxResources.get('height') + ':');
  4337. heightInput = document.createElement('input');
  4338. heightInput.setAttribute('type', 'text');
  4339. heightInput.style.width = '50px';
  4340. heightInput.style.marginLeft = '6px';
  4341. heightInput.style.marginBottom = '10px';
  4342. heightInput.value = height + 'px';
  4343. div.appendChild(heightInput);
  4344. mxUtils.br(div);
  4345. }
  4346. var linkSection = this.addLinkSection(div, showFrameOption);
  4347. var hasPages = this.pages != null && this.pages.length > 1;
  4348. var allPages = null;
  4349. if (file == null || file.constructor != window.DriveFile || hideShare)
  4350. {
  4351. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4352. }
  4353. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4354. var editSection = this.addEditButton(div, lightbox);
  4355. var edit = editSection.getEditInput();
  4356. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4357. layers.style.marginLeft = edit.style.marginLeft;
  4358. layers.style.marginBottom = '16px';
  4359. layers.style.marginTop = '8px';
  4360. mxEvent.addListener(lightbox, 'change', function()
  4361. {
  4362. if (lightbox.checked)
  4363. {
  4364. layers.removeAttribute('disabled');
  4365. edit.removeAttribute('disabled');
  4366. }
  4367. else
  4368. {
  4369. layers.setAttribute('disabled', 'disabled');
  4370. edit.setAttribute('disabled', 'disabled');
  4371. }
  4372. if (edit.checked && lightbox.checked)
  4373. {
  4374. editSection.getEditSelect().removeAttribute('disabled');
  4375. }
  4376. else
  4377. {
  4378. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4379. }
  4380. });
  4381. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4382. {
  4383. fn(linkSection.getTarget(), linkSection.getColor(),
  4384. (allPages == null) ? true : allPages.checked,
  4385. lightbox.checked, editSection.getLink(),
  4386. layers.checked, (widthInput != null) ? widthInput.value : null,
  4387. (heightInput != null) ? heightInput.value : null);
  4388. }), null, mxResources.get('create'), helpLink);
  4389. this.showDialog(dlg.container, 340, 254 + dy, true, true);
  4390. if (widthInput != null)
  4391. {
  4392. widthInput.focus();
  4393. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4394. {
  4395. widthInput.select();
  4396. }
  4397. else
  4398. {
  4399. document.execCommand('selectAll', false, null);
  4400. }
  4401. }
  4402. else
  4403. {
  4404. linkSection.focus();
  4405. }
  4406. };
  4407. /**
  4408. *
  4409. */
  4410. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  4411. {
  4412. var div = document.createElement('div');
  4413. div.style.whiteSpace = 'nowrap';
  4414. var hd = document.createElement('h3');
  4415. mxUtils.write(hd, mxResources.get('image'));
  4416. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4417. div.appendChild(hd);
  4418. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  4419. this.editor.graph.isSelectionEmpty());
  4420. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  4421. var graph = this.editor.graph;
  4422. var transparent = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('transparentBackground'),
  4423. graph.background == mxConstants.NONE || graph.background == null);
  4424. if (transparent != null)
  4425. {
  4426. transparent.style.marginBottom = '16px';
  4427. }
  4428. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4429. {
  4430. callback(!selection.checked, (include != null) ? include.checked : false,
  4431. (transparent != null) ? transparent.checked : false);
  4432. }), null, btnLabel, helpLink);
  4433. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 186, true, true);
  4434. };
  4435. /**
  4436. *
  4437. */
  4438. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  4439. cropOption, defaultInclude, format)
  4440. {
  4441. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  4442. var div = document.createElement('div');
  4443. div.style.whiteSpace = 'nowrap';
  4444. var graph = this.editor.graph;
  4445. var height = (format == 'jpeg') ? 196 : 300;
  4446. var hd = document.createElement('h3');
  4447. mxUtils.write(hd, title);
  4448. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  4449. div.appendChild(hd);
  4450. mxUtils.write(div, mxResources.get('zoom') + ':');
  4451. var zoomInput = document.createElement('input');
  4452. zoomInput.setAttribute('type', 'text');
  4453. zoomInput.style.marginRight = '16px';
  4454. zoomInput.style.width = '60px';
  4455. zoomInput.style.marginLeft = '4px';
  4456. zoomInput.style.marginRight = '12px';
  4457. zoomInput.value = this.lastExportZoom || '100%';
  4458. div.appendChild(zoomInput);
  4459. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  4460. var borderInput = document.createElement('input');
  4461. borderInput.setAttribute('type', 'text');
  4462. borderInput.style.marginRight = '16px';
  4463. borderInput.style.width = '60px';
  4464. borderInput.style.marginLeft = '4px';
  4465. borderInput.value = this.lastExportBorder || '0';
  4466. div.appendChild(borderInput);
  4467. mxUtils.br(div);
  4468. var defaultTransparent = false; /*graph.background == mxConstants.NONE || graph.background == null*/;
  4469. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  4470. defaultTransparent, null, null, format != 'jpeg');
  4471. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  4472. false, graph.isSelectionEmpty());
  4473. var cb6 = document.createElement('input');
  4474. cb6.style.marginTop = '16px';
  4475. cb6.style.marginRight = '8px';
  4476. cb6.style.marginLeft = '24px';
  4477. cb6.setAttribute('disabled', 'disabled');
  4478. cb6.setAttribute('type', 'checkbox');
  4479. if (cropOption)
  4480. {
  4481. div.appendChild(cb6);
  4482. mxUtils.write(div, mxResources.get('crop'));
  4483. mxUtils.br(div);
  4484. height += 26;
  4485. mxEvent.addListener(selection, 'change', function()
  4486. {
  4487. if (selection.checked)
  4488. {
  4489. cb6.removeAttribute('disabled');
  4490. }
  4491. else
  4492. {
  4493. cb6.setAttribute('disabled', 'disabled');
  4494. }
  4495. });
  4496. }
  4497. if (!graph.isSelectionEmpty())
  4498. {
  4499. cb6.setAttribute('checked', 'checked');
  4500. cb6.defaultChecked = true;
  4501. }
  4502. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  4503. var cb5 = document.createElement('input');
  4504. cb5.style.marginTop = '16px';
  4505. cb5.style.marginRight = '8px';
  4506. cb5.setAttribute('type', 'checkbox');
  4507. if (this.isOffline() || !this.canvasSupported)
  4508. {
  4509. cb5.setAttribute('disabled', 'disabled');
  4510. }
  4511. if (embedOption)
  4512. {
  4513. div.appendChild(cb5);
  4514. mxUtils.write(div, mxResources.get('embedImages'));
  4515. mxUtils.br(div);
  4516. height += 26;
  4517. }
  4518. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  4519. var hasPages = this.pages != null && this.pages.length > 1;
  4520. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  4521. allPages.style.marginLeft = '24px';
  4522. allPages.style.marginBottom = '16px';
  4523. if (!hasPages)
  4524. {
  4525. allPages.style.display = 'none';
  4526. }
  4527. mxEvent.addListener(include, 'change', function()
  4528. {
  4529. if (include.checked && hasPages)
  4530. {
  4531. allPages.removeAttribute('disabled');
  4532. }
  4533. else
  4534. {
  4535. allPages.setAttribute('disabled', 'disabled');
  4536. }
  4537. });
  4538. if (!defaultInclude || !hasPages)
  4539. {
  4540. allPages.setAttribute('disabled', 'disabled');
  4541. }
  4542. var linkSelect = document.createElement('select');
  4543. linkSelect.style.maxWidth = '260px';
  4544. linkSelect.style.marginLeft = '8px';
  4545. linkSelect.style.marginRight = '10px';
  4546. linkSelect.className = 'geBtn';
  4547. var autoOption = document.createElement('option');
  4548. autoOption.setAttribute('value', 'auto');
  4549. mxUtils.write(autoOption, mxResources.get('automatic'));
  4550. linkSelect.appendChild(autoOption);
  4551. var blankOption = document.createElement('option');
  4552. blankOption.setAttribute('value', 'blank');
  4553. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  4554. linkSelect.appendChild(blankOption);
  4555. var selfOption = document.createElement('option');
  4556. selfOption.setAttribute('value', 'self');
  4557. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  4558. linkSelect.appendChild(selfOption);
  4559. if (format == 'svg')
  4560. {
  4561. mxUtils.write(div, mxResources.get('links') + ':');
  4562. div.appendChild(linkSelect);
  4563. mxUtils.br(div);
  4564. mxUtils.br(div);
  4565. height += 26;
  4566. }
  4567. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4568. {
  4569. this.lastExportBorder = borderInput.value;
  4570. this.lastExportZoom = zoomInput.value;
  4571. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  4572. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked,
  4573. linkSelect.value);
  4574. }), null, btnLabel, helpLink);
  4575. this.showDialog(dlg.container, 340, height, true, true);
  4576. zoomInput.focus();
  4577. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4578. {
  4579. zoomInput.select();
  4580. }
  4581. else
  4582. {
  4583. document.execCommand('selectAll', false, null);
  4584. }
  4585. };
  4586. /**
  4587. *
  4588. */
  4589. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  4590. {
  4591. var div = document.createElement('div');
  4592. div.style.whiteSpace = 'nowrap';
  4593. var graph = this.editor.graph;
  4594. if (title != null)
  4595. {
  4596. var hd = document.createElement('h3');
  4597. mxUtils.write(hd, title);
  4598. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4599. div.appendChild(hd);
  4600. }
  4601. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4602. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  4603. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  4604. var image = this.addCheckbox(div, imageLabel);
  4605. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4606. var editSection = this.addEditButton(div, lightbox);
  4607. var edit = editSection.getEditInput();
  4608. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  4609. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  4610. layers.style.marginLeft = edit.style.marginLeft;
  4611. layers.style.marginBottom = '12px';
  4612. layers.style.marginTop = '8px';
  4613. mxEvent.addListener(lightbox, 'change', function()
  4614. {
  4615. if (lightbox.checked)
  4616. {
  4617. if (hasLayers)
  4618. {
  4619. layers.removeAttribute('disabled');
  4620. }
  4621. edit.removeAttribute('disabled');
  4622. }
  4623. else
  4624. {
  4625. layers.setAttribute('disabled', 'disabled');
  4626. edit.setAttribute('disabled', 'disabled');
  4627. }
  4628. if (edit.checked && lightbox.checked)
  4629. {
  4630. editSection.getEditSelect().removeAttribute('disabled');
  4631. }
  4632. else
  4633. {
  4634. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4635. }
  4636. });
  4637. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4638. {
  4639. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  4640. editSection.getLink(), layers.checked);
  4641. }), null, mxResources.get('embed'), helpLink);
  4642. this.showDialog(dlg.container, 280, 280, true, true);
  4643. };
  4644. /**
  4645. *
  4646. */
  4647. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  4648. {
  4649. var bounds = this.editor.graph.getGraphBounds();
  4650. function doUpdate(dataUri)
  4651. {
  4652. var onclick = ' ';
  4653. var css = '';
  4654. // Adds double click handling
  4655. if (lightbox)
  4656. {
  4657. // KNOWN: Message passing does not seem to work in IE11
  4658. 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(" +
  4659. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4660. ((edit) ? "&edit=_blank" : "") +
  4661. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4662. css += 'cursor:pointer;';
  4663. }
  4664. if (fit)
  4665. {
  4666. css += 'max-width:100%;';
  4667. }
  4668. var atts = '';
  4669. if (retina)
  4670. {
  4671. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  4672. }
  4673. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4674. };
  4675. if (this.isExportToCanvas())
  4676. {
  4677. var scale = 1;
  4678. var ignoreSelection = true;
  4679. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4680. {
  4681. var xml = (lightbox) ? this.getFileData(true) : null;
  4682. var data = this.createImageDataUri(canvas, xml, 'png');
  4683. doUpdate(data);
  4684. }), null, null, null, mxUtils.bind(this, function(e)
  4685. {
  4686. err({message: mxResources.get('unknownError')});
  4687. }), null, true, (retina) ? 2 : 1, null, shadow);
  4688. }
  4689. else
  4690. {
  4691. var data = this.getFileData(true);
  4692. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  4693. {
  4694. var size = '';
  4695. if (retina)
  4696. {
  4697. size = '&w=' + Math.round(2 * bounds.width) +
  4698. '&h=' + Math.round(2 * bounds.height);
  4699. }
  4700. var embed = (lightbox) ? '1' : '0';
  4701. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  4702. '&base64=1&embedXml=' + embed + size + '&xml=' +
  4703. encodeURIComponent(data));
  4704. // LATER: Updates on each change, add a delay
  4705. req.send(mxUtils.bind(this, function()
  4706. {
  4707. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4708. {
  4709. // Fixes possible "incorrect function" for select() on
  4710. // DOM node which is no longer in document with IE11
  4711. doUpdate('data:image/png;base64,' + req.getText());
  4712. }
  4713. else
  4714. {
  4715. err({message: mxResources.get('unknownError')});
  4716. }
  4717. }));
  4718. }
  4719. else
  4720. {
  4721. err({message: mxResources.get('drawingTooLarge')});
  4722. }
  4723. }
  4724. };
  4725. /**
  4726. *
  4727. */
  4728. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  4729. {
  4730. var svgRoot = this.editor.graph.getSvg();
  4731. // Keeps hashtag links on same page
  4732. var links = svgRoot.getElementsByTagName('a');
  4733. if (links != null)
  4734. {
  4735. for (var i = 0; i < links.length; i++)
  4736. {
  4737. var href = links[i].getAttribute('href');
  4738. if (href != null && href.charAt(0) == '#' &&
  4739. links[i].getAttribute('target') == '_blank')
  4740. {
  4741. links[i].removeAttribute('target');
  4742. }
  4743. }
  4744. }
  4745. if (lightbox)
  4746. {
  4747. svgRoot.setAttribute('content', this.getFileData(true));
  4748. }
  4749. // Adds shadow filter
  4750. if (shadow)
  4751. {
  4752. this.editor.graph.addSvgShadow(svgRoot);
  4753. }
  4754. // SVG inside image tag
  4755. if (image)
  4756. {
  4757. var onclick = ' ';
  4758. var css = '';
  4759. // Adds double click handling
  4760. if (lightbox)
  4761. {
  4762. // KNOWN: Message passing does not seem to work in IE11
  4763. 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(" +
  4764. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4765. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4766. css += 'cursor:pointer;';
  4767. }
  4768. if (fit)
  4769. {
  4770. css += 'max-width:100%;';
  4771. }
  4772. // Images inside IMG don't seem to work so embed them all
  4773. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  4774. {
  4775. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  4776. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4777. }));
  4778. }
  4779. else
  4780. {
  4781. var css = '';
  4782. // Adds double click handling
  4783. if (lightbox)
  4784. {
  4785. // KNOWN: Message passing does not seem to work in IE11
  4786. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  4787. // Ignores link events
  4788. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  4789. // Focus existing lightbox
  4790. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  4791. // Message handling
  4792. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  4793. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  4794. "window.addEventListener('message',r);" +
  4795. // Opens lightbox window
  4796. "svg.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4797. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  4798. svgRoot.setAttribute('onclick', js);
  4799. css += 'cursor:pointer;';
  4800. }
  4801. // Adds responsive size
  4802. if (fit)
  4803. {
  4804. var w = parseInt(svgRoot.getAttribute('width'));
  4805. var h = parseInt(svgRoot.getAttribute('height'));
  4806. svgRoot.setAttribute('viewBox', '-0.5 -0.5 ' + w + ' ' + h);
  4807. css += 'max-width:100%;max-height:' + h + 'px;';
  4808. svgRoot.removeAttribute('height');
  4809. }
  4810. if (css != '')
  4811. {
  4812. svgRoot.setAttribute('style', css);
  4813. }
  4814. fn(mxUtils.getXml(svgRoot));
  4815. }
  4816. };
  4817. /**
  4818. * Translates this point by the given vector.
  4819. *
  4820. * @param {number} dx X-coordinate of the translation.
  4821. * @param {number} dy Y-coordinate of the translation.
  4822. */
  4823. EditorUi.prototype.timeSince = function(date)
  4824. {
  4825. var seconds = Math.floor((new Date() - date) / 1000);
  4826. var interval = Math.floor(seconds / 31536000);
  4827. if (interval > 1)
  4828. {
  4829. return interval + ' ' + mxResources.get('years');
  4830. }
  4831. interval = Math.floor(seconds / 2592000);
  4832. if (interval > 1)
  4833. {
  4834. return interval + ' ' + mxResources.get('months');
  4835. }
  4836. interval = Math.floor(seconds / 86400);
  4837. if (interval > 1)
  4838. {
  4839. return interval + ' ' + mxResources.get('days');
  4840. }
  4841. interval = Math.floor(seconds / 3600);
  4842. if (interval > 1)
  4843. {
  4844. return interval + ' ' + mxResources.get('hours');
  4845. }
  4846. interval = Math.floor(seconds / 60);
  4847. if (interval > 1)
  4848. {
  4849. return interval + ' ' + mxResources.get('minutes');
  4850. }
  4851. if (interval == 1)
  4852. {
  4853. return interval + ' ' + mxResources.get('minute');
  4854. }
  4855. return null;
  4856. };
  4857. /**
  4858. * Converts math in the given SVG
  4859. */
  4860. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  4861. {
  4862. if (graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  4863. {
  4864. // Temporarily attaches to DOM for rendering
  4865. // FIXME: If adding svgRoot to body, the text
  4866. // value of the math is appended, if not
  4867. // added to DOM then LaTeX does not work.
  4868. // This must be fixed to enable client-side export
  4869. // if math is enabled.
  4870. // document.body.appendChild(svgRoot);
  4871. Editor.MathJaxRender(svgRoot);
  4872. window.setTimeout(mxUtils.bind(this, function()
  4873. {
  4874. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  4875. {
  4876. // Removes from DOM
  4877. // svgRoot.parentNode.removeChild(svgRoot);
  4878. callback();
  4879. }));
  4880. }), 0);
  4881. }
  4882. else
  4883. {
  4884. callback();
  4885. }
  4886. };
  4887. /**
  4888. *
  4889. */
  4890. EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
  4891. {
  4892. if (node != null)
  4893. {
  4894. var diagramNode = null;
  4895. if (node.nodeName == 'diagram')
  4896. {
  4897. diagramNode = node;
  4898. }
  4899. else if (node.nodeName == 'mxfile')
  4900. {
  4901. var diagrams = node.getElementsByTagName('diagram');
  4902. if (diagrams.length > 0)
  4903. {
  4904. diagramNode = diagrams[0];
  4905. var graphGetGlobalVariable = graph.getGlobalVariable;
  4906. graph.getGlobalVariable = function(name)
  4907. {
  4908. if (name == 'page')
  4909. {
  4910. return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
  4911. }
  4912. else if (name == 'pagenumber')
  4913. {
  4914. return 1;
  4915. }
  4916. return graphGetGlobalVariable.apply(this, arguments);
  4917. };
  4918. }
  4919. }
  4920. if (diagramNode != null)
  4921. {
  4922. var tmp = Graph.decompress(mxUtils.getTextContent(diagramNode));
  4923. if (tmp != null && tmp.length > 0)
  4924. {
  4925. node = mxUtils.parseXml(tmp).documentElement;
  4926. }
  4927. }
  4928. }
  4929. // Hack to decode XML into temp graph via editor
  4930. var prev = this.editor.graph;
  4931. try
  4932. {
  4933. this.editor.graph = graph;
  4934. this.editor.setGraphXml(node);
  4935. }
  4936. catch (e)
  4937. {
  4938. // ignore
  4939. }
  4940. finally
  4941. {
  4942. this.editor.graph = prev;
  4943. }
  4944. return node;
  4945. };
  4946. /**
  4947. *
  4948. */
  4949. EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData)
  4950. {
  4951. try
  4952. {
  4953. var graph = this.editor.graph;
  4954. var diagramData = null;
  4955. // Exports PNG for given optional data
  4956. if (optionalData != null && optionalData.length > 0)
  4957. {
  4958. graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
  4959. document.body.appendChild(graph.container);
  4960. this.decodeNodeIntoGraph(this.editor.extractGraphModel(
  4961. mxUtils.parseXml(optionalData).documentElement, true), graph);
  4962. diagramData = optionalData;
  4963. }
  4964. // Exports PNG for first page while other page is showing
  4965. else if (this.pages != null && this.currentPage != this.pages[0])
  4966. {
  4967. graph = this.createTemporaryGraph(graph.getStylesheet());
  4968. var graphGetGlobalVariable = graph.getGlobalVariable;
  4969. var page = this.pages[0];
  4970. graph.getGlobalVariable = function(name)
  4971. {
  4972. if (name == 'page')
  4973. {
  4974. return page.getName();
  4975. }
  4976. else if (name == 'pagenumber')
  4977. {
  4978. return 1;
  4979. }
  4980. return graphGetGlobalVariable.apply(this, arguments);
  4981. };
  4982. document.body.appendChild(graph.container);
  4983. graph.model.setRoot(page.root);
  4984. }
  4985. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4986. {
  4987. try
  4988. {
  4989. if (diagramData == null)
  4990. {
  4991. diagramData = this.getFileData(true);
  4992. }
  4993. var data = canvas.toDataURL('image/png');
  4994. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel',
  4995. atob(Graph.compress(diagramData)));
  4996. success(data.substring(data.lastIndexOf(',') + 1));
  4997. // Removes temporary graph from DOM
  4998. if (graph != this.editor.graph)
  4999. {
  5000. graph.container.parentNode.removeChild(graph.container);
  5001. }
  5002. }
  5003. catch (e)
  5004. {
  5005. if (error != null)
  5006. {
  5007. error(e);
  5008. }
  5009. }
  5010. }), null, null, null, mxUtils.bind(this, function(e)
  5011. {
  5012. if (error != null)
  5013. {
  5014. error(e);
  5015. }
  5016. }), null, null, null, null, graph.shadowVisible, null, graph);
  5017. }
  5018. catch (e)
  5019. {
  5020. if (error != null)
  5021. {
  5022. error(e);
  5023. }
  5024. }
  5025. }
  5026. /**
  5027. * Returns the SVG of the diagram with embedded XML. If a callback function is
  5028. * used, the images are converted to data URIs.
  5029. */
  5030. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  5031. {
  5032. var bg = graph.background;
  5033. if (bg == mxConstants.NONE)
  5034. {
  5035. bg = null;
  5036. }
  5037. // Sets or disables alternate text for foreignObjects. Disabling is needed
  5038. // because PhantomJS seems to ignore switch statements and paint all text.
  5039. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  5040. if (graph.shadowVisible)
  5041. {
  5042. graph.addSvgShadow(svgRoot);
  5043. }
  5044. if (xml != null)
  5045. {
  5046. svgRoot.setAttribute('content', xml);
  5047. }
  5048. if (url != null)
  5049. {
  5050. svgRoot.setAttribute('resource', url);
  5051. }
  5052. // LATER: Click on SVG content to start editing
  5053. // if (redirect != null)
  5054. // {
  5055. // // TODO: Ignore anchor tag source for click event
  5056. // svgRoot.setAttribute('style', 'cursor:pointer;');
  5057. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  5058. // }
  5059. if (callback != null)
  5060. {
  5061. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  5062. {
  5063. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5064. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5065. mxUtils.getXml(svgRoot));
  5066. }));
  5067. }
  5068. else
  5069. {
  5070. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5071. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5072. mxUtils.getXml(svgRoot);
  5073. }
  5074. };
  5075. /**
  5076. *
  5077. */
  5078. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  5079. {
  5080. format = (format != null) ? format : 'png';
  5081. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  5082. {
  5083. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  5084. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  5085. // Caches images
  5086. if (this.thumbImageCache == null)
  5087. {
  5088. this.thumbImageCache = new Object();
  5089. }
  5090. try
  5091. {
  5092. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  5093. {
  5094. this.spinner.stop();
  5095. try
  5096. {
  5097. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  5098. null, null, ignoreSelection, currentPage) : null, format);
  5099. }
  5100. catch (e)
  5101. {
  5102. // Fallback to server-side image export
  5103. if (e.message == 'Invalid image')
  5104. {
  5105. this.downloadFile(format);
  5106. }
  5107. else
  5108. {
  5109. this.handleError(e);
  5110. }
  5111. }
  5112. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  5113. {
  5114. this.spinner.stop();
  5115. this.handleError(e);
  5116. }), null, ignoreSelection, scale || 1, transparentBackground,
  5117. addShadow, null, null, border, noCrop);
  5118. }
  5119. catch (e)
  5120. {
  5121. this.spinner.stop();
  5122. this.handleError(e);
  5123. }
  5124. }
  5125. };
  5126. /**
  5127. * For the fontCSS to be applied when rendering images on canvas, the actual
  5128. * font data must be made available via a data URI encoding of the file.
  5129. */
  5130. EditorUi.prototype.loadFonts = function(then)
  5131. {
  5132. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  5133. {
  5134. var parts = this.editor.fontCss.split('url(');
  5135. var waiting = 0;
  5136. var fonts = {};
  5137. // Strips leading and trailing quotes and spaces
  5138. function trimString(str)
  5139. {
  5140. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  5141. };
  5142. var finish = mxUtils.bind(this, function()
  5143. {
  5144. if (waiting == 0)
  5145. {
  5146. // Constructs string
  5147. var result = [parts[0]];
  5148. for (var j = 1; j < parts.length; j++)
  5149. {
  5150. var idx = parts[j].indexOf(')');
  5151. result.push('url("');
  5152. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  5153. result.push('"' + parts[j].substring(idx));
  5154. }
  5155. this.editor.resolvedFontCss = result.join('');
  5156. then();
  5157. }
  5158. });
  5159. if (parts.length > 0)
  5160. {
  5161. for (var i = 1; i < parts.length; i++)
  5162. {
  5163. var idx = parts[i].indexOf(')');
  5164. var format = null;
  5165. // Checks if there is a format directive
  5166. var fmtIdx = parts[i].indexOf('format(', idx);
  5167. if (fmtIdx > 0)
  5168. {
  5169. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  5170. }
  5171. (mxUtils.bind(this, function(url)
  5172. {
  5173. if (fonts[url] == null)
  5174. {
  5175. // Mark font es being fetched and fetch it
  5176. fonts[url] = url;
  5177. waiting++;
  5178. var mime = 'application/x-font-ttf';
  5179. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  5180. if (format == 'svg' || /(\.svg)($|\?)/i.test(url))
  5181. {
  5182. mime = 'image/svg+xml';
  5183. }
  5184. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url))
  5185. {
  5186. mime = 'application/x-font-opentype';
  5187. }
  5188. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url))
  5189. {
  5190. mime = 'application/font-woff';
  5191. }
  5192. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url))
  5193. {
  5194. mime = 'application/font-woff2';
  5195. }
  5196. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url))
  5197. {
  5198. mime = 'application/vnd.ms-fontobject';
  5199. }
  5200. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url))
  5201. {
  5202. mime = 'application/font-sfnt';
  5203. }
  5204. var realUrl = url;
  5205. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  5206. {
  5207. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  5208. }
  5209. // LATER: Remove cache-control header
  5210. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  5211. {
  5212. fonts[url] = uri;
  5213. waiting--;
  5214. finish();
  5215. }), mxUtils.bind(this, function(err)
  5216. {
  5217. // LATER: handle error
  5218. waiting--;
  5219. finish();
  5220. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  5221. }
  5222. }))(trimString(parts[i].substring(0, idx)), format);
  5223. }
  5224. }
  5225. }
  5226. else
  5227. {
  5228. then();
  5229. }
  5230. };
  5231. /**
  5232. *
  5233. */
  5234. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  5235. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  5236. {
  5237. limitHeight = (limitHeight != null) ? limitHeight : true;
  5238. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  5239. graph = (graph != null) ? graph : this.editor.graph;
  5240. border = (border != null) ? border : 0;
  5241. var bg = (transparentBackground) ? null : graph.background;
  5242. if (bg == mxConstants.NONE)
  5243. {
  5244. bg = null;
  5245. }
  5246. if (bg == null)
  5247. {
  5248. bg = background;
  5249. }
  5250. // Handles special case where background is null but transparent is false
  5251. if (bg == null && transparentBackground == false)
  5252. {
  5253. bg = '#ffffff';
  5254. }
  5255. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection, null, null, null, addShadow),
  5256. mxUtils.bind(this, function(svgRoot)
  5257. {
  5258. var img = new Image();
  5259. img.onload = mxUtils.bind(this, function()
  5260. {
  5261. try
  5262. {
  5263. var canvas = document.createElement('canvas');
  5264. var w = parseInt(svgRoot.getAttribute('width'));
  5265. var h = parseInt(svgRoot.getAttribute('height'));
  5266. scale = (scale != null) ? scale : 1;
  5267. if (width != null)
  5268. {
  5269. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  5270. }
  5271. w = Math.ceil(scale * w) + 2 * border;
  5272. h = Math.ceil(scale * h) + 2 * border;
  5273. canvas.setAttribute('width', w);
  5274. canvas.setAttribute('height', h);
  5275. var ctx = canvas.getContext('2d');
  5276. if (bg != null)
  5277. {
  5278. ctx.beginPath();
  5279. ctx.rect(0, 0, w, h);
  5280. ctx.fillStyle = bg;
  5281. ctx.fill();
  5282. }
  5283. ctx.scale(scale, scale);
  5284. // Workaround for broken data URI images in Safari on first export
  5285. if (mxClient.IS_SF)
  5286. {
  5287. window.setTimeout(function()
  5288. {
  5289. ctx.drawImage(img, border / scale, border / scale);
  5290. callback(canvas);
  5291. }, 0);
  5292. }
  5293. else
  5294. {
  5295. ctx.drawImage(img, border / scale, border / scale);
  5296. callback(canvas);
  5297. }
  5298. }
  5299. catch (e)
  5300. {
  5301. if (error != null)
  5302. {
  5303. error(e);
  5304. }
  5305. }
  5306. });
  5307. img.onerror = function(e)
  5308. {
  5309. //console.log('img', e, img.src);
  5310. if (error != null)
  5311. {
  5312. error(e);
  5313. }
  5314. };
  5315. try
  5316. {
  5317. if (addShadow)
  5318. {
  5319. this.editor.graph.addSvgShadow(svgRoot);
  5320. }
  5321. var done = mxUtils.bind(this, function()
  5322. {
  5323. if (this.editor.resolvedFontCss != null)
  5324. {
  5325. var st = document.createElement('style');
  5326. st.setAttribute('type', 'text/css');
  5327. st.innerHTML = this.editor.resolvedFontCss;
  5328. // Must be in defs section for FF to work
  5329. var defs = svgRoot.getElementsByTagName('defs');
  5330. defs[0].appendChild(st);
  5331. }
  5332. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  5333. {
  5334. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5335. }));
  5336. });
  5337. this.loadFonts(done);
  5338. }
  5339. catch (e)
  5340. {
  5341. //console.log('src', e, img.src);
  5342. if (error != null)
  5343. {
  5344. error(e);
  5345. }
  5346. }
  5347. }), imageCache, converter);
  5348. };
  5349. /**
  5350. * Converts all images in the SVG output to data URIs for immediate rendering
  5351. */
  5352. EditorUi.prototype.createImageUrlConverter = function()
  5353. {
  5354. var converter = new mxUrlConverter();
  5355. converter.updateBaseUrl();
  5356. // Extends convert to avoid CORS using an image proxy server where needed
  5357. var convert = converter.convert;
  5358. var self = this;
  5359. converter.convert = function(src)
  5360. {
  5361. if (src != null)
  5362. {
  5363. var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  5364. if (remote && !navigator.onLine)
  5365. {
  5366. src = self.svgBrokenImage.src;
  5367. }
  5368. else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  5369. (!self.crossOriginImages || !self.editor.isCorsEnabledForUrl(src)))
  5370. {
  5371. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  5372. }
  5373. else if (src.substring(0, 19) != 'chrome-extension://')
  5374. {
  5375. src = convert.apply(this, arguments);
  5376. }
  5377. }
  5378. return src;
  5379. };
  5380. return converter;
  5381. };
  5382. /**
  5383. * Converts all images in the SVG output to data URIs for immediate rendering
  5384. */
  5385. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  5386. {
  5387. // Converts images to data URLs for immediate painting
  5388. if (converter == null)
  5389. {
  5390. converter = this.createImageUrlConverter();
  5391. }
  5392. // Barrier for asynchronous image loading
  5393. var counter = 0;
  5394. function inc()
  5395. {
  5396. counter++;
  5397. };
  5398. function dec()
  5399. {
  5400. counter--;
  5401. if (counter == 0)
  5402. {
  5403. callback(svgRoot);
  5404. }
  5405. };
  5406. var cache = imageCache || new Object();
  5407. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  5408. {
  5409. var images = svgRoot.getElementsByTagName(tagName);
  5410. for (var i = 0; i < images.length; i++)
  5411. {
  5412. (mxUtils.bind(this, function(img)
  5413. {
  5414. var src = converter.convert(img.getAttribute(srcAttr));
  5415. // Data URIs are pass-through
  5416. if (src != null && src.substring(0, 5) != 'data:')
  5417. {
  5418. var tmp = cache[src];
  5419. if (tmp == null)
  5420. {
  5421. inc();
  5422. this.convertImageToDataUri(src, function(uri)
  5423. {
  5424. if (uri != null)
  5425. {
  5426. cache[src] = uri;
  5427. img.setAttribute(srcAttr, uri);
  5428. }
  5429. dec();
  5430. });
  5431. }
  5432. else
  5433. {
  5434. img.setAttribute(srcAttr, tmp);
  5435. }
  5436. }
  5437. else if (src != null)
  5438. {
  5439. img.setAttribute(srcAttr, src);
  5440. }
  5441. }))(images[i]);
  5442. }
  5443. });
  5444. // Converts all known image tags in output
  5445. // LATER: Add support for images in CSS
  5446. convertImages('image', 'xlink:href');
  5447. convertImages('img', 'src');
  5448. // All from cache or no images
  5449. if (counter == 0)
  5450. {
  5451. callback(svgRoot);
  5452. }
  5453. };
  5454. /**
  5455. * Checks if the client is authorized and calls the next step.
  5456. */
  5457. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix, noBinary)
  5458. {
  5459. try
  5460. {
  5461. var binary = !noBinary && (forceBinary || /(\.png)($|\?)/i.test(url) ||
  5462. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url));
  5463. retry = (retry != null) ? retry : true;
  5464. var fn = mxUtils.bind(this, function()
  5465. {
  5466. mxUtils.get(url, mxUtils.bind(this, function(req)
  5467. {
  5468. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  5469. {
  5470. if (success != null)
  5471. {
  5472. var data = req.getText();
  5473. // Returns PNG as base64 encoded data URI
  5474. if (binary)
  5475. {
  5476. // NOTE: This requires BinaryToArray VB script in the page
  5477. if ((document.documentMode == 9 || document.documentMode == 10) &&
  5478. typeof window.mxUtilsBinaryToArray !== 'undefined')
  5479. {
  5480. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  5481. var tmp = new Array(bin.length);
  5482. for (var i = 0; i < bin.length; i++)
  5483. {
  5484. tmp[i] = String.fromCharCode(bin[i]);
  5485. }
  5486. data = tmp.join('');
  5487. }
  5488. // LATER: Could be JPG but modern browsers
  5489. // ignore the mime type in the data URI
  5490. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  5491. data = dataUriPrefix + this.base64Encode(data);
  5492. }
  5493. success(data);
  5494. }
  5495. }
  5496. else if (error != null)
  5497. {
  5498. error({message: mxResources.get('error') + ' ' + req.getStatus()}, req);
  5499. }
  5500. }), function(req)
  5501. {
  5502. if (error != null)
  5503. {
  5504. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  5505. }
  5506. }, binary, this.timeout, function()
  5507. {
  5508. if (retry && error != null)
  5509. {
  5510. error({code: App.ERROR_TIMEOUT, retry: fn});
  5511. }
  5512. });
  5513. });
  5514. fn();
  5515. }
  5516. catch (e)
  5517. {
  5518. if (error != null)
  5519. {
  5520. error(e);
  5521. }
  5522. }
  5523. };
  5524. /**
  5525. * Returns true if the given URL is known to have CORS headers.
  5526. */
  5527. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  5528. {
  5529. return this.editor.isCorsEnabledForUrl(url);
  5530. };
  5531. /**
  5532. * Translates this point by the given vector.
  5533. *
  5534. * @param {number} dx X-coordinate of the translation.
  5535. * @param {number} dy Y-coordinate of the translation.
  5536. */
  5537. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  5538. {
  5539. if (/(\.svg)$/i.test(url))
  5540. {
  5541. mxUtils.get(url, mxUtils.bind(this, function(req)
  5542. {
  5543. callback(this.createSvgDataUri(req.getText()));
  5544. }),
  5545. function()
  5546. {
  5547. callback(this.svgBrokenImage.src);
  5548. });
  5549. }
  5550. else
  5551. {
  5552. var img = new Image();
  5553. var self = this;
  5554. if (this.crossOriginImages)
  5555. {
  5556. img.crossOrigin = 'anonymous';
  5557. }
  5558. img.onload = function()
  5559. {
  5560. var canvas = document.createElement('canvas');
  5561. var ctx = canvas.getContext('2d');
  5562. canvas.height = img.height;
  5563. canvas.width = img.width;
  5564. ctx.drawImage(img, 0, 0);
  5565. try
  5566. {
  5567. callback(canvas.toDataURL());
  5568. }
  5569. catch (e)
  5570. {
  5571. callback(self.svgBrokenImage.src);
  5572. }
  5573. };
  5574. img.onerror = function()
  5575. {
  5576. callback(self.svgBrokenImage.src);
  5577. };
  5578. img.src = url;
  5579. }
  5580. };
  5581. /**
  5582. * Handling drag and drop and import.
  5583. */
  5584. /**
  5585. * Imports the given XML into the existing diagram.
  5586. */
  5587. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  5588. {
  5589. dx = (dx != null) ? dx : 0;
  5590. dy = (dy != null) ? dy : 0;
  5591. var cells = []
  5592. try
  5593. {
  5594. var graph = this.editor.graph;
  5595. if (xml != null && xml.length > 0)
  5596. {
  5597. // Adds pages
  5598. graph.model.beginUpdate();
  5599. try
  5600. {
  5601. var doc = mxUtils.parseXml(xml);
  5602. // Checks for mxfile with multiple pages
  5603. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  5604. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  5605. {
  5606. var diagrams = node.getElementsByTagName('diagram');
  5607. if (diagrams.length == 1)
  5608. {
  5609. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5610. }
  5611. else if (diagrams.length > 1)
  5612. {
  5613. var i0 = 0;
  5614. // Adds first page to current page if current page is only page and empty
  5615. if (this.pages != null && this.pages.length == 1 && this.isDiagramEmpty())
  5616. {
  5617. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5618. crop = false;
  5619. i0 = 1;
  5620. }
  5621. for (var i = i0; i < diagrams.length; i++)
  5622. {
  5623. // Imported pages must obtain a new ID
  5624. diagrams[i].removeAttribute('id');
  5625. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  5626. var index = this.pages.length;
  5627. // Checks for invalid page names
  5628. if (page.getName() == null)
  5629. {
  5630. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  5631. }
  5632. graph.model.execute(new ChangePage(this, page, page, index, true));
  5633. }
  5634. }
  5635. }
  5636. if (node != null && node.nodeName === 'mxGraphModel')
  5637. {
  5638. cells = graph.importGraphModel(node, dx, dy, crop);
  5639. }
  5640. }
  5641. finally
  5642. {
  5643. graph.model.endUpdate();
  5644. }
  5645. }
  5646. }
  5647. catch (e)
  5648. {
  5649. if (!noErrorHandling)
  5650. {
  5651. this.handleError(e);
  5652. }
  5653. else
  5654. {
  5655. throw e;
  5656. }
  5657. }
  5658. return cells;
  5659. };
  5660. /**
  5661. * Returns true for VSD, VDX and VSS, VSX files.
  5662. */
  5663. EditorUi.prototype.isRemoteVisioFormat = function(filename)
  5664. {
  5665. return /(\.v(sd|dx))($|\?)/i.test(filename) || /(\.vs(s|x))($|\?)/i.test(filename);
  5666. };
  5667. /**
  5668. * Imports the given Visio file
  5669. */
  5670. EditorUi.prototype.importVisio = function(file, done, onerror, filename)
  5671. {
  5672. filename = (filename != null) ? filename : file.name;
  5673. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5674. {
  5675. this.handleError(e);
  5676. });
  5677. var delayed = mxUtils.bind(this, function()
  5678. {
  5679. this.loadingExtensions = false;
  5680. if (this.doImportVisio)
  5681. {
  5682. if (this.isRemoteVisioFormat(filename) && VSD_CONVERT_URL != null)
  5683. {
  5684. var formData = new FormData();
  5685. formData.append('file1', file, filename);
  5686. var xhr = new XMLHttpRequest();
  5687. xhr.open('POST', VSD_CONVERT_URL);
  5688. xhr.responseType = 'blob';
  5689. xhr.onreadystatechange = mxUtils.bind(this, function()
  5690. {
  5691. if (xhr.readyState == 4)
  5692. {
  5693. if (xhr.status >= 200 && xhr.status <= 299)
  5694. {
  5695. try
  5696. {
  5697. //add back the file name
  5698. xhr.response.name = filename;
  5699. this.doImportVisio(xhr.response, done, onerror);
  5700. }
  5701. catch (e)
  5702. {
  5703. onerror(e);
  5704. }
  5705. }
  5706. else
  5707. {
  5708. onerror({});
  5709. }
  5710. }
  5711. });
  5712. xhr.send(formData);
  5713. }
  5714. else
  5715. {
  5716. try
  5717. {
  5718. this.doImportVisio(file, done, onerror);
  5719. }
  5720. catch (e)
  5721. {
  5722. onerror(e);
  5723. }
  5724. }
  5725. }
  5726. });
  5727. if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline())
  5728. {
  5729. this.loadingExtensions = true;
  5730. mxscript('js/extensions.min.js', delayed);
  5731. }
  5732. else
  5733. {
  5734. delayed();
  5735. }
  5736. };
  5737. /**
  5738. * Imports the given GraphML (yEd) file
  5739. */
  5740. EditorUi.prototype.importGraphML = function(xmlData, done, onerror)
  5741. {
  5742. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5743. {
  5744. this.handleError(e);
  5745. });
  5746. var delayed = mxUtils.bind(this, function()
  5747. {
  5748. this.loadingExtensions = false;
  5749. if (this.doImportGraphML)
  5750. {
  5751. try
  5752. {
  5753. this.doImportGraphML(xmlData, done, onerror);
  5754. }
  5755. catch (e)
  5756. {
  5757. onerror(e);
  5758. }
  5759. }
  5760. });
  5761. if (!this.doImportGraphML && !this.loadingExtensions && !this.isOffline())
  5762. {
  5763. this.loadingExtensions = true;
  5764. mxscript('js/extensions.min.js', delayed);
  5765. }
  5766. else
  5767. {
  5768. delayed();
  5769. }
  5770. };
  5771. /**
  5772. * Export the diagram to VSDX
  5773. */
  5774. EditorUi.prototype.exportVisio = function()
  5775. {
  5776. var delayed = mxUtils.bind(this, function()
  5777. {
  5778. this.loadingExtensions = false;
  5779. if (typeof VsdxExport !== 'undefined')
  5780. {
  5781. try
  5782. {
  5783. var expSuccess = new VsdxExport(this).exportCurrentDiagrams();
  5784. if (!expSuccess)
  5785. {
  5786. this.handleError({message: mxResources.get('unknownError')});
  5787. }
  5788. }
  5789. catch (e)
  5790. {
  5791. this.handleError(e);
  5792. }
  5793. }
  5794. });
  5795. if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline())
  5796. {
  5797. this.loadingExtensions = true;
  5798. mxscript('js/extensions.min.js', delayed);
  5799. }
  5800. else
  5801. {
  5802. delayed();
  5803. }
  5804. };
  5805. /**
  5806. * Imports the given Lucidchart data.
  5807. */
  5808. EditorUi.prototype.convertLucidChart = function(data, success, error)
  5809. {
  5810. var delayed = mxUtils.bind(this, function()
  5811. {
  5812. this.loadingExtensions = false;
  5813. // Checks for signature method
  5814. if (typeof window.LucidImporter !== 'undefined')
  5815. {
  5816. try
  5817. {
  5818. success(LucidImporter.importState(JSON.parse(data)));
  5819. }
  5820. catch (e)
  5821. {
  5822. error(e);
  5823. }
  5824. }
  5825. else
  5826. {
  5827. error({message: mxResources.get('serviceUnavailableOrBlocked')});
  5828. }
  5829. });
  5830. if (typeof window.LucidImporter === 'undefined' &&
  5831. !this.loadingExtensions && !this.isOffline())
  5832. {
  5833. this.loadingExtensions = true;
  5834. if (urlParams['dev'] == '1')
  5835. {
  5836. mxscript('js/diagramly/Extensions.js', delayed);
  5837. }
  5838. else
  5839. {
  5840. mxscript('js/extensions.min.js', delayed);
  5841. }
  5842. }
  5843. else
  5844. {
  5845. // Async needed for selection
  5846. window.setTimeout(delayed, 0);
  5847. }
  5848. };
  5849. /**
  5850. * Inserts the given text as a preformatted HTML text.
  5851. */
  5852. EditorUi.prototype.insertAsPreText = function(text, x, y)
  5853. {
  5854. var graph = this.editor.graph;
  5855. var cell = null;
  5856. graph.getModel().beginUpdate();
  5857. try
  5858. {
  5859. cell = graph.insertVertex(null, null, '<pre>' + text + '</pre>',
  5860. x, y, 1, 1, 'text;html=1;align=center;verticalAlign=middle;');
  5861. graph.updateCellSize(cell, true);
  5862. }
  5863. finally
  5864. {
  5865. graph.getModel().endUpdate();
  5866. }
  5867. return cell;
  5868. };
  5869. /**
  5870. * Imports the given XML into the existing diagram.
  5871. * TODO: Make this function asynchronous
  5872. */
  5873. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages)
  5874. {
  5875. crop = (crop != null) ? crop : true;
  5876. resizeImages = (resizeImages != null) ? resizeImages : true;
  5877. // Handles special case for Gliffy data which requires async server-side for parsing
  5878. if (text != null)
  5879. {
  5880. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  5881. {
  5882. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  5883. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  5884. {
  5885. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  5886. {
  5887. this.editor.graph.setSelectionCells(this.insertTextAt(
  5888. xhr.responseText, dx, dy, true));
  5889. }
  5890. }));
  5891. // Returns empty cells array as it is aysynchronous
  5892. return [];
  5893. }
  5894. // Handles special case of data URI which requires async loading for finding size
  5895. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() &&
  5896. (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  5897. {
  5898. var graph = this.editor.graph;
  5899. // Checks for embedded XML in PNG
  5900. if (text.substring(0, 22) == 'data:image/png;base64,')
  5901. {
  5902. var xml = this.extractGraphModelFromPng(text);
  5903. var result = this.importXml(xml, dx, dy, crop, true);
  5904. if (result.length > 0)
  5905. {
  5906. return result;
  5907. }
  5908. }
  5909. // Tries to extract embedded XML from SVG data URI
  5910. if (text.substring(0, 19) == 'data:image/svg+xml;')
  5911. {
  5912. try
  5913. {
  5914. var xml = null;
  5915. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  5916. {
  5917. xml = text.substring(text.indexOf(',') + 1);
  5918. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  5919. }
  5920. else
  5921. {
  5922. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  5923. }
  5924. var result = this.importXml(xml, dx, dy, crop, true);
  5925. if (result.length > 0)
  5926. {
  5927. return result;
  5928. }
  5929. }
  5930. catch (e)
  5931. {
  5932. // Ignore
  5933. }
  5934. }
  5935. this.loadImage(text, mxUtils.bind(this, function(img)
  5936. {
  5937. if (text.substring(0, 5) == 'data:')
  5938. {
  5939. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  5940. {
  5941. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5942. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5943. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  5944. }), resizeImages, this.maxImageSize);
  5945. }
  5946. else
  5947. {
  5948. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  5949. var w = Math.round(img.width * s);
  5950. var h = Math.round(img.height * s);
  5951. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5952. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5953. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  5954. }
  5955. }), mxUtils.bind(this, function()
  5956. {
  5957. var cell = null;
  5958. // Inserts invalid data URIs as text
  5959. graph.getModel().beginUpdate();
  5960. try
  5961. {
  5962. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  5963. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  5964. graph.updateCellSize(cell);
  5965. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  5966. }
  5967. finally
  5968. {
  5969. graph.getModel().endUpdate();
  5970. }
  5971. graph.setSelectionCell(cell);
  5972. }));
  5973. return [];
  5974. }
  5975. else
  5976. {
  5977. text = Graph.zapGremlins(mxUtils.trim(text));
  5978. if (this.isCompatibleString(text))
  5979. {
  5980. return this.importXml(text, dx, dy, crop);
  5981. }
  5982. else if (text.length > 0)
  5983. {
  5984. if (this.isLucidChartData(text))
  5985. {
  5986. this.convertLucidChart(text, mxUtils.bind(this, function(xml)
  5987. {
  5988. this.editor.graph.setSelectionCells(
  5989. this.importXml(xml, dx, dy, crop));
  5990. }), mxUtils.bind(this, function(e)
  5991. {
  5992. this.handleError(e);
  5993. }));
  5994. }
  5995. else
  5996. {
  5997. var graph = this.editor.graph;
  5998. var cell = null;
  5999. graph.getModel().beginUpdate();
  6000. try
  6001. {
  6002. // Fires cellsInserted to apply the current style to the inserted text.
  6003. // This requires the value to be empty when the event is fired.
  6004. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  6005. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  6006. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  6007. // Single tag is converted
  6008. if (text.charAt(0) == '<' && text.indexOf('>') == text.length - 1)
  6009. {
  6010. text = mxUtils.htmlEntities(text);
  6011. }
  6012. // Apply value and updates the cell size to fit the text block
  6013. cell.value = text;
  6014. graph.updateCellSize(cell);
  6015. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  6016. 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;
  6017. if (regexp.test(cell.value))
  6018. {
  6019. graph.setLinkForCell(cell, cell.value);
  6020. }
  6021. // Adds spacing
  6022. cell.geometry.width += graph.gridSize;
  6023. cell.geometry.height += graph.gridSize;
  6024. }
  6025. finally
  6026. {
  6027. graph.getModel().endUpdate();
  6028. }
  6029. return [cell];
  6030. }
  6031. }
  6032. }
  6033. }
  6034. return [];
  6035. };
  6036. /**
  6037. * Formats the given file size.
  6038. */
  6039. EditorUi.prototype.formatFileSize = function(size)
  6040. {
  6041. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  6042. var i = -1;
  6043. do
  6044. {
  6045. size = size / 1024;
  6046. i++;
  6047. } while (size > 1024);
  6048. return Math.max(size, 0.1).toFixed(1) + units[i];
  6049. };
  6050. /**
  6051. * Imports the given XML into the existing diagram.
  6052. */
  6053. EditorUi.prototype.convertDataUri = function(uri)
  6054. {
  6055. // Handles special case of data URI which needs to be rewritten
  6056. // to be used in a cell style to remove the semicolon
  6057. if (uri.substring(0, 5) == 'data:')
  6058. {
  6059. var semi = uri.indexOf(';');
  6060. if (semi > 0)
  6061. {
  6062. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  6063. }
  6064. }
  6065. return uri;
  6066. };
  6067. /**
  6068. * Returns true for Gliffy data.
  6069. */
  6070. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  6071. {
  6072. return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
  6073. };
  6074. /**
  6075. * Returns true for Gliffy
  6076. */
  6077. EditorUi.prototype.isLucidChartData = function(data)
  6078. {
  6079. return data != null && data.substring(0, 26) == '{"state":"{\\"Properties\\":';
  6080. };
  6081. /**
  6082. * Imports a local file from the device or local storage.
  6083. */
  6084. EditorUi.prototype.importLocalFile = function(device, noSplash)
  6085. {
  6086. // input.click does not work in IE on Windows 7
  6087. if (device && Graph.fileSupport && ((!mxClient.IS_IE && !mxClient.IS_IE11) ||
  6088. navigator.appVersion.indexOf('Windows NT 6.1') < 0))
  6089. {
  6090. var input = document.createElement('input');
  6091. input.setAttribute('type', 'file');
  6092. mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
  6093. {
  6094. if (input.files != null)
  6095. {
  6096. // Using null for position will disable crop of input file
  6097. this.importFiles(input.files, null, null, this.maxImageSize);
  6098. }
  6099. }));
  6100. input.click();
  6101. }
  6102. else
  6103. {
  6104. window.openNew = false;
  6105. window.openKey = 'import';
  6106. if (!noSplash)
  6107. {
  6108. var prevValue = Editor.useLocalStorage;
  6109. Editor.useLocalStorage = !device;
  6110. }
  6111. // Closes dialog after open
  6112. window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
  6113. {
  6114. this.hideDialog(cancel);
  6115. }));
  6116. window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
  6117. {
  6118. if (filename != null && Graph.fileSupport && /(\.v(dx|sdx?))($|\?)/i.test(filename))
  6119. {
  6120. // "Not a UTF 8 file" when opening VSDX in IE so this is never called
  6121. var file = new Blob([xml], {type: 'application/octet-stream'})
  6122. this.importVisio(file, mxUtils.bind(this, function(xml)
  6123. {
  6124. this.importXml(xml, 0, 0, true);
  6125. }), null, filename);
  6126. }
  6127. else
  6128. {
  6129. this.editor.graph.setSelectionCells(this.importXml(xml, 0, 0, true));
  6130. }
  6131. }));
  6132. // Removes openFile if dialog is closed
  6133. this.showDialog(new OpenDialog(this).container, 360, 220, true, true, function()
  6134. {
  6135. window.openFile = null;
  6136. });
  6137. // Extends dialog close to show splash screen
  6138. if (!noSplash)
  6139. {
  6140. var dlg = this.dialog;
  6141. var dlgClose = dlg.close;
  6142. this.dialog.close = mxUtils.bind(this, function(cancel)
  6143. {
  6144. Editor.useLocalStorage = prevValue;
  6145. dlgClose.apply(dlg, arguments);
  6146. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  6147. {
  6148. this.showSplash();
  6149. }
  6150. });
  6151. }
  6152. }
  6153. };
  6154. /**
  6155. * Imports the given XML into the existing diagram.
  6156. */
  6157. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  6158. {
  6159. crop = (crop != null) ? crop : true;
  6160. var async = false;
  6161. var cells = null;
  6162. var handleResult = mxUtils.bind(this, function(xml)
  6163. {
  6164. var importedCells = null;
  6165. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  6166. {
  6167. this.loadLibrary(new LocalLibrary(this, xml, filename));
  6168. }
  6169. else
  6170. {
  6171. importedCells = this.importXml(xml, dx, dy, crop);
  6172. }
  6173. if (done != null)
  6174. {
  6175. done(importedCells);
  6176. }
  6177. });
  6178. if (mimeType.substring(0, 5) == 'image')
  6179. {
  6180. var containsModel = false;
  6181. if (mimeType.substring(0, 9) == 'image/png')
  6182. {
  6183. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  6184. if (xml != null && xml.length > 0)
  6185. {
  6186. cells = this.importXml(xml, dx, dy, crop);
  6187. containsModel = true;
  6188. }
  6189. }
  6190. if (!containsModel)
  6191. {
  6192. var graph = this.editor.graph;
  6193. // Strips encoding bit (eg. ;base64,) for cell style
  6194. var semi = data.indexOf(';');
  6195. if (semi > 0)
  6196. {
  6197. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6198. }
  6199. if (crop && graph.isGridEnabled())
  6200. {
  6201. dx = graph.snap(dx);
  6202. dy = graph.snap(dy);
  6203. }
  6204. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  6205. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6206. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  6207. }
  6208. }
  6209. else if (/(\.*<graphml )/.test(data))
  6210. {
  6211. async = true;
  6212. this.importGraphML(data, handleResult);
  6213. }
  6214. else if (file != null && filename != null && ((/(\.v(dx|sdx?))($|\?)/i.test(filename)) || /(\.vs(x|sx?))($|\?)/i.test(filename)))
  6215. {
  6216. // LATER: done and async are a hack before making this asynchronous
  6217. async = true;
  6218. this.importVisio(file, handleResult);
  6219. }
  6220. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  6221. {
  6222. // LATER: done and async are a hack before making this asynchronous
  6223. async = true;
  6224. // Returns empty cells array as it is aysynchronous
  6225. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  6226. {
  6227. if (xhr.readyState == 4)
  6228. {
  6229. if (xhr.status >= 200 && xhr.status <= 299)
  6230. {
  6231. handleResult(xhr.responseText);
  6232. }
  6233. else if (done != null)
  6234. {
  6235. done(null);
  6236. }
  6237. }
  6238. }), filename);
  6239. }
  6240. else if (!/(\.v(sd|dx))($|\?)/i.test(filename) && !/(\.vs(s|x))($|\?)/i.test(filename))
  6241. {
  6242. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  6243. }
  6244. if (!async && done != null)
  6245. {
  6246. done(cells);
  6247. }
  6248. return cells;
  6249. };
  6250. /**
  6251. * Base64 encodes the given string. This method seems to be more
  6252. * robust for encoding PNG from binary AJAX responses.
  6253. */
  6254. EditorUi.prototype.base64Encode = function(str)
  6255. {
  6256. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6257. var out = "", i = 0, len = str.length, c1, c2, c3;
  6258. while (i < len)
  6259. {
  6260. c1 = str.charCodeAt(i++) & 0xff;
  6261. if (i == len)
  6262. {
  6263. out += CHARS.charAt(c1 >> 2);
  6264. out += CHARS.charAt((c1 & 0x3) << 4);
  6265. out += "==";
  6266. break;
  6267. }
  6268. c2 = str.charCodeAt(i++);
  6269. if (i == len)
  6270. {
  6271. out += CHARS.charAt(c1 >> 2);
  6272. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  6273. out += CHARS.charAt((c2 & 0xF) << 2);
  6274. out += "=";
  6275. break;
  6276. }
  6277. c3 = str.charCodeAt(i++);
  6278. out += CHARS.charAt(c1 >> 2);
  6279. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  6280. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  6281. out += CHARS.charAt(c3 & 0x3F);
  6282. }
  6283. return out;
  6284. };
  6285. /**
  6286. *
  6287. */
  6288. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  6289. {
  6290. x = (x != null) ? x : 0;
  6291. y = (y != null) ? y : 0;
  6292. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6293. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  6294. var crop = x != null && y != null;
  6295. var resizeImages = true;
  6296. // Checks if large images are imported
  6297. var largeImages = false;
  6298. if (!mxClient.IS_CHROMEAPP && files != null)
  6299. {
  6300. var thresh = resampleThreshold || this.resampleThreshold;
  6301. for (var i = 0; i < files.length; i++)
  6302. {
  6303. if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
  6304. {
  6305. largeImages = true;
  6306. break;
  6307. }
  6308. }
  6309. }
  6310. var doImportFiles = mxUtils.bind(this, function()
  6311. {
  6312. var graph = this.editor.graph;
  6313. var gs = graph.gridSize;
  6314. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  6315. {
  6316. if (data != null && data.substring(0, 10) == '<mxlibrary')
  6317. {
  6318. this.spinner.stop();
  6319. this.loadLibrary(new LocalLibrary(this, data, filename));
  6320. return null;
  6321. }
  6322. else
  6323. {
  6324. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  6325. }
  6326. });
  6327. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  6328. {
  6329. graph.setSelectionCells(cells);
  6330. });
  6331. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6332. {
  6333. var count = files.length;
  6334. var remain = count;
  6335. var queue = [];
  6336. // Barrier waits for all files to be loaded asynchronously
  6337. var barrier = mxUtils.bind(this, function(index, fnc)
  6338. {
  6339. queue[index] = fnc;
  6340. if (--remain == 0)
  6341. {
  6342. this.spinner.stop();
  6343. if (barrierFn != null)
  6344. {
  6345. barrierFn(queue);
  6346. }
  6347. else
  6348. {
  6349. var cells = [];
  6350. graph.getModel().beginUpdate();
  6351. try
  6352. {
  6353. for (var j = 0; j < queue.length; j++)
  6354. {
  6355. var tmp = queue[j]();
  6356. if (tmp != null)
  6357. {
  6358. cells = cells.concat(tmp);
  6359. }
  6360. }
  6361. }
  6362. finally
  6363. {
  6364. graph.getModel().endUpdate();
  6365. }
  6366. }
  6367. resultFn(cells);
  6368. }
  6369. });
  6370. for (var i = 0; i < count; i++)
  6371. {
  6372. (mxUtils.bind(this, function(index)
  6373. {
  6374. var file = files[index];
  6375. if (file != null)
  6376. {
  6377. var reader = new FileReader();
  6378. reader.onload = mxUtils.bind(this, function(e)
  6379. {
  6380. if (filterFn == null || filterFn(file))
  6381. {
  6382. if (file.type.substring(0, 6) == 'image/')
  6383. {
  6384. if (file.type.substring(0, 9) == 'image/svg')
  6385. {
  6386. // Checks if SVG contains content attribute
  6387. var data = e.target.result;
  6388. var comma = data.indexOf(',');
  6389. var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
  6390. var root = mxUtils.parseXml(svgText);
  6391. var svgs = root.getElementsByTagName('svg');
  6392. if (svgs.length > 0)
  6393. {
  6394. var svgRoot = svgs[0];
  6395. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  6396. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  6397. {
  6398. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  6399. }
  6400. if (cont != null && cont.charAt(0) == '%')
  6401. {
  6402. cont = decodeURIComponent(cont);
  6403. }
  6404. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  6405. cont.substring(0, 14) === '<mxGraphModel '))
  6406. {
  6407. barrier(index, mxUtils.bind(this, function()
  6408. {
  6409. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  6410. }));
  6411. }
  6412. else
  6413. {
  6414. // SVG needs special handling to add viewbox if missing and
  6415. // find initial size from SVG attributes (only for IE11)
  6416. barrier(index, mxUtils.bind(this, function()
  6417. {
  6418. try
  6419. {
  6420. var prefix = data.substring(0, comma + 1);
  6421. // Parses SVG and find width and height
  6422. if (root != null)
  6423. {
  6424. var svgs = root.getElementsByTagName('svg');
  6425. if (svgs.length > 0)
  6426. {
  6427. var svgRoot = svgs[0];
  6428. var w = parseFloat(svgRoot.getAttribute('width'));
  6429. var h = parseFloat(svgRoot.getAttribute('height'));
  6430. // Check if viewBox attribute already exists
  6431. var vb = svgRoot.getAttribute('viewBox');
  6432. if (vb == null || vb.length == 0)
  6433. {
  6434. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6435. }
  6436. // Uses width and height from viewbox for
  6437. // missing width and height attributes
  6438. else if (isNaN(w) || isNaN(h))
  6439. {
  6440. var tokens = vb.split(' ');
  6441. if (tokens.length > 3)
  6442. {
  6443. w = parseFloat(tokens[2]);
  6444. h = parseFloat(tokens[3]);
  6445. }
  6446. }
  6447. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6448. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6449. var cells = fn(data, file.type, x + index * gs, y + index * gs, Math.max(
  6450. 1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  6451. // Hack to fix width and height asynchronously
  6452. if (isNaN(w) || isNaN(h))
  6453. {
  6454. var img = new Image();
  6455. img.onload = mxUtils.bind(this, function()
  6456. {
  6457. w = Math.max(1, img.width);
  6458. h = Math.max(1, img.height);
  6459. cells[0].geometry.width = w;
  6460. cells[0].geometry.height = h;
  6461. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6462. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6463. var semi = data.indexOf(';');
  6464. if (semi > 0)
  6465. {
  6466. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6467. }
  6468. graph.setCellStyles('image', data, [cells[0]]);
  6469. });
  6470. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6471. }
  6472. return cells;
  6473. }
  6474. }
  6475. }
  6476. catch (e)
  6477. {
  6478. // ignores any SVG parsing errors
  6479. }
  6480. return null;
  6481. }));
  6482. }
  6483. }
  6484. else
  6485. {
  6486. barrier(index, mxUtils.bind(this, function()
  6487. {
  6488. return null;
  6489. }));
  6490. }
  6491. }
  6492. else
  6493. {
  6494. // Checks if PNG+XML is available to bypass code below
  6495. var containsModel = false;
  6496. if (file.type == 'image/png')
  6497. {
  6498. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  6499. if (xml != null && xml.length > 0)
  6500. {
  6501. var img = new Image();
  6502. img.src = e.target.result;
  6503. barrier(index, mxUtils.bind(this, function()
  6504. {
  6505. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  6506. img.width, img.height, file.name);
  6507. }));
  6508. containsModel = true;
  6509. }
  6510. }
  6511. // Additional asynchronous step for finding image size
  6512. if (!containsModel)
  6513. {
  6514. // Cannot load local files in Chrome App
  6515. if (mxClient.IS_CHROMEAPP)
  6516. {
  6517. this.spinner.stop();
  6518. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  6519. mxResources.get('cancel'), mxUtils.bind(this, function()
  6520. {
  6521. // Hides the dialog
  6522. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  6523. {
  6524. // Redirects to import function
  6525. this.actions.get('import').funct();
  6526. })
  6527. );
  6528. }
  6529. else
  6530. {
  6531. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  6532. {
  6533. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  6534. {
  6535. barrier(index, mxUtils.bind(this, function()
  6536. {
  6537. // Refuses to insert images above a certain size as they kill the app
  6538. if (data2 != null && data2.length < maxBytes)
  6539. {
  6540. var s = (!resizeImages || !this.isResampleImage(e.target.result, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  6541. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  6542. }
  6543. else
  6544. {
  6545. this.handleError({message: mxResources.get('imageTooBig')});
  6546. return null;
  6547. }
  6548. }));
  6549. }), resizeImages, maxSize, resampleThreshold);
  6550. }), mxUtils.bind(this, function()
  6551. {
  6552. this.handleError({message: mxResources.get('invalidOrMissingFile')});
  6553. }));
  6554. }
  6555. }
  6556. }
  6557. }
  6558. else
  6559. {
  6560. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6561. {
  6562. barrier(index, function()
  6563. {
  6564. return cells;
  6565. });
  6566. });
  6567. }
  6568. }
  6569. });
  6570. // Handles special cases
  6571. if (/(\.v(dx|sdx?))($|\?)/i.test(file.name) || /(\.vs(x|sx?))($|\?)/i.test(file.name))
  6572. {
  6573. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6574. {
  6575. barrier(index, function()
  6576. {
  6577. return cells;
  6578. });
  6579. }, file);
  6580. }
  6581. else if (file.type.substring(0, 5) == 'image')
  6582. {
  6583. reader.readAsDataURL(file);
  6584. }
  6585. else
  6586. {
  6587. reader.readAsText(file);
  6588. }
  6589. }
  6590. }))(i);
  6591. }
  6592. }
  6593. });
  6594. if (largeImages)
  6595. {
  6596. this.confirmImageResize(function(doResize)
  6597. {
  6598. resizeImages = doResize;
  6599. doImportFiles();
  6600. }, resizeDialog);
  6601. }
  6602. else
  6603. {
  6604. doImportFiles();
  6605. }
  6606. };
  6607. /**
  6608. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6609. * Filename is an optional parameter for blobs (that do not have a filename).
  6610. */
  6611. EditorUi.prototype.confirmImageResize = function(fn, force)
  6612. {
  6613. force = (force != null) ? force : false;
  6614. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  6615. var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
  6616. var wrapper = function(remember, resize)
  6617. {
  6618. if (remember || force)
  6619. {
  6620. mxSettings.setResizeImages((remember) ? resize : null);
  6621. mxSettings.save();
  6622. }
  6623. resume();
  6624. fn(resize);
  6625. };
  6626. if (resizeImages != null && !force)
  6627. {
  6628. wrapper(false, resizeImages);
  6629. }
  6630. else
  6631. {
  6632. this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
  6633. function(remember)
  6634. {
  6635. wrapper(remember, true);
  6636. },
  6637. function(remember)
  6638. {
  6639. wrapper(remember, false);
  6640. }, mxResources.get('resize'), mxResources.get('actualSize'),
  6641. '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
  6642. '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
  6643. isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
  6644. (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
  6645. }
  6646. };
  6647. /**
  6648. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6649. * Filename is an optional parameter for blobs (that do not have a filename).
  6650. */
  6651. EditorUi.prototype.parseFile = function(file, fn, filename)
  6652. {
  6653. filename = (filename != null) ? filename : file.name;
  6654. var formData = new FormData();
  6655. formData.append('format', 'xml');
  6656. formData.append('upfile', file, filename);
  6657. var xhr = new XMLHttpRequest();
  6658. xhr.open('POST', OPEN_URL);
  6659. xhr.onreadystatechange = function()
  6660. {
  6661. fn(xhr);
  6662. };
  6663. xhr.send(formData);
  6664. };
  6665. /**
  6666. *
  6667. */
  6668. EditorUi.prototype.isResampleImage = function(data, thresh)
  6669. {
  6670. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  6671. return data.length > thresh;
  6672. };
  6673. /**
  6674. * Resizes the given image if <maxImageBytes> is not null.
  6675. */
  6676. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  6677. {
  6678. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6679. var w = Math.max(1, img.width);
  6680. var h = Math.max(1, img.height);
  6681. if (enabled && this.isResampleImage(data, thresh))
  6682. {
  6683. try
  6684. {
  6685. var factor = Math.max(w / maxSize, h / maxSize);
  6686. if (factor > 1)
  6687. {
  6688. var w2 = Math.round(w / factor);
  6689. var h2 = Math.round(h / factor);
  6690. var canvas = document.createElement('canvas');
  6691. canvas.width = w2;
  6692. canvas.height = h2;
  6693. var ctx = canvas.getContext('2d');
  6694. ctx.drawImage(img, 0, 0, w2, h2);
  6695. var tmp = canvas.toDataURL();
  6696. // Uses new image if smaller
  6697. if (tmp.length < data.length)
  6698. {
  6699. // Checks if the image is empty by comparing
  6700. // with an empty image of the same size
  6701. var canvas2 = document.createElement('canvas');
  6702. canvas2.width = w2;
  6703. canvas2.height = h2;
  6704. var tmp2 = canvas2.toDataURL();
  6705. if (tmp !== tmp2)
  6706. {
  6707. data = tmp;
  6708. w = w2;
  6709. h = h2;
  6710. }
  6711. }
  6712. }
  6713. }
  6714. catch (e)
  6715. {
  6716. // ignores image scaling errors
  6717. }
  6718. }
  6719. fn(data, w, h);
  6720. };
  6721. EditorUi.prototype.crcTable = [];
  6722. for (var n = 0; n < 256; n++)
  6723. {
  6724. var c = n;
  6725. for (var k = 0; k < 8; k++)
  6726. {
  6727. if ((c & 1) == 1)
  6728. {
  6729. c = 0xedb88320 ^ (c >>> 1);
  6730. }
  6731. else
  6732. {
  6733. c >>>= 1;
  6734. }
  6735. EditorUi.prototype.crcTable[n] = c;
  6736. }
  6737. }
  6738. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  6739. {
  6740. var c = crc;
  6741. for (var n = 0; n < len; n++)
  6742. {
  6743. c = EditorUi.prototype.crcTable[(c ^ data.charCodeAt(off + n)) & 0xff] ^ (c >>> 8);
  6744. }
  6745. return c;
  6746. };
  6747. EditorUi.prototype.crc32 = function(str)
  6748. {
  6749. this.crcTable = this.crcTable || this.createCrcTable();
  6750. var crc = 0 ^ (-1);
  6751. for (var i = 0; i < str.length; i++ )
  6752. {
  6753. crc = (crc >>> 8) ^ this.crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
  6754. }
  6755. return (crc ^ (-1)) >>> 0;
  6756. };
  6757. /**
  6758. * Adds the given text to the compressed or non-compressed text chunk.
  6759. */
  6760. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  6761. {
  6762. var base64 = data.substring(data.indexOf(',') + 1);
  6763. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  6764. var pos = 0;
  6765. function fread(d, count)
  6766. {
  6767. var start = pos;
  6768. pos += count;
  6769. return d.substring(start, pos);
  6770. };
  6771. // Reads unsigned long 32 bit big endian
  6772. function _freadint(d)
  6773. {
  6774. var bytes = fread(d, 4);
  6775. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  6776. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  6777. };
  6778. function writeInt(num)
  6779. {
  6780. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  6781. (num >> 8) & 0x000000ff, num & 0x000000ff);
  6782. };
  6783. // Checks signature
  6784. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  6785. {
  6786. if (error != null)
  6787. {
  6788. error();
  6789. }
  6790. return;
  6791. }
  6792. // Reads header chunk
  6793. fread(f,4);
  6794. if (fread(f,4) != 'IHDR')
  6795. {
  6796. if (error != null)
  6797. {
  6798. error();
  6799. }
  6800. return;
  6801. }
  6802. fread(f, 17);
  6803. var result = f.substring(0, pos);
  6804. do
  6805. {
  6806. var n = _freadint(f);
  6807. var chunk = fread(f,4);
  6808. if (chunk == 'IDAT')
  6809. {
  6810. result = f.substring(0, pos - 8);
  6811. var chunkData = key + String.fromCharCode(0) +
  6812. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  6813. value;
  6814. var crc = 0xffffffff;
  6815. crc = this.updateCRC(crc, type, 0, 4);
  6816. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  6817. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  6818. result += f.substring(pos - 8, f.length);
  6819. break;
  6820. }
  6821. result += f.substring(pos - 8, pos - 4 + n);
  6822. fread(f,n);
  6823. fread(f,4);
  6824. }
  6825. while (n);
  6826. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  6827. }
  6828. /**
  6829. * Extracts the XML from the compressed or non-compressed text chunk.
  6830. */
  6831. EditorUi.prototype.extractGraphModelFromPng = function(data)
  6832. {
  6833. var result = null;
  6834. try
  6835. {
  6836. var base64 = data.substring(data.indexOf(',') + 1);
  6837. // Workaround for invalid character error in Safari
  6838. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  6839. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  6840. {
  6841. var value = binary.substring(pos + 8, pos + 8 + length);
  6842. if (type == 'zTXt')
  6843. {
  6844. var idx = value.indexOf(String.fromCharCode(0));
  6845. if (value.substring(0, idx) == 'mxGraphModel')
  6846. {
  6847. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  6848. var xmlData = Graph.bytesToString(pako.inflateRaw(
  6849. value.substring(idx + 2))).replace(/\+/g,' ');
  6850. if (xmlData != null && xmlData.length > 0)
  6851. {
  6852. result = xmlData;
  6853. }
  6854. }
  6855. }
  6856. // Uncompressed section is normally not used
  6857. else if (type == 'tEXt')
  6858. {
  6859. var vals = value.split(String.fromCharCode(0));
  6860. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  6861. {
  6862. result = vals[1];
  6863. }
  6864. }
  6865. if (result != null || type == 'IDAT')
  6866. {
  6867. // Stops processing the file as our text chunks
  6868. // are always placed before the data section
  6869. return true;
  6870. }
  6871. }));
  6872. }
  6873. catch (e)
  6874. {
  6875. // ignores decoding errors
  6876. }
  6877. if (result != null && result.charAt(0) == '%')
  6878. {
  6879. result = decodeURIComponent(result);
  6880. }
  6881. // Workaround for double encoded content
  6882. if (result != null && result.charAt(0) == '%')
  6883. {
  6884. result = decodeURIComponent(result);
  6885. }
  6886. return result;
  6887. };
  6888. /**
  6889. * Loads the image from the given URI.
  6890. *
  6891. * @param {number} dx X-coordinate of the translation.
  6892. * @param {number} dy Y-coordinate of the translation.
  6893. */
  6894. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  6895. {
  6896. try
  6897. {
  6898. var img = new Image();
  6899. img.onload = function()
  6900. {
  6901. onload(img);
  6902. }
  6903. if (onerror != null)
  6904. {
  6905. img.onerror = onerror;
  6906. }
  6907. img.src = uri;
  6908. }
  6909. catch (e)
  6910. {
  6911. if (onerror != null)
  6912. {
  6913. onerror(e);
  6914. }
  6915. else
  6916. {
  6917. throw e;
  6918. }
  6919. }
  6920. };
  6921. // Initializes the user interface
  6922. var editorUiInit = EditorUi.prototype.init;
  6923. EditorUi.prototype.init = function()
  6924. {
  6925. mxStencilRegistry.allowEval = mxStencilRegistry.allowEval && !this.isOfflineApp();
  6926. // Must be set before UI is created in superclass
  6927. if (typeof window.mxSettings !== 'undefined')
  6928. {
  6929. this.formatWidth = mxSettings.getFormatWidth();
  6930. }
  6931. var ui = this;
  6932. var graph = this.editor.graph;
  6933. // Redirects custom link title via UI for page links
  6934. graph.getLinkTitle = function(href)
  6935. {
  6936. return ui.getLinkTitle(href);
  6937. };
  6938. // Redirects custom link via UI for page link handling
  6939. graph.customLinkClicked = function(link)
  6940. {
  6941. var done = false;
  6942. try
  6943. {
  6944. ui.handleCustomLink(link);
  6945. done = true;
  6946. }
  6947. catch (e)
  6948. {
  6949. ui.handleError(e);
  6950. }
  6951. return done;
  6952. };
  6953. // Extends clear default style to clear persisted settings
  6954. var clearDefaultStyle = this.clearDefaultStyle;
  6955. this.clearDefaultStyle = function()
  6956. {
  6957. clearDefaultStyle.apply(this, arguments);
  6958. };
  6959. // Sets help link for placeholders
  6960. if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
  6961. {
  6962. EditDataDialog.placeholderHelpLink = 'https://desk.draw.io/support/solutions/articles/16000051979';
  6963. }
  6964. // Passes current page to editor window
  6965. var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
  6966. this.editor.getEditBlankUrl = function(params)
  6967. {
  6968. params = (params != null) ? params : '';
  6969. if (ui.pages != null && ui.currentPage != null)
  6970. {
  6971. for (var i = 0; i < ui.pages.length; i++)
  6972. {
  6973. if (ui.pages[i] == ui.currentPage)
  6974. {
  6975. if (i > 0)
  6976. {
  6977. params += ((params.length > 0) ? '&' : '?') + 'page=' + i;
  6978. }
  6979. break;
  6980. }
  6981. }
  6982. }
  6983. if (urlParams['dev'] == '1')
  6984. {
  6985. params += ((params.length > 0) ? '&' : '?') + 'dev=1&drawdev=1';
  6986. }
  6987. return editorGetEditBlankUrl.apply(this, arguments);
  6988. };
  6989. // For chromeless mode and lightbox mode in viewer
  6990. // Must be overridden before supercall to be applied
  6991. // in case of chromeless initialization
  6992. var graphAddClickHandler = graph.addClickHandler;
  6993. graph.addClickHandler = function(highlight, beforeClick, onClick)
  6994. {
  6995. var tmp = beforeClick;
  6996. beforeClick = function(evt, href)
  6997. {
  6998. if (href == null)
  6999. {
  7000. var source = mxEvent.getSource(evt);
  7001. if (source.nodeName.toLowerCase() == 'a')
  7002. {
  7003. href = source.getAttribute('href');
  7004. }
  7005. }
  7006. if (href != null && graph.isCustomLink(href) &&
  7007. (mxEvent.isTouchEvent(evt) ||
  7008. !mxEvent.isPopupTrigger(evt)) &&
  7009. graph.customLinkClicked(href))
  7010. {
  7011. mxEvent.consume(evt);
  7012. }
  7013. if (tmp != null)
  7014. {
  7015. tmp(evt, href);
  7016. }
  7017. };
  7018. // For some reason, local argument override is not enough in this case...
  7019. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  7020. };
  7021. editorUiInit.apply(this, arguments);
  7022. if (mxClient.IS_SVG)
  7023. {
  7024. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  7025. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  7026. }
  7027. // Overrides print dialog size
  7028. ui.actions.get('print').funct = function()
  7029. {
  7030. ui.showDialog(new PrintDialog(ui).container, 360,
  7031. (ui.pages != null && ui.pages.length > 1) ?
  7032. 420 : 360, true, true);
  7033. };
  7034. // Specifies the default filename
  7035. this.defaultFilename = mxResources.get('untitledDiagram');
  7036. // Adds placeholder for %page% and %pagenumber%
  7037. var graphGetGlobalVariable = graph.getGlobalVariable;
  7038. graph.getGlobalVariable = function(name)
  7039. {
  7040. if (name == 'page' && ui.currentPage != null)
  7041. {
  7042. return ui.currentPage.getName();
  7043. }
  7044. else if (name == 'pagenumber')
  7045. {
  7046. if (ui.currentPage != null && ui.pages != null)
  7047. {
  7048. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  7049. }
  7050. else
  7051. {
  7052. return 1;
  7053. }
  7054. }
  7055. return graphGetGlobalVariable.apply(this, arguments);
  7056. };
  7057. var graphLabelLinkClicked = graph.labelLinkClicked;
  7058. graph.labelLinkClicked = function(state, elt, evt)
  7059. {
  7060. var href = elt.getAttribute('href');
  7061. if (href != null && graph.isCustomLink(href) &&
  7062. (mxEvent.isTouchEvent(evt) ||
  7063. !mxEvent.isPopupTrigger(evt)))
  7064. {
  7065. // Active links are moved to the hint
  7066. if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
  7067. {
  7068. graph.customLinkClicked(href);
  7069. // Resets rubberband after click on locked cell
  7070. graph.getRubberband().reset();
  7071. }
  7072. mxEvent.consume(evt);
  7073. }
  7074. else
  7075. {
  7076. graphLabelLinkClicked.apply(this, arguments);
  7077. }
  7078. };
  7079. // Overrides editor filename
  7080. this.editor.getOrCreateFilename = function()
  7081. {
  7082. var filename = ui.defaultFilename;
  7083. var file = ui.getCurrentFile();
  7084. if (file != null)
  7085. {
  7086. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  7087. }
  7088. return filename;
  7089. };
  7090. // Disables print action for standalone apps on iOS
  7091. // because there is no way to close the new window
  7092. // LATER: Use iframe for print, disable preview
  7093. var printAction = this.actions.get('print');
  7094. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  7095. printAction.visible = printAction.isEnabled();
  7096. // Scales pages/graph to fit available size
  7097. if (!this.editor.chromeless || this.editor.editable)
  7098. {
  7099. // Defines additional hotkeys
  7100. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  7101. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  7102. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  7103. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  7104. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  7105. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  7106. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  7107. if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp)
  7108. {
  7109. this.altShiftActions[83] = 'synchronize'; // Alt+Shift+S
  7110. }
  7111. // Handles copy paste of images from clipboard
  7112. if (!mxClient.IS_IE)
  7113. {
  7114. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  7115. {
  7116. var graph = this.editor.graph;
  7117. if (!mxEvent.isConsumed(evt))
  7118. {
  7119. try
  7120. {
  7121. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  7122. var containsText = false;
  7123. // Workaround for asynchronous paste event processing in textInput
  7124. // is to ignore this event if it contains text/html/rtf (see below).
  7125. // NOTE: Image is not pasted into textInput so can't listen there.
  7126. for (var i = 0; i < data.types.length; i++)
  7127. {
  7128. if (data.types[i].substring(0, 5) === 'text/')
  7129. {
  7130. containsText = true;
  7131. break;
  7132. }
  7133. }
  7134. if (!containsText)
  7135. {
  7136. var items = data.items;
  7137. for (index in items)
  7138. {
  7139. var item = items[index];
  7140. if (item.kind === 'file')
  7141. {
  7142. if (graph.isEditing())
  7143. {
  7144. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7145. {
  7146. // Inserts image into current text box
  7147. graph.insertImage(data, w, h);
  7148. }, function()
  7149. {
  7150. // No post processing
  7151. }, function(file)
  7152. {
  7153. // Handles only images
  7154. return file.type.substring(0, 6) == 'image/';
  7155. }, function(queue)
  7156. {
  7157. // Invokes elements of queue in order
  7158. for (var i = 0; i < queue.length; i++)
  7159. {
  7160. queue[i]();
  7161. }
  7162. });
  7163. }
  7164. else
  7165. {
  7166. var pt = this.editor.graph.getInsertPoint();
  7167. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  7168. mxEvent.consume(evt);
  7169. }
  7170. break;
  7171. }
  7172. }
  7173. }
  7174. }
  7175. catch (e)
  7176. {
  7177. // ignore
  7178. }
  7179. }
  7180. }), false);
  7181. }
  7182. // Focused but invisible textarea during control or meta key events
  7183. var textInput = document.createElement('div');
  7184. textInput.style.position = 'absolute';
  7185. textInput.style.whiteSpace = 'nowrap';
  7186. textInput.style.overflow = 'hidden';
  7187. textInput.style.display = 'block';
  7188. textInput.contentEditable = true;
  7189. mxUtils.setOpacity(textInput, 0);
  7190. textInput.style.width = '1px';
  7191. textInput.style.height = '1px';
  7192. textInput.innerHTML = '&nbsp;';
  7193. var restoreFocus = false;
  7194. // Disables built-in cut, copy and paste shortcuts
  7195. this.keyHandler.bindControlKey(88, null);
  7196. this.keyHandler.bindControlKey(67, null);
  7197. this.keyHandler.bindControlKey(86, null);
  7198. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  7199. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  7200. {
  7201. // No dialog visible
  7202. var source = mxEvent.getSource(evt);
  7203. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  7204. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  7205. {
  7206. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  7207. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  7208. {
  7209. // Cannot use parentNode for check in IE
  7210. if (!restoreFocus)
  7211. {
  7212. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  7213. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  7214. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  7215. graph.container.appendChild(textInput);
  7216. restoreFocus = true;
  7217. // Workaround for selected document content in quirks mode
  7218. if (mxClient.IS_QUIRKS)
  7219. {
  7220. window.setTimeout(function()
  7221. {
  7222. textInput.focus();
  7223. document.execCommand('selectAll', false, null);
  7224. }, 0);
  7225. }
  7226. else
  7227. {
  7228. textInput.focus();
  7229. document.execCommand('selectAll', false, null);
  7230. }
  7231. }
  7232. }
  7233. }
  7234. }));
  7235. // Clears input and restores focus and selection
  7236. function clearInput()
  7237. {
  7238. window.setTimeout(function()
  7239. {
  7240. textInput.innerHTML = '&nbsp;';
  7241. textInput.focus();
  7242. document.execCommand('selectAll', false, null);
  7243. }, 0);
  7244. };
  7245. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  7246. {
  7247. // Workaround for asynchronous event read invalid in IE quirks mode
  7248. var keyCode = evt.keyCode;
  7249. // Asynchronous workaround for scroll to origin after paste if the
  7250. // Ctrl-key is not pressed for long enough in FF on Windows
  7251. window.setTimeout(mxUtils.bind(this, function()
  7252. {
  7253. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  7254. keyCode == 91 /* Meta */))
  7255. {
  7256. restoreFocus = false;
  7257. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  7258. {
  7259. graph.container.focus();
  7260. }
  7261. textInput.parentNode.removeChild(textInput);
  7262. // Workaround for lost cursor in focused element
  7263. if (this.dialog == null)
  7264. {
  7265. mxUtils.clearSelection();
  7266. }
  7267. }
  7268. }), 0);
  7269. }));
  7270. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  7271. {
  7272. if (graph.isEnabled())
  7273. {
  7274. try
  7275. {
  7276. mxClipboard.copy(graph);
  7277. this.copyCells(textInput);
  7278. clearInput();
  7279. }
  7280. catch (e)
  7281. {
  7282. this.handleError(e);
  7283. }
  7284. }
  7285. }));
  7286. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  7287. {
  7288. if (graph.isEnabled())
  7289. {
  7290. try
  7291. {
  7292. mxClipboard.copy(graph);
  7293. this.copyCells(textInput, true);
  7294. clearInput();
  7295. }
  7296. catch (e)
  7297. {
  7298. this.handleError(e);
  7299. }
  7300. }
  7301. }));
  7302. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  7303. {
  7304. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  7305. {
  7306. textInput.innerHTML = '&nbsp;';
  7307. textInput.focus();
  7308. window.setTimeout(mxUtils.bind(this, function()
  7309. {
  7310. this.pasteCells(evt, textInput);
  7311. textInput.innerHTML = '&nbsp;';
  7312. }), 0);
  7313. }
  7314. }), true);
  7315. // Needed for IE11
  7316. var isSelectionAllowed2 = this.isSelectionAllowed;
  7317. this.isSelectionAllowed = function(evt)
  7318. {
  7319. if (mxEvent.getSource(evt) == textInput)
  7320. {
  7321. return true;
  7322. }
  7323. return isSelectionAllowed2.apply(this, arguments);
  7324. };
  7325. };
  7326. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  7327. var x = document.body.clientWidth / 2 - 2;
  7328. // Holds the x-coordinate of the point
  7329. this.spinner = this.createSpinner(x, y, 24);
  7330. // Installs drag and drop handler for rich text editor
  7331. if (Graph.fileSupport)
  7332. {
  7333. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  7334. {
  7335. // Setup the dnd listeners
  7336. var graph = this.editor.graph;
  7337. var textElt = graph.cellEditor.text2;
  7338. var dropElt = null;
  7339. if (textElt != null)
  7340. {
  7341. mxEvent.addListener(textElt, 'dragleave', function(evt)
  7342. {
  7343. if (dropElt != null)
  7344. {
  7345. dropElt.parentNode.removeChild(dropElt);
  7346. dropElt = null;
  7347. }
  7348. evt.stopPropagation();
  7349. evt.preventDefault();
  7350. });
  7351. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  7352. {
  7353. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7354. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7355. {
  7356. dropElt = this.highlightElement(textElt);
  7357. }
  7358. evt.stopPropagation();
  7359. evt.preventDefault();
  7360. }));
  7361. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  7362. {
  7363. if (dropElt != null)
  7364. {
  7365. dropElt.parentNode.removeChild(dropElt);
  7366. dropElt = null;
  7367. }
  7368. if (evt.dataTransfer.files.length > 0)
  7369. {
  7370. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7371. {
  7372. // Inserts image into current text box
  7373. graph.insertImage(data, w, h);
  7374. }, function()
  7375. {
  7376. // No post processing
  7377. }, function(file)
  7378. {
  7379. // Handles only images
  7380. return file.type.substring(0, 6) == 'image/';
  7381. }, function(queue)
  7382. {
  7383. // Invokes elements of queue in order
  7384. for (var i = 0; i < queue.length; i++)
  7385. {
  7386. queue[i]();
  7387. }
  7388. }, mxEvent.isControlDown(evt));
  7389. }
  7390. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  7391. {
  7392. var uri = evt.dataTransfer.getData('text/uri-list');
  7393. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7394. {
  7395. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7396. {
  7397. var w = Math.max(1, img.width);
  7398. var h = Math.max(1, img.height);
  7399. var maxSize = this.maxImageSize;
  7400. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7401. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  7402. }));
  7403. }
  7404. else
  7405. {
  7406. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7407. }
  7408. }
  7409. else
  7410. {
  7411. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7412. {
  7413. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  7414. }
  7415. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7416. {
  7417. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7418. }
  7419. }
  7420. evt.stopPropagation();
  7421. evt.preventDefault();
  7422. }));
  7423. }
  7424. }));
  7425. }
  7426. //Add ruler in test mode only
  7427. //TODO add the ruler containers correctly and make the vertical one dynamic as the side panel size can change
  7428. if (urlParams['ruler'] == '1' && typeof mxRuler !== 'undefined')
  7429. {
  7430. var hRulerDiv = document.createElement('div');
  7431. hRulerDiv.style.position = 'absolute';
  7432. hRulerDiv.style.top = '95px';
  7433. hRulerDiv.style.left = '250px';
  7434. hRulerDiv.style.width = '2000px';
  7435. hRulerDiv.style.height = '30px';
  7436. hRulerDiv.style.background = 'whiteSmoke';
  7437. document.body.appendChild(hRulerDiv);
  7438. var vRulerDiv = document.createElement('div');
  7439. vRulerDiv.style.position = 'absolute';
  7440. vRulerDiv.style.top = '125px';
  7441. vRulerDiv.style.left = '220px';
  7442. vRulerDiv.style.width = '30px';
  7443. vRulerDiv.style.height = '1000px';
  7444. vRulerDiv.style.background = 'whiteSmoke';
  7445. document.body.appendChild(vRulerDiv);
  7446. var square = document.createElement('div');
  7447. square.style.position = 'absolute';
  7448. square.style.top = '95px';
  7449. square.style.left = '220px';
  7450. square.style.width = '30px';
  7451. square.style.height = '30px';
  7452. square.style.background = 'whiteSmoke';
  7453. document.body.appendChild(square);
  7454. this.vRuler = new mxRuler(this.editor.graph, vRulerDiv, true);
  7455. this.hRuler = new mxRuler(this.editor.graph, hRulerDiv, false);
  7456. }
  7457. // Adds an element to edit the style in the footer in test mode
  7458. if (urlParams['styledev'] == '1')
  7459. {
  7460. var footer = document.getElementById('geFooter');
  7461. if (footer != null)
  7462. {
  7463. this.styleInput = document.createElement('input');
  7464. this.styleInput.setAttribute('type', 'text');
  7465. this.styleInput.style.position = 'absolute';
  7466. this.styleInput.style.top = '14px';
  7467. this.styleInput.style.left = '2px';
  7468. // Workaround for ignore right CSS property in FF
  7469. this.styleInput.style.width = '98%';
  7470. this.styleInput.style.visibility = 'hidden';
  7471. this.styleInput.style.opacity = '0.9';
  7472. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  7473. {
  7474. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  7475. }));
  7476. footer.appendChild(this.styleInput);
  7477. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  7478. {
  7479. if (this.editor.graph.getSelectionCount() > 0)
  7480. {
  7481. var cell = this.editor.graph.getSelectionCell();
  7482. var style = this.editor.graph.getModel().getStyle(cell);
  7483. this.styleInput.value = style || '';
  7484. this.styleInput.style.visibility = 'visible';
  7485. } else
  7486. {
  7487. this.styleInput.style.visibility = 'hidden';
  7488. }
  7489. }));
  7490. }
  7491. var isSelectionAllowed = this.isSelectionAllowed;
  7492. this.isSelectionAllowed = function(evt)
  7493. {
  7494. if (mxEvent.getSource(evt) == this.styleInput)
  7495. {
  7496. return true;
  7497. }
  7498. return isSelectionAllowed.apply(this, arguments);
  7499. };
  7500. }
  7501. // Removes info text in page
  7502. var info = document.getElementById('geInfo');
  7503. if (info != null)
  7504. {
  7505. info.parentNode.removeChild(info);
  7506. }
  7507. // Installs drag and drop handler for files
  7508. // Enables dropping files
  7509. if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
  7510. {
  7511. // Setup the dnd listeners
  7512. var dropElt = null;
  7513. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  7514. {
  7515. if (graph.isEnabled())
  7516. {
  7517. if (dropElt != null)
  7518. {
  7519. dropElt.parentNode.removeChild(dropElt);
  7520. dropElt = null;
  7521. }
  7522. evt.stopPropagation();
  7523. evt.preventDefault();
  7524. }
  7525. });
  7526. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  7527. {
  7528. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7529. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7530. {
  7531. dropElt = this.highlightElement(graph.container);
  7532. }
  7533. if (this.sidebar != null)
  7534. {
  7535. this.sidebar.hideTooltip();
  7536. }
  7537. evt.stopPropagation();
  7538. evt.preventDefault();
  7539. }));
  7540. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  7541. {
  7542. if (dropElt != null)
  7543. {
  7544. dropElt.parentNode.removeChild(dropElt);
  7545. dropElt = null;
  7546. }
  7547. if (graph.isEnabled())
  7548. {
  7549. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  7550. var tr = graph.view.translate;
  7551. var scale = graph.view.scale;
  7552. var x = pt.x / scale - tr.x;
  7553. var y = pt.y / scale - tr.y;
  7554. if (mxEvent.isAltDown(evt))
  7555. {
  7556. x = 0;
  7557. y = 0;
  7558. }
  7559. if (evt.dataTransfer.files.length > 0)
  7560. {
  7561. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  7562. mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  7563. }
  7564. else
  7565. {
  7566. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  7567. evt.dataTransfer.getData('text/uri-list') : null;
  7568. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  7569. if (data != null)
  7570. {
  7571. graph.setSelectionCells(this.importXml(data, x, y, true));
  7572. }
  7573. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7574. {
  7575. var html = evt.dataTransfer.getData('text/html');
  7576. var div = document.createElement('div');
  7577. div.innerHTML = html;
  7578. // The default is based on the extension
  7579. var asImage = null;
  7580. // Extracts single image
  7581. var imgs = div.getElementsByTagName('img');
  7582. if (imgs != null && imgs.length == 1)
  7583. {
  7584. html = imgs[0].getAttribute('src');
  7585. // Handles special case where the src attribute has no valid extension
  7586. // in which case the text would be inserted as text with a link
  7587. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  7588. {
  7589. asImage = true;
  7590. }
  7591. }
  7592. else
  7593. {
  7594. // Extracts single link
  7595. var a = div.getElementsByTagName('a');
  7596. if (a != null && a.length == 1)
  7597. {
  7598. html = a[0].getAttribute('href');
  7599. }
  7600. }
  7601. var resizeImages = true;
  7602. var doInsert = mxUtils.bind(this, function()
  7603. {
  7604. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage, null, resizeImages));
  7605. });
  7606. if (asImage && html.length > this.resampleThreshold)
  7607. {
  7608. this.confirmImageResize(function(doResize)
  7609. {
  7610. resizeImages = doResize;
  7611. doInsert();
  7612. }, mxEvent.isControlDown(evt));
  7613. }
  7614. else
  7615. {
  7616. doInsert();
  7617. }
  7618. }
  7619. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7620. {
  7621. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7622. {
  7623. var w = Math.max(1, img.width);
  7624. var h = Math.max(1, img.height);
  7625. var maxSize = this.maxImageSize;
  7626. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7627. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  7628. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  7629. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  7630. }), mxUtils.bind(this, function(img)
  7631. {
  7632. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  7633. }));
  7634. }
  7635. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7636. {
  7637. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  7638. }
  7639. }
  7640. }
  7641. evt.stopPropagation();
  7642. evt.preventDefault();
  7643. }), false);
  7644. }
  7645. this.initPages();
  7646. // Installs listener for fixing references in undo history in
  7647. // collaborative editing where terminals may have vanished
  7648. // Undo/Redo listener to update edit's references before executing undo/redo
  7649. this.editUpdateListener = mxUtils.bind(this, function(sender, evt)
  7650. {
  7651. var edit = evt.getProperty('edit');
  7652. if (edit != null)
  7653. {
  7654. this.updateEditReferences(edit);
  7655. }
  7656. });
  7657. this.editor.undoManager.addListener(mxEvent.BEFORE_UNDO, this.editUpdateListener);
  7658. this.editor.undoManager.addListener(mxEvent.BEFORE_REDO, this.editUpdateListener);
  7659. // Embedded mode
  7660. if (urlParams['embed'] == '1')
  7661. {
  7662. this.initializeEmbedMode();
  7663. }
  7664. this.installSettings();
  7665. };
  7666. /**
  7667. *
  7668. */
  7669. EditorUi.prototype.getLinkTitle = function(href)
  7670. {
  7671. var title = Graph.prototype.getLinkTitle.apply(this, arguments);
  7672. if (href.substring(0, 13) == 'data:page/id,')
  7673. {
  7674. var comma = href.indexOf(',');
  7675. if (comma > 0)
  7676. {
  7677. var page = this.getPageById(href.substring(comma + 1));
  7678. if (page != null)
  7679. {
  7680. title = page.getName();
  7681. }
  7682. else
  7683. {
  7684. title = mxResources.get('pageNotFound');
  7685. }
  7686. }
  7687. }
  7688. else if (href.substring(0, 5) == 'data:')
  7689. {
  7690. title = mxResources.get('action');
  7691. }
  7692. return title;
  7693. };
  7694. /**
  7695. *
  7696. */
  7697. EditorUi.prototype.handleCustomLink = function(href)
  7698. {
  7699. if (href.substring(0, 13) == 'data:page/id,')
  7700. {
  7701. var comma = href.indexOf(',');
  7702. var page = this.getPageById(href.substring(comma + 1));
  7703. if (page)
  7704. {
  7705. this.selectPage(page)
  7706. }
  7707. else
  7708. {
  7709. // Needs fallback for missing resource in case of viewer lightbox
  7710. throw new Error(mxResources.get('pageNotFound') || 'Page not found');
  7711. }
  7712. }
  7713. else
  7714. {
  7715. this.editor.graph.handleCustomLink(href);
  7716. }
  7717. };
  7718. /**
  7719. *
  7720. */
  7721. EditorUi.prototype.isSettingsEnabled = function()
  7722. {
  7723. return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
  7724. };
  7725. /**
  7726. * Creates the format panel and adds overrides.
  7727. */
  7728. EditorUi.prototype.installSettings = function()
  7729. {
  7730. if (this.isSettingsEnabled())
  7731. {
  7732. // Gets recent colors from settings
  7733. ColorDialog.recentColors = mxSettings.getRecentColors();
  7734. // Updates UI to reflect current edge style
  7735. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  7736. /**
  7737. * Persists copy on connect switch.
  7738. */
  7739. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  7740. this.fireEvent(new mxEventObject('copyConnectChanged'));
  7741. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  7742. {
  7743. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  7744. mxSettings.save();
  7745. }));
  7746. /**
  7747. * Persists default page format.
  7748. */
  7749. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  7750. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  7751. {
  7752. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  7753. mxSettings.save();
  7754. }));
  7755. /**
  7756. * Persists default grid color.
  7757. */
  7758. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  7759. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  7760. {
  7761. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  7762. mxSettings.save();
  7763. }));
  7764. /**
  7765. * Persists autosave switch in Chrome app.
  7766. */
  7767. if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
  7768. {
  7769. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  7770. {
  7771. mxSettings.setAutosave(this.editor.autosave);
  7772. mxSettings.save();
  7773. }));
  7774. this.editor.autosave = mxSettings.getAutosave();
  7775. }
  7776. /**
  7777. *
  7778. */
  7779. if (this.sidebar != null)
  7780. {
  7781. this.sidebar.showPalette('search', mxSettings.settings.search);
  7782. }
  7783. /**
  7784. * Shows scratchpad if never shown.
  7785. */
  7786. if ((!this.editor.chromeless || this.editor.editable) &&
  7787. this.sidebar != null && (mxSettings.settings.isNew ||
  7788. parseInt(mxSettings.settings.version || 0) <= 8))
  7789. {
  7790. this.toggleScratchpad();
  7791. mxSettings.save();
  7792. }
  7793. // Saves app defaults for UI
  7794. this.addListener('formatWidthChanged', function()
  7795. {
  7796. mxSettings.setFormatWidth(this.formatWidth);
  7797. mxSettings.save();
  7798. });
  7799. }
  7800. };
  7801. /**
  7802. * Creates the format panel and adds overrides.
  7803. */
  7804. EditorUi.prototype.copyCells = function(elt, removeCells)
  7805. {
  7806. var graph = this.editor.graph;
  7807. if (!graph.isSelectionEmpty())
  7808. {
  7809. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  7810. // LATER: Add span with XML in data attribute
  7811. // var span = document.createElement('span');
  7812. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  7813. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  7814. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  7815. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  7816. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  7817. if (removeCells)
  7818. {
  7819. graph.removeCells(cells, false);
  7820. graph.lastPasteXml = null;
  7821. }
  7822. else
  7823. {
  7824. graph.lastPasteXml = xml;
  7825. graph.pasteCounter = 0;
  7826. }
  7827. elt.focus();
  7828. document.execCommand('selectAll', false, null);
  7829. }
  7830. else
  7831. {
  7832. // Disables copy on focused element
  7833. elt.innerHTML = '';
  7834. }
  7835. };
  7836. /**
  7837. * Creates the format panel and adds overrides.
  7838. */
  7839. EditorUi.prototype.pasteCells = function(evt, elt)
  7840. {
  7841. if (!mxEvent.isConsumed(evt))
  7842. {
  7843. var spans = elt.getElementsByTagName('span');
  7844. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  7845. 'application/vnd.lucid.chart.objects')
  7846. {
  7847. var content = spans[0].getAttribute('data-lucid-content');
  7848. if (content != null && content.length > 0)
  7849. {
  7850. this.convertLucidChart(content, mxUtils.bind(this, function(xml)
  7851. {
  7852. var graph = this.editor.graph;
  7853. graph.setSelectionCells(this.importXml(xml, 0, 0));
  7854. graph.scrollCellToVisible(graph.getSelectionCell());
  7855. }), mxUtils.bind(this, function(e)
  7856. {
  7857. this.handleError(e);
  7858. }));
  7859. mxEvent.consume(evt);
  7860. }
  7861. }
  7862. else
  7863. {
  7864. var graph = this.editor.graph;
  7865. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  7866. mxUtils.getTextContent(elt) : elt.textContent);
  7867. var compat = false;
  7868. // Workaround for junk after XML in VM
  7869. try
  7870. {
  7871. var idx = xml.lastIndexOf('%3E');
  7872. if (idx >= 0 && idx < xml.length - 3)
  7873. {
  7874. xml = xml.substring(0, idx + 3);
  7875. }
  7876. }
  7877. catch (e)
  7878. {
  7879. // ignore
  7880. }
  7881. // Checks for embedded XML content
  7882. try
  7883. {
  7884. var spans = elt.getElementsByTagName('span');
  7885. var tmp = (spans != null && spans.length > 0) ?
  7886. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  7887. decodeURIComponent(xml);
  7888. if (this.isCompatibleString(tmp))
  7889. {
  7890. compat = true;
  7891. xml = tmp;
  7892. }
  7893. }
  7894. catch (e)
  7895. {
  7896. // ignore
  7897. }
  7898. if (graph.lastPasteXml == xml)
  7899. {
  7900. graph.pasteCounter++;
  7901. }
  7902. else
  7903. {
  7904. graph.lastPasteXml = xml;
  7905. graph.pasteCounter = 0;
  7906. }
  7907. var dx = graph.pasteCounter * graph.gridSize;
  7908. if (xml != null && xml.length > 0)
  7909. {
  7910. if (compat || this.isCompatibleString(xml))
  7911. {
  7912. graph.setSelectionCells(this.importXml(xml, dx, dx));
  7913. }
  7914. else
  7915. {
  7916. var pt = graph.getInsertPoint();
  7917. if (graph.isMouseInsertPoint())
  7918. {
  7919. dx = 0;
  7920. // No offset for insert at mouse position
  7921. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  7922. {
  7923. graph.pasteCounter--;
  7924. }
  7925. }
  7926. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  7927. }
  7928. if (!graph.isSelectionEmpty())
  7929. {
  7930. graph.scrollCellToVisible(graph.getSelectionCell());
  7931. if (this.hoverIcons != null)
  7932. {
  7933. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  7934. }
  7935. try
  7936. {
  7937. mxEvent.consume(evt);
  7938. }
  7939. catch (e)
  7940. {
  7941. // ignore event no longer exists in async handler in IE8-
  7942. }
  7943. }
  7944. }
  7945. }
  7946. }
  7947. };
  7948. /**
  7949. * Adds a file drop handler for opening local files.
  7950. */
  7951. EditorUi.prototype.addFileDropHandler = function(elts)
  7952. {
  7953. // Installs drag and drop handler for files
  7954. if (Graph.fileSupport)
  7955. {
  7956. var dropElt = null;
  7957. for (var i = 0; i < elts.length; i++)
  7958. {
  7959. // Setup the dnd listeners
  7960. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  7961. {
  7962. if (dropElt != null)
  7963. {
  7964. dropElt.parentNode.removeChild(dropElt);
  7965. dropElt = null;
  7966. }
  7967. evt.stopPropagation();
  7968. evt.preventDefault();
  7969. });
  7970. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  7971. {
  7972. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7973. {
  7974. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7975. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  7976. {
  7977. dropElt = this.highlightElement();
  7978. }
  7979. }
  7980. evt.stopPropagation();
  7981. evt.preventDefault();
  7982. }));
  7983. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  7984. {
  7985. if (dropElt != null)
  7986. {
  7987. dropElt.parentNode.removeChild(dropElt);
  7988. dropElt = null;
  7989. }
  7990. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7991. {
  7992. if (evt.dataTransfer.files.length > 0)
  7993. {
  7994. this.hideDialog();
  7995. // Never open files in embed mode
  7996. if (urlParams['embed'] == '1')
  7997. {
  7998. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  7999. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  8000. }
  8001. else
  8002. {
  8003. this.openFiles(evt.dataTransfer.files, true);
  8004. }
  8005. }
  8006. else
  8007. {
  8008. // Handles open special files via text drag and drop
  8009. var data = this.extractGraphModelFromEvent(evt);
  8010. // Tries additional and async parsing of text content such as HTML, Gliffy data
  8011. if (data == null)
  8012. {
  8013. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  8014. if (provider != null)
  8015. {
  8016. if (document.documentMode == 10 || document.documentMode == 11)
  8017. {
  8018. data = provider.getData('Text');
  8019. }
  8020. else
  8021. {
  8022. var data = null;
  8023. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  8024. {
  8025. var data = evt.dataTransfer.getData('text/uri-list');
  8026. }
  8027. else
  8028. {
  8029. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  8030. }
  8031. if (data != null && data.length > 0)
  8032. {
  8033. var div = document.createElement('div');
  8034. div.innerHTML = data;
  8035. // Extracts single image
  8036. var imgs = div.getElementsByTagName('img');
  8037. if (imgs.length > 0)
  8038. {
  8039. data = imgs[0].getAttribute('src');
  8040. }
  8041. }
  8042. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  8043. {
  8044. data = provider.getData('text/plain');
  8045. }
  8046. }
  8047. if (data != null)
  8048. {
  8049. // Checks for embedded XML in PNG
  8050. if (data.substring(0, 22) == 'data:image/png;base64,')
  8051. {
  8052. var xml = this.extractGraphModelFromPng(data);
  8053. if (xml != null && xml.length > 0)
  8054. {
  8055. this.openLocalFile(xml, null, true);
  8056. }
  8057. }
  8058. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  8059. {
  8060. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  8061. {
  8062. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8063. {
  8064. this.openLocalFile(req.getText(), null, true);
  8065. }
  8066. }));
  8067. }
  8068. else if (/^https?:\/\//.test(data))
  8069. {
  8070. if (this.getCurrentFile() == null)
  8071. {
  8072. window.location.hash = '#U' + encodeURIComponent(data);
  8073. }
  8074. else
  8075. {
  8076. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  8077. (EditorUi.drawHost + '/') : 'https://' + location.host + '/') +
  8078. window.location.search + '#U' + encodeURIComponent(data));
  8079. }
  8080. }
  8081. }
  8082. }
  8083. }
  8084. else
  8085. {
  8086. this.openLocalFile(data, null, true);
  8087. }
  8088. }
  8089. }
  8090. evt.stopPropagation();
  8091. evt.preventDefault();
  8092. }));
  8093. }
  8094. }
  8095. };
  8096. /**
  8097. * Highlights the given element
  8098. */
  8099. EditorUi.prototype.highlightElement = function(elt)
  8100. {
  8101. var x = 0;
  8102. var y = 0;
  8103. var w = 0;
  8104. var h = 0;
  8105. if (elt == null)
  8106. {
  8107. var b = document.body;
  8108. var d = document.documentElement;
  8109. w = (b.clientWidth || d.clientWidth) - 3;
  8110. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  8111. }
  8112. else
  8113. {
  8114. x = elt.offsetTop;
  8115. y = elt.offsetLeft;
  8116. w = elt.clientWidth;
  8117. h = elt.clientHeight;
  8118. }
  8119. var hl = document.createElement('div');
  8120. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  8121. hl.style.border = '3px dotted rgb(254, 137, 12)';
  8122. hl.style.pointerEvents = 'none';
  8123. hl.style.position = 'absolute';
  8124. hl.style.top = x + 'px';
  8125. hl.style.left = y + 'px';
  8126. hl.style.width = Math.max(0, w - 3) + 'px';
  8127. hl.style.height = Math.max(0, h - 3) + 'px';
  8128. if (elt != null && elt.parentNode == this.editor.graph.container)
  8129. {
  8130. this.editor.graph.container.appendChild(hl);
  8131. }
  8132. else
  8133. {
  8134. document.body.appendChild(hl);
  8135. }
  8136. return hl;
  8137. };
  8138. /**
  8139. * Highlights the given element
  8140. */
  8141. EditorUi.prototype.stringToCells = function(xml)
  8142. {
  8143. var doc = mxUtils.parseXml(xml);
  8144. var node = this.editor.extractGraphModel(doc.documentElement);
  8145. var cells = [];
  8146. if (node != null)
  8147. {
  8148. var codec = new mxCodec(node.ownerDocument);
  8149. var model = new mxGraphModel();
  8150. codec.decode(node, model);
  8151. var parent = model.getChildAt(model.getRoot(), 0);
  8152. for (var j = 0; j < model.getChildCount(parent); j++)
  8153. {
  8154. cells.push(model.getChildAt(parent, j));
  8155. }
  8156. }
  8157. return cells;
  8158. };
  8159. /**
  8160. * Opens the given files in the editor.
  8161. */
  8162. EditorUi.prototype.openFiles = function(files, temp)
  8163. {
  8164. if (this.spinner.spin(document.body, mxResources.get('loading')))
  8165. {
  8166. for (var i = 0; i < files.length; i++)
  8167. {
  8168. (mxUtils.bind(this, function(file)
  8169. {
  8170. var reader = new FileReader();
  8171. reader.onload = mxUtils.bind(this, function(e)
  8172. {
  8173. try
  8174. {
  8175. var data = e.target.result;
  8176. var name = file.name;
  8177. if (name != null && name.length > 0)
  8178. {
  8179. if (!this.useCanvasForExport && /(\.png)$/i.test(name))
  8180. {
  8181. name = name.substring(0, name.length - 4) + '.drawio';
  8182. }
  8183. var handleResult = mxUtils.bind(this, function(xml)
  8184. {
  8185. var dot = name.lastIndexOf('.');
  8186. if (dot >= 0)
  8187. {
  8188. name = name.substring(0, name.lastIndexOf('.')) + '.drawio';
  8189. }
  8190. else
  8191. {
  8192. name = name + '.drawio';
  8193. }
  8194. if (xml.substring(0, 10) == '<mxlibrary')
  8195. {
  8196. // Creates new temporary file if library is dropped in splash screen
  8197. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8198. {
  8199. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8200. }
  8201. try
  8202. {
  8203. this.loadLibrary(new LocalLibrary(this, xml, name));
  8204. }
  8205. catch (e)
  8206. {
  8207. this.handleError(e, mxResources.get('errorLoadingFile'));
  8208. }
  8209. }
  8210. else
  8211. {
  8212. this.openLocalFile(xml, name, temp);
  8213. }
  8214. });
  8215. if (/(\.v(dx|sdx?))($|\?)/i.test(name) || /(\.vs(x|sx?))($|\?)/i.test(name))
  8216. {
  8217. this.importVisio(file, mxUtils.bind(this, function(xml)
  8218. {
  8219. this.spinner.stop();
  8220. handleResult(xml);
  8221. }));
  8222. }
  8223. else if (/(\.*<graphml )/.test(data))
  8224. {
  8225. this.importGraphML(data, mxUtils.bind(this, function(xml)
  8226. {
  8227. this.spinner.stop();
  8228. handleResult(xml);
  8229. }));
  8230. }
  8231. else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  8232. this.isRemoteFileFormat(data, name))
  8233. {
  8234. this.parseFile(file, mxUtils.bind(this, function(xhr)
  8235. {
  8236. if (xhr.readyState == 4)
  8237. {
  8238. this.spinner.stop();
  8239. if (xhr.status >= 200 && xhr.status <= 299)
  8240. {
  8241. handleResult(xhr.responseText);
  8242. }
  8243. else
  8244. {
  8245. this.handleError({message: mxResources.get((xhr.status == 413) ?
  8246. 'drawingTooLarge' : 'invalidOrMissingFile')},
  8247. mxResources.get('errorLoadingFile'));
  8248. }
  8249. }
  8250. }));
  8251. }
  8252. else if (this.isLucidChartData(data))
  8253. {
  8254. if (/(\.json)$/i.test(name))
  8255. {
  8256. name = name.substring(0, name.length - 5) + '.drawio';
  8257. }
  8258. // LATER: Add import step that produces cells and use callback
  8259. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  8260. {
  8261. this.spinner.stop();
  8262. this.openLocalFile(xml, name, temp);
  8263. }), mxUtils.bind(this, function(e)
  8264. {
  8265. this.spinner.stop();
  8266. this.handleError(e);
  8267. }));
  8268. }
  8269. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  8270. {
  8271. this.spinner.stop();
  8272. // Creates new temporary file if library is dropped in splash screen
  8273. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8274. {
  8275. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8276. }
  8277. try
  8278. {
  8279. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  8280. }
  8281. catch (e)
  8282. {
  8283. this.handleError(e, mxResources.get('errorLoadingFile'));
  8284. }
  8285. }
  8286. else
  8287. {
  8288. if (file.type.substring(0, 9) == 'image/png')
  8289. {
  8290. data = this.extractGraphModelFromPng(data);
  8291. }
  8292. this.spinner.stop();
  8293. this.openLocalFile(data, name, temp);
  8294. }
  8295. }
  8296. }
  8297. catch (e)
  8298. {
  8299. this.handleError(e);
  8300. }
  8301. });
  8302. reader.onerror = mxUtils.bind(this, function(e)
  8303. {
  8304. this.spinner.stop();
  8305. this.handleError(e);
  8306. window.openFile = null;
  8307. });
  8308. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  8309. {
  8310. reader.readAsDataURL(file);
  8311. }
  8312. else
  8313. {
  8314. reader.readAsText(file);
  8315. }
  8316. }))(files[i]);
  8317. }
  8318. }
  8319. };
  8320. /**
  8321. * Shows the layers dialog if the graph has more than one layer.
  8322. */
  8323. EditorUi.prototype.openLocalFile = function(data, name, temp)
  8324. {
  8325. var currentFile = this.getCurrentFile();
  8326. var fn = mxUtils.bind(this, function()
  8327. {
  8328. window.openFile = null;
  8329. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  8330. {
  8331. var doc = mxUtils.parseXml(data);
  8332. if (doc != null)
  8333. {
  8334. this.editor.setGraphXml(doc.documentElement);
  8335. this.editor.graph.selectAll();
  8336. }
  8337. }
  8338. else
  8339. {
  8340. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  8341. }
  8342. });
  8343. if (data != null && data.length > 0)
  8344. {
  8345. if (currentFile == null || (!currentFile.isModified() &&
  8346. (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)))
  8347. {
  8348. fn();
  8349. }
  8350. else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) &&
  8351. currentFile != null && currentFile.isModified())
  8352. {
  8353. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8354. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8355. }
  8356. else
  8357. {
  8358. window.openFile = new OpenFile(function()
  8359. {
  8360. window.openFile = null;
  8361. });
  8362. window.openFile.setData(data, name);
  8363. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  8364. {
  8365. if (currentFile != null && currentFile.isModified())
  8366. {
  8367. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8368. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8369. }
  8370. else
  8371. {
  8372. fn();
  8373. }
  8374. }));
  8375. }
  8376. }
  8377. else
  8378. {
  8379. throw new Error(mxResources.get('notADiagramFile'));
  8380. }
  8381. };
  8382. /**
  8383. * Returns a list of all shapes used in the current file.
  8384. */
  8385. EditorUi.prototype.getBasenames = function()
  8386. {
  8387. var basenames = {};
  8388. if (this.pages != null)
  8389. {
  8390. for (var i = 0; i < this.pages.length; i++)
  8391. {
  8392. this.updatePageRoot(this.pages[i]);
  8393. this.addBasenamesForCell(this.pages[i].root, basenames);
  8394. }
  8395. }
  8396. else
  8397. {
  8398. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  8399. }
  8400. var result = [];
  8401. for (var key in basenames)
  8402. {
  8403. result.push(key);
  8404. }
  8405. return result;
  8406. };
  8407. /**
  8408. * Returns a list of all shapes used in the current file.
  8409. */
  8410. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  8411. {
  8412. function addName(name)
  8413. {
  8414. if (name != null)
  8415. {
  8416. // LATER: Check if this case exists
  8417. var dot = name.lastIndexOf('.');
  8418. if (dot > 0)
  8419. {
  8420. name = name.substring(dot + 1, name.length);
  8421. }
  8422. if (basenames[name] == null)
  8423. {
  8424. basenames[name] = true;
  8425. }
  8426. }
  8427. };
  8428. var graph = this.editor.graph;
  8429. var style = graph.getCellStyle(cell);
  8430. var shape = style[mxConstants.STYLE_SHAPE];
  8431. addName(mxStencilRegistry.getBasenameForStencil(shape));
  8432. // Adds package names for markers in edges
  8433. if (graph.model.isEdge(cell))
  8434. {
  8435. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  8436. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  8437. }
  8438. var childCount = graph.model.getChildCount(cell);
  8439. for (var i = 0; i < childCount; i++)
  8440. {
  8441. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  8442. }
  8443. };
  8444. /**
  8445. * Shows the layers dialog if the graph has more than one layer.
  8446. */
  8447. EditorUi.prototype.setGraphEnabled = function(enabled)
  8448. {
  8449. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  8450. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  8451. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  8452. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  8453. this.hsplit.style.display = (enabled) ? '' : 'none';
  8454. this.editor.graph.setEnabled(enabled);
  8455. if (this.tabContainer != null)
  8456. {
  8457. this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
  8458. }
  8459. if (!enabled)
  8460. {
  8461. if (this.actions.outlineWindow != null)
  8462. {
  8463. this.actions.outlineWindow.window.setVisible(false);
  8464. }
  8465. if (this.actions.layersWindow != null)
  8466. {
  8467. this.actions.layersWindow.window.setVisible(false);
  8468. }
  8469. if (this.menus.tagsWindow != null)
  8470. {
  8471. this.menus.tagsWindow.window.setVisible(false);
  8472. }
  8473. if (this.menus.findWindow != null)
  8474. {
  8475. this.menus.findWindow.window.setVisible(false);
  8476. }
  8477. }
  8478. };
  8479. /**
  8480. * Shows the layers dialog if the graph has more than one layer.
  8481. */
  8482. EditorUi.prototype.initializeEmbedMode = function()
  8483. {
  8484. this.setGraphEnabled(false);
  8485. var parent = window.opener || window.parent;
  8486. if (parent != window)
  8487. {
  8488. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  8489. {
  8490. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  8491. {
  8492. this.spinner.stop();
  8493. this.addEmbedButtons();
  8494. this.setGraphEnabled(true);
  8495. if (xml != null && xml.length > 0)
  8496. {
  8497. this.setFileData(xml);
  8498. if (!this.editor.isChromelessView())
  8499. {
  8500. this.showLayersDialog();
  8501. }
  8502. else if (this.editor.graph.isLightboxView())
  8503. {
  8504. this.lightboxFit();
  8505. }
  8506. if (this.chromelessResize)
  8507. {
  8508. this.chromelessResize();
  8509. }
  8510. }
  8511. else
  8512. {
  8513. this.editor.graph.model.clear();
  8514. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  8515. }
  8516. this.editor.undoManager.clear();
  8517. this.editor.modified = (modified != null) ? modified : false;
  8518. this.updateUi();
  8519. // Workaround for no initial focus in FF
  8520. // (does not work in Conf Cloud with FF)
  8521. if (window.self !== window.top)
  8522. {
  8523. window.focus();
  8524. }
  8525. if (this.format != null)
  8526. {
  8527. this.format.refresh();
  8528. }
  8529. }));
  8530. }
  8531. }
  8532. };
  8533. /**
  8534. * Shows the layers dialog if the graph has more than one layer.
  8535. */
  8536. EditorUi.prototype.showLayersDialog = function()
  8537. {
  8538. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  8539. {
  8540. if (this.actions.layersWindow == null)
  8541. {
  8542. this.actions.get('layers').funct();
  8543. }
  8544. else
  8545. {
  8546. this.actions.layersWindow.window.setVisible(true);
  8547. }
  8548. }
  8549. };
  8550. /**
  8551. * Tries to find a public URL for the given file.
  8552. */
  8553. EditorUi.prototype.getPublicUrl = function(file, fn)
  8554. {
  8555. if (file != null)
  8556. {
  8557. file.getPublicUrl(fn);
  8558. }
  8559. else
  8560. {
  8561. fn(null);
  8562. }
  8563. };
  8564. /**
  8565. * Adds the buttons for embedded mode.
  8566. */
  8567. EditorUi.prototype.createLoadMessage = function(eventName)
  8568. {
  8569. var graph = this.editor.graph;
  8570. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  8571. bounds: graph.getGraphBounds(), currentPage: this.getSelectedPageIndex(),
  8572. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds()};
  8573. };
  8574. /**
  8575. * Adds the buttons for embedded mode.
  8576. */
  8577. EditorUi.prototype.installMessageHandler = function(fn)
  8578. {
  8579. var changeListener = null;
  8580. var ignoreChange = false;
  8581. var autosave = false;
  8582. var lastData = null;
  8583. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  8584. {
  8585. if (!this.editor.modified || urlParams['modified'] == '0')
  8586. {
  8587. this.editor.setStatus('');
  8588. }
  8589. else if (urlParams['modified'] != null)
  8590. {
  8591. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  8592. }
  8593. });
  8594. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  8595. // Receives XML message from opener and puts it into the graph
  8596. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  8597. {
  8598. var validSource = window.opener || window.parent;
  8599. if (evt.source != validSource)
  8600. {
  8601. return;
  8602. }
  8603. var data = evt.data;
  8604. var extractDiagramXml = mxUtils.bind(this, function(data)
  8605. {
  8606. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  8607. {
  8608. try
  8609. {
  8610. if (data.substring(0, 22) == 'data:image/png;base64,')
  8611. {
  8612. data = this.extractGraphModelFromPng(data);
  8613. }
  8614. else if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  8615. {
  8616. data = atob(data.substring(26));
  8617. }
  8618. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  8619. {
  8620. data = data.substring(24);
  8621. }
  8622. if (data != null)
  8623. {
  8624. if (data.charAt(0) == '%')
  8625. {
  8626. data = decodeURIComponent(data);
  8627. }
  8628. else if (data.charAt(0) != '<')
  8629. {
  8630. data = Graph.decompress(data);
  8631. }
  8632. }
  8633. }
  8634. catch (e)
  8635. {
  8636. // ignore compression errors and use empty data
  8637. }
  8638. }
  8639. return data;
  8640. });
  8641. if (urlParams['proto'] == 'json')
  8642. {
  8643. try
  8644. {
  8645. data = JSON.parse(data);
  8646. }
  8647. catch (e)
  8648. {
  8649. data = null;
  8650. }
  8651. if (data == null)
  8652. {
  8653. // Ignore
  8654. return;
  8655. }
  8656. else if (data.action == 'dialog')
  8657. {
  8658. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  8659. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  8660. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  8661. if (data.modified != null)
  8662. {
  8663. this.editor.modified = data.modified;
  8664. }
  8665. return;
  8666. }
  8667. else if (data.action == 'prompt')
  8668. {
  8669. this.spinner.stop();
  8670. var dlg = new FilenameDialog(this, data.defaultValue || '',
  8671. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  8672. {
  8673. if (value != null)
  8674. {
  8675. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  8676. }
  8677. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  8678. this.showDialog(dlg.container, 300, 80, true, false);
  8679. dlg.init();
  8680. return;
  8681. }
  8682. else if (data.action == 'draft')
  8683. {
  8684. var tmp = extractDiagramXml(data.xml);
  8685. this.spinner.stop();
  8686. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  8687. tmp, mxUtils.bind(this, function()
  8688. {
  8689. this.hideDialog();
  8690. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  8691. }), mxUtils.bind(this, function()
  8692. {
  8693. this.hideDialog();
  8694. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  8695. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  8696. (data.discardKey) ? mxResources.get(data.discardKey) : null,
  8697. (data.ignore) ? mxUtils.bind(this, function()
  8698. {
  8699. this.hideDialog();
  8700. parent.postMessage(JSON.stringify({event: 'draft', result: 'ignore', message: data}), '*');
  8701. }) : null);
  8702. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  8703. {
  8704. if (cancel)
  8705. {
  8706. this.actions.get('exit').funct();
  8707. }
  8708. }));
  8709. try
  8710. {
  8711. dlg.init();
  8712. }
  8713. catch (e)
  8714. {
  8715. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  8716. }
  8717. return;
  8718. }
  8719. else if (data.action == 'template')
  8720. {
  8721. this.spinner.stop();
  8722. var enableRecentDocs = data.enableRecent == 1;
  8723. var enableSearchDocs = data.enableSearch == 1;
  8724. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  8725. {
  8726. xml = xml || this.emptyDiagramXml;
  8727. // LATER: Add autosave option in template message
  8728. if (data.callback != null)
  8729. {
  8730. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  8731. blank: xml == this.emptyDiagramXml, name: name}), '*');
  8732. }
  8733. else
  8734. {
  8735. fn(xml, evt, xml != this.emptyDiagramXml);
  8736. // Workaround for status updated before modified applied
  8737. if (!this.editor.modified)
  8738. {
  8739. this.editor.setStatus('');
  8740. }
  8741. }
  8742. }), null, null, null, null, null, null, null,
  8743. enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
  8744. {
  8745. this.remoteInvoke('getRecentDiagrams', null, null, recentReadyCallback, function()
  8746. {
  8747. recentReadyCallback(null, 'Network Error!');
  8748. });
  8749. }) : null,
  8750. enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
  8751. {
  8752. this.remoteInvoke('searchDiagrams', [searchStr], null, searchReadyCallback, function()
  8753. {
  8754. searchReadyCallback(null, 'Network Error!');
  8755. });
  8756. }) : null,
  8757. function(url, info, name)
  8758. {
  8759. parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
  8760. name: name}), '*');
  8761. });
  8762. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  8763. {
  8764. if (cancel)
  8765. {
  8766. this.actions.get('exit').funct();
  8767. }
  8768. }));
  8769. dlg.init();
  8770. return;
  8771. }
  8772. else if (data.action == 'textContent')
  8773. {
  8774. //TODO Remove this message and use remove invokation instead
  8775. var allPagesTxt = this.getDiagramTextContent();
  8776. parent.postMessage(JSON.stringify({event: 'textContent', data: allPagesTxt, message: data}), '*');
  8777. return;
  8778. }
  8779. else if (data.action == 'status')
  8780. {
  8781. if (data.messageKey != null)
  8782. {
  8783. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  8784. }
  8785. else if (data.message != null)
  8786. {
  8787. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  8788. }
  8789. if (data.modified != null)
  8790. {
  8791. this.editor.modified = data.modified;
  8792. }
  8793. return;
  8794. }
  8795. else if (data.action == 'spinner')
  8796. {
  8797. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  8798. if (data.show != null && !data.show)
  8799. {
  8800. this.spinner.stop();
  8801. }
  8802. else
  8803. {
  8804. this.spinner.spin(document.body, msg)
  8805. }
  8806. return;
  8807. }
  8808. else if (data.action == 'export')
  8809. {
  8810. if (data.format == 'png' || data.format == 'xmlpng')
  8811. {
  8812. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8813. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8814. {
  8815. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  8816. this.editor.graph.setEnabled(false);
  8817. var graph = this.editor.graph;
  8818. var postDataBack = mxUtils.bind(this, function(uri)
  8819. {
  8820. this.editor.graph.setEnabled(true);
  8821. this.spinner.stop();
  8822. var msg = this.createLoadMessage('export');
  8823. msg.format = data.format;
  8824. msg.message = data;
  8825. msg.data = uri;
  8826. msg.xml = encodeURIComponent(xml);
  8827. parent.postMessage(JSON.stringify(msg), '*');
  8828. });
  8829. var processUri = mxUtils.bind(this, function(uri)
  8830. {
  8831. if (uri == null)
  8832. {
  8833. uri = Editor.blankImage;
  8834. }
  8835. if (data.format == 'xmlpng')
  8836. {
  8837. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  8838. atob(Graph.compress(xml)));
  8839. }
  8840. // Removes temporary graph from DOM
  8841. if (graph != this.editor.graph)
  8842. {
  8843. graph.container.parentNode.removeChild(graph.container);
  8844. }
  8845. postDataBack(uri);
  8846. });
  8847. // LATER: Uses external export if current page (not first page) has mathEnabled
  8848. if (this.isExportToCanvas())
  8849. {
  8850. // Exports PNG for first page while other page is visible by creating a graph
  8851. // LATER: Add caching for the graph or SVG while not on first page
  8852. if (this.pages != null && this.currentPage != this.pages[0])
  8853. {
  8854. graph = this.createTemporaryGraph(graph.getStylesheet());
  8855. var graphGetGlobalVariable = graph.getGlobalVariable;
  8856. var page = this.pages[0];
  8857. graph.getGlobalVariable = function(name)
  8858. {
  8859. if (name == 'page')
  8860. {
  8861. return page.getName();
  8862. }
  8863. else if (name == 'pagenumber')
  8864. {
  8865. return 1;
  8866. }
  8867. return graphGetGlobalVariable.apply(this, arguments);
  8868. };
  8869. document.body.appendChild(graph.container);
  8870. graph.model.setRoot(page.root);
  8871. }
  8872. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  8873. {
  8874. processUri(canvas.toDataURL('image/png'));
  8875. }), null, null, null, mxUtils.bind(this, function()
  8876. {
  8877. processUri(null);
  8878. }), null, null, null, null, null, null, graph);
  8879. }
  8880. else
  8881. {
  8882. // Data from server is base64 encoded to avoid binary XHR
  8883. // Double encoding for XML arg is needed for UTF8 encoding
  8884. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  8885. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  8886. encodeURIComponent(encodeURIComponent(xml)));
  8887. req.send(mxUtils.bind(this, function(req)
  8888. {
  8889. // Temp graph was never created at this point so we can
  8890. // skip processUri since it already contains the XML
  8891. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8892. {
  8893. postDataBack('data:image/png;base64,' + req.getText());
  8894. }
  8895. else
  8896. {
  8897. processUri(null);
  8898. }
  8899. }), mxUtils.bind(this, function()
  8900. {
  8901. processUri(null);
  8902. }));
  8903. }
  8904. }
  8905. }
  8906. else
  8907. {
  8908. // SVG is generated from graph so parse optional XML
  8909. if (data.xml != null && data.xml.length > 0)
  8910. {
  8911. this.setFileData(data.xml);
  8912. }
  8913. var msg = this.createLoadMessage('export');
  8914. // Forces new HTML format if pages exists
  8915. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  8916. (this.pages != null && this.pages.length > 1))))
  8917. {
  8918. var node = this.getXmlFileData();
  8919. msg.xml = mxUtils.getXml(node);
  8920. msg.data = this.getFileData(null, null, true, null, null, null, node);
  8921. msg.format = data.format;
  8922. }
  8923. else if (data.format == 'html')
  8924. {
  8925. var xml = this.editor.getGraphXml();
  8926. msg.data = this.getHtml(xml, this.editor.graph);
  8927. msg.xml = mxUtils.getXml(xml);
  8928. msg.format = data.format;
  8929. }
  8930. else
  8931. {
  8932. // Creates a preview with no alt text for unsupported browsers
  8933. mxSvgCanvas2D.prototype.foAltText = null;
  8934. var bg = this.editor.graph.background;
  8935. if (bg == mxConstants.NONE)
  8936. {
  8937. bg = null;
  8938. }
  8939. msg.xml = this.getFileData(true);
  8940. msg.format = 'svg';
  8941. if (data.embedImages || data.embedImages == null)
  8942. {
  8943. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8944. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8945. {
  8946. this.editor.graph.setEnabled(false);
  8947. if (data.format == 'xmlsvg')
  8948. {
  8949. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  8950. {
  8951. this.editor.graph.setEnabled(true);
  8952. this.spinner.stop();
  8953. msg.data = this.createSvgDataUri(svg);
  8954. parent.postMessage(JSON.stringify(msg), '*');
  8955. }));
  8956. }
  8957. else
  8958. {
  8959. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  8960. {
  8961. this.editor.graph.setEnabled(true);
  8962. this.spinner.stop();
  8963. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  8964. parent.postMessage(JSON.stringify(msg), '*');
  8965. }));
  8966. }
  8967. }
  8968. return;
  8969. }
  8970. else
  8971. {
  8972. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  8973. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  8974. msg.data = this.createSvgDataUri(svg);
  8975. }
  8976. }
  8977. parent.postMessage(JSON.stringify(msg), '*');
  8978. }
  8979. return;
  8980. }
  8981. else if (data.action == 'load')
  8982. {
  8983. autosave = data.autosave == 1;
  8984. this.hideDialog();
  8985. if (data.modified != null && urlParams['modified'] == null)
  8986. {
  8987. urlParams['modified'] = data.modified;
  8988. }
  8989. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  8990. {
  8991. urlParams['saveAndExit'] = data.saveAndExit;
  8992. }
  8993. if (data.title != null && this.buttonContainer != null)
  8994. {
  8995. var tmp = document.createElement('span');
  8996. mxUtils.write(tmp, data.title);
  8997. if (uiTheme == 'atlas')
  8998. {
  8999. this.buttonContainer.style.paddingRight = '12px';
  9000. this.buttonContainer.style.paddingTop = '6px';
  9001. this.buttonContainer.style.right = '25px';
  9002. }
  9003. else if (uiTheme != 'min')
  9004. {
  9005. this.buttonContainer.style.paddingRight = '38px';
  9006. this.buttonContainer.style.paddingTop = '6px';
  9007. }
  9008. if (this.embedFilenameSpan != null)
  9009. {
  9010. this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
  9011. }
  9012. this.buttonContainer.appendChild(tmp);
  9013. this.embedFilenameSpan = tmp;
  9014. }
  9015. if (data.xmlpng != null)
  9016. {
  9017. data = this.extractGraphModelFromPng(data.xmlpng);
  9018. }
  9019. else
  9020. {
  9021. data = data.xml;
  9022. }
  9023. }
  9024. else if (data.action == 'remoteInvokeReady')
  9025. {
  9026. this.handleRemoteInvokeReady(parent);
  9027. return;
  9028. }
  9029. else if (data.action == 'remoteInvoke')
  9030. {
  9031. this.handleRemoteInvoke(data);
  9032. return;
  9033. }
  9034. else if (data.action == 'remoteInvokeResponse')
  9035. {
  9036. this.handleRemoteInvokeResponse(data);
  9037. return;
  9038. }
  9039. else
  9040. {
  9041. // Unknown message must stop execution
  9042. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  9043. return;
  9044. }
  9045. }
  9046. var doLoad = mxUtils.bind(this, function(data, evt)
  9047. {
  9048. ignoreChange = true;
  9049. try
  9050. {
  9051. fn(data, evt);
  9052. }
  9053. catch (e)
  9054. {
  9055. this.handleError(e);
  9056. }
  9057. ignoreChange = false;
  9058. if (urlParams['modified'] != null)
  9059. {
  9060. this.editor.setStatus('');
  9061. }
  9062. var getData = mxUtils.bind(this, function()
  9063. {
  9064. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  9065. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  9066. });;
  9067. lastData = getData();
  9068. if (autosave && changeListener == null)
  9069. {
  9070. changeListener = mxUtils.bind(this, function(sender, eventObject)
  9071. {
  9072. var data = getData();
  9073. if (data != lastData && !ignoreChange)
  9074. {
  9075. var msg = this.createLoadMessage('autosave');
  9076. msg.xml = data;
  9077. data = JSON.stringify(msg);
  9078. var parent = window.opener || window.parent;
  9079. parent.postMessage(data, '*');
  9080. }
  9081. lastData = data;
  9082. });
  9083. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  9084. // Some options trigger autosave
  9085. this.editor.graph.addListener('gridSizeChanged', changeListener);
  9086. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  9087. this.addListener('pageFormatChanged', changeListener);
  9088. this.addListener('pageScaleChanged', changeListener);
  9089. this.addListener('backgroundColorChanged', changeListener);
  9090. this.addListener('backgroundImageChanged', changeListener);
  9091. this.addListener('foldingEnabledChanged', changeListener);
  9092. this.addListener('mathEnabledChanged', changeListener);
  9093. this.addListener('gridEnabledChanged', changeListener);
  9094. this.addListener('guidesEnabledChanged', changeListener);
  9095. this.addListener('pageViewChanged', changeListener);
  9096. }
  9097. // Sends the bounds of the graph to the host after parsing
  9098. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  9099. {
  9100. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  9101. }
  9102. });
  9103. if (data != null && typeof data.substring === 'function' && data.substring(0, 34) == 'data:application/vnd.visio;base64,')
  9104. {
  9105. // Checks VND binary magic number in base64
  9106. var filename = (data.substring(34, 45) == '0M8R4KGxGuE') ? 'raw.vsd' : 'raw.vsdx';
  9107. this.importVisio(this.base64ToBlob(data.substring(data.indexOf(',') + 1)), function(xml)
  9108. {
  9109. doLoad(xml, evt);
  9110. }, mxUtils.bind(this, function(e)
  9111. {
  9112. this.handleError(e);
  9113. }), filename);
  9114. }
  9115. else if (data != null && typeof data.substring === 'function' && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, ''))
  9116. {
  9117. // Asynchronous parsing via server
  9118. this.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  9119. {
  9120. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299 &&
  9121. xhr.responseText.substring(0, 13) == '<mxGraphModel')
  9122. {
  9123. doLoad(xhr.responseText, evt);
  9124. }
  9125. }), '');
  9126. }
  9127. else if (data != null && typeof data.substring === 'function' && this.isLucidChartData(data))
  9128. {
  9129. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  9130. {
  9131. doLoad(xml);
  9132. }), mxUtils.bind(this, function(e)
  9133. {
  9134. this.handleError(e);
  9135. }));
  9136. }
  9137. else
  9138. {
  9139. data = extractDiagramXml(data);
  9140. doLoad(data, evt);
  9141. }
  9142. }));
  9143. // Requests data from the sender. This is a workaround for not allowing
  9144. // the opener to listen for the onload event if not in the same origin.
  9145. var parent = window.opener || window.parent;
  9146. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  9147. parent.postMessage(msg, '*');
  9148. };
  9149. /**
  9150. * Adds the buttons for embedded mode.
  9151. */
  9152. EditorUi.prototype.addEmbedButtons = function()
  9153. {
  9154. if (this.menubar != null)
  9155. {
  9156. var div = document.createElement('div');
  9157. div.style.display = 'inline-block';
  9158. div.style.position = 'absolute';
  9159. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  9160. div.style.paddingLeft = '8px';
  9161. div.style.paddingBottom = '2px';
  9162. var button = document.createElement('button');
  9163. mxUtils.write(button, mxResources.get('save'));
  9164. button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
  9165. button.className = 'geBigButton';
  9166. button.style.fontSize = '12px';
  9167. button.style.padding = '4px 6px 4px 6px';
  9168. button.style.borderRadius = '3px';
  9169. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9170. {
  9171. this.actions.get('save').funct();
  9172. }));
  9173. div.appendChild(button);
  9174. if (urlParams['saveAndExit'] == '1')
  9175. {
  9176. button = document.createElement('a');
  9177. mxUtils.write(button, mxResources.get('saveAndExit'));
  9178. button.setAttribute('title', mxResources.get('saveAndExit'));
  9179. button.style.fontSize = '12px';
  9180. button.style.marginLeft = '6px';
  9181. button.style.padding = '4px';
  9182. button.style.cursor = 'pointer';
  9183. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9184. {
  9185. this.actions.get('saveAndExit').funct();
  9186. }));
  9187. div.appendChild(button);
  9188. }
  9189. button = document.createElement('a');
  9190. mxUtils.write(button, mxResources.get('exit'));
  9191. button.setAttribute('title', mxResources.get('exit'));
  9192. button.style.fontSize = '12px';
  9193. button.style.marginLeft = '6px';
  9194. button.style.marginRight = '20px';
  9195. button.style.padding = '4px';
  9196. button.style.cursor = 'pointer';
  9197. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9198. {
  9199. this.actions.get('exit').funct();
  9200. }));
  9201. div.appendChild(button);
  9202. this.toolbar.container.appendChild(div);
  9203. this.toolbar.staticElements.push(div);
  9204. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  9205. }
  9206. };
  9207. /**
  9208. *
  9209. */
  9210. EditorUi.prototype.showImportCsvDialog = function()
  9211. {
  9212. if (this.importCsvDialog == null)
  9213. {
  9214. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  9215. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  9216. {
  9217. this.importCsv(newValue);
  9218. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  9219. }
  9220. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  9221. this.importCsvDialog.init();
  9222. };
  9223. /**
  9224. * TODO: Move to Editor
  9225. */
  9226. EditorUi.prototype.importCsv = function(text, done)
  9227. {
  9228. try
  9229. {
  9230. var lines = text.split('\n');
  9231. var cells = [];
  9232. if (lines.length > 0)
  9233. {
  9234. // Internal lookup table
  9235. var lookups = {};
  9236. // Default values
  9237. var style = null;
  9238. var parentstyle = null;
  9239. var identity = null;
  9240. var parent = null;
  9241. var namespace = '';
  9242. var width = 'auto';
  9243. var height = 'auto';
  9244. var left = null;
  9245. var top = null;
  9246. var edgespacing = 40;
  9247. var nodespacing = 40;
  9248. var levelspacing = 100;
  9249. var padding = 0;
  9250. var graph = this.editor.graph;
  9251. var view = graph.view;
  9252. var bds = graph.getGraphBounds();
  9253. // Delayed after optional layout
  9254. var afterInsert = function()
  9255. {
  9256. if (done != null)
  9257. {
  9258. done(select);
  9259. }
  9260. else
  9261. {
  9262. graph.setSelectionCells(select);
  9263. graph.scrollCellToVisible(graph.getSelectionCell());
  9264. }
  9265. };
  9266. // Computes unscaled, untranslated graph bounds
  9267. var pt = graph.getFreeInsertPoint();
  9268. var x0 = pt.x;
  9269. var y0 = pt.y;
  9270. var y = y0;
  9271. // Default label value depends on column names
  9272. var label = null;
  9273. // Default layout to run.
  9274. var layout = 'auto';
  9275. // Name of the attribute that contains the parent reference
  9276. var parent = null;
  9277. // Name of the attribute that contains the references for creating edges
  9278. var edges = [];
  9279. // Name of the column for hyperlinks
  9280. var link = null;
  9281. // String array of names to remove from metadata
  9282. var ignore = null;
  9283. // Read processing instructions first
  9284. var index = 0;
  9285. while (index < lines.length && lines[index].charAt(0) == '#')
  9286. {
  9287. var text = lines[index];
  9288. index++;
  9289. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  9290. lines[index].charAt(0) == '#')
  9291. {
  9292. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  9293. index++;
  9294. }
  9295. if (text.charAt(1) != '#')
  9296. {
  9297. // Processing instruction
  9298. var idx = text.indexOf(':');
  9299. if (idx > 0)
  9300. {
  9301. var key = mxUtils.trim(text.substring(1, idx));
  9302. var value = mxUtils.trim(text.substring(idx + 1));
  9303. if (key == 'label')
  9304. {
  9305. label = graph.sanitizeHtml(value);
  9306. }
  9307. else if (key == 'style')
  9308. {
  9309. style = value;
  9310. }
  9311. else if (key == 'parentstyle')
  9312. {
  9313. parentstyle = value;
  9314. }
  9315. else if (key == 'identity' && value.length > 0 && value != '-')
  9316. {
  9317. identity = value;
  9318. }
  9319. else if (key == 'parent' && value.length > 0 && value != '-')
  9320. {
  9321. parent = value;
  9322. }
  9323. else if (key == 'namespace' && value.length > 0 && value != '-')
  9324. {
  9325. namespace = value;
  9326. }
  9327. else if (key == 'width')
  9328. {
  9329. width = value;
  9330. }
  9331. else if (key == 'height')
  9332. {
  9333. height = value;
  9334. }
  9335. else if (key == 'left' && value.length > 0)
  9336. {
  9337. left = value;
  9338. }
  9339. else if (key == 'top' && value.length > 0)
  9340. {
  9341. top = value;
  9342. }
  9343. else if (key == 'ignore')
  9344. {
  9345. ignore = value.split(',');
  9346. }
  9347. else if (key == 'connect')
  9348. {
  9349. edges.push(JSON.parse(value));
  9350. }
  9351. else if (key == 'link')
  9352. {
  9353. link = value;
  9354. }
  9355. else if (key == 'padding')
  9356. {
  9357. padding = parseFloat(value);
  9358. }
  9359. else if (key == 'edgespacing')
  9360. {
  9361. edgespacing = parseFloat(value);
  9362. }
  9363. else if (key == 'nodespacing')
  9364. {
  9365. nodespacing = parseFloat(value);
  9366. }
  9367. else if (key == 'levelspacing')
  9368. {
  9369. levelspacing = parseFloat(value);
  9370. }
  9371. else if (key == 'layout')
  9372. {
  9373. layout = value;
  9374. }
  9375. }
  9376. }
  9377. }
  9378. var keys = this.editor.csvToArray(lines[index]);
  9379. // Converts name of identity and parent to indexes of column
  9380. var identityIndex = null;
  9381. var parentIndex = null;
  9382. if (identity != null || parent != null)
  9383. {
  9384. for (var i = 0; i < keys.length; i++)
  9385. {
  9386. if (identity == keys[i])
  9387. {
  9388. identityIndex = i;
  9389. }
  9390. if (parent == keys[i])
  9391. {
  9392. parentIndex = i;
  9393. }
  9394. }
  9395. }
  9396. if (label == null)
  9397. {
  9398. label = '%' + keys[0] + '%';
  9399. }
  9400. if (edges != null)
  9401. {
  9402. for (var e = 0; e < edges.length; e++)
  9403. {
  9404. if (lookups[edges[e].to] == null)
  9405. {
  9406. lookups[edges[e].to] = {};
  9407. }
  9408. }
  9409. }
  9410. graph.model.beginUpdate();
  9411. try
  9412. {
  9413. for (var i = index + 1; i < lines.length; i++)
  9414. {
  9415. var values = this.editor.csvToArray(lines[i]);
  9416. if (values == null)
  9417. {
  9418. var short = (lines[i].length > 40) ? lines[i].substring(0, 40) + '...' : lines[i];
  9419. throw new Error(i + ' (' + short + ') ' + mxResources.get('containsValidationErrors'));
  9420. }
  9421. else if (values.length == keys.length)
  9422. {
  9423. var cell = null;
  9424. var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
  9425. if (id != null)
  9426. {
  9427. cell = graph.model.getCell(id);
  9428. }
  9429. if (cell == null)
  9430. {
  9431. var cell = new mxCell(label, new mxGeometry(x0, y,
  9432. 0, 0), style || 'whiteSpace=wrap;html=1;');
  9433. cell.vertex = true;
  9434. cell.id = id;
  9435. }
  9436. for (var j = 0; j < values.length; j++)
  9437. {
  9438. graph.setAttributeForCell(cell, keys[j], values[j]);
  9439. }
  9440. graph.setAttributeForCell(cell, 'placeholders', '1');
  9441. cell.style = graph.replacePlaceholders(cell, cell.style);
  9442. for (var e = 0; e < edges.length; e++)
  9443. {
  9444. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  9445. }
  9446. if (link != null && link != 'link')
  9447. {
  9448. graph.setLinkForCell(cell, cell.getAttribute(link));
  9449. // Removes attribute
  9450. graph.setAttributeForCell(cell, link, null);
  9451. }
  9452. // Sets the size
  9453. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
  9454. var size = this.editor.graph.getPreferredSizeForCell(cell);
  9455. if (cell.vertex)
  9456. {
  9457. if (left != null && cell.getAttribute(left) != null)
  9458. {
  9459. cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
  9460. }
  9461. if (top != null && cell.getAttribute(top) != null)
  9462. {
  9463. cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
  9464. }
  9465. if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
  9466. {
  9467. cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
  9468. }
  9469. else
  9470. {
  9471. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  9472. }
  9473. if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
  9474. {
  9475. cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
  9476. }
  9477. else
  9478. {
  9479. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  9480. }
  9481. y += cell.geometry.height + nodespacing;
  9482. }
  9483. var parent = (parentIndex != null) ? graph.model.getCell(
  9484. namespace + values[parentIndex]) : null;
  9485. if (parent != null)
  9486. {
  9487. parent.style = graph.replacePlaceholders(parent, parentstyle);
  9488. graph.addCell(cell, parent);
  9489. }
  9490. else
  9491. {
  9492. cells.push(graph.addCell(cell));
  9493. }
  9494. }
  9495. }
  9496. var roots = cells.slice();
  9497. var select = cells.slice();
  9498. for (var e = 0; e < edges.length; e++)
  9499. {
  9500. var edge = edges[e];
  9501. for (var i = 0; i < cells.length; i++)
  9502. {
  9503. var cell = cells[i];
  9504. var tmp = cell.getAttribute(edge.from);
  9505. if (tmp != null)
  9506. {
  9507. // Removes attribute
  9508. graph.setAttributeForCell(cell, edge.from, null);
  9509. var refs = tmp.split(',');
  9510. for (var j = 0; j < refs.length; j++)
  9511. {
  9512. var ref = lookups[edge.to][refs[j]];
  9513. if (ref != null)
  9514. {
  9515. var label = edge.label;
  9516. if (edge.fromlabel != null)
  9517. {
  9518. label = (cell.getAttribute(edge.fromlabel) || '') + (label || '');
  9519. }
  9520. if (edge.tolabel != null)
  9521. {
  9522. label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
  9523. }
  9524. select.push(graph.insertEdge(null, null, label || '',
  9525. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  9526. edge.style || graph.createCurrentEdgeStyle()));
  9527. mxUtils.remove((edge.invert) ? cell : ref, roots);
  9528. }
  9529. }
  9530. }
  9531. }
  9532. }
  9533. // Removes ignored attributes after processing above
  9534. if (ignore != null)
  9535. {
  9536. for (var i = 0; i < cells.length; i++)
  9537. {
  9538. var cell = cells[i];
  9539. for (var j = 0; j < ignore.length; j++)
  9540. {
  9541. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  9542. }
  9543. }
  9544. }
  9545. var edgeLayout = new mxParallelEdgeLayout(graph);
  9546. edgeLayout.spacing = edgespacing;
  9547. var postProcess = function()
  9548. {
  9549. edgeLayout.execute(graph.getDefaultParent());
  9550. // Aligns cells to grid and/or rounds positions
  9551. for (var i = 0; i < cells.length; i++)
  9552. {
  9553. var geo = graph.getCellGeometry(cells[i]);
  9554. geo.x = Math.round(graph.snap(geo.x));
  9555. geo.y = Math.round(graph.snap(geo.y));
  9556. if (width == 'auto')
  9557. {
  9558. geo.width = Math.round(graph.snap(geo.width));
  9559. }
  9560. if (height == 'auto')
  9561. {
  9562. geo.height = Math.round(graph.snap(geo.height));
  9563. }
  9564. }
  9565. };
  9566. if (layout == 'circle')
  9567. {
  9568. var circleLayout = new mxCircleLayout(graph);
  9569. circleLayout.resetEdges = false;
  9570. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  9571. // Ignore other cells
  9572. circleLayout.isVertexIgnored = function(vertex)
  9573. {
  9574. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  9575. mxUtils.indexOf(cells, vertex) < 0;
  9576. };
  9577. this.executeLayout(function()
  9578. {
  9579. circleLayout.execute(graph.getDefaultParent());
  9580. postProcess();
  9581. }, true, afterInsert);
  9582. afterInsert = null;
  9583. }
  9584. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  9585. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  9586. {
  9587. // Required for layouts to work with new cells
  9588. graph.view.validate();
  9589. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  9590. treeLayout.levelDistance = nodespacing;
  9591. treeLayout.edgeRouting = false;
  9592. treeLayout.resetEdges = false;
  9593. this.executeLayout(function()
  9594. {
  9595. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  9596. }, true, afterInsert);
  9597. afterInsert = null;
  9598. }
  9599. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  9600. (layout == 'auto' && roots.length == 1))
  9601. {
  9602. // Required for layouts to work with new cells
  9603. graph.view.validate();
  9604. var flowLayout = new mxHierarchicalLayout(graph,
  9605. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  9606. flowLayout.intraCellSpacing = nodespacing;
  9607. flowLayout.parallelEdgeSpacing = edgespacing;
  9608. flowLayout.interRankCellSpacing = levelspacing;
  9609. flowLayout.disableEdgeStyle = false;
  9610. this.executeLayout(function()
  9611. {
  9612. flowLayout.execute(graph.getDefaultParent(), select);
  9613. // Workaround for flow layout moving cells to origin
  9614. graph.moveCells(select, x0, y0);
  9615. }, true, afterInsert);
  9616. afterInsert = null;
  9617. }
  9618. else if (layout == 'organic' || (layout == 'auto' &&
  9619. select.length > cells.length))
  9620. {
  9621. // Required for layouts to work with new cells
  9622. graph.view.validate();
  9623. var organicLayout = new mxFastOrganicLayout(graph);
  9624. organicLayout.forceConstant = nodespacing * 3;
  9625. organicLayout.resetEdges = false;
  9626. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  9627. // Ignore other cells
  9628. organicLayout.isVertexIgnored = function(vertex)
  9629. {
  9630. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  9631. mxUtils.indexOf(cells, vertex) < 0;
  9632. };
  9633. var edgeLayout = new mxParallelEdgeLayout(graph);
  9634. edgeLayout.spacing = edgespacing;
  9635. this.executeLayout(function()
  9636. {
  9637. organicLayout.execute(graph.getDefaultParent());
  9638. postProcess();
  9639. }, true, afterInsert);
  9640. afterInsert = null;
  9641. }
  9642. this.hideDialog();
  9643. }
  9644. finally
  9645. {
  9646. graph.model.endUpdate();
  9647. }
  9648. if (afterInsert != null)
  9649. {
  9650. afterInsert();
  9651. }
  9652. }
  9653. }
  9654. catch (e)
  9655. {
  9656. this.handleError(e);
  9657. }
  9658. };
  9659. /**
  9660. * Translates this point by the given vector.
  9661. *
  9662. * @param {number} dx X-coordinate of the translation.
  9663. * @param {number} dy Y-coordinate of the translation.
  9664. */
  9665. EditorUi.prototype.getSearch = function(exclude)
  9666. {
  9667. var result = '';
  9668. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  9669. {
  9670. var amp = '?';
  9671. for (var key in urlParams)
  9672. {
  9673. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  9674. {
  9675. result += amp + key + '=' + urlParams[key];
  9676. amp = '&';
  9677. }
  9678. }
  9679. }
  9680. else
  9681. {
  9682. result = window.location.search;
  9683. }
  9684. return result;
  9685. };
  9686. /**
  9687. * Returns the URL for a copy of this editor with no state.
  9688. */
  9689. EditorUi.prototype.getUrl = function(pathname)
  9690. {
  9691. var href = (pathname != null) ? pathname : window.location.pathname;
  9692. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  9693. if (urlParams['offline'] == '1')
  9694. {
  9695. href += window.location.search;
  9696. }
  9697. else
  9698. {
  9699. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  9700. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  9701. // Removes template URL parameter for new blank diagram
  9702. for (var key in urlParams)
  9703. {
  9704. if (mxUtils.indexOf(ignored, key) < 0)
  9705. {
  9706. if (parms == 0)
  9707. {
  9708. href += '?';
  9709. }
  9710. else
  9711. {
  9712. href += '&';
  9713. }
  9714. if (urlParams[key] != null)
  9715. {
  9716. href += key + '=' + urlParams[key];
  9717. parms++;
  9718. }
  9719. }
  9720. }
  9721. }
  9722. return href;
  9723. };
  9724. /**
  9725. * Overrides link dialog.
  9726. */
  9727. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  9728. {
  9729. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  9730. this.showDialog(dlg.container, 480, 130, true, true);
  9731. dlg.init();
  9732. };
  9733. /**
  9734. * Overrides createOutline
  9735. */
  9736. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  9737. EditorUi.prototype.createOutline = function(wnd)
  9738. {
  9739. var outline = editorUiCreateOutline.apply(this, arguments);
  9740. var graph = this.editor.graph;
  9741. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  9742. outline.getSourceGraphBounds = function()
  9743. {
  9744. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  9745. {
  9746. var pb = this.source.getPagePadding();
  9747. var s = this.source.view.scale;
  9748. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  9749. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  9750. return result;
  9751. }
  9752. return outlineGetSourceGraphBounds.apply(this, arguments);
  9753. };
  9754. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  9755. outline.getSourceContainerSize = function()
  9756. {
  9757. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9758. {
  9759. var pad = this.source.getPagePadding();
  9760. var s = this.source.view.scale;
  9761. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  9762. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  9763. }
  9764. return outlineGetSourceContainerSize.apply(this, arguments);
  9765. };
  9766. outline.getOutlineOffset = function(scale)
  9767. {
  9768. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9769. {
  9770. var pb = this.source.getPagePadding();
  9771. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  9772. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  9773. // Why is vertical offset negative relative to dy
  9774. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  9775. }
  9776. return new mxPoint(8 / scale, 8 / scale);
  9777. };
  9778. var outlineInit = outline.init;
  9779. outline.init = function()
  9780. {
  9781. outlineInit.apply(this, arguments);
  9782. // Problem: Need to override a function in the view but the view is created
  9783. // with the graph so a refresh of the page is needed to see this change.
  9784. outline.outline.view.getBackgroundPageBounds = function()
  9785. {
  9786. var layout = graph.getPageLayout();
  9787. var page = graph.getPageSize();
  9788. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  9789. this.scale * (this.translate.y + layout.y * page.height),
  9790. this.scale * layout.width * page.width,
  9791. this.scale * layout.height * page.height);
  9792. };
  9793. outline.outline.view.validateBackgroundPage();
  9794. };
  9795. this.editor.addListener('pageSelected', function(sender, evt)
  9796. {
  9797. var change = evt.getProperty('change');
  9798. var graph = outline.source;
  9799. var g = outline.outline;
  9800. g.pageScale = graph.pageScale;
  9801. g.pageFormat = graph.pageFormat;
  9802. g.background = graph.background;
  9803. g.pageVisible = graph.pageVisible;
  9804. g.background = graph.background;
  9805. var current = mxUtils.getCurrentStyle(graph.container);
  9806. g.container.style.backgroundColor = current.backgroundColor;
  9807. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  9808. {
  9809. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  9810. }
  9811. outline.outline.view.clear(change.previousPage.root, true);
  9812. outline.outline.view.validate();
  9813. });
  9814. return outline;
  9815. };
  9816. /**
  9817. * Returns the number of storage options enabled
  9818. */
  9819. EditorUi.prototype.getServiceCount = function(allowBrowser, splash)
  9820. {
  9821. var serviceCount = 0;
  9822. if (this.drive != null || typeof window.DriveClient === 'function')
  9823. {
  9824. serviceCount++
  9825. }
  9826. if (!splash && (this.dropbox != null || typeof window.DropboxClient === 'function'))
  9827. {
  9828. serviceCount++
  9829. }
  9830. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  9831. {
  9832. serviceCount++
  9833. }
  9834. if (!splash && (this.gitHub != null))
  9835. {
  9836. serviceCount++
  9837. }
  9838. if (!splash && (this.trello != null || typeof window.TrelloClient === 'function'))
  9839. {
  9840. serviceCount++
  9841. }
  9842. if (allowBrowser && isLocalStorage && urlParams['browser'] == '1')
  9843. {
  9844. serviceCount++
  9845. }
  9846. else
  9847. {
  9848. serviceCount++
  9849. }
  9850. return serviceCount;
  9851. }
  9852. /**
  9853. * Updates action and menu states depending on the file.
  9854. */
  9855. EditorUi.prototype.updateUi = function()
  9856. {
  9857. this.updateButtonContainer();
  9858. this.updateActionStates();
  9859. // Action states that only need update for new files
  9860. var file = this.getCurrentFile();
  9861. var active = file != null || (urlParams['embed'] == '1' &&
  9862. this.editor.graph.isEnabled());
  9863. this.menus.get('viewPanels').setEnabled(active);
  9864. this.menus.get('viewZoom').setEnabled(active);
  9865. var restricted = (urlParams['embed'] != '1' ||
  9866. !this.editor.graph.isEnabled()) &&
  9867. (file == null || file.isRestricted());
  9868. this.actions.get('makeCopy').setEnabled(!restricted);
  9869. this.actions.get('print').setEnabled(!restricted);
  9870. this.menus.get('exportAs').setEnabled(!restricted);
  9871. this.menus.get('embed').setEnabled(!restricted);
  9872. // Disables libraries and extras menu in embed mode
  9873. // while waiting for file data
  9874. var libsEnabled = urlParams['embed'] != '1' ||
  9875. this.editor.graph.isEnabled();
  9876. this.menus.get('extras').setEnabled(libsEnabled);
  9877. if (Editor.enableCustomLibraries)
  9878. {
  9879. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  9880. this.menus.get('newLibrary').setEnabled(libsEnabled);
  9881. }
  9882. // Disables actions in the toolbar
  9883. var editable = (urlParams['embed'] == '1' &&
  9884. this.editor.graph.isEnabled()) ||
  9885. (file != null && file.isEditable());
  9886. this.actions.get('image').setEnabled(active);
  9887. this.actions.get('zoomIn').setEnabled(active);
  9888. this.actions.get('zoomOut').setEnabled(active);
  9889. this.actions.get('resetView').setEnabled(active);
  9890. // Updates undo history states
  9891. this.actions.get('undo').setEnabled(this.canUndo() && editable);
  9892. this.actions.get('redo').setEnabled(this.canRedo() && editable);
  9893. // Disables menus
  9894. this.menus.get('edit').setEnabled(active);
  9895. this.menus.get('view').setEnabled(active);
  9896. this.menus.get('importFrom').setEnabled(editable);
  9897. this.menus.get('arrange').setEnabled(editable);
  9898. // Disables connection drop downs in toolbar
  9899. if (this.toolbar != null)
  9900. {
  9901. if (this.toolbar.edgeShapeMenu != null)
  9902. {
  9903. this.toolbar.edgeShapeMenu.setEnabled(editable);
  9904. }
  9905. if (this.toolbar.edgeStyleMenu != null)
  9906. {
  9907. this.toolbar.edgeStyleMenu.setEnabled(editable);
  9908. }
  9909. }
  9910. if (this.isAppCache())
  9911. {
  9912. var appCache = applicationCache;
  9913. // NOTE: HTML5 Cache is deprecated
  9914. if (appCache != null && this.offlineStatus == null)
  9915. {
  9916. this.offlineStatus = document.createElement('div');
  9917. this.offlineStatus.className = 'geItem';
  9918. this.offlineStatus.style.position = 'absolute';
  9919. this.offlineStatus.style.fontSize = '8pt';
  9920. this.offlineStatus.style.top = '2px';
  9921. this.offlineStatus.style.right = '12px';
  9922. this.offlineStatus.style.color = '#666';
  9923. this.offlineStatus.style.margin = '4px';
  9924. this.offlineStatus.style.padding = '2px';
  9925. this.offlineStatus.style.verticalAlign = 'middle';
  9926. this.offlineStatus.innerHTML = '';
  9927. this.menubarContainer.appendChild(this.offlineStatus);
  9928. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  9929. {
  9930. var img = this.offlineStatus.getElementsByTagName('img');
  9931. if (img != null && img.length > 0)
  9932. {
  9933. this.alert(img[0].getAttribute('title'));
  9934. }
  9935. }));
  9936. var appCache = window.applicationCache;
  9937. var lastStatus = null;
  9938. var updateStatus = mxUtils.bind(this, function()
  9939. {
  9940. var newStatus = appCache.status;
  9941. var html = '';
  9942. if (newStatus == appCache.CHECKING)
  9943. {
  9944. newStatus = appCache.DOWNLOADING;
  9945. }
  9946. switch (newStatus)
  9947. {
  9948. case appCache.UNCACHED: // UNCACHED == 0
  9949. html = '';
  9950. break;
  9951. case appCache.IDLE: // IDLE == 1
  9952. html = (uiTheme == 'min') ? '' : '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  9953. break;
  9954. case appCache.DOWNLOADING: // DOWNLOADING == 3
  9955. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  9956. break;
  9957. case appCache.UPDATEREADY: // UPDATEREADY == 4
  9958. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  9959. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  9960. break;
  9961. case appCache.OBSOLETE: // OBSOLETE == 5
  9962. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9963. break;
  9964. default:
  9965. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9966. break;
  9967. }
  9968. if (newStatus != lastStatus)
  9969. {
  9970. this.offlineStatus.innerHTML = html;
  9971. lastStatus = newStatus;
  9972. }
  9973. });
  9974. mxEvent.addListener(appCache, 'checking', updateStatus);
  9975. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  9976. mxEvent.addListener(appCache, 'downloading', updateStatus);
  9977. mxEvent.addListener(appCache, 'progress', updateStatus);
  9978. mxEvent.addListener(appCache, 'cached', updateStatus);
  9979. mxEvent.addListener(appCache, 'updateready', updateStatus);
  9980. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  9981. mxEvent.addListener(appCache, 'error', updateStatus);
  9982. updateStatus();
  9983. }
  9984. }
  9985. else
  9986. {
  9987. this.updateUserElement();
  9988. }
  9989. };
  9990. /**
  9991. * Hook for subclassers
  9992. */
  9993. EditorUi.prototype.updateButtonContainer = function()
  9994. {
  9995. // do nothing
  9996. };
  9997. /**
  9998. * Hook for subclassers
  9999. */
  10000. EditorUi.prototype.updateUserElement = function()
  10001. {
  10002. // do nothing
  10003. };
  10004. /**
  10005. * Returns true if a diagram is cative and editable.
  10006. */
  10007. EditorUi.prototype.isDiagramActive = function()
  10008. {
  10009. var file = this.getCurrentFile();
  10010. return (file != null && file.isEditable()) ||
  10011. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  10012. };
  10013. /**
  10014. * Updates action states depending on the selection.
  10015. */
  10016. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  10017. EditorUi.prototype.updateActionStates = function()
  10018. {
  10019. editorUiUpdateActionStates.apply(this, arguments);
  10020. var graph = this.editor.graph;
  10021. var active = this.isDiagramActive();
  10022. var file = this.getCurrentFile();
  10023. var enabled = file != null || urlParams['embed'] == '1';
  10024. this.actions.get('pageSetup').setEnabled(active);
  10025. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  10026. this.actions.get('guides').setEnabled(active);
  10027. this.actions.get('editData').setEnabled(active);
  10028. this.actions.get('shadowVisible').setEnabled(active);
  10029. this.actions.get('connectionArrows').setEnabled(active);
  10030. this.actions.get('connectionPoints').setEnabled(active);
  10031. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  10032. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  10033. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  10034. this.actions.get('createShape').setEnabled(active);
  10035. this.actions.get('createRevision').setEnabled(active);
  10036. this.actions.get('moveToFolder').setEnabled(file != null);
  10037. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  10038. this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
  10039. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  10040. this.actions.get('tags').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10041. this.actions.get('find').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10042. this.actions.get('layers').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10043. this.actions.get('outline').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10044. this.actions.get('rename').setEnabled((file != null && file.isRenamable()) || urlParams['embed'] == '1');
  10045. this.actions.get('close').setEnabled(file != null);
  10046. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  10047. var state = graph.view.getState(graph.getSelectionCell());
  10048. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  10049. };
  10050. /**
  10051. * Overridden to remove export dialog in chromeless lightbox.
  10052. */
  10053. var editoUiDestroy = EditorUi.prototype.destroy;
  10054. EditorUi.prototype.destroy = function()
  10055. {
  10056. if (this.editUpdateListener)
  10057. {
  10058. this.editor.undoManager.removeListener(this.editUpdateListener);
  10059. this.editUpdateListener = null;
  10060. }
  10061. if (this.exportDialog != null)
  10062. {
  10063. this.exportDialog.parentNode.removeChild(this.exportDialog);
  10064. this.exportDialog = null;
  10065. }
  10066. editoUiDestroy.apply(this, arguments);
  10067. };
  10068. /**
  10069. * Overrides export dialog for using ui functions for save and setting global switches.
  10070. */
  10071. if (window.ExportDialog != null)
  10072. {
  10073. ExportDialog.showXmlOption = false;
  10074. ExportDialog.showGifOption = false;
  10075. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  10076. {
  10077. var graph = editorUi.editor.graph;
  10078. if (format == 'xml')
  10079. {
  10080. editorUi.hideDialog();
  10081. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  10082. }
  10083. else if (format == 'svg')
  10084. {
  10085. editorUi.hideDialog();
  10086. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  10087. }
  10088. else
  10089. {
  10090. var data = editorUi.getFileData(true, null, null, null, null, true);
  10091. var bounds = graph.getGraphBounds();
  10092. var w = Math.floor(bounds.width * s / graph.view.scale);
  10093. var h = Math.floor(bounds.height * s / graph.view.scale);
  10094. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  10095. {
  10096. editorUi.hideDialog();
  10097. editorUi.saveRequest(name, format,
  10098. function(newTitle, base64)
  10099. {
  10100. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  10101. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  10102. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  10103. '&border=' + b + '&xml=' + encodeURIComponent(data));
  10104. });
  10105. }
  10106. else
  10107. {
  10108. mxUtils.alert(mxResources.get('drawingTooLarge'));
  10109. }
  10110. }
  10111. };
  10112. }
  10113. /*********************************************************************************************
  10114. * This section is a fix for undo/redo edits having stale 1st- and 2nd-order references *
  10115. * The code might be reworked or even thrown out when a conceptually nicer solution is found *
  10116. *********************************************************************************************/
  10117. /**
  10118. * Updates all references in all edits and their changes in order to correspond to current model
  10119. */
  10120. EditorUi.prototype.updateEditReferences = function(edit)
  10121. {
  10122. for (var i = 0; i < edit.changes.length; i++)
  10123. {
  10124. var change = edit.changes[i];
  10125. if (change != null && change.constructor == mxChildChange)
  10126. {
  10127. if (change.child != null)
  10128. {
  10129. var child = change.child;
  10130. if (child.source != null && child.source.id != null)
  10131. {
  10132. var modelSource = this.getFutureCellForEdit(change.model, edit, child.source.id);
  10133. if (modelSource != child.source)
  10134. {
  10135. child.source = modelSource
  10136. }
  10137. }
  10138. if (child.target != null && child.target.id != null)
  10139. {
  10140. var modelTarget = this.getFutureCellForEdit(change.model, edit, child.target.id);
  10141. if (modelTarget != child.target)
  10142. {
  10143. child.target = modelTarget
  10144. }
  10145. }
  10146. }
  10147. }
  10148. }
  10149. };
  10150. /**
  10151. * Looks ahead in edit's changes to see if the last child change containing ID is one that creates a cell, then returns it.
  10152. * If cell already exists in a model, returns it first.
  10153. */
  10154. EditorUi.prototype.getFutureCellForEdit = function(model, edit, id)
  10155. {
  10156. var result = model.getCell(id);
  10157. if (result == null)
  10158. {
  10159. // Scans changes backwards
  10160. for (var i = edit.changes.length - 1; i >= 0; i--)
  10161. {
  10162. var change = edit.changes[i];
  10163. if (change.constructor == mxChildChange)
  10164. {
  10165. // Checks if child is being added in this change
  10166. if (change.child != null && change.child.id == id)
  10167. {
  10168. // Checks if cell is being removed
  10169. if (model.contains(change.previous))
  10170. {
  10171. result = change.child;
  10172. }
  10173. // Stops scan in any case, at the end of the edit
  10174. // the cell will be either added or deleted
  10175. break;
  10176. }
  10177. }
  10178. }
  10179. }
  10180. return result;
  10181. };
  10182. EditorUi.prototype.getDiagramTextContent = function()
  10183. {
  10184. this.editor.graph.setEnabled(false);
  10185. var graph = this.editor.graph;
  10186. var allPagesTxt = '';
  10187. if (this.pages != null)
  10188. {
  10189. for (var i = 0; i < this.pages.length; i++)
  10190. {
  10191. var pageGraph = graph;
  10192. if (this.currentPage != this.pages[i])
  10193. {
  10194. pageGraph = this.createTemporaryGraph(graph.getStylesheet());
  10195. pageGraph.model.setRoot(this.pages[i].root);
  10196. }
  10197. allPagesTxt += this.pages[i].getName() + ' ' + pageGraph.getIndexableText() + ' ';
  10198. }
  10199. }
  10200. else
  10201. {
  10202. allPagesTxt = graph.getIndexableText();
  10203. }
  10204. this.editor.graph.setEnabled(true);
  10205. return allPagesTxt;
  10206. };
  10207. EditorUi.prototype.showRemotelyStoredLibrary = function(title)
  10208. {
  10209. var selectedLibs = {};
  10210. var div = document.createElement('div');
  10211. div.style.whiteSpace = 'nowrap';
  10212. var graph = this.editor.graph;
  10213. var hd = document.createElement('h3');
  10214. mxUtils.write(hd, mxUtils.htmlEntities(title));
  10215. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  10216. div.appendChild(hd);
  10217. var libsSection = document.createElement('div');
  10218. libsSection.style.cssText = 'border:1px solid lightGray;overflow: auto;height:300px';
  10219. libsSection.innerHTML = '<img src="/images/spin.gif">';
  10220. var loadedLibs = {};
  10221. try
  10222. {
  10223. var custLibs = mxSettings.getCustomLibraries();
  10224. for (var j = 0; j < custLibs.length; j++)
  10225. {
  10226. var l = custLibs[j];
  10227. if (l.substring(0, 1) == 'R')
  10228. {
  10229. var libDesc = JSON.parse(decodeURIComponent(l.substring(1)));
  10230. loadedLibs[libDesc[0]] = {
  10231. id: libDesc[0],
  10232. title: libDesc[1],
  10233. downloadUrl: libDesc[2]
  10234. };
  10235. }
  10236. }
  10237. }
  10238. catch(e){}
  10239. this.remoteInvoke('getCustomLibraries', null, null, function(libsList)
  10240. {
  10241. libsSection.innerHTML = '';
  10242. if (libsList.length == 0)
  10243. {
  10244. libsSection.innerHTML = '<div style="text-align:center;padding-top:20px;color:gray;">' +
  10245. mxUtils.htmlEntities(mxResources.get('noLibraries')) + '</div>';
  10246. }
  10247. else
  10248. {
  10249. for (var i = 0; i < libsList.length; i++)
  10250. {
  10251. var lib = libsList[i];
  10252. if (loadedLibs[lib.id])
  10253. {
  10254. selectedLibs[lib.id] = lib;
  10255. }
  10256. var libCheck = this.addCheckbox(libsSection, lib.title, loadedLibs[lib.id]);
  10257. (function(lib2, check)
  10258. {
  10259. mxEvent.addListener(check, 'change', function()
  10260. {
  10261. if (this.checked)
  10262. {
  10263. selectedLibs[lib2.id] = lib2;
  10264. }
  10265. else
  10266. {
  10267. delete selectedLibs[lib2.id];
  10268. }
  10269. });
  10270. })(lib, libCheck)
  10271. }
  10272. }
  10273. }, function()
  10274. {
  10275. this.handleError(null, mxResources.get('errorLoadingFile'));
  10276. });
  10277. div.appendChild(libsSection);
  10278. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  10279. {
  10280. this.spinner.spin(document.body, mxResources.get('loading'));
  10281. var pendingLibs = 0;
  10282. for (var id in selectedLibs)
  10283. {
  10284. if (loadedLibs[id] != null) continue; //already loaded!
  10285. pendingLibs++;
  10286. (mxUtils.bind(this, function(lib)
  10287. {
  10288. this.remoteInvoke('getFileContent', [lib.downloadUrl], null, mxUtils.bind(this, function(libContent)
  10289. {
  10290. pendingLibs--;
  10291. if (pendingLibs == 0) this.spinner.stop();
  10292. try
  10293. {
  10294. this.loadLibrary(new RemoteLibrary(this, libContent, lib));
  10295. }
  10296. catch (e)
  10297. {
  10298. this.handleError(e, mxResources.get('errorLoadingFile'));
  10299. }
  10300. }), mxUtils.bind(this, function()
  10301. {
  10302. pendingLibs--;
  10303. if (pendingLibs == 0) this.spinner.stop();
  10304. this.handleError(null, mxResources.get('errorLoadingFile'));
  10305. }));
  10306. }))(selectedLibs[id]);
  10307. }
  10308. for (var id in loadedLibs)
  10309. {
  10310. if (!selectedLibs[id]) //Removed
  10311. {
  10312. this.closeLibrary(new RemoteLibrary(this, null, loadedLibs[id])); //create a dummy library such that we can call closeLibrary
  10313. }
  10314. }
  10315. if (pendingLibs == 0) this.spinner.stop();
  10316. }), null, null, 'https://desk.draw.io/support/solutions/articles/16000092763');
  10317. this.showDialog(dlg.container, 340, 375, true, true);
  10318. };
  10319. //Remote invokation, currently limited to functions in EditorUi (and its sub objects) for security reasons
  10320. //White-listed functions and some info about it
  10321. EditorUi.prototype.remoteInvokableFns = {
  10322. getDiagramTextContent: {isAsync: false}
  10323. };
  10324. EditorUi.prototype.remoteInvokeCallbacks = [];
  10325. EditorUi.prototype.remoteInvokeQueue = [];
  10326. EditorUi.prototype.handleRemoteInvokeReady = function(remoteWin)
  10327. {
  10328. this.remoteWin = remoteWin;
  10329. for (var i = 0; i < this.remoteInvokeQueue.length; i++)
  10330. {
  10331. remoteWin.postMessage(this.remoteInvokeQueue[i], '*');
  10332. }
  10333. this.remoteInvokeQueue = [];
  10334. };
  10335. EditorUi.prototype.handleRemoteInvokeResponse = function(msg)
  10336. {
  10337. var msgMarkers = msg.msgMarkers;
  10338. var callback = this.remoteInvokeCallbacks[msgMarkers.callbackId];
  10339. if (msg.error)
  10340. {
  10341. if (callback.error) callback.error(msg.error.errResp);
  10342. }
  10343. else if (callback.callback)
  10344. {
  10345. callback.callback.apply(this, msg.resp);
  10346. }
  10347. this.remoteInvokeCallbacks[msgMarkers.callbackId] = null; //set it to null only to keep the index
  10348. };
  10349. EditorUi.prototype.remoteInvoke = function(remoteFn, remoteFnArgs, msgMarkers, callback, error)
  10350. {
  10351. msgMarkers = msgMarkers || {};
  10352. msgMarkers.callbackId = this.remoteInvokeCallbacks.length;
  10353. this.remoteInvokeCallbacks.push({callback: callback, error: error});
  10354. var msg = JSON.stringify({event: 'remoteInvoke', funtionName: remoteFn, functionArgs: remoteFnArgs, msgMarkers: msgMarkers});
  10355. if (this.remoteWin != null) //remote invoke is ready
  10356. {
  10357. this.remoteWin.postMessage(msg, '*');
  10358. }
  10359. else
  10360. {
  10361. this.remoteInvokeQueue.push(msg);
  10362. }
  10363. };
  10364. EditorUi.prototype.handleRemoteInvoke = function(msg)
  10365. {
  10366. var sendResponse = mxUtils.bind(this, function(resp, error)
  10367. {
  10368. var respMsg = {event: 'remoteInvokeResponse', msgMarkers: msg.msgMarkers};
  10369. if (error != null)
  10370. {
  10371. respMsg.error = {errResp: error};
  10372. }
  10373. else if (resp != null)
  10374. {
  10375. respMsg.resp = resp;
  10376. }
  10377. this.remoteWin.postMessage(JSON.stringify(respMsg), '*');
  10378. });
  10379. try
  10380. {
  10381. //Remote invoke are allowed to call functions in AC
  10382. var funtionName = msg.funtionName;
  10383. var functionInfo = this.remoteInvokableFns[funtionName];
  10384. if (functionInfo != null && typeof this[funtionName] === 'function')
  10385. {
  10386. var functionArgs = msg.functionArgs;
  10387. //Confirm functionArgs are not null and is array, otherwise, discard it
  10388. if (!Array.isArray(functionArgs))
  10389. {
  10390. functionArgs = [];
  10391. }
  10392. //for functions with callbacks (async) we assume last two arguments are success, error
  10393. if (functionInfo.isAsync)
  10394. {
  10395. //success
  10396. functionArgs.push(function()
  10397. {
  10398. sendResponse(Array.prototype.slice.apply(arguments));
  10399. });
  10400. //error
  10401. functionArgs.push(function(err)
  10402. {
  10403. sendResponse(null, err || 'Unkown Error');
  10404. });
  10405. this[funtionName].apply(this, functionArgs);
  10406. }
  10407. else
  10408. {
  10409. var resp = this[funtionName].apply(this, functionArgs);
  10410. sendResponse([resp]);
  10411. }
  10412. }
  10413. else
  10414. {
  10415. sendResponse(null, 'Invalid Call: ' + funtionName + ' is not found.');
  10416. }
  10417. }
  10418. catch(e)
  10419. {
  10420. sendResponse(null, 'Invalid Call: An error occured, ' + e.message);
  10421. }
  10422. };
  10423. /**
  10424. *
  10425. * Comments: We need these functions as wrapper of File functions in order to facilitate overriding them if comments are needed without having a file
  10426. * (e.g. Confluence Plugin)
  10427. *
  10428. */
  10429. /**
  10430. * Are comments supported
  10431. */
  10432. EditorUi.prototype.commentsSupported = function()
  10433. {
  10434. var file = this.getCurrentFile();
  10435. return file != null? file.commentsSupported() : false;
  10436. };
  10437. /**
  10438. * Show refresh button?
  10439. */
  10440. EditorUi.prototype.commentsRefreshNeeded = function()
  10441. {
  10442. var file = this.getCurrentFile();
  10443. return file != null? file.commentsRefreshNeeded() : true;
  10444. };
  10445. /**
  10446. * Show save button?
  10447. */
  10448. EditorUi.prototype.commentsSaveNeeded = function()
  10449. {
  10450. var file = this.getCurrentFile();
  10451. return file != null? file.commentsSaveNeeded() : false;
  10452. };
  10453. /**
  10454. * Get comments
  10455. */
  10456. EditorUi.prototype.getComments = function(success, error)
  10457. {
  10458. var file = this.getCurrentFile();
  10459. if (file != null)
  10460. {
  10461. file.getComments(success, error);
  10462. }
  10463. else
  10464. {
  10465. success([]); //placeholder
  10466. }
  10467. };
  10468. /**
  10469. * Add a comment
  10470. */
  10471. EditorUi.prototype.addComment = function(comment, success, error)
  10472. {
  10473. var file = this.getCurrentFile();
  10474. if (file != null)
  10475. {
  10476. file.addComment(comment, success, error);
  10477. }
  10478. else
  10479. {
  10480. success(Date.now()); //placeholder
  10481. }
  10482. };
  10483. /**
  10484. * Can add a reply to a reply
  10485. */
  10486. EditorUi.prototype.canReplyToReplies = function()
  10487. {
  10488. var file = this.getCurrentFile();
  10489. return file != null? file.canReplyToReplies() : true;
  10490. };
  10491. /**
  10492. * Can add comments (The permission to comment)
  10493. */
  10494. EditorUi.prototype.canComment = function()
  10495. {
  10496. var file = this.getCurrentFile();
  10497. return file != null? file.canComment() : true;
  10498. };
  10499. /**
  10500. * Get a new comment object
  10501. */
  10502. EditorUi.prototype.newComment = function(content, user)
  10503. {
  10504. var file = this.getCurrentFile();
  10505. if (file != null)
  10506. {
  10507. return file.newComment(content, user)
  10508. }
  10509. else
  10510. {
  10511. return new DrawioComment(this, null, content, Date.now(), Date.now(), false, user);
  10512. }
  10513. };
  10514. })();
  10515. /**
  10516. * Comments Window, It is used by both editor and viewer. So, it is here in a common place
  10517. */
  10518. var CommentsWindow = function(editorUi, x, y, w, h, saveCallback)
  10519. {
  10520. var readOnly = !editorUi.canComment();
  10521. var canReplyToReplies = editorUi.canReplyToReplies();
  10522. var div = document.createElement('div');
  10523. div.className = 'geCommentsWin';
  10524. div.style.background = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10525. var tbarHeight = (!EditorUi.compactUi) ? '30px' : '26px';
  10526. var listDiv = document.createElement('div');
  10527. listDiv.className = 'geCommentsList';
  10528. listDiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10529. listDiv.style.bottom = (parseInt(tbarHeight) + 7) + 'px';
  10530. div.appendChild(listDiv);
  10531. var noComments = document.createElement('span');
  10532. noComments.style.cssText = 'display:none;padding-top:10px;text-align:center;';
  10533. mxUtils.write(noComments, mxResources.get('noCommentsFound'));
  10534. var selectionComment = null;
  10535. var ldiv = document.createElement('div');
  10536. ldiv.className = 'geToolbarContainer geCommentsToolbar';
  10537. ldiv.style.height = tbarHeight;
  10538. ldiv.style.padding = (!EditorUi.compactUi) ? '1px' : '4px 0px 3px 0px';
  10539. ldiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10540. if (mxClient.IS_QUIRKS)
  10541. {
  10542. ldiv.style.filter = 'none';
  10543. }
  10544. var link = document.createElement('a');
  10545. link.className = 'geButton';
  10546. if (mxClient.IS_QUIRKS)
  10547. {
  10548. link.style.filter = 'none';
  10549. }
  10550. function updateNoComments()
  10551. {
  10552. var divs = listDiv.getElementsByTagName('div');
  10553. var visibleCount = 0;
  10554. for (var i = 0; i < divs.length; i++)
  10555. {
  10556. if (divs[i].style.display != 'none' && divs[i].parentNode == listDiv)
  10557. {
  10558. visibleCount++;
  10559. }
  10560. }
  10561. noComments.style.display = (visibleCount == 0) ? 'block' : 'none';
  10562. };
  10563. function editComment(comment, cdiv, saveCallback, deleteOnCancel)
  10564. {
  10565. var commentTxt = cdiv.querySelector('.geCommentTxt');
  10566. var actionsDiv = cdiv.querySelector('.geCommentActionsList');
  10567. var textArea = document.createElement('textarea');
  10568. textArea.className = 'geCommentEditTxtArea';
  10569. textArea.style.minHeight = commentTxt.offsetHeight + 'px';
  10570. textArea.value = commentTxt.innerHTML;
  10571. cdiv.insertBefore(textArea, commentTxt);
  10572. var btnDiv = document.createElement('div');
  10573. btnDiv.className = 'geCommentEditBtns';
  10574. function reset()
  10575. {
  10576. cdiv.removeChild(textArea);
  10577. cdiv.removeChild(btnDiv);
  10578. actionsDiv.style.display = 'block';
  10579. commentTxt.style.display = 'block';
  10580. };
  10581. var cancelBtn = mxUtils.button(mxResources.get('cancel'), function()
  10582. {
  10583. if (deleteOnCancel)
  10584. {
  10585. cdiv.parentNode.removeChild(cdiv);
  10586. updateNoComments();
  10587. }
  10588. else
  10589. {
  10590. reset();
  10591. }
  10592. });
  10593. cancelBtn.className = 'geCommentEditBtn';
  10594. btnDiv.appendChild(cancelBtn);
  10595. var saveBtn = mxUtils.button(mxResources.get('save'), function()
  10596. {
  10597. commentTxt.innerHTML = '';
  10598. comment.content = textArea.value;
  10599. mxUtils.write(commentTxt, comment.content);
  10600. reset();
  10601. saveCallback(comment);
  10602. });
  10603. // Updates modified state and handles placeholder text
  10604. mxEvent.addListener(textArea, 'keydown', mxUtils.bind(this, function(evt)
  10605. {
  10606. if (!mxEvent.isConsumed(evt))
  10607. {
  10608. if ((mxEvent.isControlDown(evt) || (mxClient.IS_MAC &&
  10609. mxEvent.isMetaDown(evt))) && evt.keyCode == 13 /* Ctrl+Enter */)
  10610. {
  10611. saveBtn.click();
  10612. mxEvent.consume(evt);
  10613. }
  10614. else if (evt.keyCode == 27 /* Escape */)
  10615. {
  10616. cancelBtn.click();
  10617. mxEvent.consume(evt);
  10618. }
  10619. }
  10620. }));
  10621. // Focused to include in viewport before focusin textbox
  10622. saveBtn.focus();
  10623. saveBtn.className = 'geCommentEditBtn gePrimaryBtn';
  10624. btnDiv.appendChild(saveBtn);
  10625. cdiv.insertBefore(btnDiv, commentTxt);
  10626. actionsDiv.style.display = 'none';
  10627. commentTxt.style.display = 'none';
  10628. textArea.focus();
  10629. };
  10630. function writeCommentDate(comment, dateDiv)
  10631. {
  10632. dateDiv.innerHTML = '';
  10633. var str = editorUi.timeSince(new Date(comment.modifiedDate));
  10634. if (str == null)
  10635. {
  10636. str = mxResources.get('lessThanAMinute');
  10637. }
  10638. mxUtils.write(dateDiv, mxResources.get('timeAgo', [str], '{1} ago'));
  10639. };
  10640. function showBusy(commentDiv)
  10641. {
  10642. var busyImg = document.createElement('img');
  10643. busyImg.className = 'geCommentBusyImg';
  10644. busyImg.src= '/images/spin.gif';
  10645. commentDiv.appendChild(busyImg);
  10646. commentDiv.busyImg = busyImg;
  10647. };
  10648. function showError(commentDiv)
  10649. {
  10650. commentDiv.style.border = '1px solid red';
  10651. commentDiv.removeChild(commentDiv.busyImg);
  10652. };
  10653. function showDone(commentDiv)
  10654. {
  10655. commentDiv.style.border = '';
  10656. commentDiv.removeChild(commentDiv.busyImg);
  10657. };
  10658. function addComment(comment, parentArr, parent, level, showResolved)
  10659. {
  10660. //Skip resolved comments if showResolved is not set
  10661. if (!showResolved && comment.isResolved)
  10662. {
  10663. return;
  10664. }
  10665. noComments.style.display = 'none';
  10666. var cdiv = document.createElement('div');
  10667. cdiv.className = 'geCommentContainer';
  10668. cdiv.setAttribute('data-commentId', comment.id);
  10669. cdiv.style.marginLeft = (level * 20 + 5) + 'px';
  10670. if (comment.isResolved && uiTheme != 'dark')
  10671. {
  10672. cdiv.style.backgroundColor = 'ghostWhite';
  10673. }
  10674. var headerDiv = document.createElement('div');
  10675. headerDiv.className = 'geCommentHeader';
  10676. var userImg = document.createElement('img');
  10677. userImg.className = 'geCommentUserImg';
  10678. userImg.src = comment.user.pictureUrl || Editor.userImage;
  10679. headerDiv.appendChild(userImg);
  10680. var headerTxt = document.createElement('div');
  10681. headerTxt.className = 'geCommentHeaderTxt';
  10682. headerDiv.appendChild(headerTxt);
  10683. var usernameDiv = document.createElement('div');
  10684. usernameDiv.className = 'geCommentUsername';
  10685. mxUtils.write(usernameDiv, comment.user.displayName || '');
  10686. headerTxt.appendChild(usernameDiv);
  10687. var dateDiv = document.createElement('div');
  10688. dateDiv.className = 'geCommentDate';
  10689. dateDiv.setAttribute('data-commentId', comment.id);
  10690. writeCommentDate(comment, dateDiv);
  10691. headerTxt.appendChild(dateDiv);
  10692. cdiv.appendChild(headerDiv);
  10693. var commentTxtDiv = document.createElement('div');
  10694. commentTxtDiv.className = 'geCommentTxt';
  10695. mxUtils.write(commentTxtDiv, comment.content || '');
  10696. cdiv.appendChild(commentTxtDiv);
  10697. var actionsDiv = document.createElement('div');
  10698. actionsDiv.className = 'geCommentActions';
  10699. var actionsList = document.createElement('ul');
  10700. actionsList.className = 'geCommentActionsList';
  10701. actionsDiv.appendChild(actionsList);
  10702. function addAction(name, evtHandler, hide)
  10703. {
  10704. var action = document.createElement('li');
  10705. action.className = 'geCommentAction';
  10706. var actionLnk = document.createElement('a');
  10707. actionLnk.className = 'geCommentActionLnk';
  10708. mxUtils.write(actionLnk, name);
  10709. action.appendChild(actionLnk);
  10710. mxEvent.addListener(actionLnk, 'click', function(evt)
  10711. {
  10712. evtHandler(evt, comment);
  10713. evt.preventDefault();
  10714. mxEvent.consume(evt);
  10715. });
  10716. actionsList.appendChild(action);
  10717. if (hide) action.style.display = 'none';
  10718. };
  10719. function collectReplies()
  10720. {
  10721. var replies = [];
  10722. var pdiv = cdiv;
  10723. function collectReplies(comment)
  10724. {
  10725. replies.push(pdiv);
  10726. if (comment.replies != null)
  10727. {
  10728. for (var i = 0; i < comment.replies.length; i++)
  10729. {
  10730. pdiv = pdiv.nextSibling;
  10731. collectReplies(comment.replies[i]);
  10732. }
  10733. }
  10734. }
  10735. collectReplies(comment);
  10736. return {pdiv: pdiv, replies: replies};
  10737. };
  10738. function addReply(initContent, editIt, saveCallback, doResolve, doReopen)
  10739. {
  10740. var pdiv = collectReplies().pdiv;
  10741. var newReply = editorUi.newComment(initContent, editorUi.getCurrentUser());
  10742. newReply.pCommentId = comment.id;
  10743. if (comment.replies == null) comment.replies = [];
  10744. var replyComment = addComment(newReply, comment.replies, pdiv, level + 1);
  10745. function doAddReply()
  10746. {
  10747. showBusy(replyComment);
  10748. comment.addReply(newReply, function(id)
  10749. {
  10750. newReply.id = id;
  10751. comment.replies.push(newReply);
  10752. showDone(replyComment);
  10753. if (saveCallback) saveCallback();
  10754. }, function(err)
  10755. {
  10756. doEdit();
  10757. showError(replyComment);
  10758. editorUi.handleError(err, null, null, null,
  10759. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  10760. }, doResolve, doReopen);
  10761. };
  10762. function doEdit()
  10763. {
  10764. editComment(newReply, replyComment, function(newReply)
  10765. {
  10766. doAddReply();
  10767. }, true);
  10768. };
  10769. if (editIt)
  10770. {
  10771. doEdit();
  10772. }
  10773. else
  10774. {
  10775. doAddReply();
  10776. }
  10777. };
  10778. if (!readOnly && (level == 0 || canReplyToReplies))
  10779. {
  10780. addAction(mxResources.get('reply'), function()
  10781. {
  10782. addReply('', true);
  10783. }, comment.isResolved);
  10784. }
  10785. var user = editorUi.getCurrentUser();
  10786. if (user != null && user.id == comment.user.id && !readOnly)
  10787. {
  10788. addAction(mxResources.get('edit'), function()
  10789. {
  10790. function doEditComment()
  10791. {
  10792. editComment(comment, cdiv, function()
  10793. {
  10794. showBusy(cdiv);
  10795. comment.editComment(comment.content, function()
  10796. {
  10797. showDone(cdiv);
  10798. }, function(err)
  10799. {
  10800. showError(cdiv);
  10801. doEditComment();
  10802. editorUi.handleError(err, null, null, null,
  10803. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  10804. });
  10805. });
  10806. };
  10807. doEditComment();
  10808. }, comment.isResolved);
  10809. addAction(mxResources.get('delete'), function()
  10810. {
  10811. editorUi.confirm(mxResources.get('areYouSure'), function()
  10812. {
  10813. showBusy(cdiv);
  10814. comment.deleteComment(function()
  10815. {
  10816. var replies = collectReplies(comment).replies;
  10817. for (var i = 0; i < replies.length; i++)
  10818. {
  10819. listDiv.removeChild(replies[i]);
  10820. }
  10821. for (var i = 0; i < parentArr.length; i++)
  10822. {
  10823. if (parentArr[i] == comment)
  10824. {
  10825. parentArr.splice(i, 1);
  10826. break;
  10827. }
  10828. }
  10829. noComments.style.display = (listDiv.getElementsByTagName('div').length == 0) ? 'block' : 'none';
  10830. }, function(err)
  10831. {
  10832. showError(cdiv);
  10833. editorUi.handleError(err, null, null, null,
  10834. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  10835. });
  10836. });
  10837. }, comment.isResolved);
  10838. }
  10839. if (!readOnly && level == 0) //Resolve is a top-level action only
  10840. {
  10841. function toggleResolve(evt)
  10842. {
  10843. function doToggle()
  10844. {
  10845. var resolveActionLnk = evt.target;
  10846. resolveActionLnk.innerHTML = '';
  10847. comment.isResolved = !comment.isResolved;
  10848. mxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));
  10849. var actionsDisplay = comment.isResolved? 'none' : '';
  10850. var replies = collectReplies(comment).replies;
  10851. var color = (uiTheme == 'dark') ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');
  10852. for (var i = 0; i < replies.length; i++)
  10853. {
  10854. replies[i].style.backgroundColor = color;
  10855. var forOpenActions = replies[i].querySelectorAll('.geCommentAction');
  10856. for (var j = 0; j < forOpenActions.length; j ++)
  10857. {
  10858. if (forOpenActions[j] == resolveActionLnk.parentNode) continue;
  10859. forOpenActions[j].style.display = actionsDisplay;
  10860. }
  10861. if (!resolvedChecked)
  10862. {
  10863. replies[i].style.display = 'none';
  10864. }
  10865. }
  10866. updateNoComments();
  10867. };
  10868. if (comment.isResolved)
  10869. {
  10870. addReply(mxResources.get('reOpened') + ': ', true, doToggle, false, true);
  10871. }
  10872. else
  10873. {
  10874. addReply(mxResources.get('markedAsResolved'), false, doToggle, true);
  10875. }
  10876. };
  10877. addAction(comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'), toggleResolve);
  10878. }
  10879. cdiv.appendChild(actionsDiv);
  10880. if (parent != null)
  10881. {
  10882. listDiv.insertBefore(cdiv, parent.nextSibling);
  10883. }
  10884. else
  10885. {
  10886. listDiv.appendChild(cdiv);
  10887. }
  10888. for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
  10889. {
  10890. var reply = comment.replies[i];
  10891. reply.isResolved = comment.isResolved; //copy isResolved to child comments (replies)
  10892. addComment(reply, comment.replies, null, level + 1, showResolved);
  10893. }
  10894. return cdiv;
  10895. };
  10896. if (!readOnly)
  10897. {
  10898. var addLink = link.cloneNode();
  10899. addLink.innerHTML = '<div class="geSprite geSprite-plus" style="display:inline-block;"></div>';
  10900. addLink.setAttribute('title', mxResources.get('create') + '...');
  10901. mxEvent.addListener(addLink, 'click', function(evt)
  10902. {
  10903. var newComment = editorUi.newComment('', editorUi.getCurrentUser());
  10904. var newCommentDiv = addComment(newComment, comments, null, 0);
  10905. function doAddComment()
  10906. {
  10907. editComment(newComment, newCommentDiv, function(newComment)
  10908. {
  10909. showBusy(newCommentDiv);
  10910. editorUi.addComment(newComment, function(id)
  10911. {
  10912. newComment.id = id;
  10913. comments.push(newComment);
  10914. showDone(newCommentDiv);
  10915. }, function(err)
  10916. {
  10917. showError(newCommentDiv);
  10918. doAddComment();
  10919. editorUi.handleError(err, null, null, null,
  10920. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  10921. });
  10922. }, true);
  10923. }
  10924. doAddComment();
  10925. evt.preventDefault();
  10926. mxEvent.consume(evt);
  10927. });
  10928. ldiv.appendChild(addLink);
  10929. }
  10930. var resolvedLink = link.cloneNode();
  10931. resolvedLink.innerHTML = '<img src="/images/check.png" style="width: 16px; padding: 2px;">';
  10932. resolvedLink.setAttribute('title', mxResources.get('showResolved'));
  10933. var resolvedChecked = false;
  10934. if (uiTheme == 'dark')
  10935. {
  10936. resolvedLink.style.filter = 'invert(100%)';
  10937. }
  10938. mxEvent.addListener(resolvedLink, 'click', function(evt)
  10939. {
  10940. resolvedChecked = !resolvedChecked;
  10941. this.className = resolvedChecked? 'geButton geCheckedBtn' : 'geButton';
  10942. refresh();
  10943. evt.preventDefault();
  10944. mxEvent.consume(evt);
  10945. });
  10946. ldiv.appendChild(resolvedLink);
  10947. if (editorUi.commentsRefreshNeeded())
  10948. {
  10949. var refreshLink = link.cloneNode();
  10950. refreshLink.innerHTML = '<img src="/images/update16.png" style="width: 16px; padding: 2px;">';
  10951. refreshLink.setAttribute('title', mxResources.get('refresh'));
  10952. if (uiTheme == 'dark')
  10953. {
  10954. refreshLink.style.filter = 'invert(100%)';
  10955. }
  10956. mxEvent.addListener(refreshLink, 'click', function(evt)
  10957. {
  10958. refresh();
  10959. evt.preventDefault();
  10960. mxEvent.consume(evt);
  10961. });
  10962. ldiv.appendChild(refreshLink);
  10963. }
  10964. if (editorUi.commentsSaveNeeded())
  10965. {
  10966. var saveLink = link.cloneNode();
  10967. saveLink.innerHTML = '<img src="/images/save.png" style="width: 20px; padding: 2px;">';
  10968. saveLink.setAttribute('title', mxResources.get('save'));
  10969. if (uiTheme == 'dark')
  10970. {
  10971. saveLink.style.filter = 'invert(100%)';
  10972. }
  10973. mxEvent.addListener(saveLink, 'click', function(evt)
  10974. {
  10975. saveCallback();
  10976. evt.preventDefault();
  10977. mxEvent.consume(evt);
  10978. });
  10979. ldiv.appendChild(saveLink);
  10980. }
  10981. div.appendChild(ldiv);
  10982. var comments = [];
  10983. var refresh = mxUtils.bind(this, function()
  10984. {
  10985. listDiv.innerHTML = '<div style="padding-top:10px;text-align:center;"><img src="/images/spin.gif" valign="middle"> ' +
  10986. mxUtils.htmlEntities(mxResources.get('loading')) + '...</div>';
  10987. canReplyToReplies = editorUi.canReplyToReplies();
  10988. if (editorUi.commentsSupported())
  10989. {
  10990. editorUi.getComments(function(list)
  10991. {
  10992. function sortReplies(replies)
  10993. {
  10994. if (replies != null)
  10995. {
  10996. //Sort replies old to new
  10997. replies.sort(function(r1, r2)
  10998. {
  10999. return new Date(r1.modifiedDate) - new Date(r2.modifiedDate);
  11000. });
  11001. for (var i = 0; i < replies.length; i++)
  11002. {
  11003. sortReplies(replies[i].replies);
  11004. }
  11005. }
  11006. };
  11007. //Sort comments old to new
  11008. list.sort(function(c1, c2)
  11009. {
  11010. return new Date(c1.modifiedDate) - new Date(c2.modifiedDate);
  11011. });
  11012. listDiv.innerHTML = '';
  11013. listDiv.appendChild(noComments);
  11014. noComments.style.display = 'block';
  11015. comments = list;
  11016. for (var i = 0; i < comments.length; i++)
  11017. {
  11018. sortReplies(comments[i].replies);
  11019. addComment(comments[i], comments, null, 0, resolvedChecked);
  11020. }
  11021. }, function()
  11022. {
  11023. listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error'));
  11024. });
  11025. }
  11026. else
  11027. {
  11028. //TODO if comments are not supported, close the dialog
  11029. listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error'));
  11030. }
  11031. });
  11032. refresh();
  11033. this.refreshComments = refresh;
  11034. //Refresh the modified date of each comment if the window is visible
  11035. var refreshCommentsTime = mxUtils.bind(this, function()
  11036. {
  11037. if (!this.window.isVisible()) return; //only update if it is visible
  11038. var modDateDivs = listDiv.querySelectorAll('.geCommentDate');
  11039. var modDateDivsMap = {};
  11040. for (var i = 0; i < modDateDivs.length; i++)
  11041. {
  11042. var div = modDateDivs[i];
  11043. modDateDivsMap[div.getAttribute('data-commentId')] = div;
  11044. }
  11045. function processComment(comment)
  11046. {
  11047. var div = modDateDivsMap[comment.id];
  11048. if (div == null) return; //resolved comments
  11049. writeCommentDate(comment, div);
  11050. for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
  11051. {
  11052. processComment(comment.replies[i]);
  11053. }
  11054. };
  11055. for (var i = 0; i < comments.length; i++)
  11056. {
  11057. processComment(comments[i]);
  11058. }
  11059. });
  11060. //Periodically refresh time every one minute
  11061. setInterval(refreshCommentsTime, 60000);
  11062. this.refreshCommentsTime = refreshCommentsTime;
  11063. this.window = new mxWindow(mxResources.get('comments'), div, x, y, w, h, true, true);
  11064. this.window.minimumSize = new mxRectangle(0, 0, 300, 200);
  11065. this.window.destroyOnClose = false;
  11066. this.window.setMaximizable(false);
  11067. this.window.setResizable(true);
  11068. this.window.setClosable(true);
  11069. this.window.setVisible(true);
  11070. this.window.addListener(mxEvent.SHOW, mxUtils.bind(this, function()
  11071. {
  11072. this.window.fit();
  11073. }));
  11074. this.window.setLocation = function(x, y)
  11075. {
  11076. var iw = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
  11077. var ih = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
  11078. x = Math.max(0, Math.min(x, iw - this.table.clientWidth));
  11079. y = Math.max(0, Math.min(y, ih - this.table.clientHeight - 48));
  11080. if (this.getX() != x || this.getY() != y)
  11081. {
  11082. mxWindow.prototype.setLocation.apply(this, arguments);
  11083. }
  11084. };
  11085. var resizeListener = mxUtils.bind(this, function()
  11086. {
  11087. var x = this.window.getX();
  11088. var y = this.window.getY();
  11089. this.window.setLocation(x, y);
  11090. });
  11091. mxEvent.addListener(window, 'resize', resizeListener);
  11092. this.destroy = function()
  11093. {
  11094. mxEvent.removeListener(window, 'resize', resizeListener);
  11095. this.window.destroy();
  11096. }
  11097. };
  11098. /**
  11099. *
  11100. */
  11101. var ConfirmDialog = function(editorUi, message, okFn, cancelFn, okLabel, cancelLabel, okImg, cancelImg, showRememberOption, imgSrc)
  11102. {
  11103. var div = document.createElement('div');
  11104. div.style.textAlign = 'center';
  11105. var p2 = document.createElement('div');
  11106. p2.style.padding = '6px';
  11107. p2.style.overflow = 'auto';
  11108. p2.style.maxHeight = '44px';
  11109. p2.style.lineHeight = '1.2em';
  11110. if (mxClient.IS_QUIRKS)
  11111. {
  11112. p2.style.height = '60px';
  11113. }
  11114. mxUtils.write(p2, message);
  11115. div.appendChild(p2);
  11116. if (imgSrc != null)
  11117. {
  11118. var p3 = document.createElement('div');
  11119. p3.style.padding = '6px 0 6px 0';
  11120. var img = document.createElement('img');
  11121. img.setAttribute('src', imgSrc);
  11122. p3.appendChild(img);
  11123. div.appendChild(p3);
  11124. }
  11125. var btns = document.createElement('div');
  11126. btns.style.textAlign = 'center';
  11127. btns.style.whiteSpace = 'nowrap';
  11128. var cb = document.createElement('input');
  11129. cb.setAttribute('type', 'checkbox');
  11130. var cancelBtn = mxUtils.button(cancelLabel || mxResources.get('cancel'), function()
  11131. {
  11132. editorUi.hideDialog();
  11133. if (cancelFn != null)
  11134. {
  11135. cancelFn(cb.checked);
  11136. }
  11137. });
  11138. cancelBtn.className = 'geBtn';
  11139. if (cancelImg != null)
  11140. {
  11141. cancelBtn.innerHTML = cancelImg + '<br>' + cancelBtn.innerHTML;
  11142. cancelBtn.style.paddingBottom = '8px';
  11143. cancelBtn.style.paddingTop = '8px';
  11144. cancelBtn.style.height = 'auto';
  11145. cancelBtn.style.width = '40%';
  11146. }
  11147. if (editorUi.editor.cancelFirst)
  11148. {
  11149. btns.appendChild(cancelBtn);
  11150. }
  11151. var okBtn = mxUtils.button(okLabel || mxResources.get('ok'), function()
  11152. {
  11153. editorUi.hideDialog();
  11154. if (okFn != null)
  11155. {
  11156. okFn(cb.checked);
  11157. }
  11158. });
  11159. btns.appendChild(okBtn);
  11160. if (okImg != null)
  11161. {
  11162. okBtn.innerHTML = okImg + '<br>' + okBtn.innerHTML + '<br>';
  11163. okBtn.style.paddingBottom = '8px';
  11164. okBtn.style.paddingTop = '8px';
  11165. okBtn.style.height = 'auto';
  11166. okBtn.className = 'geBtn';
  11167. okBtn.style.width = '40%';
  11168. }
  11169. else
  11170. {
  11171. okBtn.className = 'geBtn gePrimaryBtn';
  11172. }
  11173. if (!editorUi.editor.cancelFirst)
  11174. {
  11175. btns.appendChild(cancelBtn);
  11176. }
  11177. div.appendChild(btns);
  11178. if (showRememberOption)
  11179. {
  11180. btns.style.marginTop = '10px';
  11181. var p2 = document.createElement('p');
  11182. p2.style.marginTop = '20px';
  11183. p2.appendChild(cb);
  11184. var span = document.createElement('span');
  11185. mxUtils.write(span, ' ' + mxResources.get('rememberThisSetting'));
  11186. p2.appendChild(span);
  11187. div.appendChild(p2);
  11188. mxEvent.addListener(span, 'click', function(evt)
  11189. {
  11190. cb.checked = !cb.checked;
  11191. mxEvent.consume(evt);
  11192. });
  11193. }
  11194. else
  11195. {
  11196. btns.style.marginTop = '12px';
  11197. }
  11198. this.init = function()
  11199. {
  11200. okBtn.focus();
  11201. };
  11202. this.container = div;
  11203. };