EditorUi.js 178 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199
  1. /**
  2. * Copyright (c) 2006-2012, JGraph Ltd
  3. */
  4. /**
  5. * Constructs a new graph editor
  6. */
  7. EditorUi = function (editor, container, lightbox) {
  8. mxEventSource.call(this);
  9. this.destroyFunctions = [];
  10. this.editor = editor || new Editor();
  11. this.container = container || document.body;
  12. var ui = this;
  13. var graph = this.editor.graph;
  14. graph.lightbox = lightbox;
  15. // Overrides graph bounds to include background images
  16. var graphGetGraphBounds = graph.getGraphBounds;
  17. graph.getGraphBounds = function () {
  18. var bounds = graphGetGraphBounds.apply(this, arguments);
  19. var img = this.backgroundImage;
  20. if (img != null && img.width != null && img.height != null) {
  21. var t = this.view.translate;
  22. var s = this.view.scale;
  23. bounds = mxRectangle.fromRectangle(bounds);
  24. bounds.add(new mxRectangle(
  25. (t.x + img.x) * s, (t.y + img.y) * s,
  26. img.width * s, img.height * s));
  27. }
  28. return bounds;
  29. };
  30. // Faster scrollwheel zoom is possible with CSS transforms
  31. if (graph.useCssTransforms) {
  32. this.lazyZoomDelay = 0;
  33. }
  34. // Pre-fetches submenu image or replaces with embedded image if supported
  35. if (mxClient.IS_SVG) {
  36. mxPopupMenu.prototype.submenuImage = 'data:image/gif;base64,R0lGODlhCQAJAIAAAP///zMzMyH5BAEAAAAALAAAAAAJAAkAAAIPhI8WebHsHopSOVgb26AAADs=';
  37. }
  38. else {
  39. new Image().src = mxPopupMenu.prototype.submenuImage;
  40. }
  41. // Pre-fetches connect image
  42. if (!mxClient.IS_SVG && mxConnectionHandler.prototype.connectImage != null) {
  43. new Image().src = mxConnectionHandler.prototype.connectImage.src;
  44. }
  45. // Installs selection state listener
  46. this.selectionStateListener = mxUtils.bind(this, function (sender, evt) {
  47. this.clearSelectionState();
  48. });
  49. graph.getSelectionModel().addListener(mxEvent.CHANGE, this.selectionStateListener);
  50. graph.getModel().addListener(mxEvent.CHANGE, this.selectionStateListener);
  51. graph.addListener(mxEvent.EDITING_STARTED, this.selectionStateListener);
  52. graph.addListener(mxEvent.EDITING_STOPPED, this.selectionStateListener);
  53. graph.getView().addListener('unitChanged', this.selectionStateListener);
  54. // Disables graph and forced panning in chromeless mode
  55. if (this.editor.chromeless && !this.editor.editable) {
  56. this.footerHeight = 0;
  57. graph.isEnabled = function () { return false; };
  58. graph.panningHandler.isForcePanningEvent = function (me) {
  59. return !mxEvent.isPopupTrigger(me.getEvent());
  60. };
  61. }
  62. // Creates the user interface
  63. this.actions = new Actions(this);
  64. this.menus = this.createMenus();
  65. if (!graph.standalone) {
  66. // Stores the current style and assigns it to new cells
  67. var styles = ['rounded', 'shadow', 'glass', 'dashed', 'dashPattern', 'labelBackgroundColor',
  68. 'labelBorderColor', 'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
  69. 'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
  70. 'simplification', 'sketchStyle', 'pointerEvents', 'strokeColor', 'strokeWidth'];
  71. var connectStyles = ['shape', 'edgeStyle', 'curved', 'rounded', 'elbow', 'jumpStyle', 'jumpSize',
  72. 'comic', 'sketch', 'fillWeight', 'hachureGap', 'hachureAngle', 'jiggle',
  73. 'disableMultiStroke', 'disableMultiStrokeFill', 'fillStyle', 'curveFitting',
  74. 'simplification', 'sketchStyle'];
  75. // Styles to be ignored if applyAll is false
  76. var ignoredEdgeStyles = ['curved', 'sourcePerimeterSpacing', 'targetPerimeterSpacing',
  77. 'startArrow', 'startFill', 'startSize', 'endArrow', 'endFill', 'endSize'];
  78. var vertexStyleIgnored = false;
  79. var edgeStyleIgnored = false;
  80. // Note: Everything that is not in styles is ignored (styles is augmented below)
  81. this.setDefaultStyle = function (cell) {
  82. try {
  83. if (graph.getModel().isEdge(cell)) {
  84. edgeStyleIgnored = false;
  85. }
  86. else {
  87. vertexStyleIgnored = false;
  88. }
  89. var style = graph.getCellStyle(cell, false);
  90. var values = [];
  91. var keys = [];
  92. for (var key in style) {
  93. values.push(style[key]);
  94. keys.push(key);
  95. }
  96. // Resets current style
  97. if (graph.getModel().isEdge(cell)) {
  98. graph.currentEdgeStyle = {};
  99. }
  100. else {
  101. graph.currentVertexStyle = {}
  102. }
  103. this.fireEvent(new mxEventObject('styleChanged',
  104. 'keys', keys, 'values', values,
  105. 'cells', [cell], 'force', true));
  106. // Blocks update of default style with style changes
  107. // once the it was set using this function
  108. if (graph.getModel().isEdge(cell)) {
  109. edgeStyleIgnored = true;
  110. }
  111. else {
  112. vertexStyleIgnored = true;
  113. }
  114. }
  115. catch (e) {
  116. this.handleError(e);
  117. }
  118. };
  119. this.clearDefaultStyle = function () {
  120. graph.currentEdgeStyle = mxUtils.clone(graph.defaultEdgeStyle);
  121. graph.currentVertexStyle = mxUtils.clone(graph.defaultVertexStyle);
  122. edgeStyleIgnored = false;
  123. vertexStyleIgnored = false;
  124. // Updates UI
  125. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  126. };
  127. // Keys that should be ignored if the cell has a value (known: new default for all cells is html=1 so
  128. // for the html key this effecticely only works for edges inserted via the connection handler)
  129. var valueStyles = ['fontFamily', 'fontSource', 'fontSize', 'fontColor'];
  130. for (var i = 0; i < valueStyles.length; i++) {
  131. if (mxUtils.indexOf(styles, valueStyles[i]) < 0) {
  132. styles.push(valueStyles[i]);
  133. }
  134. }
  135. // Keys that always update the current edge style regardless of selection
  136. var alwaysEdgeStyles = ['edgeStyle', 'startArrow', 'startFill', 'startSize', 'endArrow',
  137. 'endFill', 'endSize'];
  138. // Keys that are ignored together (if one appears all are ignored)
  139. var keyGroups = [['startArrow', 'startFill', 'endArrow', 'endFill'],
  140. ['startSize', 'endSize'],
  141. ['sourcePerimeterSpacing', 'targetPerimeterSpacing'],
  142. ['fillColor', 'gradientColor', 'gradientDirection'],
  143. ['opacity'],
  144. ['html']];
  145. // Adds all keys used above to the styles array
  146. for (var i = 0; i < keyGroups.length; i++) {
  147. for (var j = 0; j < keyGroups[i].length; j++) {
  148. styles.push(keyGroups[i][j]);
  149. }
  150. }
  151. for (var i = 0; i < connectStyles.length; i++) {
  152. if (mxUtils.indexOf(styles, connectStyles[i]) < 0) {
  153. styles.push(connectStyles[i]);
  154. }
  155. }
  156. // Implements a global current style for edges and vertices that is applied to new cells
  157. var insertHandler = function (cells, asText, model, vertexStyle, edgeStyle, applyAll, recurse) {
  158. vertexStyle = (vertexStyle != null) ? vertexStyle : graph.currentVertexStyle;
  159. edgeStyle = (edgeStyle != null) ? edgeStyle : graph.currentEdgeStyle;
  160. applyAll = (applyAll != null) ? applyAll : true;
  161. model = (model != null) ? model : graph.getModel();
  162. if (recurse) {
  163. var temp = [];
  164. for (var i = 0; i < cells.length; i++) {
  165. temp = temp.concat(model.getDescendants(cells[i]));
  166. }
  167. cells = temp;
  168. }
  169. model.beginUpdate();
  170. try {
  171. for (var i = 0; i < cells.length; i++) {
  172. var cell = cells[i];
  173. var isText = asText;
  174. var appliedStyles;
  175. // Applies basic text styles for cells with text class
  176. if (cell.style != null && !isText) {
  177. pairs = cell.style.split(';');
  178. isText = isText || mxUtils.indexOf(pairs, 'text') >= 0;
  179. }
  180. if (isText) {
  181. // Applies only basic text styles
  182. appliedStyles = ['fontSize', 'fontFamily', 'fontColor'];
  183. }
  184. else {
  185. // Removes styles defined in the cell style from the styles to be applied
  186. var cellStyle = model.getStyle(cell);
  187. var tokens = (cellStyle != null) ? cellStyle.split(';') : [];
  188. appliedStyles = styles.slice();
  189. for (var j = 0; j < tokens.length; j++) {
  190. var tmp = tokens[j];
  191. var pos = tmp.indexOf('=');
  192. if (pos >= 0) {
  193. var key = tmp.substring(0, pos);
  194. var index = mxUtils.indexOf(appliedStyles, key);
  195. if (index >= 0) {
  196. appliedStyles.splice(index, 1);
  197. }
  198. // Handles special cases where one defined style ignores other styles
  199. for (var k = 0; k < keyGroups.length; k++) {
  200. var group = keyGroups[k];
  201. if (mxUtils.indexOf(group, key) >= 0) {
  202. for (var l = 0; l < group.length; l++) {
  203. var index2 = mxUtils.indexOf(appliedStyles, group[l]);
  204. if (index2 >= 0) {
  205. appliedStyles.splice(index2, 1);
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. // Applies the current style to the cell
  214. var edge = model.isEdge(cell);
  215. var current = (edge) ? edgeStyle : vertexStyle;
  216. var newStyle = model.getStyle(cell);
  217. for (var j = 0; j < appliedStyles.length; j++) {
  218. var key = appliedStyles[j];
  219. var styleValue = current[key];
  220. if (styleValue != null && key != 'edgeStyle' && (key != 'shape' || edge)) {
  221. // Special case: Connect styles are not applied here but in the connection handler
  222. if (!edge || applyAll || mxUtils.indexOf(ignoredEdgeStyles, key) < 0) {
  223. newStyle = mxUtils.setStyle(newStyle, key, styleValue);
  224. }
  225. }
  226. }
  227. if (Editor.simpleLabels) {
  228. newStyle = mxUtils.setStyle(mxUtils.setStyle(
  229. newStyle, 'html', null), 'whiteSpace', null);
  230. }
  231. model.setStyle(cell, newStyle);
  232. }
  233. }
  234. finally {
  235. model.endUpdate();
  236. }
  237. return cells;
  238. };
  239. graph.addListener('cellsInserted', function (sender, evt) {
  240. insertHandler(evt.getProperty('cells'), null, null, null, null, true, true);
  241. });
  242. graph.addListener('textInserted', function (sender, evt) {
  243. insertHandler(evt.getProperty('cells'), true);
  244. });
  245. this.insertHandler = insertHandler;
  246. this.createDivs();
  247. this.createUi();
  248. this.refresh();
  249. // Disables HTML and text selection
  250. var textEditing = mxUtils.bind(this, function (evt) {
  251. if (evt == null) {
  252. evt = window.event;
  253. }
  254. return graph.isEditing() || (evt != null && this.isSelectionAllowed(evt));
  255. });
  256. // Disables text selection while not editing and no dialog visible
  257. if (this.container == document.body) {
  258. this.menubarContainer.onselectstart = textEditing;
  259. this.menubarContainer.onmousedown = textEditing;
  260. this.toolbarContainer.onselectstart = textEditing;
  261. this.toolbarContainer.onmousedown = textEditing;
  262. this.diagramContainer.onselectstart = textEditing;
  263. this.diagramContainer.onmousedown = textEditing;
  264. this.sidebarContainer.onselectstart = textEditing;
  265. this.sidebarContainer.onmousedown = textEditing;
  266. this.formatContainer.onselectstart = textEditing;
  267. this.formatContainer.onmousedown = textEditing;
  268. this.footerContainer.onselectstart = textEditing;
  269. this.footerContainer.onmousedown = textEditing;
  270. if (this.tabContainer != null) {
  271. // Mouse down is needed for drag and drop
  272. this.tabContainer.onselectstart = textEditing;
  273. }
  274. // Workaround for rubberband selection on iPadOS 16
  275. // Avoid on previous versions to allow label editing
  276. if (mxClient.IS_IOS) {
  277. function iOSversion() {
  278. if (/iP(hone|od|ad)/.test(navigator.platform)) {
  279. // supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
  280. var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
  281. return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
  282. }
  283. }
  284. var ver = iOSversion();
  285. if (ver != null && ver[0] >= 16) {
  286. mxUtils.setPrefixedStyle(this.menubarContainer.style, 'userSelect', 'none');
  287. mxUtils.setPrefixedStyle(this.diagramContainer.style, 'userSelect', 'none');
  288. mxUtils.setPrefixedStyle(this.sidebarContainer.style, 'userSelect', 'none');
  289. mxUtils.setPrefixedStyle(this.formatContainer.style, 'userSelect', 'none');
  290. mxUtils.setPrefixedStyle(this.footerContainer.style, 'userSelect', 'none');
  291. if (this.tabContainer != null) {
  292. mxUtils.setPrefixedStyle(this.tabContainer.style, 'userSelect', 'none');
  293. }
  294. }
  295. }
  296. }
  297. // And uses built-in context menu while editing
  298. if (!this.editor.chromeless || this.editor.editable) {
  299. // Allows context menu for links in hints
  300. var linkHandler = function (evt) {
  301. if (evt != null) {
  302. var source = mxEvent.getSource(evt);
  303. if (source.nodeName == 'A') {
  304. while (source != null) {
  305. if (source.className == 'geHint') {
  306. return true;
  307. }
  308. source = source.parentNode;
  309. }
  310. }
  311. }
  312. return textEditing(evt);
  313. };
  314. if (mxClient.IS_IE && (typeof (document.documentMode) === 'undefined' || document.documentMode < 9)) {
  315. mxEvent.addListener(this.diagramContainer, 'contextmenu', linkHandler);
  316. }
  317. else {
  318. // Allows browser context menu outside of diagram and sidebar
  319. this.diagramContainer.oncontextmenu = linkHandler;
  320. }
  321. }
  322. else {
  323. graph.panningHandler.usePopupTrigger = false;
  324. }
  325. // Contains the main graph instance inside the given panel
  326. graph.init(this.diagramContainer);
  327. // Improves line wrapping for in-place editor
  328. if (mxClient.IS_SVG && graph.view.getDrawPane() != null) {
  329. var root = graph.view.getDrawPane().ownerSVGElement;
  330. if (root != null) {
  331. root.style.position = 'absolute';
  332. }
  333. }
  334. // Creates hover icons
  335. this.hoverIcons = this.createHoverIcons();
  336. // Hides hover icons when cells are moved
  337. if (graph.graphHandler != null) {
  338. var graphHandlerStart = graph.graphHandler.start;
  339. graph.graphHandler.start = function () {
  340. if (ui.hoverIcons != null) {
  341. ui.hoverIcons.reset();
  342. }
  343. graphHandlerStart.apply(this, arguments);
  344. };
  345. }
  346. // Adds tooltip when mouse is over scrollbars to show space-drag panning option
  347. mxEvent.addListener(this.diagramContainer, 'mousemove', mxUtils.bind(this, function (evt) {
  348. var off = mxUtils.getOffset(this.diagramContainer);
  349. if (mxEvent.getClientX(evt) - off.x - this.diagramContainer.clientWidth > 0 ||
  350. mxEvent.getClientY(evt) - off.y - this.diagramContainer.clientHeight > 0) {
  351. this.diagramContainer.setAttribute('title', mxResources.get('panTooltip'));
  352. }
  353. else {
  354. this.diagramContainer.removeAttribute('title');
  355. }
  356. }));
  357. // Overrides hovericons to disable while space key is pressed
  358. var hoverIconsIsResetEvent = this.hoverIcons.isResetEvent;
  359. this.hoverIcons.isResetEvent = function (evt, allowShift) {
  360. return ui.isSpaceDown() || hoverIconsIsResetEvent.apply(this, arguments);
  361. };
  362. this.keydownHandler = mxUtils.bind(this, function (evt) {
  363. if (evt.which == 16 /* Shift */) {
  364. this.shiftDown = true;
  365. }
  366. else if (evt.which == 32 /* Space */ && !graph.isEditing()) {
  367. this.spaceDown = true;
  368. this.hoverIcons.reset();
  369. graph.container.style.cursor = 'move';
  370. // Disables scroll after space keystroke with scrollbars
  371. if (!graph.isEditing() && mxEvent.getSource(evt) == graph.container) {
  372. mxEvent.consume(evt);
  373. }
  374. }
  375. else if (!mxEvent.isConsumed(evt) && evt.keyCode == 27 /* Escape */) {
  376. this.hideDialog(null, true);
  377. }
  378. });
  379. mxEvent.addListener(document, 'keydown', this.keydownHandler);
  380. this.keyupHandler = mxUtils.bind(this, function (evt) {
  381. graph.container.style.cursor = '';
  382. this.spaceDown = false;
  383. this.shiftDown = false;
  384. });
  385. mxEvent.addListener(document, 'keyup', this.keyupHandler);
  386. // Forces panning for middle and right mouse buttons
  387. var panningHandlerIsForcePanningEvent = graph.panningHandler.isForcePanningEvent;
  388. graph.panningHandler.isForcePanningEvent = function (me) {
  389. // Ctrl+left button is reported as right button in FF on Mac
  390. return panningHandlerIsForcePanningEvent.apply(this, arguments) ||
  391. ui.isSpaceDown() || (mxEvent.isMouseEvent(me.getEvent()) &&
  392. (this.usePopupTrigger || !mxEvent.isPopupTrigger(me.getEvent())) &&
  393. ((!mxEvent.isControlDown(me.getEvent()) &&
  394. mxEvent.isRightMouseButton(me.getEvent())) ||
  395. mxEvent.isMiddleMouseButton(me.getEvent())));
  396. };
  397. // Ctrl/Cmd+Enter applies editing value except in Safari where Ctrl+Enter creates
  398. // a new line (while Enter creates a new paragraph and Shift+Enter stops)
  399. var cellEditorIsStopEditingEvent = graph.cellEditor.isStopEditingEvent;
  400. graph.cellEditor.isStopEditingEvent = function (evt) {
  401. return cellEditorIsStopEditingEvent.apply(this, arguments) ||
  402. (evt.keyCode == 13 && ((!mxClient.IS_SF && mxEvent.isControlDown(evt)) ||
  403. (mxClient.IS_MAC && mxEvent.isMetaDown(evt)) ||
  404. (mxClient.IS_SF && mxEvent.isShiftDown(evt))));
  405. };
  406. // Adds space+wheel for zoom
  407. var graphIsZoomWheelEvent = graph.isZoomWheelEvent;
  408. graph.isZoomWheelEvent = function () {
  409. return ui.isSpaceDown() || graphIsZoomWheelEvent.apply(this, arguments);
  410. };
  411. // Switches toolbar for text editing
  412. var textMode = false;
  413. var fontMenu = null;
  414. var sizeMenu = null;
  415. var nodes = null;
  416. var updateToolbar = mxUtils.bind(this, function () {
  417. if (this.toolbar != null && textMode != graph.cellEditor.isContentEditing()) {
  418. var node = this.toolbar.container.firstChild;
  419. var newNodes = [];
  420. while (node != null) {
  421. var tmp = node.nextSibling;
  422. if (mxUtils.indexOf(this.toolbar.staticElements, node) < 0) {
  423. node.parentNode.removeChild(node);
  424. newNodes.push(node);
  425. }
  426. node = tmp;
  427. }
  428. // Saves references to special items
  429. var tmp1 = this.toolbar.fontMenu;
  430. var tmp2 = this.toolbar.sizeMenu;
  431. if (nodes == null) {
  432. this.toolbar.createTextToolbar();
  433. }
  434. else {
  435. for (var i = 0; i < nodes.length; i++) {
  436. this.toolbar.container.appendChild(nodes[i]);
  437. }
  438. // Restores references to special items
  439. this.toolbar.fontMenu = fontMenu;
  440. this.toolbar.sizeMenu = sizeMenu;
  441. }
  442. textMode = graph.cellEditor.isContentEditing();
  443. fontMenu = tmp1;
  444. sizeMenu = tmp2;
  445. nodes = newNodes;
  446. }
  447. });
  448. // Overrides cell editor to update toolbar
  449. var cellEditorStartEditing = graph.cellEditor.startEditing;
  450. graph.cellEditor.startEditing = function () {
  451. cellEditorStartEditing.apply(this, arguments);
  452. updateToolbar();
  453. if (graph.cellEditor.isContentEditing()) {
  454. var updating = false;
  455. var updateCssHandler = function () {
  456. if (!updating) {
  457. updating = true;
  458. window.setTimeout(function () {
  459. var node = graph.getSelectedEditingElement();
  460. if (node != null) {
  461. var css = mxUtils.getCurrentStyle(node);
  462. if (css != null && ui.toolbar != null) {
  463. ui.toolbar.setFontName(Graph.stripQuotes(css.fontFamily));
  464. ui.toolbar.setFontSize(parseInt(css.fontSize));
  465. }
  466. }
  467. updating = false;
  468. }, 0);
  469. }
  470. };
  471. mxEvent.addListener(graph.cellEditor.textarea, 'input', updateCssHandler)
  472. mxEvent.addListener(graph.cellEditor.textarea, 'touchend', updateCssHandler);
  473. mxEvent.addListener(graph.cellEditor.textarea, 'mouseup', updateCssHandler);
  474. mxEvent.addListener(graph.cellEditor.textarea, 'keyup', updateCssHandler);
  475. updateCssHandler();
  476. }
  477. };
  478. // Updates toolbar and handles possible errors
  479. var cellEditorStopEditing = graph.cellEditor.stopEditing;
  480. graph.cellEditor.stopEditing = function (cell, trigger) {
  481. try {
  482. cellEditorStopEditing.apply(this, arguments);
  483. updateToolbar();
  484. }
  485. catch (e) {
  486. ui.handleError(e);
  487. }
  488. };
  489. // Enables scrollbars and sets cursor style for the container
  490. graph.container.setAttribute('tabindex', '0');
  491. graph.container.style.cursor = 'default';
  492. // Workaround for page scroll if embedded via iframe
  493. if (window.self === window.top && graph.container.parentNode != null) {
  494. try {
  495. graph.container.focus();
  496. }
  497. catch (e) {
  498. // ignores error in old versions of IE
  499. }
  500. }
  501. // Keeps graph container focused on mouse down
  502. var graphFireMouseEvent = graph.fireMouseEvent;
  503. graph.fireMouseEvent = function (evtName, me, sender) {
  504. try {
  505. if (evtName == mxEvent.MOUSE_DOWN) {
  506. this.container.focus();
  507. }
  508. graphFireMouseEvent.apply(this, arguments);
  509. }
  510. catch (e) {
  511. ui.handleError(e);
  512. }
  513. };
  514. // Adds error handling for foldCells
  515. var graphFoldCells = graph.foldCells;
  516. graph.foldCells = function (collapse, recurse, cells, checkFoldable, evt) {
  517. try {
  518. graphFoldCells.apply(this, arguments);
  519. }
  520. catch (e) {
  521. ui.handleError(e);
  522. }
  523. };
  524. // Configures automatic expand on mouseover
  525. graph.popupMenuHandler.autoExpand = true;
  526. // Installs context menu
  527. if (this.menus != null) {
  528. graph.popupMenuHandler.factoryMethod = mxUtils.bind(this, function (menu, cell, evt) {
  529. this.menus.createPopupMenu(menu, cell, evt);
  530. });
  531. }
  532. // Hides context menu
  533. mxEvent.addGestureListeners(document, mxUtils.bind(this, function (evt) {
  534. graph.popupMenuHandler.hideMenu();
  535. }));
  536. // Create handler for key events
  537. this.keyHandler = this.createKeyHandler(editor);
  538. // Getter for key handler
  539. this.getKeyHandler = function () {
  540. return keyHandler;
  541. };
  542. graph.connectionHandler.addListener(mxEvent.CONNECT, function (sender, evt) {
  543. var cells = [evt.getProperty('cell')];
  544. if (evt.getProperty('terminalInserted')) {
  545. cells.push(evt.getProperty('terminal'));
  546. window.setTimeout(function () {
  547. if (ui.hoverIcons != null) {
  548. ui.hoverIcons.update(graph.view.getState(cells[cells.length - 1]));
  549. }
  550. }, 0);
  551. }
  552. insertHandler(cells);
  553. });
  554. this.addListener('styleChanged', mxUtils.bind(this, function (sender, evt) {
  555. var force = evt.getProperty('force');
  556. // Checks if edges and/or vertices were modified
  557. if (this.updateDefaultStyle || force) {
  558. var cells = evt.getProperty('cells');
  559. var vertex = false;
  560. var edge = false;
  561. if (cells.length > 0) {
  562. for (var i = 0; i < cells.length; i++) {
  563. vertex = graph.getModel().isVertex(cells[i]) || vertex;
  564. edge = graph.getModel().isEdge(cells[i]) || edge;
  565. if (edge && vertex) {
  566. break;
  567. }
  568. }
  569. }
  570. else {
  571. vertex = true;
  572. edge = true;
  573. }
  574. vertex = vertex && !vertexStyleIgnored;
  575. edge = edge && !edgeStyleIgnored;
  576. var keys = evt.getProperty('keys');
  577. var values = evt.getProperty('values');
  578. for (var i = 0; i < keys.length; i++) {
  579. var common = mxUtils.indexOf(valueStyles, keys[i]) >= 0;
  580. // Ignores transparent stroke colors
  581. if (keys[i] != 'strokeColor' || (values[i] != null && values[i] != 'none')) {
  582. // Special case: Edge style and shape
  583. if (mxUtils.indexOf(connectStyles, keys[i]) >= 0) {
  584. if (edge || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0) {
  585. if (values[i] == null) {
  586. delete graph.currentEdgeStyle[keys[i]];
  587. }
  588. else {
  589. graph.currentEdgeStyle[keys[i]] = values[i];
  590. }
  591. }
  592. // Uses style for vertex if defined in styles
  593. else if (vertex && mxUtils.indexOf(styles, keys[i]) >= 0) {
  594. if (values[i] == null) {
  595. delete graph.currentVertexStyle[keys[i]];
  596. }
  597. else {
  598. graph.currentVertexStyle[keys[i]] = values[i];
  599. }
  600. }
  601. }
  602. else if (mxUtils.indexOf(styles, keys[i]) >= 0) {
  603. if (vertex || common) {
  604. if (values[i] == null) {
  605. delete graph.currentVertexStyle[keys[i]];
  606. }
  607. else {
  608. graph.currentVertexStyle[keys[i]] = values[i];
  609. }
  610. }
  611. if (edge || common || mxUtils.indexOf(alwaysEdgeStyles, keys[i]) >= 0) {
  612. if (values[i] == null) {
  613. delete graph.currentEdgeStyle[keys[i]];
  614. }
  615. else {
  616. graph.currentEdgeStyle[keys[i]] = values[i];
  617. }
  618. }
  619. }
  620. }
  621. }
  622. }
  623. if (this.toolbar != null) {
  624. this.toolbar.setFontName(graph.currentVertexStyle['fontFamily'] || Menus.prototype.defaultFont);
  625. this.toolbar.setFontSize(graph.currentVertexStyle['fontSize'] || Menus.prototype.defaultFontSize);
  626. if (this.toolbar.edgeStyleMenu != null) {
  627. // Updates toolbar icon for edge style
  628. var edgeStyleDiv = this.toolbar.edgeStyleMenu.getElementsByTagName('div')[0];
  629. if (graph.currentEdgeStyle['edgeStyle'] == 'orthogonalEdgeStyle' && graph.currentEdgeStyle['curved'] == '1') {
  630. edgeStyleDiv.className = 'geSprite geSprite-curved';
  631. }
  632. else if (graph.currentEdgeStyle['edgeStyle'] == 'straight' || graph.currentEdgeStyle['edgeStyle'] == 'none' ||
  633. graph.currentEdgeStyle['edgeStyle'] == null) {
  634. edgeStyleDiv.className = 'geSprite geSprite-straight';
  635. }
  636. else if (graph.currentEdgeStyle['edgeStyle'] == 'entityRelationEdgeStyle') {
  637. edgeStyleDiv.className = 'geSprite geSprite-entity';
  638. }
  639. else if (graph.currentEdgeStyle['edgeStyle'] == 'elbowEdgeStyle') {
  640. edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
  641. 'verticalelbow' : 'horizontalelbow');
  642. }
  643. else if (graph.currentEdgeStyle['edgeStyle'] == 'isometricEdgeStyle') {
  644. edgeStyleDiv.className = 'geSprite geSprite-' + ((graph.currentEdgeStyle['elbow'] == 'vertical') ?
  645. 'verticalisometric' : 'horizontalisometric');
  646. }
  647. else {
  648. edgeStyleDiv.className = 'geSprite geSprite-orthogonal';
  649. }
  650. }
  651. if (this.toolbar.edgeShapeMenu != null) {
  652. // Updates icon for edge shape
  653. var edgeShapeDiv = this.toolbar.edgeShapeMenu.getElementsByTagName('div')[0];
  654. if (graph.currentEdgeStyle['shape'] == 'link') {
  655. edgeShapeDiv.className = 'geSprite geSprite-linkedge';
  656. }
  657. else if (graph.currentEdgeStyle['shape'] == 'flexArrow') {
  658. edgeShapeDiv.className = 'geSprite geSprite-arrow';
  659. }
  660. else if (graph.currentEdgeStyle['shape'] == 'arrow') {
  661. edgeShapeDiv.className = 'geSprite geSprite-simplearrow';
  662. }
  663. else {
  664. edgeShapeDiv.className = 'geSprite geSprite-connection';
  665. }
  666. }
  667. }
  668. }));
  669. // Update font size and font family labels
  670. if (this.toolbar != null) {
  671. var update = mxUtils.bind(this, function () {
  672. var ff = graph.currentVertexStyle['fontFamily'] || 'Helvetica';
  673. var fs = String(graph.currentVertexStyle['fontSize'] || '12');
  674. var state = graph.getView().getState(graph.getSelectionCell());
  675. if (state != null) {
  676. ff = state.style[mxConstants.STYLE_FONTFAMILY] || ff;
  677. fs = state.style[mxConstants.STYLE_FONTSIZE] || fs;
  678. if (ff.length > 10) {
  679. ff = ff.substring(0, 8) + '...';
  680. }
  681. }
  682. this.toolbar.setFontName(ff);
  683. this.toolbar.setFontSize(fs);
  684. });
  685. graph.getSelectionModel().addListener(mxEvent.CHANGE, update);
  686. graph.getModel().addListener(mxEvent.CHANGE, update);
  687. }
  688. // Makes sure the current layer is visible when cells are added
  689. graph.addListener(mxEvent.CELLS_ADDED, function (sender, evt) {
  690. var cells = evt.getProperty('cells');
  691. var parent = evt.getProperty('parent');
  692. if (parent != null && graph.getModel().isLayer(parent) &&
  693. !graph.isCellVisible(parent) && cells != null &&
  694. cells.length > 0) {
  695. graph.getModel().setVisible(parent, true);
  696. }
  697. });
  698. // Global handler to hide the current menu
  699. this.gestureHandler = mxUtils.bind(this, function (evt) {
  700. if (this.currentMenu != null && mxEvent.getSource(evt) != this.currentMenu.div) {
  701. this.hideCurrentMenu();
  702. }
  703. });
  704. mxEvent.addGestureListeners(document, this.gestureHandler);
  705. // Updates the editor UI after the window has been resized or the orientation changes
  706. // Timeout is workaround for old IE versions which have a delay for DOM client sizes.
  707. var resizeThread = null;
  708. this.resizeHandler = mxUtils.bind(this, function () {
  709. if (resizeThread != null) {
  710. window.clearTimeout(resizeThread);
  711. }
  712. resizeThread = window.setTimeout(mxUtils.bind(this, function () {
  713. resizeThread = null;
  714. this.windowResized();
  715. }), 100);
  716. });
  717. mxEvent.addListener(window, 'resize', this.resizeHandler);
  718. this.orientationChangeHandler = mxUtils.bind(this, function () {
  719. this.refresh();
  720. });
  721. mxEvent.addListener(window, 'orientationchange', this.orientationChangeHandler);
  722. // Workaround for bug on iOS see
  723. // http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
  724. if (mxClient.IS_IOS && !window.navigator.standalone && typeof Menus !== 'undefined') {
  725. this.scrollHandler = mxUtils.bind(this, function () {
  726. window.scrollTo(0, 0);
  727. });
  728. mxEvent.addListener(window, 'scroll', this.scrollHandler);
  729. }
  730. /**
  731. * Sets the initial scrollbar locations after a file was loaded.
  732. */
  733. this.editor.addListener('resetGraphView', mxUtils.bind(this, function () {
  734. this.resetScrollbars();
  735. }));
  736. /**
  737. * Repaints the grid.
  738. */
  739. this.addListener('gridEnabledChanged', mxUtils.bind(this, function () {
  740. graph.view.validateBackground();
  741. }));
  742. this.addListener('backgroundColorChanged', mxUtils.bind(this, function () {
  743. graph.view.validateBackground();
  744. }));
  745. /**
  746. * Repaints the grid.
  747. */
  748. graph.addListener('gridSizeChanged', mxUtils.bind(this, function () {
  749. if (graph.isGridEnabled()) {
  750. graph.view.validateBackground();
  751. }
  752. }));
  753. // Resets UI, updates action and menu states
  754. this.editor.resetGraph();
  755. }
  756. this.init();
  757. if (!graph.standalone) {
  758. this.open();
  759. }
  760. };
  761. /**
  762. * Global config that specifies if the compact UI elements should be used.
  763. */
  764. EditorUi.compactUi = true;
  765. /**
  766. * Static method for pasing PNG files.
  767. */
  768. EditorUi.parsePng = function (f, fn, error) {
  769. var pos = 0;
  770. function fread(d, count) {
  771. var start = pos;
  772. pos += count;
  773. return d.substring(start, pos);
  774. };
  775. // Reads unsigned long 32 bit big endian
  776. function _freadint(d) {
  777. var bytes = fread(d, 4);
  778. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  779. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  780. };
  781. // Checks signature
  782. if (fread(f, 8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10)) {
  783. if (error != null) {
  784. error();
  785. }
  786. return;
  787. }
  788. // Reads header chunk
  789. fread(f, 4);
  790. if (fread(f, 4) != 'IHDR') {
  791. if (error != null) {
  792. error();
  793. }
  794. return;
  795. }
  796. fread(f, 17);
  797. do {
  798. var n = _freadint(f);
  799. var type = fread(f, 4);
  800. if (fn != null) {
  801. if (fn(pos - 8, type, n)) {
  802. break;
  803. }
  804. }
  805. value = fread(f, n);
  806. fread(f, 4);
  807. if (type == 'IEND') {
  808. break;
  809. }
  810. }
  811. while (n);
  812. };
  813. // Extends mxEventSource
  814. mxUtils.extend(EditorUi, mxEventSource);
  815. /**
  816. * Specifies the size of the split bar.
  817. */
  818. EditorUi.prototype.splitSize = (mxClient.IS_TOUCH || mxClient.IS_POINTER) ? 12 : 8;
  819. /**
  820. * Specifies the height of the menubar. Default is 30.
  821. */
  822. EditorUi.prototype.menubarHeight = 30;
  823. /**
  824. * Specifies the width of the format panel should be enabled. Default is true.
  825. */
  826. EditorUi.prototype.formatEnabled = true;
  827. /**
  828. * Specifies the width of the format panel. Default is 240.
  829. */
  830. EditorUi.prototype.formatWidth = 240;
  831. /**
  832. * Specifies the height of the toolbar. Default is 38.
  833. */
  834. EditorUi.prototype.toolbarHeight = 38;
  835. /**
  836. * Specifies the height of the footer. Default is 28.
  837. */
  838. EditorUi.prototype.footerHeight = 28;
  839. /**
  840. * Specifies the position of the horizontal split bar. Default is 240 or 118 for
  841. * screen widths <= 640px.
  842. */
  843. EditorUi.prototype.hsplitPosition = (screen.width <= Editor.smallScreenWidth) ? 0 :
  844. ((urlParams['sidebar-entries'] != 'large') ? 212 : 240);
  845. /**
  846. * Specifies if animations are allowed in <executeLayout>. Default is true.
  847. */
  848. EditorUi.prototype.allowAnimation = true;
  849. /**
  850. * Default is 2.
  851. */
  852. EditorUi.prototype.lightboxMaxFitScale = 2;
  853. /**
  854. * Default is 4.
  855. */
  856. EditorUi.prototype.lightboxVerticalDivider = 4;
  857. /**
  858. * Specifies if single click on horizontal split should collapse sidebar. Default is false.
  859. */
  860. EditorUi.prototype.hsplitClickEnabled = false;
  861. /**
  862. * Whether the default styles should be updated when styles are changed. Default is true.
  863. */
  864. EditorUi.prototype.updateDefaultStyle = false;
  865. /**
  866. * Whether the default styles should be updated when styles are changed. Default is true.
  867. */
  868. EditorUi.prototype.spaceDown = false;
  869. /**
  870. * Whether the default styles should be updated when styles are changed. Default is true.
  871. */
  872. EditorUi.prototype.shiftDown = false;
  873. /**
  874. * Installs the listeners to update the action states.
  875. */
  876. EditorUi.prototype.init = function () {
  877. var graph = this.editor.graph;
  878. if (!graph.standalone) {
  879. if (urlParams['shape-picker'] != '0') {
  880. this.installShapePicker();
  881. }
  882. // Hides tooltips and connection points when scrolling
  883. mxEvent.addListener(graph.container, 'scroll', mxUtils.bind(this, function () {
  884. graph.tooltipHandler.hide();
  885. if (graph.connectionHandler != null && graph.connectionHandler.constraintHandler != null) {
  886. graph.connectionHandler.constraintHandler.reset();
  887. }
  888. }));
  889. // Hides tooltip on escape
  890. graph.addListener(mxEvent.ESCAPE, mxUtils.bind(this, function () {
  891. graph.tooltipHandler.hide();
  892. var rb = graph.getRubberband();
  893. if (rb != null) {
  894. rb.cancel();
  895. }
  896. }));
  897. mxEvent.addListener(graph.container, 'keydown', mxUtils.bind(this, function (evt) {
  898. this.onKeyDown(evt);
  899. }));
  900. mxEvent.addListener(graph.container, 'keypress', mxUtils.bind(this, function (evt) {
  901. this.onKeyPress(evt);
  902. }));
  903. // Updates action states
  904. this.addUndoListener();
  905. this.addBeforeUnloadListener();
  906. graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
  907. this.updateActionStates();
  908. }));
  909. graph.getModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function () {
  910. this.updateActionStates();
  911. }));
  912. // Changes action states after change of default parent
  913. var graphSetDefaultParent = graph.setDefaultParent;
  914. var ui = this;
  915. this.editor.graph.setDefaultParent = function () {
  916. graphSetDefaultParent.apply(this, arguments);
  917. ui.updateActionStates();
  918. };
  919. // Hack to make showLinkDialog and editLink available in vertex handler
  920. graph.showLinkDialog = mxUtils.bind(ui, ui.showLinkDialog);
  921. graph.editLink = ui.actions.get('editLink').funct;
  922. this.updateActionStates();
  923. this.initClipboard();
  924. this.initCanvas();
  925. if (this.format != null) {
  926. this.format.init();
  927. }
  928. }
  929. };
  930. /**
  931. * Returns information about the current selection.
  932. */
  933. EditorUi.prototype.clearSelectionState = function () {
  934. this.selectionState = null;
  935. };
  936. /**
  937. * Returns information about the current selection.
  938. */
  939. EditorUi.prototype.getSelectionState = function () {
  940. if (this.selectionState == null) {
  941. this.selectionState = this.createSelectionState();
  942. }
  943. return this.selectionState;
  944. };
  945. /**
  946. * Returns information about the current selection.
  947. */
  948. EditorUi.prototype.createSelectionState = function () {
  949. var graph = this.editor.graph;
  950. var cells = graph.getSelectionCells();
  951. var result = this.initSelectionState();
  952. var initial = true;
  953. for (var i = 0; i < cells.length; i++) {
  954. var style = graph.getCurrentCellStyle(cells[i]);
  955. if (mxUtils.getValue(style, mxConstants.STYLE_EDITABLE, '1') != '0') {
  956. this.updateSelectionStateForCell(result, cells[i], cells, initial);
  957. initial = false;
  958. }
  959. }
  960. this.updateSelectionStateForTableCells(result);
  961. return result;
  962. };
  963. /**
  964. * Returns information about the current selection.
  965. */
  966. EditorUi.prototype.initSelectionState = function () {
  967. return {
  968. vertices: [], edges: [], cells: [], x: null, y: null, width: null, height: null,
  969. style: {}, containsImage: false, containsLabel: false, fill: true, glass: true,
  970. rounded: true, autoSize: false, image: false, shadow: true, lineJumps: true, resizable: true,
  971. table: false, cell: false, row: false, movable: true, rotatable: true, stroke: true,
  972. swimlane: false, unlocked: this.editor.graph.isEnabled(), connections: false
  973. };
  974. };
  975. /**
  976. * Adds information about current selected table cells range.
  977. */
  978. EditorUi.prototype.updateSelectionStateForTableCells = function (result) {
  979. if (result.cells.length > 1 && result.cell) {
  980. var cells = mxUtils.sortCells(result.cells);
  981. var model = this.editor.graph.model;
  982. var parent = model.getParent(cells[0]);
  983. var table = model.getParent(parent);
  984. if (parent != null && table != null) {
  985. var col = parent.getIndex(cells[0]);
  986. var row = table.getIndex(parent);
  987. var lastspan = null;
  988. var colspan = 1;
  989. var rowspan = 1;
  990. var index = 0;
  991. var nextRowCell = (row < table.getChildCount() - 1) ?
  992. model.getChildAt(model.getChildAt(
  993. table, row + 1), col) : null;
  994. while (index < cells.length - 1) {
  995. var next = cells[++index];
  996. if (nextRowCell != null && nextRowCell == next &&
  997. (lastspan == null || colspan == lastspan)) {
  998. lastspan = colspan;
  999. colspan = 0;
  1000. rowspan++;
  1001. parent = model.getParent(nextRowCell);
  1002. nextRowCell = (row + rowspan < table.getChildCount()) ?
  1003. model.getChildAt(model.getChildAt(
  1004. table, row + rowspan), col) : null;
  1005. }
  1006. var state = this.editor.graph.view.getState(next);
  1007. if (next == model.getChildAt(parent, col + colspan) && state != null &&
  1008. mxUtils.getValue(state.style, 'colspan', 1) == 1 &&
  1009. mxUtils.getValue(state.style, 'rowspan', 1) == 1) {
  1010. colspan++;
  1011. }
  1012. else {
  1013. break;
  1014. }
  1015. }
  1016. if (index == rowspan * colspan - 1) {
  1017. result.mergeCell = cells[0];
  1018. result.colspan = colspan;
  1019. result.rowspan = rowspan;
  1020. }
  1021. }
  1022. }
  1023. };
  1024. /**
  1025. * Returns information about the current selection.
  1026. */
  1027. EditorUi.prototype.windowResized = function () {
  1028. window.setTimeout(mxUtils.bind(this, function () {
  1029. if (this.editor.graph != null) {
  1030. this.refresh();
  1031. }
  1032. }), 0);
  1033. };
  1034. /**
  1035. * Returns information about the current selection.
  1036. */
  1037. EditorUi.prototype.createTimeout = function (timeout, fn, error) {
  1038. var acceptResponse = true;
  1039. var result = null;
  1040. var handleError = mxUtils.bind(this, function (e) {
  1041. if (result.clear()) {
  1042. acceptResponse = false;
  1043. e = (e != null) ? e : {
  1044. code: App.ERROR_TIMEOUT,
  1045. message: mxResources.get('timeout'),
  1046. retry: mxUtils.bind(this, function () {
  1047. this.createTimeout(timeout, fn, error);
  1048. })
  1049. };
  1050. if (error != null) {
  1051. error(e);
  1052. }
  1053. else {
  1054. this.handleError(e);
  1055. }
  1056. }
  1057. });
  1058. var timeoutThread = window.setTimeout(handleError,
  1059. (timeout != null) ? timeout : this.timeout);
  1060. var result = {
  1061. clear: function () {
  1062. window.clearTimeout(timeoutThread);
  1063. return acceptResponse;
  1064. },
  1065. isAlive: function () {
  1066. return acceptResponse;
  1067. }
  1068. };
  1069. if (fn != null) {
  1070. this.tryAndHandle(mxUtils.bind(this, function () {
  1071. fn(result);
  1072. }), handleError);
  1073. }
  1074. return result;
  1075. };
  1076. /**
  1077. * Returns information about the current selection.
  1078. */
  1079. EditorUi.prototype.tryAndHandle = function (fn, error) {
  1080. try {
  1081. fn();
  1082. }
  1083. catch (e) {
  1084. if (error != null) {
  1085. error(e);
  1086. }
  1087. else {
  1088. this.handleError(e);
  1089. }
  1090. }
  1091. };
  1092. /**
  1093. * Returns information about the current selection.
  1094. */
  1095. EditorUi.prototype.updateSelectionStateForCell = function (result, cell, cells, initial) {
  1096. var graph = this.editor.graph;
  1097. result.cells.push(cell);
  1098. if (graph.getModel().isVertex(cell)) {
  1099. result.connections = graph.model.getEdgeCount(cell) > 0;
  1100. result.unlocked = result.unlocked && !graph.isCellLocked(cell);
  1101. result.resizable = result.resizable && graph.isCellResizable(cell);
  1102. result.rotatable = result.rotatable && graph.isCellRotatable(cell);
  1103. result.movable = result.movable && graph.isCellMovable(cell) &&
  1104. !graph.isTableRow(cell) && !graph.isTableCell(cell);
  1105. result.swimlane = result.swimlane || graph.isSwimlane(cell);
  1106. result.table = result.table || graph.isTable(cell);
  1107. result.cell = result.cell || graph.isTableCell(cell);
  1108. result.row = result.row || graph.isTableRow(cell);
  1109. result.vertices.push(cell);
  1110. var geo = graph.getCellGeometry(cell);
  1111. if (geo != null) {
  1112. if (geo.width > 0) {
  1113. if (result.width == null) {
  1114. result.width = geo.width;
  1115. }
  1116. else if (result.width != geo.width) {
  1117. result.width = '';
  1118. }
  1119. }
  1120. else {
  1121. result.containsLabel = true;
  1122. }
  1123. if (geo.height > 0) {
  1124. if (result.height == null) {
  1125. result.height = geo.height;
  1126. }
  1127. else if (result.height != geo.height) {
  1128. result.height = '';
  1129. }
  1130. }
  1131. else {
  1132. result.containsLabel = true;
  1133. }
  1134. if (!geo.relative || geo.offset != null) {
  1135. var x = (geo.relative) ? geo.offset.x : geo.x;
  1136. var y = (geo.relative) ? geo.offset.y : geo.y;
  1137. if (result.x == null) {
  1138. result.x = x;
  1139. }
  1140. else if (result.x != x) {
  1141. result.x = '';
  1142. }
  1143. if (result.y == null) {
  1144. result.y = y;
  1145. }
  1146. else if (result.y != y) {
  1147. result.y = '';
  1148. }
  1149. }
  1150. }
  1151. }
  1152. else if (graph.getModel().isEdge(cell)) {
  1153. result.edges.push(cell);
  1154. result.connections = true;
  1155. result.resizable = false;
  1156. result.rotatable = false;
  1157. result.movable = false;
  1158. }
  1159. var state = graph.view.getState(cell);
  1160. if (state != null) {
  1161. result.autoSize = result.autoSize || graph.isAutoSizeState(state);
  1162. result.glass = result.glass && graph.isGlassState(state);
  1163. result.rounded = result.rounded && graph.isRoundedState(state);
  1164. result.lineJumps = result.lineJumps && graph.isLineJumpState(state);
  1165. result.image = result.image || graph.isImageState(state);
  1166. result.shadow = result.shadow && graph.isShadowState(state);
  1167. result.fill = result.fill && graph.isFillState(state);
  1168. result.gradient = result.fill && graph.isGradientState(state);
  1169. result.stroke = result.stroke && graph.isStrokeState(state);
  1170. var shape = mxUtils.getValue(state.style, mxConstants.STYLE_SHAPE, null);
  1171. result.containsImage = result.containsImage || shape == 'image';
  1172. graph.mergeStyle(state.style, result.style, initial);
  1173. }
  1174. };
  1175. /**
  1176. * Returns true if the given event should start editing. This implementation returns true.
  1177. */
  1178. EditorUi.prototype.installShapePicker = function () {
  1179. var graph = this.editor.graph;
  1180. var ui = this;
  1181. // Uses this event to process mouseDown to check the selection state before it is changed
  1182. graph.addListener(mxEvent.FIRE_MOUSE_EVENT, mxUtils.bind(this, function (sender, evt) {
  1183. if (evt.getProperty('eventName') == 'mouseDown') {
  1184. ui.hideShapePicker();
  1185. }
  1186. }));
  1187. var hidePicker = mxUtils.bind(this, function () {
  1188. ui.hideShapePicker(true);
  1189. });
  1190. graph.addListener('wheel', hidePicker);
  1191. graph.addListener(mxEvent.ESCAPE, hidePicker);
  1192. graph.view.addListener(mxEvent.SCALE, hidePicker);
  1193. graph.view.addListener(mxEvent.SCALE_AND_TRANSLATE, hidePicker);
  1194. graph.getSelectionModel().addListener(mxEvent.CHANGE, hidePicker);
  1195. // Counts as popup menu
  1196. var popupMenuHandlerIsMenuShowing = graph.popupMenuHandler.isMenuShowing;
  1197. graph.popupMenuHandler.isMenuShowing = function () {
  1198. return popupMenuHandlerIsMenuShowing.apply(this, arguments) ||
  1199. ui.shapePicker != null || ui.currentMenu != null;
  1200. };
  1201. // Adds dbl click dialog for inserting shapes
  1202. var graphDblClick = graph.dblClick;
  1203. graph.dblClick = function (evt, cell) {
  1204. if (this.isEnabled()) {
  1205. if (cell == null && ui.sidebar != null && !mxEvent.isShiftDown(evt) &&
  1206. !graph.isCellLocked(graph.getDefaultParent())) {
  1207. var pt = mxUtils.convertPoint(this.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  1208. mxEvent.consume(evt);
  1209. // Asynchronous to avoid direct insert after double tap
  1210. window.setTimeout(mxUtils.bind(this, function () {
  1211. ui.showShapePicker(pt.x, pt.y);
  1212. }), 30);
  1213. }
  1214. else {
  1215. graphDblClick.apply(this, arguments);
  1216. }
  1217. }
  1218. };
  1219. if (this.hoverIcons != null) {
  1220. this.hoverIcons.addListener('reset', hidePicker);
  1221. var hoverIconsDrag = this.hoverIcons.drag;
  1222. this.hoverIcons.drag = function () {
  1223. ui.hideShapePicker();
  1224. hoverIconsDrag.apply(this, arguments);
  1225. };
  1226. var hoverIconsExecute = this.hoverIcons.execute;
  1227. this.hoverIcons.execute = function (state, dir, me) {
  1228. var evt = me.getEvent();
  1229. if (!this.graph.isCloneEvent(evt) && !mxEvent.isShiftDown(evt)) {
  1230. this.graph.connectVertex(state.cell, dir, this.graph.defaultEdgeLength, evt, null, null, mxUtils.bind(this, function (x, y, execute) {
  1231. var temp = graph.getCompositeParent(state.cell);
  1232. var geo = graph.getCellGeometry(temp);
  1233. me.consume();
  1234. while (temp != null && graph.model.isVertex(temp) && geo != null && geo.relative) {
  1235. cell = temp;
  1236. temp = graph.model.getParent(cell)
  1237. geo = graph.getCellGeometry(temp);
  1238. }
  1239. // Asynchronous to avoid direct insert after double tap
  1240. window.setTimeout(mxUtils.bind(this, function () {
  1241. ui.showShapePicker(me.getGraphX(), me.getGraphY(), temp, mxUtils.bind(this, function (cell) {
  1242. execute(cell);
  1243. if (ui.hoverIcons != null) {
  1244. ui.hoverIcons.update(graph.view.getState(cell));
  1245. }
  1246. }), dir);
  1247. }), 30);
  1248. }), mxUtils.bind(this, function (result) {
  1249. this.graph.selectCellsForConnectVertex(result, evt, this);
  1250. }));
  1251. }
  1252. else {
  1253. hoverIconsExecute.apply(this, arguments);
  1254. }
  1255. };
  1256. var thread = null;
  1257. this.hoverIcons.addListener('focus', mxUtils.bind(this, function (sender, evt) {
  1258. if (thread != null) {
  1259. window.clearTimeout(thread);
  1260. }
  1261. thread = window.setTimeout(mxUtils.bind(this, function () {
  1262. var arrow = evt.getProperty('arrow');
  1263. var dir = evt.getProperty('direction');
  1264. var mouseEvent = evt.getProperty('event');
  1265. var rect = arrow.getBoundingClientRect();
  1266. var offset = mxUtils.getOffset(graph.container);
  1267. var x = graph.container.scrollLeft + rect.x - offset.x;
  1268. var y = graph.container.scrollTop + rect.y - offset.y;
  1269. var temp = graph.getCompositeParent((this.hoverIcons.currentState != null) ?
  1270. this.hoverIcons.currentState.cell : null);
  1271. var div = ui.showShapePicker(x, y, temp, mxUtils.bind(this, function (cell) {
  1272. if (cell != null) {
  1273. graph.connectVertex(temp, dir, graph.defaultEdgeLength, mouseEvent, true, false, function (x, y, execute) {
  1274. execute(cell);
  1275. if (ui.hoverIcons != null) {
  1276. ui.hoverIcons.update(graph.view.getState(cell));
  1277. }
  1278. }, function (cells) {
  1279. graph.selectCellsForConnectVertex(cells);
  1280. }, mouseEvent, this.hoverIcons);
  1281. }
  1282. }), dir, true);
  1283. this.centerShapePicker(div, rect, x, y, dir);
  1284. mxUtils.setOpacity(div, 30);
  1285. mxEvent.addListener(div, 'mouseenter', function () {
  1286. mxUtils.setOpacity(div, 100);
  1287. });
  1288. mxEvent.addListener(div, 'mouseleave', function () {
  1289. ui.hideShapePicker();
  1290. });
  1291. }), Editor.shapePickerHoverDelay);
  1292. }));
  1293. this.hoverIcons.addListener('blur', mxUtils.bind(this, function (sender, evt) {
  1294. if (thread != null) {
  1295. window.clearTimeout(thread);
  1296. }
  1297. }));
  1298. }
  1299. };
  1300. /**
  1301. * Creates a temporary graph instance for rendering off-screen content.
  1302. */
  1303. EditorUi.prototype.centerShapePicker = function (div, rect, x, y, dir) {
  1304. if (dir == mxConstants.DIRECTION_EAST || dir == mxConstants.DIRECTION_WEST) {
  1305. div.style.width = '40px';
  1306. }
  1307. var r2 = div.getBoundingClientRect();
  1308. if (dir == mxConstants.DIRECTION_NORTH) {
  1309. x -= r2.width / 2 - 10;
  1310. y -= r2.height + 6;
  1311. }
  1312. else if (dir == mxConstants.DIRECTION_SOUTH) {
  1313. x -= r2.width / 2 - 10;
  1314. y += rect.height + 6;
  1315. }
  1316. else if (dir == mxConstants.DIRECTION_WEST) {
  1317. x -= r2.width + 6;
  1318. y -= r2.height / 2 - 10;
  1319. }
  1320. else if (dir == mxConstants.DIRECTION_EAST) {
  1321. x += rect.width + 6;
  1322. y -= r2.height / 2 - 10;
  1323. }
  1324. div.style.left = x + 'px';
  1325. div.style.top = y + 'px';
  1326. };
  1327. /**
  1328. * Creates a temporary graph instance for rendering off-screen content.
  1329. */
  1330. EditorUi.prototype.showShapePicker = function (x, y, source, callback, direction, hovering,
  1331. getInsertLocationFn, showEdges, startEditing) {
  1332. showEdges = showEdges || source == null;
  1333. var div = this.createShapePicker(x, y, source, callback, direction, mxUtils.bind(this, function () {
  1334. this.hideShapePicker();
  1335. }), this.getCellsForShapePicker(source, hovering, showEdges), hovering,
  1336. getInsertLocationFn, showEdges, startEditing);
  1337. if (div != null) {
  1338. if (this.hoverIcons != null && !hovering) {
  1339. this.hoverIcons.reset();
  1340. }
  1341. var graph = this.editor.graph;
  1342. graph.popupMenuHandler.hideMenu();
  1343. graph.tooltipHandler.hideTooltip();
  1344. this.hideCurrentMenu();
  1345. this.hideShapePicker();
  1346. this.shapePickerCallback = callback;
  1347. this.shapePicker = div;
  1348. }
  1349. return div;
  1350. };
  1351. /**
  1352. * Creates a temporary graph instance for rendering off-screen content.
  1353. */
  1354. EditorUi.prototype.createShapePicker = function (x, y, source, callback, direction,
  1355. afterClick, cells, hovering, getInsertLocationFn, showEdges, startEditing) {
  1356. startEditing = (startEditing != null) ? startEditing : true;
  1357. var graph = this.editor.graph;
  1358. var div = null;
  1359. getInsertLocationFn = (getInsertLocationFn != null) ? getInsertLocationFn : function (cells) {
  1360. var cell = cells[0];
  1361. var w = 0;
  1362. var h = 0;
  1363. var geo = cell.geometry;
  1364. if (geo != null) {
  1365. if (graph.model.isEdge(cell)) {
  1366. var pt = geo.getTerminalPoint(false);
  1367. geo = new mxRectangle(0, 0, pt.x, pt.y);
  1368. }
  1369. w = geo.width / 2;
  1370. h = geo.height / 2;
  1371. }
  1372. return new mxPoint(graph.snap(Math.round(x / graph.view.scale) - graph.view.translate.x - w),
  1373. graph.snap(Math.round(y / graph.view.scale) - graph.view.translate.y - h));
  1374. };
  1375. if (cells != null && cells.length > 0) {
  1376. var ui = this;
  1377. var graph = this.editor.graph;
  1378. div = document.createElement('div');
  1379. var sourceState = graph.view.getState(source);
  1380. var style = (source != null && (sourceState == null ||
  1381. !graph.isTransparentState(sourceState))) ?
  1382. graph.copyStyle(source) : null;
  1383. // Do not place entry under pointer for touch devices
  1384. var w = (cells.length < 6) ? cells.length * 35 : 140;
  1385. div.className = 'geToolbarContainer geSidebarContainer geShapePicker';
  1386. div.setAttribute('title', mxResources.get('sidebarTooltip'));
  1387. div.style.left = x + 'px';
  1388. div.style.top = y + 'px';
  1389. div.style.width = w + 'px';
  1390. // Disables built-in pan and zoom on touch devices
  1391. if (mxClient.IS_POINTER) {
  1392. div.style.touchAction = 'none';
  1393. }
  1394. if (!hovering) {
  1395. mxUtils.setPrefixedStyle(div.style, 'transform', 'translate(-22px,-22px)');
  1396. }
  1397. if (graph.background != null && graph.background != mxConstants.NONE) {
  1398. div.style.backgroundColor = graph.background;
  1399. }
  1400. graph.container.appendChild(div);
  1401. var addCell = mxUtils.bind(this, function (cell) {
  1402. // Wrapper needed to catch events
  1403. var node = document.createElement('a');
  1404. node.className = 'geItem';
  1405. node.style.cssText = 'position:relative;display:inline-block;position:relative;' +
  1406. 'width:30px;height:30px;cursor:pointer;overflow:hidden;padding:1px';
  1407. div.appendChild(node);
  1408. if (style != null && urlParams['sketch'] != '1') {
  1409. this.sidebar.graph.pasteStyle(style, [cell]);
  1410. }
  1411. else {
  1412. ui.insertHandler([cell], cell.value != '' && urlParams['sketch'] != '1', this.sidebar.graph.model);
  1413. }
  1414. var geo = cell.geometry;
  1415. if (graph.model.isEdge(cell)) {
  1416. var pt = geo.getTerminalPoint(false);
  1417. geo = new mxRectangle(0, 0, pt.x, pt.y);
  1418. }
  1419. if (geo != null) {
  1420. node.appendChild(this.sidebar.createVertexTemplateFromCells([cell],
  1421. geo.width, geo.height, '', true, false, null, false,
  1422. mxUtils.bind(this, function (evt) {
  1423. if (mxEvent.isShiftDown(evt) && (source != null ||
  1424. !graph.isSelectionEmpty())) {
  1425. var temp = graph.getEditableCells((source != null) ?
  1426. [source] : graph.getSelectionCells());
  1427. graph.updateShapes(cell, temp);
  1428. }
  1429. else {
  1430. var clone = graph.cloneCell(cell);
  1431. if (callback != null) {
  1432. callback(clone);
  1433. }
  1434. else {
  1435. var pt = getInsertLocationFn([clone]);
  1436. if (graph.model.isEdge(clone)) {
  1437. clone.geometry.translate(pt.x, pt.y);
  1438. }
  1439. else {
  1440. clone.geometry.x = pt.x;
  1441. clone.geometry.y = pt.y;
  1442. }
  1443. graph.model.beginUpdate();
  1444. try {
  1445. graph.addCell(clone);
  1446. if (graph.model.isVertex(clone) &&
  1447. graph.isAutoSizeCell(clone)) {
  1448. graph.updateCellSize(clone);
  1449. }
  1450. }
  1451. finally {
  1452. graph.model.endUpdate();
  1453. }
  1454. graph.setSelectionCell(clone);
  1455. graph.scrollCellToVisible(clone);
  1456. if (startEditing) {
  1457. graph.startEditing(clone);
  1458. }
  1459. if (ui.hoverIcons != null) {
  1460. ui.hoverIcons.update(graph.view.getState(clone));
  1461. }
  1462. }
  1463. }
  1464. if (afterClick != null) {
  1465. afterClick(evt);
  1466. }
  1467. mxEvent.consume(evt);
  1468. }), 25, 25, null, null, source));
  1469. }
  1470. });
  1471. for (var i = 0; i < (hovering ? Math.min(cells.length, 4) : cells.length); i++) {
  1472. addCell(cells[i]);
  1473. }
  1474. var b = graph.container.scrollTop + graph.container.offsetHeight;
  1475. var dy = div.offsetTop + div.clientHeight - b;
  1476. if (dy > 0) {
  1477. div.style.top = Math.max(graph.container.scrollTop + 22, y - dy) + 'px';
  1478. }
  1479. var r = graph.container.scrollLeft + graph.container.offsetWidth;
  1480. var dx = div.offsetLeft + div.clientWidth - r;
  1481. if (dx > 0) {
  1482. div.style.left = Math.max(graph.container.scrollLeft + 22, x - dx) + 'px';
  1483. }
  1484. }
  1485. return div;
  1486. };
  1487. /**
  1488. * Creates a temporary graph instance for rendering off-screen content.
  1489. */
  1490. EditorUi.prototype.getCellsForShapePicker = function (cell, hovering, showEdges) {
  1491. var graph = this.editor.graph;
  1492. var createVertex = mxUtils.bind(this, function (style, w, h, value) {
  1493. return graph.createVertex(null, null, value || '', 0, 0, w || 120, h || 60, style, false);
  1494. });
  1495. var createEdge = mxUtils.bind(this, function (style, y, value) {
  1496. var cell = new mxCell(value || '', new mxGeometry(0, 0, graph.defaultEdgeLength + 20, 0), style);
  1497. cell.geometry.setTerminalPoint(new mxPoint(0, 0), true);
  1498. cell.geometry.setTerminalPoint(new mxPoint(cell.geometry.width, (y != null) ? y : 0), false);
  1499. cell.geometry.points = (y != null) ? [new mxPoint(cell.geometry.width / 2, y)] : [];
  1500. cell.geometry.relative = true;
  1501. cell.edge = true;
  1502. return cell;
  1503. });
  1504. // Creates a clone of the source cell and moves it to the origin
  1505. if (cell != null) {
  1506. try {
  1507. cell = graph.cloneCell(cell);
  1508. if (graph.model.isVertex(cell) && cell.geometry != null) {
  1509. cell.geometry.x = 0;
  1510. cell.geometry.y = 0;
  1511. }
  1512. }
  1513. catch (e) {
  1514. cell = null;
  1515. }
  1516. }
  1517. if (cell == null) {
  1518. cell = createVertex('text;html=1;align=center;verticalAlign=middle;resizable=0;' +
  1519. 'points=[];autosize=1;strokeColor=none;fillColor=none;', 40, 20, 'Text');
  1520. if (graph.model.isVertex(cell) && graph.isAutoSizeCell(cell)) {
  1521. // Uses offscreen graph to bypass undo history
  1522. var tempGraph = Graph.createOffscreenGraph(graph.getStylesheet());
  1523. tempGraph.updateCellSize(cell);
  1524. }
  1525. }
  1526. var cells = [cell, createVertex('whiteSpace=wrap;html=1;'),
  1527. createVertex('ellipse;whiteSpace=wrap;html=1;', 80, 80),
  1528. createVertex('rhombus;whiteSpace=wrap;html=1;', 80, 80),
  1529. createVertex('rounded=1;whiteSpace=wrap;html=1;'),
  1530. createVertex('shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fixedSize=1;'),
  1531. createVertex('shape=trapezoid;perimeter=trapezoidPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 60),
  1532. createVertex('shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
  1533. createVertex('shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;', 120, 80),
  1534. createVertex('shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;'),
  1535. createVertex('triangle;whiteSpace=wrap;html=1;', 60, 80),
  1536. createVertex('shape=document;whiteSpace=wrap;html=1;boundedLbl=1;', 120, 80),
  1537. createVertex('shape=tape;whiteSpace=wrap;html=1;', 120, 100),
  1538. createVertex('ellipse;shape=cloud;whiteSpace=wrap;html=1;', 120, 80),
  1539. createVertex('shape=singleArrow;whiteSpace=wrap;html=1;arrowWidth=0.4;arrowSize=0.4;', 80, 60),
  1540. createVertex('shape=waypoint;sketch=0;size=6;pointerEvents=1;points=[];fillColor=none;resizable=0;' +
  1541. 'rotatable=0;perimeter=centerPerimeter;snapToPoint=1;', 20, 20)];
  1542. if (showEdges) {
  1543. cells = cells.concat([
  1544. createEdge('edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;'),
  1545. createEdge('edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;endArrow=classic;startArrow=classic;endSize=8;startSize=8;'),
  1546. createEdge('edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;shape=flexArrow;rounded=1;startSize=8;endSize=8;'),
  1547. createEdge('edgeStyle=segmentEdgeStyle;endArrow=classic;html=1;curved=0;rounded=0;endSize=8;startSize=8;sourcePerimeterSpacing=0;targetPerimeterSpacing=0;',
  1548. this.editor.graph.defaultEdgeLength / 2)
  1549. ]);
  1550. }
  1551. return cells;
  1552. };
  1553. /**
  1554. * Creates a temporary graph instance for rendering off-screen content.
  1555. */
  1556. EditorUi.prototype.isShapePickerVisible = function (cancel) {
  1557. return this.shapePicker != null;
  1558. };
  1559. /**
  1560. * Creates a temporary graph instance for rendering off-screen content.
  1561. */
  1562. EditorUi.prototype.hideShapePicker = function (cancel) {
  1563. if (this.shapePicker != null) {
  1564. this.shapePicker.parentNode.removeChild(this.shapePicker);
  1565. this.shapePicker = null;
  1566. if (!cancel && this.shapePickerCallback != null) {
  1567. this.shapePickerCallback();
  1568. }
  1569. this.shapePickerCallback = null;
  1570. }
  1571. };
  1572. /**
  1573. * Whether the default styles should be updated when styles are changed. Default is true.
  1574. */
  1575. EditorUi.prototype.isSpaceDown = function () {
  1576. return this.spaceDown;
  1577. };
  1578. /**
  1579. * Whether the default styles should be updated when styles are changed. Default is true.
  1580. */
  1581. EditorUi.prototype.isShiftDown = function () {
  1582. return this.shiftDown;
  1583. };
  1584. /**
  1585. * Returns true if the given event should start editing. This implementation returns true.
  1586. */
  1587. EditorUi.prototype.onKeyDown = function (evt) {
  1588. var graph = this.editor.graph;
  1589. // Alt+tab for task switcher in Windows, ctrl+tab for tab control in Chrome
  1590. if (evt.which == 9 && graph.isEnabled() && !mxEvent.isControlDown(evt)) {
  1591. if (graph.isEditing()) {
  1592. if (mxEvent.isAltDown(evt)) {
  1593. graph.stopEditing(false);
  1594. }
  1595. else {
  1596. try {
  1597. var nesting = graph.cellEditor.isContentEditing() && graph.cellEditor.isTextSelected();
  1598. if (window.getSelection && graph.cellEditor.isContentEditing() &&
  1599. !nesting && !mxClient.IS_IE && !mxClient.IS_IE11) {
  1600. var selection = window.getSelection();
  1601. var container = (selection.rangeCount > 0) ? selection.getRangeAt(0).commonAncestorContainer : null;
  1602. nesting = container != null && (container.nodeName == 'LI' || (container.parentNode != null &&
  1603. container.parentNode.nodeName == 'LI'));
  1604. }
  1605. if (nesting) {
  1606. // (Shift+)tab indents/outdents with text selection or inside list elements
  1607. document.execCommand(mxEvent.isShiftDown(evt) ? 'outdent' : 'indent', false, null);
  1608. }
  1609. // Shift+tab applies value with cursor
  1610. else if (mxEvent.isShiftDown(evt)) {
  1611. graph.stopEditing(false);
  1612. }
  1613. else {
  1614. // Inserts tab character
  1615. graph.cellEditor.insertTab(!graph.cellEditor.isContentEditing() ? 4 : null);
  1616. }
  1617. }
  1618. catch (e) {
  1619. // ignore
  1620. }
  1621. }
  1622. }
  1623. else if (mxEvent.isAltDown(evt)) {
  1624. graph.selectParentCell();
  1625. }
  1626. else {
  1627. graph.selectCell(!mxEvent.isShiftDown(evt));
  1628. }
  1629. mxEvent.consume(evt);
  1630. }
  1631. };
  1632. /**
  1633. * Returns true if the given event should start editing. This implementation returns true.
  1634. */
  1635. EditorUi.prototype.onKeyPress = function (evt) {
  1636. var graph = this.editor.graph;
  1637. // KNOWN: Focus does not work if label is empty in quirks mode
  1638. if (this.isImmediateEditingEvent(evt) && !graph.isEditing() && !graph.isSelectionEmpty() && evt.which !== 0 &&
  1639. evt.which !== 27 && !mxEvent.isAltDown(evt) && !mxEvent.isControlDown(evt) && !mxEvent.isMetaDown(evt)) {
  1640. graph.escape();
  1641. graph.startEditing();
  1642. // Workaround for FF where char is lost if cursor is placed before char
  1643. if (mxClient.IS_FF) {
  1644. var ce = graph.cellEditor;
  1645. if (ce.textarea != null) {
  1646. ce.textarea.innerHTML = String.fromCharCode(evt.which);
  1647. // Moves cursor to end of textarea
  1648. var range = document.createRange();
  1649. range.selectNodeContents(ce.textarea);
  1650. range.collapse(false);
  1651. var sel = window.getSelection();
  1652. sel.removeAllRanges();
  1653. sel.addRange(range);
  1654. }
  1655. }
  1656. }
  1657. };
  1658. /**
  1659. * Returns true if the given event should start editing. This implementation returns true.
  1660. */
  1661. EditorUi.prototype.isImmediateEditingEvent = function (evt) {
  1662. return true;
  1663. };
  1664. /**
  1665. * Updates the CSS for the given element to match the selection.
  1666. */
  1667. EditorUi.prototype.updateCssForMarker = function (markerDiv, prefix, shape, marker, fill) {
  1668. markerDiv.style.display = 'inline-flex';
  1669. markerDiv.style.alignItems = 'center';
  1670. markerDiv.style.justifyContent = 'center';
  1671. markerDiv.innerText = '';
  1672. if (shape == 'flexArrow') {
  1673. markerDiv.className = (marker != null && marker != mxConstants.NONE) ?
  1674. 'geSprite geSprite-' + prefix + 'blocktrans' : 'geSprite geSprite-noarrow';
  1675. }
  1676. else {
  1677. var src = this.getImageForMarker(marker, fill);
  1678. if (src != null) {
  1679. var img = document.createElement('img');
  1680. img.className = 'geAdaptiveAsset';
  1681. img.setAttribute('src', src);
  1682. markerDiv.className = '';
  1683. if (prefix == 'end') {
  1684. mxUtils.setPrefixedStyle(img.style, 'transform', 'scaleX(-1)');
  1685. }
  1686. markerDiv.appendChild(img);
  1687. }
  1688. else {
  1689. markerDiv.className = 'geSprite geSprite-noarrow';
  1690. markerDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('none'));
  1691. markerDiv.style.backgroundImage = 'none';
  1692. markerDiv.style.fontSize = '11px';
  1693. markerDiv.style.filter = 'none';
  1694. }
  1695. }
  1696. };
  1697. /**
  1698. * Returns true if the given event should start editing. This implementation returns true.
  1699. */
  1700. EditorUi.prototype.getImageForMarker = function (marker, fill) {
  1701. var result = null;
  1702. if (marker == mxConstants.ARROW_CLASSIC) {
  1703. result = (fill != '1') ? Format.classicMarkerImage.src :
  1704. Format.classicFilledMarkerImage.src
  1705. }
  1706. else if (marker == mxConstants.ARROW_CLASSIC_THIN) {
  1707. result = (fill != '1') ? Format.classicThinMarkerImage.src :
  1708. Format.openThinFilledMarkerImage.src;
  1709. }
  1710. else if (marker == mxConstants.ARROW_OPEN) {
  1711. result = Format.openFilledMarkerImage.src;
  1712. }
  1713. else if (marker == mxConstants.ARROW_OPEN_THIN) {
  1714. result = Format.openThinFilledMarkerImage.src;
  1715. }
  1716. else if (marker == mxConstants.ARROW_BLOCK) {
  1717. result = (fill != '1') ? Format.blockMarkerImage.src :
  1718. Format.blockFilledMarkerImage.src;
  1719. }
  1720. else if (marker == mxConstants.ARROW_BLOCK_THIN) {
  1721. result = (fill != '1') ? Format.blockThinMarkerImage.src :
  1722. Format.blockThinFilledMarkerImage.src;
  1723. }
  1724. else if (marker == mxConstants.ARROW_OVAL) {
  1725. result = (fill != '1') ? Format.ovalMarkerImage.src :
  1726. Format.ovalFilledMarkerImage.src;
  1727. }
  1728. else if (marker == mxConstants.ARROW_DIAMOND) {
  1729. result = (fill != '1') ? Format.diamondMarkerImage.src :
  1730. Format.diamondFilledMarkerImage.src;
  1731. }
  1732. else if (marker == mxConstants.ARROW_DIAMOND_THIN) {
  1733. result = (fill != '1') ? Format.diamondThinMarkerImage.src :
  1734. Format.diamondThinFilledMarkerImage.src;
  1735. }
  1736. else if (marker == 'doubleBlock') {
  1737. result = (fill != '1') ? Format.doubleBlockMarkerImage.src :
  1738. Format.doubleBlockFilledMarkerImage.src;
  1739. }
  1740. else if (marker == 'box') {
  1741. result = Format.boxMarkerImage.src;
  1742. }
  1743. else if (marker == 'halfCircle') {
  1744. result = Format.halfCircleMarkerImage.src;
  1745. }
  1746. else if (marker == 'openAsync') {
  1747. result = Format.openAsyncFilledMarkerImage.src;
  1748. }
  1749. else if (marker == 'async') {
  1750. result = (fill != '1') ? Format.asyncMarkerImage.src :
  1751. Format.asyncFilledMarkerImage.src;
  1752. }
  1753. else if (marker == 'dash') {
  1754. result = Format.dashMarkerImage.src;
  1755. }
  1756. else if (marker == 'baseDash') {
  1757. result = Format.baseDashMarkerImage.src;
  1758. }
  1759. else if (marker == 'cross') {
  1760. result = Format.crossMarkerImage.src;
  1761. }
  1762. else if (marker == 'circle') {
  1763. result = Format.circleMarkerImage.src;
  1764. }
  1765. else if (marker == 'circlePlus') {
  1766. result = Format.circlePlusMarkerImage.src;
  1767. }
  1768. else if (marker == 'ERone') {
  1769. result = Format.EROneMarkerImage.src;
  1770. }
  1771. else if (marker == 'ERmandOne') {
  1772. result = Format.ERmandOneMarkerImage.src;
  1773. }
  1774. else if (marker == 'ERmany') {
  1775. result = Format.ERmanyMarkerImage.src;
  1776. }
  1777. else if (marker == 'ERoneToMany') {
  1778. result = Format.ERoneToManyMarkerImage.src;
  1779. }
  1780. else if (marker == 'ERzeroToOne') {
  1781. result = Format.ERzeroToOneMarkerImage.src;
  1782. }
  1783. else if (marker == 'ERzeroToMany') {
  1784. result = Format.ERzeroToManyMarkerImage.src;
  1785. }
  1786. return result;
  1787. };
  1788. /**
  1789. * Overridden in Menus.js
  1790. */
  1791. EditorUi.prototype.createMenus = function () {
  1792. return null;
  1793. };
  1794. /**
  1795. * Hook for allowing selection and context menu for certain events.
  1796. */
  1797. EditorUi.prototype.updatePasteActionStates = function () {
  1798. var graph = this.editor.graph;
  1799. var paste = this.actions.get('paste');
  1800. var pasteHere = this.actions.get('pasteHere');
  1801. paste.setEnabled(this.editor.graph.cellEditor.isContentEditing() ||
  1802. (((!mxClient.IS_FF && navigator.clipboard != null) || !mxClipboard.isEmpty()) &&
  1803. graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent())));
  1804. pasteHere.setEnabled(paste.isEnabled());
  1805. };
  1806. /**
  1807. * Hook for allowing selection and context menu for certain events.
  1808. */
  1809. EditorUi.prototype.initClipboard = function () {
  1810. var ui = this;
  1811. var mxClipboardCut = mxClipboard.cut;
  1812. mxClipboard.cut = function (graph) {
  1813. if (graph.cellEditor.isContentEditing()) {
  1814. document.execCommand('cut', false, null);
  1815. }
  1816. else {
  1817. mxClipboardCut.apply(this, arguments);
  1818. }
  1819. ui.updatePasteActionStates();
  1820. };
  1821. var mxClipboardCopy = mxClipboard.copy;
  1822. mxClipboard.copy = function (graph) {
  1823. var result = null;
  1824. if (graph.cellEditor.isContentEditing()) {
  1825. document.execCommand('copy', false, null);
  1826. }
  1827. else {
  1828. result = result || graph.getSelectionCells();
  1829. result = graph.getExportableCells(graph.model.getTopmostCells(result));
  1830. var cloneMap = new Object();
  1831. var lookup = graph.createCellLookup(result);
  1832. var clones = graph.cloneCells(result, null, cloneMap);
  1833. // Uses temporary model to force new IDs to be assigned
  1834. // to avoid having to carry over the mapping from object
  1835. // ID to cell ID to the paste operation
  1836. var model = new mxGraphModel();
  1837. var parent = model.getChildAt(model.getRoot(), 0);
  1838. for (var i = 0; i < clones.length; i++) {
  1839. model.add(parent, clones[i]);
  1840. // Checks for orphaned relative children and makes absolute
  1841. var state = graph.view.getState(result[i]);
  1842. if (state != null) {
  1843. var geo = graph.getCellGeometry(clones[i]);
  1844. if (geo != null && geo.relative && !model.isEdge(result[i]) &&
  1845. lookup[mxObjectIdentity.get(model.getParent(result[i]))] == null) {
  1846. geo.offset = null;
  1847. geo.relative = false;
  1848. geo.x = state.x / state.view.scale - state.view.translate.x;
  1849. geo.y = state.y / state.view.scale - state.view.translate.y;
  1850. }
  1851. }
  1852. }
  1853. graph.updateCustomLinks(graph.createCellMapping(cloneMap, lookup), clones);
  1854. mxClipboard.insertCount = 1;
  1855. mxClipboard.setCells(clones);
  1856. }
  1857. ui.updatePasteActionStates();
  1858. return result;
  1859. };
  1860. var mxClipboardPaste = mxClipboard.paste;
  1861. mxClipboard.paste = function (graph) {
  1862. var result = null;
  1863. if (graph.cellEditor.isContentEditing()) {
  1864. document.execCommand('paste', false, null);
  1865. }
  1866. else {
  1867. result = mxClipboardPaste.apply(this, arguments);
  1868. }
  1869. ui.updatePasteActionStates();
  1870. return result;
  1871. };
  1872. // Overrides cell editor to update paste action state
  1873. var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;
  1874. this.editor.graph.cellEditor.startEditing = function () {
  1875. cellEditorStartEditing.apply(this, arguments);
  1876. ui.updatePasteActionStates();
  1877. };
  1878. var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;
  1879. this.editor.graph.cellEditor.stopEditing = function (cell, trigger) {
  1880. cellEditorStopEditing.apply(this, arguments);
  1881. ui.updatePasteActionStates();
  1882. };
  1883. this.updatePasteActionStates();
  1884. };
  1885. /**
  1886. * Delay between zoom steps when not using preview.
  1887. */
  1888. EditorUi.prototype.lazyZoomDelay = 20;
  1889. /**
  1890. * Delay before update of DOM when using preview.
  1891. */
  1892. EditorUi.prototype.wheelZoomDelay = 500;
  1893. /**
  1894. * Delay before update of DOM when using preview.
  1895. */
  1896. EditorUi.prototype.buttonZoomDelay = 600;
  1897. /**
  1898. * Initializes the infinite canvas.
  1899. */
  1900. EditorUi.prototype.initCanvas = function () {
  1901. // Initial page layout view, scrollBuffer and timer-based scrolling
  1902. var graph = this.editor.graph;
  1903. graph.timerAutoScroll = true;
  1904. /**
  1905. * Returns the padding for pages in page view with scrollbars.
  1906. */
  1907. graph.getPagePadding = function () {
  1908. return new mxPoint(Math.max(0, Math.round((graph.container.offsetWidth - 34) / graph.view.scale)),
  1909. Math.max(0, Math.round((graph.container.offsetHeight - 34) / graph.view.scale)));
  1910. };
  1911. // Fits the number of background pages to the graph
  1912. graph.view.getBackgroundPageBounds = function () {
  1913. var layout = this.graph.getPageLayout();
  1914. var page = this.graph.getPageSize();
  1915. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  1916. this.scale * (this.translate.y + layout.y * page.height),
  1917. this.scale * layout.width * page.width,
  1918. this.scale * layout.height * page.height);
  1919. };
  1920. graph.getPreferredPageSize = function (bounds, width, height) {
  1921. var pages = this.getPageLayout();
  1922. var size = this.getPageSize();
  1923. return new mxRectangle(0, 0, pages.width * size.width, pages.height * size.height);
  1924. };
  1925. // Scales pages/graph to fit available size
  1926. var resize = null;
  1927. var ui = this;
  1928. if (this.editor.isChromelessView()) {
  1929. resize = mxUtils.bind(this, function (autoscale, maxScale, cx, cy) {
  1930. if (graph.container != null && !graph.isViewer()) {
  1931. cx = (cx != null) ? cx : 0;
  1932. cy = (cy != null) ? cy : 0;
  1933. var bds = (graph.pageVisible) ?
  1934. graph.view.getBackgroundPageBounds() :
  1935. graph.getGraphBounds();
  1936. var scroll = mxUtils.hasScrollbars(graph.container);
  1937. var tr = graph.view.translate;
  1938. var s = graph.view.scale;
  1939. // Normalizes the bounds
  1940. var b = mxRectangle.fromRectangle(bds);
  1941. b.x = b.x / s - tr.x;
  1942. b.y = b.y / s - tr.y;
  1943. b.width /= s;
  1944. b.height /= s;
  1945. var st = graph.container.scrollTop;
  1946. var sl = graph.container.scrollLeft;
  1947. var sb = (document.documentMode >= 8) ? 20 : 14;
  1948. if (document.documentMode == 8 || document.documentMode == 9) {
  1949. sb += 3;
  1950. }
  1951. var cw = graph.container.offsetWidth - sb;
  1952. var ch = graph.container.offsetHeight - sb;
  1953. var ns = (autoscale) ? Math.max(0.3, Math.min(maxScale || 1, cw / b.width)) : s;
  1954. var dx = ((cw - ns * b.width) / 2) / ns;
  1955. var dy = (this.lightboxVerticalDivider == 0) ? 0 : ((ch - ns * b.height) / this.lightboxVerticalDivider) / ns;
  1956. if (scroll) {
  1957. dx = Math.max(dx, 0);
  1958. dy = Math.max(dy, 0);
  1959. }
  1960. if (scroll || bds.width < cw || bds.height < ch) {
  1961. graph.view.scaleAndTranslate(ns, Math.floor(dx - b.x), Math.floor(dy - b.y));
  1962. graph.container.scrollTop = st * ns / s;
  1963. graph.container.scrollLeft = sl * ns / s;
  1964. }
  1965. else if (cx != 0 || cy != 0) {
  1966. var t = graph.view.translate;
  1967. graph.view.setTranslate(Math.floor(t.x + cx / s), Math.floor(t.y + cy / s));
  1968. }
  1969. }
  1970. });
  1971. // Hack to make function available to subclassers
  1972. this.chromelessResize = resize;
  1973. // Hook for subclassers for override
  1974. this.chromelessWindowResize = mxUtils.bind(this, function () {
  1975. this.chromelessResize(false);
  1976. });
  1977. // Removable resize listener
  1978. var autoscaleResize = mxUtils.bind(this, function () {
  1979. this.chromelessWindowResize(false);
  1980. });
  1981. mxEvent.addListener(window, 'resize', autoscaleResize);
  1982. this.destroyFunctions.push(function () {
  1983. mxEvent.removeListener(window, 'resize', autoscaleResize);
  1984. });
  1985. this.editor.addListener('resetGraphView', mxUtils.bind(this, function () {
  1986. this.chromelessResize(true);
  1987. }));
  1988. this.actions.get('zoomIn').funct = mxUtils.bind(this, function (evt) {
  1989. graph.zoomIn();
  1990. this.chromelessResize(false);
  1991. });
  1992. this.actions.get('zoomOut').funct = mxUtils.bind(this, function (evt) {
  1993. graph.zoomOut();
  1994. this.chromelessResize(false);
  1995. });
  1996. // Creates toolbar for viewer - do not use CSS here
  1997. // as this may be used in a viewer that has no CSS
  1998. if (urlParams['toolbar'] != '0') {
  1999. var toolbarConfig = JSON.parse(decodeURIComponent(urlParams['toolbar-config'] || '{}'));
  2000. this.chromelessToolbar = document.createElement('div');
  2001. this.chromelessToolbar.style.position = 'fixed';
  2002. this.chromelessToolbar.style.overflow = 'hidden';
  2003. this.chromelessToolbar.style.boxSizing = 'border-box';
  2004. this.chromelessToolbar.style.whiteSpace = 'nowrap';
  2005. this.chromelessToolbar.style.padding = '10px 10px 8px 10px';
  2006. this.chromelessToolbar.style.left = (graph.isViewer()) ? '0' : '50%';
  2007. if (!mxClient.IS_IE && !mxClient.IS_IE11) {
  2008. this.chromelessToolbar.style.backgroundColor = '#000000';
  2009. }
  2010. else {
  2011. this.chromelessToolbar.style.backgroundColor = '#ffffff';
  2012. this.chromelessToolbar.style.border = '3px solid black';
  2013. }
  2014. mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'borderRadius', '16px');
  2015. mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transition', 'opacity 600ms ease-in-out');
  2016. var updateChromelessToolbarPosition = mxUtils.bind(this, function () {
  2017. var css = mxUtils.getCurrentStyle(graph.container);
  2018. if (graph.isViewer()) {
  2019. this.chromelessToolbar.style.top = '0';
  2020. }
  2021. else {
  2022. this.chromelessToolbar.style.bottom = ((css != null) ? parseInt(css['margin-bottom'] || 0) : 0) +
  2023. ((this.tabContainer != null) ? (20 + parseInt(this.tabContainer.style.height)) : 20) + 'px';
  2024. }
  2025. });
  2026. this.editor.addListener('resetGraphView', updateChromelessToolbarPosition);
  2027. updateChromelessToolbarPosition();
  2028. var btnCount = 0;
  2029. var addButton = mxUtils.bind(this, function (fn, imgSrc, tip) {
  2030. btnCount++;
  2031. var a = document.createElement('span');
  2032. a.style.paddingLeft = '8px';
  2033. a.style.paddingRight = '8px';
  2034. a.style.cursor = 'pointer';
  2035. mxEvent.addListener(a, 'click', fn);
  2036. if (tip != null) {
  2037. a.setAttribute('title', tip);
  2038. }
  2039. var img = document.createElement('img');
  2040. img.setAttribute('border', '0');
  2041. img.setAttribute('src', imgSrc);
  2042. img.style.width = '36px';
  2043. img.style.filter = 'invert(100%)';
  2044. a.appendChild(img);
  2045. this.chromelessToolbar.appendChild(a);
  2046. return a;
  2047. });
  2048. if (toolbarConfig.backBtn != null) {
  2049. var backUrl = Graph.sanitizeLink(toolbarConfig.backBtn.url);
  2050. if (backUrl != null) {
  2051. addButton(mxUtils.bind(this, function (evt) {
  2052. window.location.href = backUrl;
  2053. mxEvent.consume(evt);
  2054. }), Editor.backImage, mxResources.get('back', null, 'Back'));
  2055. }
  2056. }
  2057. if (this.isPagesEnabled()) {
  2058. var prevButton = addButton(mxUtils.bind(this, function (evt) {
  2059. this.actions.get('previousPage').funct();
  2060. mxEvent.consume(evt);
  2061. }), Editor.previousImage, mxResources.get('previousPage'));
  2062. var pageInfo = document.createElement('div');
  2063. pageInfo.style.fontFamily = Editor.defaultHtmlFont;
  2064. pageInfo.style.display = 'inline-block';
  2065. pageInfo.style.verticalAlign = 'top';
  2066. pageInfo.style.fontWeight = 'bold';
  2067. pageInfo.style.marginTop = '8px';
  2068. pageInfo.style.fontSize = '14px';
  2069. if (!mxClient.IS_IE && !mxClient.IS_IE11) {
  2070. pageInfo.style.color = '#ffffff';
  2071. }
  2072. else {
  2073. pageInfo.style.color = '#000000';
  2074. }
  2075. this.chromelessToolbar.appendChild(pageInfo);
  2076. var nextButton = addButton(mxUtils.bind(this, function (evt) {
  2077. this.actions.get('nextPage').funct();
  2078. mxEvent.consume(evt);
  2079. }), Editor.nextImage, mxResources.get('nextPage'));
  2080. var updatePageInfo = mxUtils.bind(this, function () {
  2081. if (this.pages != null && this.pages.length > 1 && this.currentPage != null) {
  2082. pageInfo.innerText = '';
  2083. mxUtils.write(pageInfo, (mxUtils.indexOf(this.pages, this.currentPage) + 1) + ' / ' + this.pages.length);
  2084. }
  2085. });
  2086. prevButton.style.paddingLeft = '0px';
  2087. prevButton.style.paddingRight = '4px';
  2088. nextButton.style.paddingLeft = '4px';
  2089. nextButton.style.paddingRight = '0px';
  2090. var updatePageButtons = mxUtils.bind(this, function () {
  2091. if (this.pages != null && this.pages.length > 1 && this.currentPage != null) {
  2092. nextButton.style.display = '';
  2093. prevButton.style.display = '';
  2094. pageInfo.style.display = 'inline-block';
  2095. }
  2096. else {
  2097. nextButton.style.display = 'none';
  2098. prevButton.style.display = 'none';
  2099. pageInfo.style.display = 'none';
  2100. }
  2101. updatePageInfo();
  2102. });
  2103. this.editor.addListener('resetGraphView', updatePageButtons);
  2104. this.editor.addListener('pageSelected', updatePageInfo);
  2105. }
  2106. addButton(mxUtils.bind(this, function (evt) {
  2107. this.actions.get('zoomOut').funct();
  2108. mxEvent.consume(evt);
  2109. }), Editor.zoomOutImage, mxResources.get('zoomOut') + ' (Alt+Mousewheel)');
  2110. addButton(mxUtils.bind(this, function (evt) {
  2111. this.actions.get('zoomIn').funct();
  2112. mxEvent.consume(evt);
  2113. }), Editor.zoomInImage, mxResources.get('zoomIn') + ' (Alt+Mousewheel)');
  2114. addButton(mxUtils.bind(this, function (evt) {
  2115. if (graph.isLightboxView()) {
  2116. if (graph.view.scale == 1) {
  2117. this.lightboxFit();
  2118. }
  2119. else {
  2120. graph.zoomTo(1);
  2121. }
  2122. this.chromelessResize(false);
  2123. }
  2124. else {
  2125. this.chromelessResize(true);
  2126. }
  2127. mxEvent.consume(evt);
  2128. }), Editor.zoomFitImage, mxResources.get('fit'));
  2129. // Changes toolbar opacity on hover
  2130. var fadeThread = null;
  2131. var fadeThread2 = null;
  2132. var fadeOut = mxUtils.bind(this, function (delay) {
  2133. if (fadeThread != null) {
  2134. window.clearTimeout(fadeThread);
  2135. fadeThread = null;
  2136. }
  2137. if (fadeThread2 != null) {
  2138. window.clearTimeout(fadeThread2);
  2139. fadeThread2 = null;
  2140. }
  2141. fadeThread = window.setTimeout(mxUtils.bind(this, function () {
  2142. mxUtils.setOpacity(this.chromelessToolbar, 0);
  2143. fadeThread = null;
  2144. fadeThread2 = window.setTimeout(mxUtils.bind(this, function () {
  2145. this.chromelessToolbar.style.display = 'none';
  2146. fadeThread2 = null;
  2147. }), 600);
  2148. }), delay || 200);
  2149. });
  2150. var fadeIn = mxUtils.bind(this, function (opacity) {
  2151. if (fadeThread != null) {
  2152. window.clearTimeout(fadeThread);
  2153. fadeThread = null;
  2154. }
  2155. if (fadeThread2 != null) {
  2156. window.clearTimeout(fadeThread2);
  2157. fadeThread2 = null;
  2158. }
  2159. this.chromelessToolbar.style.display = '';
  2160. mxUtils.setOpacity(this.chromelessToolbar, opacity || 30);
  2161. });
  2162. if (urlParams['layers'] == '1') {
  2163. this.layersDialog = null;
  2164. var layersButton = addButton(mxUtils.bind(this, function (evt) {
  2165. if (this.layersDialog != null) {
  2166. this.layersDialog.parentNode.removeChild(this.layersDialog);
  2167. this.layersDialog = null;
  2168. }
  2169. else {
  2170. this.layersDialog = graph.createLayersDialog(null, true);
  2171. mxEvent.addListener(this.layersDialog, 'mouseleave', mxUtils.bind(this, function () {
  2172. this.layersDialog.parentNode.removeChild(this.layersDialog);
  2173. this.layersDialog = null;
  2174. }));
  2175. var r = layersButton.getBoundingClientRect();
  2176. mxUtils.setPrefixedStyle(this.layersDialog.style, 'borderRadius', '5px');
  2177. this.layersDialog.style.position = 'fixed';
  2178. this.layersDialog.style.fontFamily = Editor.defaultHtmlFont;
  2179. this.layersDialog.style.width = '160px';
  2180. this.layersDialog.style.padding = '4px 2px 4px 2px';
  2181. this.layersDialog.style.left = r.left + 'px';
  2182. this.layersDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  2183. this.chromelessToolbar.offsetHeight + 4 + 'px';
  2184. if (!mxClient.IS_IE && !mxClient.IS_IE11) {
  2185. this.layersDialog.style.backgroundColor = '#000000';
  2186. this.layersDialog.style.color = '#ffffff';
  2187. mxUtils.setOpacity(this.layersDialog, 80);
  2188. }
  2189. else {
  2190. this.layersDialog.style.backgroundColor = '#ffffff';
  2191. this.layersDialog.style.border = '2px solid black';
  2192. this.layersDialog.style.color = '#000000';
  2193. }
  2194. // Puts the dialog on top of the container z-index
  2195. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  2196. this.layersDialog.style.zIndex = style.zIndex;
  2197. document.body.appendChild(this.layersDialog);
  2198. this.editor.fireEvent(new mxEventObject('layersDialogShown'));
  2199. }
  2200. mxEvent.consume(evt);
  2201. }), Editor.layersImage, mxResources.get('layers'));
  2202. // Shows/hides layers button depending on content
  2203. var model = graph.getModel();
  2204. model.addListener(mxEvent.CHANGE, function () {
  2205. layersButton.style.display = (model.getChildCount(model.root) > 1) ? '' : 'none';
  2206. });
  2207. }
  2208. if (urlParams['openInSameWin'] != '1' || navigator.standalone) {
  2209. this.addChromelessToolbarItems(addButton);
  2210. }
  2211. if (this.editor.editButtonLink != null || this.editor.editButtonFunc != null) {
  2212. addButton(mxUtils.bind(this, function (evt) {
  2213. if (this.editor.editButtonFunc != null) {
  2214. this.editor.editButtonFunc();
  2215. }
  2216. else if (this.editor.editButtonLink == '_blank') {
  2217. this.editor.editAsNew(this.getEditBlankXml());
  2218. }
  2219. else {
  2220. graph.openLink(this.editor.editButtonLink, 'editWindow');
  2221. }
  2222. mxEvent.consume(evt);
  2223. }), Editor.editImage, mxResources.get('edit'));
  2224. }
  2225. if (this.lightboxToolbarActions != null) {
  2226. for (var i = 0; i < this.lightboxToolbarActions.length; i++) {
  2227. var lbAction = this.lightboxToolbarActions[i];
  2228. lbAction.elem = addButton(lbAction.fn, lbAction.icon, lbAction.tooltip);
  2229. }
  2230. }
  2231. if (toolbarConfig.refreshBtn != null) {
  2232. var refreshUrl = (toolbarConfig.refreshBtn.url == null) ? null :
  2233. Graph.sanitizeLink(toolbarConfig.refreshBtn.url);
  2234. addButton(mxUtils.bind(this, function (evt) {
  2235. if (refreshUrl != null) {
  2236. window.location.href = refreshUrl;
  2237. }
  2238. else {
  2239. window.location.reload();
  2240. }
  2241. mxEvent.consume(evt);
  2242. }), Editor.refreshImage, mxResources.get('refresh', null, 'Refresh'));
  2243. }
  2244. if (toolbarConfig.fullscreenBtn != null && window.self !== window.top) {
  2245. addButton(mxUtils.bind(this, function (evt) {
  2246. if (toolbarConfig.fullscreenBtn.url) {
  2247. graph.openLink(toolbarConfig.fullscreenBtn.url);
  2248. }
  2249. else {
  2250. graph.openLink(window.location.href);
  2251. }
  2252. mxEvent.consume(evt);
  2253. }), Editor.fullscreenImage, mxResources.get('openInNewWindow', null, 'Open in New Window'));
  2254. }
  2255. if (!toolbarConfig.noCloseBtn && ((toolbarConfig.closeBtn && window.self === window.top) ||
  2256. (graph.lightbox && (urlParams['close'] == '1' || this.container != document.body)))) {
  2257. addButton(mxUtils.bind(this, function (evt) {
  2258. if (urlParams['close'] == '1' || toolbarConfig.closeBtn) {
  2259. window.close();
  2260. }
  2261. else {
  2262. this.destroy();
  2263. mxEvent.consume(evt);
  2264. }
  2265. }), Editor.closeImage, mxResources.get('close') + ' (Escape)');
  2266. }
  2267. // Initial state invisible
  2268. this.chromelessToolbar.style.display = 'none';
  2269. if (!graph.isViewer()) {
  2270. mxUtils.setPrefixedStyle(this.chromelessToolbar.style, 'transform', 'translate(-50%,0)');
  2271. }
  2272. graph.container.appendChild(this.chromelessToolbar);
  2273. mxEvent.addListener(graph.container, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', mxUtils.bind(this, function (evt) {
  2274. if (!mxEvent.isTouchEvent(evt)) {
  2275. if (!mxEvent.isShiftDown(evt)) {
  2276. fadeIn(30);
  2277. }
  2278. fadeOut();
  2279. }
  2280. }));
  2281. mxEvent.addListener(this.chromelessToolbar, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', function (evt) {
  2282. mxEvent.consume(evt);
  2283. });
  2284. mxEvent.addListener(this.chromelessToolbar, 'mouseenter', mxUtils.bind(this, function (evt) {
  2285. graph.tooltipHandler.resetTimer();
  2286. graph.tooltipHandler.hideTooltip();
  2287. if (!mxEvent.isShiftDown(evt)) {
  2288. fadeIn(100);
  2289. }
  2290. else {
  2291. fadeOut();
  2292. }
  2293. }));
  2294. mxEvent.addListener(this.chromelessToolbar, 'mousemove', mxUtils.bind(this, function (evt) {
  2295. if (!mxEvent.isShiftDown(evt)) {
  2296. fadeIn(100);
  2297. }
  2298. else {
  2299. fadeOut();
  2300. }
  2301. mxEvent.consume(evt);
  2302. }));
  2303. mxEvent.addListener(this.chromelessToolbar, 'mouseleave', mxUtils.bind(this, function (evt) {
  2304. if (!mxEvent.isTouchEvent(evt)) {
  2305. fadeIn(30);
  2306. }
  2307. }));
  2308. // Shows/hides toolbar for touch devices
  2309. var tol = graph.getTolerance();
  2310. graph.addMouseListener(
  2311. {
  2312. startX: 0,
  2313. startY: 0,
  2314. scrollLeft: 0,
  2315. scrollTop: 0,
  2316. mouseDown: function (sender, me) {
  2317. this.startX = me.getGraphX();
  2318. this.startY = me.getGraphY();
  2319. this.scrollLeft = graph.container.scrollLeft;
  2320. this.scrollTop = graph.container.scrollTop;
  2321. },
  2322. mouseMove: function (sender, me) { },
  2323. mouseUp: function (sender, me) {
  2324. if (mxEvent.isTouchEvent(me.getEvent())) {
  2325. if ((Math.abs(this.scrollLeft - graph.container.scrollLeft) < tol &&
  2326. Math.abs(this.scrollTop - graph.container.scrollTop) < tol) &&
  2327. (Math.abs(this.startX - me.getGraphX()) < tol &&
  2328. Math.abs(this.startY - me.getGraphY()) < tol)) {
  2329. if (parseFloat(ui.chromelessToolbar.style.opacity || 0) > 0) {
  2330. fadeOut();
  2331. }
  2332. else {
  2333. fadeIn(30);
  2334. }
  2335. }
  2336. }
  2337. }
  2338. });
  2339. } // end if toolbar
  2340. // Installs handling of highlight and handling links to relative links and anchors
  2341. if (!this.editor.editable) {
  2342. this.addChromelessClickHandler();
  2343. }
  2344. }
  2345. else if (this.editor.extendCanvas) {
  2346. /**
  2347. * Guesses autoTranslate to avoid another repaint (see below).
  2348. * Works if only the scale of the graph changes or if pages
  2349. * are visible and the visible pages do not change. Uses
  2350. * geometries to guess the bounding box of the graph.
  2351. */
  2352. var graphViewValidate = graph.view.validate;
  2353. var zero = new mxPoint();
  2354. var lastPage = null;
  2355. graph.view.validate = function () {
  2356. if (graph.container != null &&
  2357. mxUtils.hasScrollbars(graph.container)) {
  2358. // Sets initial state after page changes
  2359. if (ui.currentPage != null &&
  2360. lastPage != ui.currentPage) {
  2361. lastPage = ui.currentPage;
  2362. // Sets initial translate based on geometries
  2363. // to avoid revalidation in sizeDidChange
  2364. var bbox = graph.getBoundingBoxFromGeometry(
  2365. graph.model.getCells(), true);
  2366. // Handles blank diagrams
  2367. if (bbox == null) {
  2368. bbox = new mxRectangle(
  2369. graph.view.translate.x * graph.view.scale,
  2370. graph.view.translate.y * graph.view.scale);
  2371. }
  2372. var pageLayout = graph.getPageLayout(bbox, zero, 1);
  2373. var tr = graph.getDefaultTranslate(pageLayout);
  2374. this.x0 = pageLayout.x;
  2375. this.y0 = pageLayout.y;
  2376. if (tr.x != this.translate.x ||
  2377. tr.y != this.translate.y) {
  2378. this.invalidate();
  2379. this.translate.x = tr.x;
  2380. this.translate.y = tr.y;
  2381. }
  2382. }
  2383. var pad = graph.getPagePadding();
  2384. var size = graph.getPageSize();
  2385. var tx = pad.x - (this.x0 || 0) * size.width;
  2386. var ty = pad.y - (this.y0 || 0) * size.height;
  2387. if (this.translate.x != tx || this.translate.y != ty) {
  2388. this.invalidate();
  2389. this.translate.x = tx
  2390. this.translate.y = ty
  2391. }
  2392. }
  2393. graphViewValidate.apply(this, arguments);
  2394. };
  2395. if (!graph.isViewer()) {
  2396. var graphSizeDidChange = graph.sizeDidChange;
  2397. graph.sizeDidChange = function () {
  2398. if (this.container != null &&
  2399. mxUtils.hasScrollbars(this.container)) {
  2400. this.updateMinimumSize();
  2401. if (!this.autoTranslate) {
  2402. var pageLayout = this.getPageLayout();
  2403. var tr = this.getDefaultTranslate(pageLayout);
  2404. var tx = this.view.translate.x;
  2405. var ty = this.view.translate.y;
  2406. if (tr.x != tx || tr.y != ty) {
  2407. this.view.x0 = pageLayout.x;
  2408. this.view.y0 = pageLayout.y;
  2409. this.autoTranslate = true;
  2410. // Requires full revalidation
  2411. this.view.setTranslate(tr.x, tr.y);
  2412. this.container.scrollLeft += Math.round((tr.x - tx) * this.view.scale);
  2413. this.container.scrollTop += Math.round((tr.y - ty) * this.view.scale);
  2414. this.autoTranslate = false;
  2415. return;
  2416. }
  2417. }
  2418. graphSizeDidChange.apply(this, arguments);
  2419. }
  2420. else {
  2421. // Fires event but does not invoke superclass
  2422. this.fireEvent(new mxEventObject(mxEvent.SIZE,
  2423. 'bounds', this.getGraphBounds()));
  2424. }
  2425. };
  2426. }
  2427. }
  2428. // Accumulates the zoom factor while the rendering is taking place
  2429. // so that not the complete sequence of zoom steps must be painted
  2430. var bgGroup = graph.view.getBackgroundPane();
  2431. var mainGroup = graph.view.getDrawPane();
  2432. graph.cumulativeZoomFactor = 1;
  2433. var updateZoomTimeout = null;
  2434. var cursorPosition = null;
  2435. var scrollPosition = null;
  2436. var forcedZoom = null;
  2437. var filter = null;
  2438. var mult = 20;
  2439. var scheduleZoom = function (delay) {
  2440. if (updateZoomTimeout != null) {
  2441. window.clearTimeout(updateZoomTimeout);
  2442. }
  2443. if (delay >= 0) {
  2444. window.setTimeout(function () {
  2445. if (!graph.isMouseDown || forcedZoom) {
  2446. updateZoomTimeout = window.setTimeout(mxUtils.bind(this, function () {
  2447. if (graph.isFastZoomEnabled()) {
  2448. // Transforms background page
  2449. if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null) {
  2450. mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform-origin', null);
  2451. mxUtils.setPrefixedStyle(graph.view.backgroundPageShape.node.style, 'transform', null);
  2452. }
  2453. // Transforms graph and background image
  2454. mainGroup.style.transformOrigin = '';
  2455. bgGroup.style.transformOrigin = '';
  2456. // Workaround for no reset of transform in Safari
  2457. if (mxClient.IS_SF) {
  2458. mainGroup.style.transform = 'scale(1)';
  2459. bgGroup.style.transform = 'scale(1)';
  2460. window.setTimeout(function () {
  2461. mainGroup.style.transform = '';
  2462. bgGroup.style.transform = '';
  2463. }, 0)
  2464. }
  2465. else {
  2466. mainGroup.style.transform = '';
  2467. bgGroup.style.transform = '';
  2468. }
  2469. // Shows interactive elements
  2470. graph.view.getDecoratorPane().style.opacity = '';
  2471. graph.view.getOverlayPane().style.opacity = '';
  2472. }
  2473. var sp = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);
  2474. var offset = mxUtils.getOffset(graph.container);
  2475. var prev = graph.view.scale;
  2476. var dx = 0;
  2477. var dy = 0;
  2478. if (cursorPosition != null) {
  2479. dx = graph.container.offsetWidth / 2 - cursorPosition.x + offset.x;
  2480. dy = graph.container.offsetHeight / 2 - cursorPosition.y + offset.y;
  2481. }
  2482. graph.zoom(graph.cumulativeZoomFactor, null,
  2483. graph.isFastZoomEnabled() ? mult : null);
  2484. var s = graph.view.scale;
  2485. if (s != prev) {
  2486. if (scrollPosition != null) {
  2487. dx += sp.x - scrollPosition.x;
  2488. dy += sp.y - scrollPosition.y;
  2489. }
  2490. if (resize != null) {
  2491. ui.chromelessResize(false, null, dx * (graph.cumulativeZoomFactor - 1),
  2492. dy * (graph.cumulativeZoomFactor - 1));
  2493. }
  2494. if (mxUtils.hasScrollbars(graph.container) && (dx != 0 || dy != 0)) {
  2495. graph.container.scrollLeft -= dx * (graph.cumulativeZoomFactor - 1);
  2496. graph.container.scrollTop -= dy * (graph.cumulativeZoomFactor - 1);
  2497. }
  2498. }
  2499. if (filter != null) {
  2500. mainGroup.setAttribute('filter', filter);
  2501. }
  2502. graph.cumulativeZoomFactor = 1;
  2503. updateZoomTimeout = null;
  2504. scrollPosition = null;
  2505. cursorPosition = null;
  2506. forcedZoom = null;
  2507. filter = null;
  2508. }), (delay != null) ? delay : ((graph.isFastZoomEnabled()) ? ui.wheelZoomDelay : ui.lazyZoomDelay));
  2509. }
  2510. }, 0);
  2511. }
  2512. };
  2513. graph.lazyZoom = function (zoomIn, ignoreCursorPosition, delay, factor) {
  2514. factor = (factor != null) ? factor : this.zoomFactor;
  2515. // TODO: Fix ignored cursor position if scrollbars are disabled
  2516. ignoreCursorPosition = ignoreCursorPosition || !graph.scrollbars;
  2517. if (ignoreCursorPosition) {
  2518. cursorPosition = new mxPoint(
  2519. graph.container.offsetLeft + graph.container.clientWidth / 2,
  2520. graph.container.offsetTop + graph.container.clientHeight / 2);
  2521. }
  2522. // Switches to 5% zoom steps below 15%
  2523. if (zoomIn) {
  2524. if (this.view.scale * this.cumulativeZoomFactor <= 0.15) {
  2525. this.cumulativeZoomFactor *= (this.view.scale + 0.05) / this.view.scale;
  2526. }
  2527. else {
  2528. this.cumulativeZoomFactor *= factor;
  2529. this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 100) / 100 / this.view.scale;
  2530. }
  2531. }
  2532. else {
  2533. if (this.view.scale * this.cumulativeZoomFactor <= 0.15) {
  2534. this.cumulativeZoomFactor *= (this.view.scale - 0.05) / this.view.scale;
  2535. }
  2536. else {
  2537. this.cumulativeZoomFactor /= factor;
  2538. this.cumulativeZoomFactor = Math.round(this.view.scale * this.cumulativeZoomFactor * 100) / 100 / this.view.scale;
  2539. }
  2540. }
  2541. this.cumulativeZoomFactor = Math.max(0.05, Math.min(this.view.scale * this.cumulativeZoomFactor, 160)) / this.view.scale;
  2542. if (graph.isFastZoomEnabled()) {
  2543. if (filter == null && mainGroup.getAttribute('filter') != '') {
  2544. filter = mainGroup.getAttribute('filter');
  2545. mainGroup.removeAttribute('filter');
  2546. }
  2547. scrollPosition = new mxPoint(graph.container.scrollLeft, graph.container.scrollTop);
  2548. // Applies final rounding to preview
  2549. var f = Math.round((Math.round(this.view.scale * this.cumulativeZoomFactor *
  2550. 100) / 100) * mult) / (mult * this.view.scale);
  2551. var cx = (ignoreCursorPosition || cursorPosition == null) ?
  2552. graph.container.scrollLeft + graph.container.clientWidth / 2 :
  2553. cursorPosition.x + graph.container.scrollLeft - graph.container.offsetLeft;
  2554. var cy = (ignoreCursorPosition || cursorPosition == null) ?
  2555. graph.container.scrollTop + graph.container.clientHeight / 2 :
  2556. cursorPosition.y + graph.container.scrollTop - graph.container.offsetTop;
  2557. mainGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
  2558. mainGroup.style.transform = 'scale(' + f + ')';
  2559. bgGroup.style.transformOrigin = cx + 'px ' + cy + 'px';
  2560. bgGroup.style.transform = 'scale(' + f + ')';
  2561. if (graph.view.backgroundPageShape != null && graph.view.backgroundPageShape.node != null) {
  2562. var page = graph.view.backgroundPageShape.node;
  2563. mxUtils.setPrefixedStyle(page.style, 'transform-origin',
  2564. ((ignoreCursorPosition || cursorPosition == null) ?
  2565. ((graph.container.clientWidth / 2 + graph.container.scrollLeft -
  2566. page.offsetLeft) + 'px') : ((cursorPosition.x + graph.container.scrollLeft -
  2567. page.offsetLeft - graph.container.offsetLeft) + 'px')) + ' ' +
  2568. ((ignoreCursorPosition || cursorPosition == null) ?
  2569. ((graph.container.clientHeight / 2 + graph.container.scrollTop -
  2570. page.offsetTop) + 'px') : ((cursorPosition.y + graph.container.scrollTop -
  2571. page.offsetTop - graph.container.offsetTop) + 'px')));
  2572. mxUtils.setPrefixedStyle(page.style, 'transform', 'scale(' + f + ')');
  2573. }
  2574. else {
  2575. graph.view.validateBackgroundStyles(f, cx, cy);
  2576. }
  2577. graph.view.getDecoratorPane().style.opacity = '0';
  2578. graph.view.getOverlayPane().style.opacity = '0';
  2579. if (ui.hoverIcons != null) {
  2580. ui.hoverIcons.reset();
  2581. }
  2582. graph.fireEvent(new mxEventObject('zoomPreview', 'factor', f));
  2583. }
  2584. scheduleZoom(graph.isFastZoomEnabled() ? delay : 0);
  2585. };
  2586. // Holds back repaint until after mouse gestures
  2587. mxEvent.addGestureListeners(graph.container, function (evt) {
  2588. if (updateZoomTimeout != null) {
  2589. window.clearTimeout(updateZoomTimeout);
  2590. }
  2591. }, null, function (evt) {
  2592. if (graph.cumulativeZoomFactor != 1) {
  2593. scheduleZoom(0);
  2594. }
  2595. });
  2596. // Holds back repaint until scroll ends
  2597. mxEvent.addListener(graph.container, 'scroll', function (evt) {
  2598. if (updateZoomTimeout != null && !graph.isMouseDown && graph.cumulativeZoomFactor != 1) {
  2599. scheduleZoom(0);
  2600. }
  2601. });
  2602. mxEvent.addMouseWheelListener(mxUtils.bind(this, function (evt, up, force, cx, cy) {
  2603. graph.fireEvent(new mxEventObject('wheel'));
  2604. if (this.dialogs == null || this.dialogs.length == 0) {
  2605. // Scrolls with scrollbars turned off
  2606. if (!graph.scrollbars && !force && graph.isScrollWheelEvent(evt)) {
  2607. var t = graph.view.getTranslate();
  2608. var step = 40 / graph.view.scale;
  2609. if (!mxEvent.isShiftDown(evt)) {
  2610. graph.view.setTranslate(t.x, t.y + ((up) ? step : -step));
  2611. }
  2612. else {
  2613. graph.view.setTranslate(t.x + ((up) ? -step : step), t.y);
  2614. }
  2615. }
  2616. else if (force || graph.isZoomWheelEvent(evt)) {
  2617. var source = mxEvent.getSource(evt);
  2618. while (source != null) {
  2619. if (source == graph.container) {
  2620. graph.tooltipHandler.hideTooltip();
  2621. cursorPosition = (cx != null && cy != null) ? new mxPoint(cx, cy) :
  2622. new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  2623. forcedZoom = force;
  2624. var factor = graph.zoomFactor;
  2625. var delay = null;
  2626. // Slower zoom for pinch gesture on trackpad with max delta to
  2627. // filter out mouse wheel events in Brave browser for Windows
  2628. if (evt.ctrlKey && evt.deltaY != null && Math.abs(evt.deltaY) < 40 &&
  2629. Math.round(evt.deltaY) != evt.deltaY) {
  2630. factor = 1 + (Math.abs(evt.deltaY) / 20) * (factor - 1);
  2631. }
  2632. // Slower zoom for pinch gesture on touch screens
  2633. else if (evt.movementY != null && evt.type == 'pointermove') {
  2634. factor = 1 + (Math.max(1, Math.abs(evt.movementY)) / 20) * (factor - 1);
  2635. delay = -1;
  2636. }
  2637. graph.lazyZoom(up, null, delay, factor);
  2638. mxEvent.consume(evt);
  2639. return false;
  2640. }
  2641. source = source.parentNode;
  2642. }
  2643. }
  2644. }
  2645. }), graph.container);
  2646. // Uses fast zoom for pinch gestures on iOS
  2647. graph.panningHandler.zoomGraph = function (evt) {
  2648. graph.cumulativeZoomFactor = evt.scale;
  2649. graph.lazyZoom(evt.scale > 0, true);
  2650. mxEvent.consume(evt);
  2651. };
  2652. };
  2653. /**
  2654. * Creates a temporary graph instance for rendering off-screen content.
  2655. */
  2656. EditorUi.prototype.addChromelessToolbarItems = function (addButton) {
  2657. addButton(mxUtils.bind(this, function (evt) {
  2658. this.actions.get('print').funct();
  2659. mxEvent.consume(evt);
  2660. }), Editor.printImage, mxResources.get('print'));
  2661. };
  2662. /**
  2663. * Creates a temporary graph instance for rendering off-screen content.
  2664. */
  2665. EditorUi.prototype.isPagesEnabled = function () {
  2666. return this.editor.editable || urlParams['hide-pages'] != '1';
  2667. };
  2668. /**
  2669. * Creates a temporary graph instance for rendering off-screen content.
  2670. */
  2671. EditorUi.prototype.createTemporaryGraph = function (stylesheet) {
  2672. return Graph.createOffscreenGraph(stylesheet);
  2673. };
  2674. /**
  2675. *
  2676. */
  2677. EditorUi.prototype.addChromelessClickHandler = function () {
  2678. var hl = urlParams['highlight'];
  2679. // Adds leading # for highlight color code
  2680. if (hl != null && hl.length > 0) {
  2681. hl = '#' + hl;
  2682. }
  2683. this.editor.graph.addClickHandler(hl);
  2684. };
  2685. /**
  2686. *
  2687. */
  2688. EditorUi.prototype.toggleFormatPanel = function (visible) {
  2689. visible = (visible != null) ? visible : this.formatWidth == 0;
  2690. if (this.format != null) {
  2691. this.formatWidth = (visible) ? 240 : 0;
  2692. this.formatContainer.style.width = this.formatWidth + 'px';
  2693. this.refresh();
  2694. this.format.refresh();
  2695. this.fireEvent(new mxEventObject('formatWidthChanged'));
  2696. }
  2697. };
  2698. /**
  2699. *
  2700. */
  2701. EditorUi.prototype.isFormatPanelVisible = function () {
  2702. return this.formatWidth > 0;
  2703. };
  2704. /**
  2705. * Adds support for placeholders in labels.
  2706. */
  2707. EditorUi.prototype.lightboxFit = function (maxHeight) {
  2708. if (this.isDiagramEmpty()) {
  2709. this.editor.graph.view.setScale(1);
  2710. }
  2711. else {
  2712. var p = urlParams['border'];
  2713. var border = 60;
  2714. if (p != null) {
  2715. border = parseInt(p);
  2716. }
  2717. // LATER: Use initial graph bounds to avoid rounding errors
  2718. this.editor.graph.maxFitScale = this.lightboxMaxFitScale;
  2719. this.editor.graph.fit(border, null, null, null, null, null, maxHeight);
  2720. this.editor.graph.maxFitScale = null;
  2721. }
  2722. };
  2723. /**
  2724. * Translates this point by the given vector.
  2725. *
  2726. * @param {number} dx X-coordinate of the translation.
  2727. * @param {number} dy Y-coordinate of the translation.
  2728. */
  2729. EditorUi.prototype.isDiagramEmpty = function () {
  2730. var model = this.editor.graph.getModel();
  2731. return model.getChildCount(model.root) == 1 && model.getChildCount(model.getChildAt(model.root, 0)) == 0;
  2732. };
  2733. /**
  2734. * Hook for allowing selection and context menu for certain events.
  2735. */
  2736. EditorUi.prototype.isSelectionAllowed = function (evt) {
  2737. return mxEvent.getSource(evt).nodeName == 'SELECT' || (mxEvent.getSource(evt).nodeName == 'INPUT' &&
  2738. mxUtils.isAncestorNode(this.formatContainer, mxEvent.getSource(evt)));
  2739. };
  2740. /**
  2741. * Installs dialog if browser window is closed without saving
  2742. * This must be disabled during save and image export.
  2743. */
  2744. EditorUi.prototype.addBeforeUnloadListener = function () {
  2745. // Installs dialog if browser window is closed without saving
  2746. // This must be disabled during save and image export
  2747. window.onbeforeunload = mxUtils.bind(this, function () {
  2748. if (!this.editor.isChromelessView()) {
  2749. return this.onBeforeUnload();
  2750. }
  2751. });
  2752. };
  2753. /**
  2754. * Sets the onbeforeunload for the application
  2755. */
  2756. EditorUi.prototype.onBeforeUnload = function () {
  2757. if (this.editor.modified) {
  2758. return mxResources.get('allChangesLost');
  2759. }
  2760. };
  2761. /**
  2762. * Opens the current diagram via the window.opener if one exists.
  2763. */
  2764. EditorUi.prototype.open = function () {
  2765. // Cross-domain window access is not allowed in FF, so if we
  2766. // were opened from another domain then this will fail.
  2767. try {
  2768. if (window.opener != null && window.opener.openFile != null) {
  2769. window.opener.openFile.setConsumer(mxUtils.bind(this, function (xml, filename) {
  2770. try {
  2771. var doc = mxUtils.parseXml(xml);
  2772. this.editor.setGraphXml(doc.documentElement);
  2773. this.editor.setModified(false);
  2774. this.editor.undoManager.clear();
  2775. if (filename != null) {
  2776. this.editor.setFilename(filename);
  2777. this.updateDocumentTitle();
  2778. }
  2779. return;
  2780. }
  2781. catch (e) {
  2782. mxUtils.alert(mxResources.get('invalidOrMissingFile') + ': ' + e.message);
  2783. }
  2784. }));
  2785. }
  2786. }
  2787. catch (e) {
  2788. // ignore
  2789. }
  2790. // Fires as the last step if no file was loaded
  2791. this.editor.graph.view.validate();
  2792. // Required only in special cases where an initial file is opened
  2793. // and the minimumGraphSize changes and CSS must be updated.
  2794. this.editor.graph.sizeDidChange();
  2795. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  2796. };
  2797. /**
  2798. * Shows the given popup menu.
  2799. */
  2800. EditorUi.prototype.showPopupMenu = function (fn, x, y, evt) {
  2801. this.editor.graph.popupMenuHandler.hideMenu();
  2802. var menu = new mxPopupMenu(fn);
  2803. menu.div.className += ' geMenubarMenu';
  2804. menu.smartSeparators = true;
  2805. menu.showDisabled = true;
  2806. menu.autoExpand = true;
  2807. // Disables autoexpand and destroys menu when hidden
  2808. menu.hideMenu = mxUtils.bind(this, function () {
  2809. mxPopupMenu.prototype.hideMenu.apply(menu, arguments);
  2810. menu.destroy();
  2811. });
  2812. menu.popup(x, y, null, evt);
  2813. // Allows hiding by clicking on document
  2814. this.setCurrentMenu(menu);
  2815. };
  2816. /**
  2817. * Sets the current menu and element.
  2818. */
  2819. EditorUi.prototype.setCurrentMenu = function (menu, elt) {
  2820. this.currentMenuElt = elt;
  2821. this.currentMenu = menu;
  2822. this.hideShapePicker();
  2823. };
  2824. /**
  2825. * Resets the current menu and element.
  2826. */
  2827. EditorUi.prototype.resetCurrentMenu = function () {
  2828. this.currentMenuElt = null;
  2829. this.currentMenu = null;
  2830. };
  2831. /**
  2832. * Hides and destroys the current menu.
  2833. */
  2834. EditorUi.prototype.hideCurrentMenu = function () {
  2835. if (this.currentMenu != null) {
  2836. this.currentMenu.hideMenu();
  2837. this.resetCurrentMenu();
  2838. }
  2839. };
  2840. /**
  2841. * Updates the document title.
  2842. */
  2843. EditorUi.prototype.updateDocumentTitle = function () {
  2844. var title = this.editor.getOrCreateFilename();
  2845. if (this.editor.appName != null) {
  2846. title += ' - ' + this.editor.appName;
  2847. }
  2848. document.title = title;
  2849. };
  2850. /**
  2851. * Updates the document title.
  2852. */
  2853. EditorUi.prototype.createHoverIcons = function () {
  2854. return new HoverIcons(this.editor.graph);
  2855. };
  2856. /**
  2857. * Returns the URL for a copy of this editor with no state.
  2858. */
  2859. EditorUi.prototype.redo = function () {
  2860. try {
  2861. var graph = this.editor.graph;
  2862. if (graph.isEditing()) {
  2863. document.execCommand('redo', false, null);
  2864. }
  2865. else {
  2866. this.editor.undoManager.redo();
  2867. }
  2868. }
  2869. catch (e) {
  2870. // ignore all errors
  2871. }
  2872. };
  2873. /**
  2874. * Returns the URL for a copy of this editor with no state.
  2875. */
  2876. EditorUi.prototype.undo = function () {
  2877. try {
  2878. var graph = this.editor.graph;
  2879. if (graph.isEditing()) {
  2880. // Stops editing and executes undo on graph if native undo
  2881. // does not affect current editing value
  2882. var value = graph.cellEditor.textarea.innerHTML;
  2883. document.execCommand('undo', false, null);
  2884. if (value == graph.cellEditor.textarea.innerHTML) {
  2885. graph.stopEditing(true);
  2886. this.editor.undoManager.undo();
  2887. }
  2888. }
  2889. else {
  2890. this.editor.undoManager.undo();
  2891. }
  2892. }
  2893. catch (e) {
  2894. // ignore all errors
  2895. }
  2896. };
  2897. /**
  2898. * Returns the URL for a copy of this editor with no state.
  2899. */
  2900. EditorUi.prototype.canRedo = function () {
  2901. return this.editor.graph.isEditing() || this.editor.undoManager.canRedo();
  2902. };
  2903. /**
  2904. * Returns the URL for a copy of this editor with no state.
  2905. */
  2906. EditorUi.prototype.canUndo = function () {
  2907. return this.editor.graph.isEditing() || this.editor.undoManager.canUndo();
  2908. };
  2909. /**
  2910. *
  2911. */
  2912. EditorUi.prototype.getEditBlankXml = function () {
  2913. return mxUtils.getXml(this.editor.getGraphXml());
  2914. };
  2915. /**
  2916. * Returns the URL for a copy of this editor with no state.
  2917. */
  2918. EditorUi.prototype.getUrl = function (pathname) {
  2919. var href = (pathname != null) ? pathname : window.location.pathname;
  2920. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  2921. // Removes template URL parameter for new blank diagram
  2922. for (var key in urlParams) {
  2923. if (parms == 0) {
  2924. href += '?';
  2925. }
  2926. else {
  2927. href += '&';
  2928. }
  2929. href += key + '=' + urlParams[key];
  2930. parms++;
  2931. }
  2932. return href;
  2933. };
  2934. /**
  2935. * Specifies if the graph has scrollbars.
  2936. */
  2937. EditorUi.prototype.setScrollbars = function (value) {
  2938. var graph = this.editor.graph;
  2939. var prev = graph.container.style.overflow;
  2940. graph.scrollbars = value;
  2941. this.editor.updateGraphComponents();
  2942. if (prev != graph.container.style.overflow) {
  2943. graph.container.scrollTop = 0;
  2944. graph.container.scrollLeft = 0;
  2945. graph.view.scaleAndTranslate(1, 0, 0);
  2946. this.resetScrollbars();
  2947. }
  2948. this.fireEvent(new mxEventObject('scrollbarsChanged'));
  2949. };
  2950. /**
  2951. * Function: fitDiagramToWindow
  2952. *
  2953. * Zooms the diagram to fit into the window.
  2954. */
  2955. EditorUi.prototype.fitDiagramToWindow = function () {
  2956. var graph = this.editor.graph;
  2957. var bounds = (graph.isSelectionEmpty()) ?
  2958. mxRectangle.fromRectangle(graph.getGraphBounds()) :
  2959. graph.getBoundingBox(graph.getSelectionCells())
  2960. var t = graph.view.translate;
  2961. var s = graph.view.scale;
  2962. bounds.x = bounds.x / s - t.x;
  2963. bounds.y = bounds.y / s - t.y;
  2964. bounds.width /= s;
  2965. bounds.height /= s;
  2966. if (graph.backgroundImage != null) {
  2967. bounds.add(new mxRectangle(0, 0,
  2968. graph.backgroundImage.width,
  2969. graph.backgroundImage.height));
  2970. }
  2971. if (bounds.width == 0 || bounds.height == 0) {
  2972. graph.zoomTo(1);
  2973. this.resetScrollbars();
  2974. }
  2975. else {
  2976. var b = Editor.fitWindowBorders;
  2977. if (b != null) {
  2978. bounds.x -= b.x;
  2979. bounds.y -= b.y;
  2980. bounds.width += b.width + b.x;
  2981. bounds.height += b.height + b.y;
  2982. }
  2983. graph.fitWindow(bounds);
  2984. }
  2985. };
  2986. /**
  2987. * Returns true if the graph has scrollbars.
  2988. */
  2989. EditorUi.prototype.hasScrollbars = function () {
  2990. return this.editor.graph.scrollbars;
  2991. };
  2992. /**
  2993. * Resets the state of the scrollbars.
  2994. */
  2995. EditorUi.prototype.resetScrollbars = function () {
  2996. var graph = this.editor.graph;
  2997. var c = graph.container;
  2998. if (!this.editor.extendCanvas) {
  2999. c.scrollTop = 0;
  3000. c.scrollLeft = 0;
  3001. if (!mxUtils.hasScrollbars(c)) {
  3002. graph.view.setTranslate(0, 0);
  3003. }
  3004. }
  3005. else if (!this.editor.isChromelessView()) {
  3006. if (mxUtils.hasScrollbars(c)) {
  3007. if (graph.pageVisible) {
  3008. var pad = graph.getPagePadding();
  3009. c.scrollTop = Math.floor(pad.y - this.editor.initialTopSpacing) - 1;
  3010. c.scrollLeft = Math.floor(Math.min(pad.x,
  3011. (c.scrollWidth - c.clientWidth) / 2)) - 1;
  3012. // Scrolls graph to visible area
  3013. var bounds = graph.getGraphBounds();
  3014. if (bounds.width > 0 && bounds.height > 0) {
  3015. if (bounds.x > c.scrollLeft + c.clientWidth * 0.9) {
  3016. c.scrollLeft = Math.min(bounds.x + bounds.width - c.clientWidth, bounds.x - 10);
  3017. }
  3018. if (bounds.y > c.scrollTop + c.clientHeight * 0.9) {
  3019. c.scrollTop = Math.min(bounds.y + bounds.height - c.clientHeight, bounds.y - 10);
  3020. }
  3021. }
  3022. }
  3023. else {
  3024. var bounds = graph.getGraphBounds();
  3025. if (bounds.width == 0 && bounds.height == 0) {
  3026. c.scrollLeft = (c.scrollWidth - c.clientWidth) / 2;
  3027. c.scrollTop = (c.scrollHeight - c.clientHeight) / 2;
  3028. }
  3029. else {
  3030. var width = Math.max(bounds.width, graph.scrollTileSize.width * graph.view.scale);
  3031. var height = Math.max(bounds.height, graph.scrollTileSize.height * graph.view.scale);
  3032. c.scrollLeft = Math.floor(Math.max(0, bounds.x - Math.max(0, (c.clientWidth - width) / 2)));
  3033. c.scrollTop = Math.floor(Math.max(0, bounds.y - Math.max(20, (c.clientHeight - height) / 4)));
  3034. }
  3035. }
  3036. }
  3037. else {
  3038. var b = mxRectangle.fromRectangle((graph.pageVisible) ?
  3039. graph.view.getBackgroundPageBounds() :
  3040. graph.getGraphBounds())
  3041. var tr = graph.view.translate;
  3042. var s = graph.view.scale;
  3043. b.x = b.x / s - tr.x;
  3044. b.y = b.y / s - tr.y;
  3045. b.width /= s;
  3046. b.height /= s;
  3047. var dy = (graph.pageVisible) ? 0 : Math.max(0, (c.clientHeight - b.height) / 4);
  3048. graph.view.setTranslate(Math.floor(Math.max(0,
  3049. (c.clientWidth - b.width) / 2) - b.x + 2),
  3050. Math.floor(dy - b.y + 1));
  3051. }
  3052. }
  3053. };
  3054. /**
  3055. * Loads the stylesheet for this graph.
  3056. */
  3057. EditorUi.prototype.setPageVisible = function (value) {
  3058. var graph = this.editor.graph;
  3059. var hasScrollbars = mxUtils.hasScrollbars(graph.container);
  3060. var tx = 0;
  3061. var ty = 0;
  3062. if (hasScrollbars) {
  3063. tx = graph.view.translate.x * graph.view.scale - graph.container.scrollLeft;
  3064. ty = graph.view.translate.y * graph.view.scale - graph.container.scrollTop;
  3065. }
  3066. graph.pageVisible = value;
  3067. graph.pageBreaksVisible = value;
  3068. graph.preferPageSize = value;
  3069. graph.view.validateBackground();
  3070. // Workaround for possible handle offset
  3071. if (hasScrollbars) {
  3072. var cells = graph.getSelectionCells();
  3073. graph.clearSelection();
  3074. graph.setSelectionCells(cells);
  3075. }
  3076. // Calls updatePageBreaks
  3077. graph.sizeDidChange();
  3078. if (hasScrollbars) {
  3079. graph.container.scrollLeft = graph.view.translate.x * graph.view.scale - tx;
  3080. graph.container.scrollTop = graph.view.translate.y * graph.view.scale - ty;
  3081. }
  3082. graph.defaultPageVisible = value;
  3083. this.fireEvent(new mxEventObject('pageViewChanged'));
  3084. };
  3085. /**
  3086. * Loads the stylesheet for this graph.
  3087. */
  3088. EditorUi.prototype.installResizeHandler = function (dialog, resizable, destroy) {
  3089. if (resizable) {
  3090. dialog.window.setSize = function (w, h) {
  3091. if (!this.minimized) {
  3092. var iw = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
  3093. var ih = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
  3094. w = Math.min(w, iw - this.getX());
  3095. h = Math.min(h, ih - this.getY());
  3096. }
  3097. mxWindow.prototype.setSize.apply(this, arguments);
  3098. };
  3099. }
  3100. dialog.window.setLocation = function (x, y) {
  3101. var iw = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
  3102. var ih = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
  3103. var w = parseInt(this.div.style.width);
  3104. var h = parseInt(this.div.style.height);
  3105. x = Math.max(0, Math.min(x, iw - w));
  3106. y = Math.max(0, Math.min(y, ih - h));
  3107. if (this.getX() != x || this.getY() != y) {
  3108. mxWindow.prototype.setLocation.apply(this, arguments);
  3109. }
  3110. if (resizable && !this.minimized) {
  3111. this.setSize(w, h);
  3112. }
  3113. };
  3114. var resizeListener = mxUtils.bind(this, function () {
  3115. var x = dialog.window.getX();
  3116. var y = dialog.window.getY();
  3117. dialog.window.setLocation(x, y);
  3118. });
  3119. mxEvent.addListener(window, 'resize', resizeListener);
  3120. dialog.destroy = function () {
  3121. mxEvent.removeListener(window, 'resize', resizeListener);
  3122. dialog.window.destroy();
  3123. if (destroy != null) {
  3124. destroy();
  3125. }
  3126. }
  3127. };
  3128. /**
  3129. * Class: ChangeGridColor
  3130. *
  3131. * Undoable change to grid color.
  3132. */
  3133. function ChangeGridColor(ui, color) {
  3134. this.ui = ui;
  3135. this.color = color;
  3136. };
  3137. /**
  3138. * Executes selection of a new page.
  3139. */
  3140. ChangeGridColor.prototype.execute = function () {
  3141. var temp = this.ui.editor.graph.view.gridColor;
  3142. this.ui.setGridColor(this.color);
  3143. this.color = temp;
  3144. };
  3145. // Registers codec for ChangePageSetup
  3146. (function () {
  3147. var codec = new mxObjectCodec(new ChangeGridColor(), ['ui']);
  3148. mxCodecRegistry.register(codec);
  3149. })();
  3150. /**
  3151. * Change types
  3152. */
  3153. function ChangePageSetup(ui, color, image, format, pageScale) {
  3154. this.ui = ui;
  3155. this.color = color;
  3156. this.previousColor = color;
  3157. this.image = image;
  3158. this.previousImage = image;
  3159. this.format = format;
  3160. this.previousFormat = format;
  3161. this.pageScale = pageScale;
  3162. this.previousPageScale = pageScale;
  3163. // Needed since null are valid values for color and image
  3164. this.ignoreColor = false;
  3165. this.ignoreImage = false;
  3166. }
  3167. /**
  3168. * Implementation of the undoable page rename.
  3169. */
  3170. ChangePageSetup.prototype.execute = function () {
  3171. var graph = this.ui.editor.graph;
  3172. if (!this.ignoreColor) {
  3173. this.color = this.previousColor;
  3174. var tmp = graph.background;
  3175. this.ui.setBackgroundColor(this.previousColor);
  3176. this.previousColor = tmp;
  3177. }
  3178. if (!this.ignoreImage) {
  3179. this.image = this.previousImage;
  3180. var tmp = graph.backgroundImage;
  3181. var img = this.previousImage;
  3182. if (img != null && Graph.isPageLink(img.src)) {
  3183. img = this.ui.createImageForPageLink(img.src, this.ui.currentPage);
  3184. }
  3185. this.ui.setBackgroundImage(img);
  3186. this.previousImage = tmp;
  3187. }
  3188. if (this.previousFormat != null) {
  3189. this.format = this.previousFormat;
  3190. var tmp = graph.pageFormat;
  3191. if (this.previousFormat.width != tmp.width ||
  3192. this.previousFormat.height != tmp.height) {
  3193. this.ui.setPageFormat(this.previousFormat);
  3194. this.previousFormat = tmp;
  3195. }
  3196. }
  3197. if (this.foldingEnabled != null && this.foldingEnabled != this.ui.editor.graph.foldingEnabled) {
  3198. this.ui.setFoldingEnabled(this.foldingEnabled);
  3199. this.foldingEnabled = !this.foldingEnabled;
  3200. }
  3201. if (this.previousPageScale != null) {
  3202. var currentPageScale = this.ui.editor.graph.pageScale;
  3203. if (this.previousPageScale != currentPageScale) {
  3204. this.ui.setPageScale(this.previousPageScale);
  3205. this.previousPageScale = currentPageScale;
  3206. }
  3207. }
  3208. };
  3209. // Registers codec for ChangePageSetup
  3210. (function () {
  3211. var codec = new mxObjectCodec(new ChangePageSetup(), ['ui', 'previousColor', 'previousImage', 'previousFormat', 'previousPageScale']);
  3212. codec.afterDecode = function (dec, node, obj) {
  3213. obj.previousColor = obj.color;
  3214. obj.previousImage = obj.image;
  3215. obj.previousFormat = obj.format;
  3216. obj.previousPageScale = obj.pageScale;
  3217. if (obj.foldingEnabled != null) {
  3218. obj.foldingEnabled = !obj.foldingEnabled;
  3219. }
  3220. return obj;
  3221. };
  3222. mxCodecRegistry.register(codec);
  3223. })();
  3224. /**
  3225. * Loads the stylesheet for this graph.
  3226. */
  3227. EditorUi.prototype.setBackgroundColor = function (value) {
  3228. this.editor.graph.background = value;
  3229. this.editor.graph.view.validateBackground();
  3230. this.fireEvent(new mxEventObject('backgroundColorChanged'));
  3231. };
  3232. /**
  3233. * Loads the stylesheet for this graph.
  3234. */
  3235. EditorUi.prototype.setFoldingEnabled = function (value) {
  3236. this.editor.graph.foldingEnabled = value;
  3237. this.editor.graph.view.revalidate();
  3238. this.fireEvent(new mxEventObject('foldingEnabledChanged'));
  3239. };
  3240. /**
  3241. * Loads the stylesheet for this graph.
  3242. */
  3243. EditorUi.prototype.setPageFormat = function (value, ignorePageVisible) {
  3244. ignorePageVisible = (ignorePageVisible != null) ? ignorePageVisible : urlParams['sketch'] == '1';
  3245. this.editor.graph.pageFormat = value;
  3246. if (!ignorePageVisible) {
  3247. if (!this.editor.graph.pageVisible) {
  3248. this.actions.get('pageView').funct();
  3249. }
  3250. else {
  3251. this.editor.graph.view.validateBackground();
  3252. this.editor.graph.sizeDidChange();
  3253. }
  3254. }
  3255. this.fireEvent(new mxEventObject('pageFormatChanged'));
  3256. };
  3257. /**
  3258. * Loads the stylesheet for this graph.
  3259. */
  3260. EditorUi.prototype.setPageScale = function (value) {
  3261. this.editor.graph.pageScale = value;
  3262. if (!this.editor.graph.pageVisible) {
  3263. this.actions.get('pageView').funct();
  3264. }
  3265. else {
  3266. this.editor.graph.view.validateBackground();
  3267. this.editor.graph.sizeDidChange();
  3268. }
  3269. this.fireEvent(new mxEventObject('pageScaleChanged'));
  3270. };
  3271. /**
  3272. * Loads the stylesheet for this graph.
  3273. */
  3274. EditorUi.prototype.setGridColor = function (value) {
  3275. this.editor.graph.view.gridColor = value;
  3276. this.editor.graph.view.validateBackground();
  3277. this.fireEvent(new mxEventObject('gridColorChanged'));
  3278. };
  3279. /**
  3280. * Updates the states of the given undo/redo items.
  3281. */
  3282. EditorUi.prototype.addUndoListener = function () {
  3283. var undoMgr = this.editor.undoManager;
  3284. var undoListener = mxUtils.bind(this, function () {
  3285. this.updateActionStates();
  3286. });
  3287. undoMgr.addListener(mxEvent.ADD, undoListener);
  3288. undoMgr.addListener(mxEvent.UNDO, undoListener);
  3289. undoMgr.addListener(mxEvent.REDO, undoListener);
  3290. undoMgr.addListener(mxEvent.CLEAR, undoListener);
  3291. // Overrides cell editor to update action states
  3292. var cellEditorStartEditing = this.editor.graph.cellEditor.startEditing;
  3293. this.editor.graph.cellEditor.startEditing = function () {
  3294. cellEditorStartEditing.apply(this, arguments);
  3295. undoListener();
  3296. };
  3297. var cellEditorStopEditing = this.editor.graph.cellEditor.stopEditing;
  3298. this.editor.graph.cellEditor.stopEditing = function (cell, trigger) {
  3299. cellEditorStopEditing.apply(this, arguments);
  3300. undoListener();
  3301. };
  3302. // Updates the button states once
  3303. undoListener();
  3304. };
  3305. /**
  3306. * Updates the states of the given toolbar items based on the selection.
  3307. */
  3308. EditorUi.prototype.updateActionStates = function () {
  3309. var graph = this.editor.graph;
  3310. var ss = this.getSelectionState();
  3311. var unlocked = graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent());
  3312. var editable = !this.editor.chromeless || this.editor.editable;
  3313. // Updates action states
  3314. var actions = ['cut', 'copy', 'bold', 'italic', 'underline', 'delete', 'duplicate',
  3315. 'editStyle', 'editTooltip', 'editLink', 'backgroundColor', 'borderColor',
  3316. 'edit', 'toFront', 'toBack', 'solid', 'dashed', 'pasteSize',
  3317. 'dotted', 'fillColor', 'gradientColor', 'shadow', 'fontColor',
  3318. 'formattedText', 'rounded', 'toggleRounded', 'strokeColor',
  3319. 'sharp', 'snapToGrid'];
  3320. for (var i = 0; i < actions.length; i++) {
  3321. this.actions.get(actions[i]).setEnabled(ss.cells.length > 0);
  3322. }
  3323. this.actions.get('grid').setEnabled(editable);
  3324. this.actions.get('undo').setEnabled(this.canUndo() && editable);
  3325. this.actions.get('redo').setEnabled(this.canRedo() && editable);
  3326. this.actions.get('pasteSize').setEnabled(this.copiedSize != null && ss.vertices.length > 0);
  3327. this.actions.get('pasteData').setEnabled(this.copiedValue != null && ss.cells.length > 0);
  3328. this.actions.get('setAsDefaultStyle').setEnabled(graph.getSelectionCount() == 1);
  3329. this.actions.get('lockUnlock').setEnabled(!graph.isSelectionEmpty());
  3330. this.actions.get('bringForward').setEnabled(ss.cells.length == 1);
  3331. this.actions.get('sendBackward').setEnabled(ss.cells.length == 1);
  3332. this.actions.get('rotation').setEnabled(ss.vertices.length == 1);
  3333. this.actions.get('wordWrap').setEnabled(ss.vertices.length == 1);
  3334. this.actions.get('autosize').setEnabled(ss.vertices.length > 0);
  3335. this.actions.get('copySize').setEnabled(ss.vertices.length == 1);
  3336. this.actions.get('clearWaypoints').setEnabled(ss.connections);
  3337. this.actions.get('curved').setEnabled(ss.edges.length > 0);
  3338. this.actions.get('turn').setEnabled(ss.cells.length > 0);
  3339. this.actions.get('group').setEnabled(!ss.row && !ss.cell &&
  3340. (ss.cells.length > 1 || (ss.vertices.length == 1 &&
  3341. graph.model.getChildCount(ss.cells[0]) == 0 &&
  3342. !graph.isContainer(ss.vertices[0]))));
  3343. this.actions.get('ungroup').setEnabled(!ss.row && !ss.cell && !ss.table &&
  3344. ss.vertices.length > 0 && (graph.isContainer(ss.vertices[0]) ||
  3345. graph.getModel().getChildCount(ss.vertices[0]) > 0));
  3346. this.actions.get('removeFromGroup').setEnabled(ss.cells.length == 1 &&
  3347. graph.getModel().isVertex(graph.getModel().getParent(ss.cells[0])));
  3348. this.actions.get('collapsible').setEnabled(ss.vertices.length == 1 &&
  3349. (graph.model.getChildCount(ss.vertices[0]) > 0 ||
  3350. graph.isContainer(ss.vertices[0])));
  3351. this.actions.get('exitGroup').setEnabled(graph.view.currentRoot != null);
  3352. this.actions.get('home').setEnabled(graph.view.currentRoot != null);
  3353. this.actions.get('enterGroup').setEnabled(ss.cells.length == 1 &&
  3354. graph.isValidRoot(ss.cells[0]));
  3355. this.actions.get('copyData').setEnabled(ss.cells.length == 1);
  3356. this.actions.get('editLink').setEnabled(ss.cells.length == 1);
  3357. this.actions.get('editStyle').setEnabled(ss.cells.length == 1);
  3358. this.actions.get('editTooltip').setEnabled(ss.cells.length == 1);
  3359. this.actions.get('openLink').setEnabled(ss.cells.length == 1 &&
  3360. graph.getLinkForCell(ss.cells[0]) != null);
  3361. this.actions.get('guides').setEnabled(graph.isEnabled());
  3362. this.actions.get('selectVertices').setEnabled(unlocked);
  3363. this.actions.get('selectEdges').setEnabled(unlocked);
  3364. this.actions.get('selectAll').setEnabled(unlocked);
  3365. this.actions.get('selectNone').setEnabled(unlocked);
  3366. var foldable = ss.vertices.length == 1 &&
  3367. graph.isCellFoldable(ss.vertices[0]);
  3368. this.actions.get('expand').setEnabled(foldable);
  3369. this.actions.get('collapse').setEnabled(foldable);
  3370. // Updates menu states
  3371. this.menus.get('navigation').setEnabled(ss.cells.length > 0 ||
  3372. graph.view.currentRoot != null);
  3373. this.menus.get('layout').setEnabled(unlocked);
  3374. this.menus.get('insert').setEnabled(unlocked);
  3375. this.menus.get('direction').setEnabled(ss.unlocked &&
  3376. ss.vertices.length == 1);
  3377. this.menus.get('distribute').setEnabled(ss.unlocked &&
  3378. ss.vertices.length > 1);
  3379. this.menus.get('align').setEnabled(ss.unlocked &&
  3380. ss.cells.length > 0);
  3381. this.updatePasteActionStates();
  3382. };
  3383. EditorUi.prototype.zeroOffset = new mxPoint(0, 0);
  3384. EditorUi.prototype.getDiagramContainerOffset = function () {
  3385. return this.zeroOffset;
  3386. };
  3387. /**
  3388. * Refreshes the viewport.
  3389. */
  3390. EditorUi.prototype.refresh = function (sizeDidChange) {
  3391. sizeDidChange = (sizeDidChange != null) ? sizeDidChange : true;
  3392. var w = this.container.clientWidth;
  3393. var h = this.container.clientHeight;
  3394. if (this.container == document.body) {
  3395. w = document.body.clientWidth || document.documentElement.clientWidth;
  3396. h = document.documentElement.clientHeight;
  3397. }
  3398. // Workaround for bug on iOS see
  3399. // http://stackoverflow.com/questions/19012135/ios-7-ipad-safari-landscape-innerheight-outerheight-layout-issue
  3400. // FIXME: Fix if footer visible
  3401. var off = 0;
  3402. if (mxClient.IS_IOS && !window.navigator.standalone && typeof Menus !== 'undefined') {
  3403. if (window.innerHeight != document.documentElement.clientHeight) {
  3404. off = document.documentElement.clientHeight - window.innerHeight;
  3405. window.scrollTo(0, 0);
  3406. }
  3407. }
  3408. var effHsplitPosition = Math.max(0, Math.min(
  3409. this.hsplitPosition, w - this.splitSize - 40));
  3410. var tmp = 0;
  3411. if (this.menubar != null) {
  3412. this.menubarContainer.style.height = this.menubarHeight + 'px';
  3413. tmp += this.menubarHeight;
  3414. }
  3415. if (this.toolbar != null) {
  3416. this.toolbarContainer.style.top = this.menubarHeight + 'px';
  3417. this.toolbarContainer.style.height = this.toolbarHeight + 'px';
  3418. tmp += this.toolbarHeight;
  3419. }
  3420. if (tmp > 0) {
  3421. tmp += 1;
  3422. }
  3423. var fw = (this.format != null) ? this.formatWidth : 0;
  3424. this.sidebarContainer.style.top = tmp + 'px';
  3425. this.sidebarContainer.style.width = effHsplitPosition + 'px';
  3426. this.formatContainer.style.top = tmp + 'px';
  3427. this.formatContainer.style.width = fw + 'px';
  3428. this.formatContainer.style.display = (this.format != null) ? '' : 'none';
  3429. var diagContOffset = this.getDiagramContainerOffset();
  3430. var contLeft = (this.hsplit.parentNode != null) ? (effHsplitPosition) : 0;
  3431. this.footerContainer.style.height = this.footerHeight + 'px';
  3432. this.hsplit.style.top = this.sidebarContainer.style.top;
  3433. this.hsplit.style.left = effHsplitPosition + 'px';
  3434. this.footerContainer.style.display = (this.footerHeight == 0) ? 'none' : '';
  3435. if (this.tabContainer != null) {
  3436. this.tabContainer.style.left = contLeft + 'px';
  3437. this.hsplit.style.bottom = this.tabContainer.offsetHeight + 'px';
  3438. }
  3439. else {
  3440. this.hsplit.style.bottom = (this.footerHeight + off) + 'px';
  3441. }
  3442. if (this.footerHeight > 0) {
  3443. this.footerContainer.style.bottom = off + 'px';
  3444. }
  3445. var th = 0;
  3446. if (this.tabContainer != null) {
  3447. this.tabContainer.style.bottom = (this.footerHeight + off) + 'px';
  3448. this.tabContainer.style.right = fw + 'px';
  3449. th = this.tabContainer.clientHeight;
  3450. this.checkTabScrollerOverflow();
  3451. }
  3452. this.sidebarContainer.style.bottom = (this.footerHeight + off) + 'px';
  3453. this.formatContainer.style.bottom = (this.footerHeight + off) + 'px';
  3454. this.diagramContainer.style.left = (contLeft + diagContOffset.x) + 'px';
  3455. this.diagramContainer.style.top = (tmp + diagContOffset.y) + 'px';
  3456. this.diagramContainer.style.right = fw + 'px';
  3457. this.diagramContainer.style.bottom = (this.footerHeight + off + th) + 'px';
  3458. if (sizeDidChange) {
  3459. this.editor.graph.sizeDidChange();
  3460. }
  3461. };
  3462. /**
  3463. * Creates the required containers.
  3464. */
  3465. EditorUi.prototype.createTabContainer = function () {
  3466. return null;
  3467. };
  3468. /**
  3469. * Creates the required containers.
  3470. */
  3471. EditorUi.prototype.createDivs = function () {
  3472. this.menubarContainer = this.createDiv('geMenubarContainer');
  3473. this.toolbarContainer = this.createDiv('geToolbarContainer');
  3474. this.sidebarContainer = this.createDiv('geSidebarContainer');
  3475. this.formatContainer = this.createDiv('geSidebarContainer geFormatContainer');
  3476. this.diagramContainer = this.createDiv('geDiagramContainer');
  3477. this.footerContainer = this.createDiv('geFooterContainer');
  3478. this.hsplit = this.createDiv('geHsplit');
  3479. // Sets static style for containers
  3480. this.menubarContainer.style.top = '0px';
  3481. this.menubarContainer.style.left = '0px';
  3482. this.menubarContainer.style.right = '0px';
  3483. this.toolbarContainer.style.left = '0px';
  3484. this.toolbarContainer.style.right = '0px';
  3485. this.sidebarContainer.style.left = '0px';
  3486. this.sidebarContainer.style.zIndex = '1';
  3487. this.formatContainer.style.right = '0px';
  3488. this.formatContainer.style.zIndex = '1';
  3489. this.diagramContainer.style.right = ((this.format != null) ? this.formatWidth : 0) + 'px';
  3490. this.footerContainer.style.left = '0px';
  3491. this.footerContainer.style.right = '0px';
  3492. this.footerContainer.style.bottom = '0px';
  3493. this.footerContainer.style.zIndex = mxPopupMenu.prototype.zIndex - 3;
  3494. this.hsplit.style.width = this.splitSize + 'px';
  3495. this.hsplit.style.zIndex = '1';
  3496. if (!this.editor.chromeless) {
  3497. this.tabContainer = this.createTabContainer();
  3498. }
  3499. else {
  3500. this.diagramContainer.style.border = 'none';
  3501. }
  3502. };
  3503. /**
  3504. * Hook for sidebar footer container. This implementation returns null.
  3505. */
  3506. EditorUi.prototype.createSidebarContainer = function () {
  3507. var div = document.createElement('div');
  3508. div.className = 'geSidebarContainer';
  3509. return div;
  3510. };
  3511. /**
  3512. * Creates the required containers.
  3513. */
  3514. EditorUi.prototype.createUi = function () {
  3515. // Creates menubar
  3516. this.menubar = (this.editor.chromeless) ? null : this.menus.createMenubar(this.createDiv('geMenubar'));
  3517. if (this.menubar != null) {
  3518. this.menubarContainer.appendChild(this.menubar.container);
  3519. }
  3520. // Adds status bar in menubar
  3521. if (this.menubar != null) {
  3522. this.statusContainer = this.createStatusContainer();
  3523. // Connects the status bar to the editor status
  3524. this.editor.addListener('statusChanged', mxUtils.bind(this, function () {
  3525. this.setStatusText(this.editor.getStatus());
  3526. }));
  3527. this.setStatusText(this.editor.getStatus());
  3528. this.menubar.container.appendChild(this.statusContainer);
  3529. // Inserts into DOM
  3530. this.container.appendChild(this.menubarContainer);
  3531. }
  3532. // Creates the sidebar
  3533. this.sidebar = (this.editor.chromeless) ? null : this.createSidebar(this.sidebarContainer);
  3534. if (this.sidebar != null) {
  3535. this.container.appendChild(this.sidebarContainer);
  3536. }
  3537. // Creates the format sidebar
  3538. this.format = (this.editor.chromeless || !this.formatEnabled) ? null : this.createFormat(this.formatContainer);
  3539. if (this.format != null) {
  3540. this.container.appendChild(this.formatContainer);
  3541. }
  3542. // Creates the footer
  3543. var footer = (this.editor.chromeless) ? null : this.createFooter();
  3544. if (footer != null) {
  3545. this.footerContainer.appendChild(footer);
  3546. this.container.appendChild(this.footerContainer);
  3547. }
  3548. this.container.appendChild(this.diagramContainer);
  3549. if (this.container != null && this.tabContainer != null) {
  3550. this.container.appendChild(this.tabContainer);
  3551. }
  3552. // Creates toolbar
  3553. this.toolbar = (this.editor.chromeless) ? null : this.createToolbar(this.createDiv('geToolbar'));
  3554. if (this.toolbar != null) {
  3555. this.toolbarContainer.appendChild(this.toolbar.container);
  3556. this.container.appendChild(this.toolbarContainer);
  3557. }
  3558. // HSplit
  3559. if (this.sidebar != null) {
  3560. this.container.appendChild(this.hsplit);
  3561. this.addSplitHandler(this.hsplit, true, 0, mxUtils.bind(this, function (value) {
  3562. this.hsplitPosition = value;
  3563. this.refresh();
  3564. }));
  3565. }
  3566. };
  3567. /**
  3568. * Creates a new toolbar for the given container.
  3569. */
  3570. EditorUi.prototype.createStatusContainer = function () {
  3571. var container = document.createElement('a');
  3572. container.className = 'geItem geStatus';
  3573. // Handles data-action attribute
  3574. mxEvent.addListener(container, 'click', mxUtils.bind(this, function (evt) {
  3575. var elt = mxEvent.getSource(evt);
  3576. if (elt.nodeName != 'A') {
  3577. var name = elt.getAttribute('data-action');
  3578. // Make generic
  3579. if (name == 'statusFunction' && this.editor.statusFunction != null) {
  3580. this.editor.statusFunction();
  3581. }
  3582. else if (name != null) {
  3583. var action = this.actions.get(name);
  3584. if (action != null) {
  3585. action.funct();
  3586. }
  3587. }
  3588. else {
  3589. var title = elt.getAttribute('data-title');
  3590. var msg = elt.getAttribute('data-message');
  3591. if (title != null && msg != null) {
  3592. this.showError(title, msg);
  3593. }
  3594. else {
  3595. var link = elt.getAttribute('data-link');
  3596. if (link != null) {
  3597. this.editor.graph.openLink(link);
  3598. }
  3599. }
  3600. }
  3601. mxEvent.consume(evt);
  3602. }
  3603. }));
  3604. return container;
  3605. };
  3606. /**
  3607. * Creates a new toolbar for the given container.
  3608. */
  3609. EditorUi.prototype.setStatusText = function (value) {
  3610. this.statusContainer.innerHTML = Graph.sanitizeHtml(value);
  3611. // Wraps simple status messages in a div for styling
  3612. if (this.statusContainer.getElementsByTagName('div').length == 0 &&
  3613. value != null && value.length > 0) {
  3614. this.statusContainer.innerText = '';
  3615. var div = this.createStatusDiv(value);
  3616. this.statusContainer.appendChild(div);
  3617. }
  3618. // Handles data-effect attribute
  3619. var spans = this.statusContainer.querySelectorAll('[data-effect="fade"]');
  3620. if (spans != null) {
  3621. for (var i = 0; i < spans.length; i++) {
  3622. (function (temp) {
  3623. mxUtils.setOpacity(temp, 0);
  3624. mxUtils.setPrefixedStyle(temp.style, 'transform', 'scaleX(0)');
  3625. mxUtils.setPrefixedStyle(temp.style, 'transition', 'all 0.2s ease');
  3626. window.setTimeout(mxUtils.bind(this, function () {
  3627. mxUtils.setOpacity(temp, 100);
  3628. mxUtils.setPrefixedStyle(temp.style, 'transform', 'scaleX(1)');
  3629. mxUtils.setPrefixedStyle(temp.style, 'transition', 'all 1s ease');
  3630. window.setTimeout(mxUtils.bind(this, function () {
  3631. mxUtils.setPrefixedStyle(temp.style, 'transform', 'scaleX(0)');
  3632. mxUtils.setOpacity(temp, 0);
  3633. window.setTimeout(mxUtils.bind(this, function () {
  3634. if (temp.parentNode != null) {
  3635. temp.parentNode.removeChild(temp);
  3636. }
  3637. }), 1000);
  3638. }), Editor.updateStatusInterval / 2);
  3639. }), 0);
  3640. })(spans[i]);
  3641. }
  3642. }
  3643. };
  3644. /**
  3645. * Creates a new toolbar for the given container.
  3646. */
  3647. EditorUi.prototype.createStatusDiv = function (value) {
  3648. var div = document.createElement('div');
  3649. div.style.textOverflow = 'ellipsis';
  3650. div.style.display = 'inline-block';
  3651. div.style.whiteSpace = 'nowrap';
  3652. div.style.overflow = 'hidden';
  3653. div.style.minWidth = '0';
  3654. div.setAttribute('title', value);
  3655. div.innerHTML = Graph.sanitizeHtml(value);
  3656. return div;
  3657. };
  3658. /**
  3659. * Creates a new toolbar for the given container.
  3660. */
  3661. EditorUi.prototype.createToolbar = function (container) {
  3662. return new Toolbar(this, container);
  3663. };
  3664. /**
  3665. * Creates a new sidebar for the given container.
  3666. */
  3667. EditorUi.prototype.createSidebar = function (container) {
  3668. return new Sidebar(this, container);
  3669. };
  3670. /**
  3671. * Creates a new sidebar for the given container.
  3672. */
  3673. EditorUi.prototype.createFormat = function (container) {
  3674. return new Format(this, container);
  3675. };
  3676. /**
  3677. * Creates and returns a new footer.
  3678. */
  3679. EditorUi.prototype.createFooter = function () {
  3680. return this.createDiv('geFooter');
  3681. };
  3682. /**
  3683. * Creates the actual toolbar for the toolbar container.
  3684. */
  3685. EditorUi.prototype.createDiv = function (classname) {
  3686. var elt = document.createElement('div');
  3687. elt.className = classname;
  3688. return elt;
  3689. };
  3690. /**
  3691. * Updates the states of the given undo/redo items.
  3692. */
  3693. EditorUi.prototype.addSplitHandler = function (elt, horizontal, dx, onChange) {
  3694. var start = null;
  3695. var initial = null;
  3696. var ignoreClick = true;
  3697. var last = null;
  3698. // Disables built-in pan and zoom in IE10 and later
  3699. if (mxClient.IS_POINTER) {
  3700. elt.style.touchAction = 'none';
  3701. }
  3702. var getValue = mxUtils.bind(this, function () {
  3703. var result = parseInt(((horizontal) ? elt.style.left : elt.style.bottom));
  3704. // Takes into account hidden footer
  3705. if (!horizontal) {
  3706. result = result + dx - this.footerHeight;
  3707. }
  3708. return result;
  3709. });
  3710. function moveHandler(evt) {
  3711. if (start != null) {
  3712. var pt = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  3713. onChange(Math.max(0, initial + ((horizontal) ? (pt.x - start.x) : (start.y - pt.y)) - dx));
  3714. mxEvent.consume(evt);
  3715. if (initial != getValue()) {
  3716. ignoreClick = true;
  3717. last = null;
  3718. }
  3719. }
  3720. };
  3721. function dropHandler(evt) {
  3722. moveHandler(evt);
  3723. initial = null;
  3724. start = null;
  3725. };
  3726. mxEvent.addGestureListeners(elt, function (evt) {
  3727. start = new mxPoint(mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  3728. initial = getValue();
  3729. ignoreClick = false;
  3730. mxEvent.consume(evt);
  3731. });
  3732. mxEvent.addListener(elt, 'click', mxUtils.bind(this, function (evt) {
  3733. if (!ignoreClick && this.hsplitClickEnabled) {
  3734. var next = (last != null) ? last - dx : 0;
  3735. last = getValue();
  3736. onChange(next);
  3737. mxEvent.consume(evt);
  3738. }
  3739. }));
  3740. mxEvent.addGestureListeners(document, null, moveHandler, dropHandler);
  3741. this.destroyFunctions.push(function () {
  3742. mxEvent.removeGestureListeners(document, null, moveHandler, dropHandler);
  3743. });
  3744. };
  3745. /**
  3746. * Translates this point by the given vector.
  3747. *
  3748. * @param {number} dx X-coordinate of the translation.
  3749. * @param {number} dy Y-coordinate of the translation.
  3750. */
  3751. EditorUi.prototype.prompt = function (title, defaultValue, fn) {
  3752. var dlg = new FilenameDialog(this, defaultValue, mxResources.get('apply'), function (newValue) {
  3753. fn(parseFloat(newValue));
  3754. }, title);
  3755. this.showDialog(dlg.container, 300, 80, true, true);
  3756. dlg.init();
  3757. };
  3758. /**
  3759. * Translates this point by the given vector.
  3760. *
  3761. * @param {number} dx X-coordinate of the translation.
  3762. * @param {number} dy Y-coordinate of the translation.
  3763. */
  3764. EditorUi.prototype.handleError = function (resp, title, fn, invokeFnOnClose, notFoundMessage) {
  3765. var e = (resp != null && resp.error != null) ? resp.error : resp;
  3766. if (e != null || title != null) {
  3767. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  3768. var btn = mxResources.get('ok');
  3769. title = (title != null) ? title : mxResources.get('error');
  3770. if (e != null && e.message != null) {
  3771. msg = mxUtils.htmlEntities(e.message);
  3772. }
  3773. this.showError(title, msg, btn, fn, null, null, null, null, null,
  3774. null, null, null, (invokeFnOnClose) ? fn : null);
  3775. }
  3776. else if (fn != null) {
  3777. fn();
  3778. }
  3779. };
  3780. /**
  3781. * Translates this point by the given vector.
  3782. *
  3783. * @param {number} dx X-coordinate of the translation.
  3784. * @param {number} dy Y-coordinate of the translation.
  3785. */
  3786. EditorUi.prototype.showError = function (title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose) {
  3787. var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
  3788. fn, retry, btn2, fn2, hide, btn3, fn3);
  3789. var lines = Math.ceil((msg != null) ? msg.length / 50 : 1);
  3790. this.showDialog(dlg.container, w || 340, h || (100 + lines * 20), true, false, onClose);
  3791. dlg.init();
  3792. };
  3793. /**
  3794. * Displays a print dialog.
  3795. */
  3796. EditorUi.prototype.showDialog = function (elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick) {
  3797. this.editor.graph.tooltipHandler.resetTimer();
  3798. this.editor.graph.tooltipHandler.hideTooltip();
  3799. if (this.dialogs == null) {
  3800. this.dialogs = [];
  3801. }
  3802. this.dialog = new Dialog(this, elt, w, h, modal, closable, onClose, noScroll, transparent, onResize, ignoreBgClick);
  3803. this.dialogs.push(this.dialog);
  3804. };
  3805. /**
  3806. * Displays a print dialog.
  3807. */
  3808. EditorUi.prototype.hideDialog = function (cancel, isEsc, matchContainer) {
  3809. if (this.dialogs != null && this.dialogs.length > 0) {
  3810. if (matchContainer != null && matchContainer != this.dialog.container.firstChild) {
  3811. return;
  3812. }
  3813. var dlg = this.dialogs.pop();
  3814. if (dlg.close(cancel, isEsc) == false) {
  3815. //add the dialog back if dialog closing is cancelled
  3816. this.dialogs.push(dlg);
  3817. return;
  3818. }
  3819. this.dialog = (this.dialogs.length > 0) ? this.dialogs[this.dialogs.length - 1] : null;
  3820. this.editor.fireEvent(new mxEventObject('hideDialog'));
  3821. if (this.dialog == null && this.editor.graph.container != null &&
  3822. this.editor.graph.container.style.visibility != 'hidden') {
  3823. window.setTimeout(mxUtils.bind(this, function () {
  3824. if (this.editor != null && (this.dialogs == null || this.dialogs.length == 0)) {
  3825. if (this.editor.graph.isEditing() && this.editor.graph.cellEditor.textarea != null) {
  3826. this.editor.graph.cellEditor.textarea.focus();
  3827. }
  3828. else {
  3829. mxUtils.clearSelection();
  3830. this.editor.graph.container.focus();
  3831. }
  3832. }
  3833. }), 0);
  3834. }
  3835. }
  3836. };
  3837. /**
  3838. * Handles ctrl+enter keystroke to clone cells.
  3839. */
  3840. EditorUi.prototype.ctrlEnter = function () {
  3841. var graph = this.editor.graph;
  3842. if (graph.isEnabled()) {
  3843. try {
  3844. var cells = graph.getSelectionCells();
  3845. var lookup = new mxDictionary();
  3846. var newCells = [];
  3847. for (var i = 0; i < cells.length; i++) {
  3848. // Clones table rows instead of cells
  3849. var cell = (graph.isTableCell(cells[i])) ? graph.model.getParent(cells[i]) : cells[i];
  3850. if (cell != null && !lookup.get(cell)) {
  3851. lookup.put(cell, true);
  3852. newCells.push(cell);
  3853. }
  3854. }
  3855. graph.setSelectionCells(graph.duplicateCells(newCells, false));
  3856. }
  3857. catch (e) {
  3858. this.handleError(e);
  3859. }
  3860. }
  3861. };
  3862. /**
  3863. * Display a color dialog.
  3864. */
  3865. EditorUi.prototype.pickColor = function (color, apply) {
  3866. var graph = this.editor.graph;
  3867. var selState = graph.cellEditor.saveSelection();
  3868. var h = 230 + ((Math.ceil(ColorDialog.prototype.presetColors.length / 12) +
  3869. Math.ceil(ColorDialog.prototype.defaultColors.length / 12)) * 17);
  3870. var dlg = new ColorDialog(this, mxUtils.rgba2hex(color) || 'none', function (color) {
  3871. graph.cellEditor.restoreSelection(selState);
  3872. apply(color);
  3873. }, function () {
  3874. graph.cellEditor.restoreSelection(selState);
  3875. });
  3876. this.showDialog(dlg.container, 230, h, true, false);
  3877. dlg.init();
  3878. };
  3879. /**
  3880. * Adds the label menu items to the given menu and parent.
  3881. */
  3882. EditorUi.prototype.openFile = function () {
  3883. // Closes dialog after open
  3884. window.openFile = new OpenFile(mxUtils.bind(this, function (cancel) {
  3885. this.hideDialog(cancel);
  3886. }));
  3887. // Removes openFile if dialog is closed
  3888. this.showDialog(new OpenDialog(this).container, (Editor.useLocalStorage) ? 640 : 320,
  3889. (Editor.useLocalStorage) ? 480 : 220, true, true, function () {
  3890. window.openFile = null;
  3891. });
  3892. };
  3893. /**
  3894. * Extracs the graph model from the given HTML data from a data transfer event.
  3895. */
  3896. EditorUi.prototype.extractGraphModelFromHtml = function (data) {
  3897. var result = null;
  3898. try {
  3899. var idx = data.indexOf('&lt;mxGraphModel ');
  3900. if (idx >= 0) {
  3901. var idx2 = data.lastIndexOf('&lt;/mxGraphModel&gt;');
  3902. if (idx2 > idx) {
  3903. result = data.substring(idx, idx2 + 21).replace(/&gt;/g, '>').
  3904. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  3905. }
  3906. }
  3907. }
  3908. catch (e) {
  3909. // ignore
  3910. }
  3911. return result;
  3912. };
  3913. /**
  3914. * Opens the given files in the editor.
  3915. */
  3916. EditorUi.prototype.readGraphModelFromClipboard = function (fn) {
  3917. this.readGraphModelFromClipboardWithType(mxUtils.bind(this, function (xml) {
  3918. if (xml != null) {
  3919. fn(xml);
  3920. }
  3921. else {
  3922. this.readGraphModelFromClipboardWithType(mxUtils.bind(this, function (xml) {
  3923. if (xml != null) {
  3924. var tmp = decodeURIComponent(xml);
  3925. if (this.isCompatibleString(tmp)) {
  3926. xml = tmp;
  3927. }
  3928. }
  3929. fn(xml);
  3930. }), 'text');
  3931. }
  3932. }), 'html');
  3933. };
  3934. /**
  3935. * Opens the given files in the editor.
  3936. */
  3937. EditorUi.prototype.readGraphModelFromClipboardWithType = function (fn, type) {
  3938. navigator.clipboard.read().then(mxUtils.bind(this, function (data) {
  3939. if (data != null && data.length > 0 && type == 'html' &&
  3940. mxUtils.indexOf(data[0].types, 'text/html') >= 0) {
  3941. data[0].getType('text/html').then(mxUtils.bind(this, function (blob) {
  3942. blob.text().then(mxUtils.bind(this, function (value) {
  3943. try {
  3944. var elt = this.parseHtmlData(value);
  3945. var asHtml = elt.getAttribute('data-type') != 'text/plain';
  3946. // KNOWN: Paste from IE11 to other browsers on Windows
  3947. // seems to paste the contents of index.html
  3948. var xml = (asHtml) ? elt.innerHTML :
  3949. mxUtils.trim((elt.innerText == null) ?
  3950. mxUtils.getTextContent(elt) : elt.innerText);
  3951. // Workaround for junk after XML in VM
  3952. try {
  3953. var idx = xml.lastIndexOf('%3E');
  3954. if (idx >= 0 && idx < xml.length - 3) {
  3955. xml = xml.substring(0, idx + 3);
  3956. }
  3957. }
  3958. catch (e) {
  3959. // ignore
  3960. }
  3961. // Checks for embedded XML content
  3962. try {
  3963. var spans = elt.getElementsByTagName('span');
  3964. var tmp = (spans != null && spans.length > 0) ?
  3965. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  3966. decodeURIComponent(xml);
  3967. if (this.isCompatibleString(tmp)) {
  3968. xml = tmp;
  3969. }
  3970. }
  3971. catch (e) {
  3972. // ignore
  3973. }
  3974. }
  3975. catch (e) {
  3976. // ignore
  3977. }
  3978. fn(this.isCompatibleString(xml) ? xml : null);
  3979. }))['catch'](function (data) {
  3980. fn(null);
  3981. });
  3982. }))['catch'](function (data) {
  3983. fn(null);
  3984. });
  3985. }
  3986. else if (data != null && data.length > 0 && type == 'text' &&
  3987. mxUtils.indexOf(data[0].types, 'text/plain') >= 0) {
  3988. data[0].getType('text/plain').then(function (blob) {
  3989. blob.text().then(function (value) {
  3990. fn(value);
  3991. })['catch'](function () {
  3992. fn(null);
  3993. });
  3994. })['catch'](function () {
  3995. fn(null);
  3996. });
  3997. }
  3998. else {
  3999. fn(null);
  4000. }
  4001. }))['catch'](function (data) {
  4002. fn(null);
  4003. });
  4004. };
  4005. /**
  4006. * Parses the given HTML data and returns a DIV.
  4007. */
  4008. EditorUi.prototype.parseHtmlData = function (data) {
  4009. var elt = null;
  4010. if (data != null && data.length > 0) {
  4011. var hasMeta = data.substring(0, 6) == '<meta ';
  4012. elt = document.createElement('div');
  4013. elt.innerHTML = ((hasMeta) ? '<meta charset="utf-8">' : '') +
  4014. Graph.sanitizeHtml(data);
  4015. asHtml = true;
  4016. // Workaround for innerText not ignoring style elements in Chrome
  4017. var styles = elt.getElementsByTagName('style');
  4018. if (styles != null) {
  4019. while (styles.length > 0) {
  4020. styles[0].parentNode.removeChild(styles[0]);
  4021. }
  4022. }
  4023. // Special case of link pasting from Chrome
  4024. if (elt.firstChild != null && elt.firstChild.nodeType == mxConstants.NODETYPE_ELEMENT &&
  4025. elt.firstChild.nextSibling != null && elt.firstChild.nextSibling.nodeType == mxConstants.NODETYPE_ELEMENT &&
  4026. elt.firstChild.nodeName == 'META' && elt.firstChild.nextSibling.nodeName == 'A' &&
  4027. elt.firstChild.nextSibling.nextSibling == null) {
  4028. var temp = (elt.firstChild.nextSibling.innerText == null) ?
  4029. mxUtils.getTextContent(elt.firstChild.nextSibling) :
  4030. elt.firstChild.nextSibling.innerText;
  4031. if (temp == elt.firstChild.nextSibling.getAttribute('href')) {
  4032. mxUtils.setTextContent(elt, temp);
  4033. asHtml = false;
  4034. }
  4035. }
  4036. // Extracts single image source address with meta tag in markup
  4037. var img = (hasMeta && elt.firstChild != null) ? elt.firstChild.nextSibling : elt.firstChild;
  4038. if (img != null && img.nextSibling == null &&
  4039. img.nodeType == mxConstants.NODETYPE_ELEMENT &&
  4040. img.nodeName == 'IMG') {
  4041. var temp = img.getAttribute('src');
  4042. if (temp != null) {
  4043. if (Editor.isPngDataUrl(temp)) {
  4044. var xml = Editor.extractGraphModelFromPng(temp);
  4045. if (xml != null && xml.length > 0) {
  4046. temp = xml;
  4047. }
  4048. }
  4049. mxUtils.setTextContent(elt, temp);
  4050. asHtml = false;
  4051. }
  4052. }
  4053. else {
  4054. // Extracts embedded XML or image source address from single PNG image
  4055. var images = elt.getElementsByTagName('img');
  4056. if (images.length == 1) {
  4057. var img = images[0];
  4058. var temp = img.getAttribute('src');
  4059. if (temp != null && img.parentNode == elt && elt.children.length == 1) {
  4060. if (Editor.isPngDataUrl(temp)) {
  4061. var xml = Editor.extractGraphModelFromPng(temp);
  4062. if (xml != null && xml.length > 0) {
  4063. temp = xml;
  4064. }
  4065. }
  4066. mxUtils.setTextContent(elt, temp);
  4067. asHtml = false;
  4068. }
  4069. }
  4070. }
  4071. if (asHtml) {
  4072. Graph.removePasteFormatting(elt);
  4073. }
  4074. }
  4075. if (!asHtml) {
  4076. elt.setAttribute('data-type', 'text/plain');
  4077. }
  4078. return elt;
  4079. };
  4080. /**
  4081. * Opens the given files in the editor.
  4082. */
  4083. EditorUi.prototype.extractGraphModelFromEvent = function (evt) {
  4084. var result = null;
  4085. var data = null;
  4086. if (evt != null) {
  4087. var provider = (evt.dataTransfer != null) ?
  4088. evt.dataTransfer : evt.clipboardData;
  4089. if (provider != null) {
  4090. if (document.documentMode == 10 || document.documentMode == 11) {
  4091. data = provider.getData('Text');
  4092. }
  4093. else {
  4094. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ?
  4095. provider.getData('text/html') : null;
  4096. if (mxUtils.indexOf(provider.types, 'text/plain') >= 0 &&
  4097. (data == null || data.length == 0)) {
  4098. data = provider.getData('text/plain');
  4099. }
  4100. }
  4101. if (data != null) {
  4102. data = Graph.zapGremlins(mxUtils.trim(data));
  4103. // Tries parsing as HTML document with embedded XML
  4104. var xml = this.extractGraphModelFromHtml(data);
  4105. if (xml != null) {
  4106. data = xml;
  4107. }
  4108. }
  4109. }
  4110. }
  4111. if (data != null && this.isCompatibleString(data)) {
  4112. result = data;
  4113. }
  4114. return result;
  4115. };
  4116. /**
  4117. * Hook for subclassers to return true if event data is a supported format.
  4118. * This implementation always returns false.
  4119. */
  4120. EditorUi.prototype.isCompatibleString = function (data) {
  4121. return false;
  4122. };
  4123. /**
  4124. * Adds the label menu items to the given menu and parent.
  4125. */
  4126. EditorUi.prototype.saveFile = function (forceDialog) {
  4127. if (!forceDialog && this.editor.filename != null) {
  4128. this.save(this.editor.getOrCreateFilename());
  4129. }
  4130. else {
  4131. var dlg = new FilenameDialog(this, this.editor.getOrCreateFilename(), mxResources.get('save'), mxUtils.bind(this, function (name) {
  4132. this.save(name);
  4133. }), null, mxUtils.bind(this, function (name) {
  4134. if (name != null && name.length > 0) {
  4135. return true;
  4136. }
  4137. mxUtils.confirm(mxResources.get('invalidName'));
  4138. return false;
  4139. }));
  4140. this.showDialog(dlg.container, 300, 100, true, true);
  4141. dlg.init();
  4142. }
  4143. };
  4144. /**
  4145. * Saves the current graph under the given filename.
  4146. */
  4147. EditorUi.prototype.save = function (name) {
  4148. if (name != null) {
  4149. if (this.editor.graph.isEditing()) {
  4150. this.editor.graph.stopEditing();
  4151. }
  4152. var xml = mxUtils.getXml(this.editor.getGraphXml());
  4153. try {
  4154. if (Editor.useLocalStorage) {
  4155. if (localStorage.getItem(name) != null &&
  4156. !mxUtils.confirm(mxResources.get('replaceIt', [name]))) {
  4157. return;
  4158. }
  4159. localStorage.setItem(name, xml);
  4160. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get('saved')) + ' ' + new Date());
  4161. }
  4162. else {
  4163. if (xml.length < MAX_REQUEST_SIZE) {
  4164. new mxXmlRequest(SAVE_URL, 'filename=' + encodeURIComponent(name) +
  4165. '&xml=' + encodeURIComponent(xml)).simulate(document, '_blank');
  4166. }
  4167. else {
  4168. mxUtils.alert(mxResources.get('drawingTooLarge'));
  4169. mxUtils.popup(xml);
  4170. return;
  4171. }
  4172. }
  4173. this.editor.setModified(false);
  4174. this.editor.setFilename(name);
  4175. this.updateDocumentTitle();
  4176. }
  4177. catch (e) {
  4178. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get('errorSavingFile')));
  4179. }
  4180. }
  4181. };
  4182. /**
  4183. * Executes the given array of graph layouts using executeLayout and
  4184. * calls done after the last layout has finished.
  4185. */
  4186. EditorUi.prototype.executeLayouts = function (layouts, post) {
  4187. this.executeLayout(mxUtils.bind(this, function () {
  4188. var layout = new mxCompositeLayout(this.editor.graph, layouts);
  4189. var cells = this.editor.graph.getSelectionCells();
  4190. layout.execute(this.editor.graph.getDefaultParent(),
  4191. cells.length == 0 ? null : cells);
  4192. }), true, post);
  4193. };
  4194. /**
  4195. * Executes the given layout.
  4196. */
  4197. EditorUi.prototype.executeLayout = function (exec, animate, post) {
  4198. var graph = this.editor.graph;
  4199. graph.getModel().beginUpdate();
  4200. try {
  4201. exec();
  4202. }
  4203. catch (e) {
  4204. throw e;
  4205. }
  4206. finally {
  4207. // Animates the changes in the graph model
  4208. if (this.allowAnimation && animate && graph.isEnabled()) {
  4209. // New API for animating graph layout results asynchronously
  4210. var morph = new mxMorphing(graph);
  4211. morph.addListener(mxEvent.DONE, mxUtils.bind(this, function () {
  4212. graph.getModel().endUpdate();
  4213. if (post != null) {
  4214. post();
  4215. }
  4216. }));
  4217. morph.startAnimation();
  4218. }
  4219. else {
  4220. graph.getModel().endUpdate();
  4221. if (post != null) {
  4222. post();
  4223. }
  4224. }
  4225. }
  4226. };
  4227. /**
  4228. * Hides the current menu.
  4229. */
  4230. EditorUi.prototype.showImageDialog = function (title, value, fn, ignoreExisting) {
  4231. var cellEditor = this.editor.graph.cellEditor;
  4232. var selState = cellEditor.saveSelection();
  4233. var newValue = mxUtils.prompt(title, value);
  4234. cellEditor.restoreSelection(selState);
  4235. if (newValue != null && newValue.length > 0) {
  4236. var img = new Image();
  4237. img.onload = function () {
  4238. fn(newValue, img.width, img.height);
  4239. };
  4240. img.onerror = function () {
  4241. fn(null);
  4242. mxUtils.alert(mxResources.get('fileNotFound'));
  4243. };
  4244. img.src = newValue;
  4245. }
  4246. else {
  4247. fn(null);
  4248. }
  4249. };
  4250. /**
  4251. * Hides the current menu.
  4252. */
  4253. EditorUi.prototype.showLinkDialog = function (value, btnLabel, fn) {
  4254. var dlg = new LinkDialog(this, value, btnLabel, fn);
  4255. this.showDialog(dlg.container, 420, 90, true, true);
  4256. dlg.init();
  4257. };
  4258. /**
  4259. * Hides the current menu.
  4260. */
  4261. EditorUi.prototype.showDataDialog = function (cell) {
  4262. if (cell != null && typeof window.EditDataDialog !== 'undefined') {
  4263. var dlg = new EditDataDialog(this, cell);
  4264. this.showDialog(dlg.container, 480, 420, true, false, null, false);
  4265. dlg.init();
  4266. }
  4267. };
  4268. /**
  4269. * Hides the current menu.
  4270. */
  4271. EditorUi.prototype.showBackgroundImageDialog = function (apply, img) {
  4272. apply = (apply != null) ? apply : mxUtils.bind(this, function (image) {
  4273. var change = new ChangePageSetup(this, null, image);
  4274. change.ignoreColor = true;
  4275. this.editor.graph.model.execute(change);
  4276. });
  4277. var newValue = mxUtils.prompt(mxResources.get('backgroundImage'), (img != null) ? img.src : '');
  4278. if (newValue != null && newValue.length > 0) {
  4279. var img = new Image();
  4280. img.onload = function () {
  4281. apply(new mxImage(newValue, img.width, img.height), false);
  4282. };
  4283. img.onerror = function () {
  4284. apply(null, true);
  4285. mxUtils.alert(mxResources.get('fileNotFound'));
  4286. };
  4287. img.src = newValue;
  4288. }
  4289. else {
  4290. apply(null);
  4291. }
  4292. };
  4293. /**
  4294. * Loads the stylesheet for this graph.
  4295. */
  4296. EditorUi.prototype.setBackgroundImage = function (image) {
  4297. this.editor.graph.setBackgroundImage(image);
  4298. this.editor.graph.view.validateBackgroundImage();
  4299. this.fireEvent(new mxEventObject('backgroundImageChanged'));
  4300. };
  4301. /**
  4302. * Creates the keyboard event handler for the current graph and history.
  4303. */
  4304. EditorUi.prototype.confirm = function (msg, okFn, cancelFn) {
  4305. if (mxUtils.confirm(msg)) {
  4306. if (okFn != null) {
  4307. okFn();
  4308. }
  4309. }
  4310. else if (cancelFn != null) {
  4311. cancelFn();
  4312. }
  4313. };
  4314. /**
  4315. * Creates the keyboard event handler for the current graph and history.
  4316. */
  4317. EditorUi.prototype.createOutline = function (wnd) {
  4318. var outline = new mxOutline(this.editor.graph);
  4319. mxEvent.addListener(window, 'resize', function () {
  4320. outline.update(false);
  4321. });
  4322. return outline;
  4323. };
  4324. // Alt+Shift+Keycode mapping to action
  4325. EditorUi.prototype.altShiftActions = {
  4326. 65: 'connectionArrows', // Alt+Shift+A
  4327. 82: 'clearWaypoints', // Alt+Shift+R
  4328. 76: 'editLink', // Alt+Shift+L
  4329. 79: 'connectionPoints', // Alt+Shift+O
  4330. 81: 'editConnectionPoints', // Alt+Shift+Q
  4331. 84: 'editTooltip', // Alt+Shift+T
  4332. 86: 'pasteSize', // Alt+Shift+V
  4333. 70: 'copySize', // Alt+Shift+F
  4334. 66: 'copyData', // Alt+Shift+B
  4335. 69: 'pasteData' // Alt+Shift+E
  4336. };
  4337. /**
  4338. * Creates the keyboard event handler for the current graph and history.
  4339. */
  4340. EditorUi.prototype.createKeyHandler = function (editor) {
  4341. var editorUi = this;
  4342. var graph = this.editor.graph;
  4343. var keyHandler = new mxKeyHandler(graph);
  4344. var isEventIgnored = keyHandler.isEventIgnored;
  4345. keyHandler.isEventIgnored = function (evt) {
  4346. // Handles undo/redo/ctrl+./,/u via action and allows ctrl+b/i
  4347. // only if editing value is HTML (except for FF and Safari)
  4348. // 66, 73 are keycodes for editing actions like bold, italic
  4349. return !(mxEvent.isShiftDown(evt) && evt.keyCode == 9) &&
  4350. ((!this.isControlDown(evt) || mxEvent.isShiftDown(evt) ||
  4351. (evt.keyCode != 90 && evt.keyCode != 89 && evt.keyCode != 188 &&
  4352. evt.keyCode != 190 && evt.keyCode != 85)) && ((evt.keyCode != 66 && evt.keyCode != 73) ||
  4353. !this.isControlDown(evt) || (this.graph.cellEditor.isContentEditing() &&
  4354. !mxClient.IS_FF && !mxClient.IS_SF)) &&
  4355. ((evt.keyCode != 109 && evt.keyCode != 107) ||
  4356. (!this.isControlDown(evt) && !mxEvent.isShiftDown(evt)) ||
  4357. (!this.graph.cellEditor.isContentEditing() &&
  4358. !mxClient.IS_FF && !mxClient.IS_SF)) &&
  4359. isEventIgnored.apply(this, arguments));
  4360. };
  4361. // Ignores graph enabled state but not chromeless state
  4362. keyHandler.isEnabledForEvent = function (evt) {
  4363. return (!mxEvent.isConsumed(evt) && this.isGraphEvent(evt) && this.isEnabled() &&
  4364. (editorUi.dialogs == null || editorUi.dialogs.length == 0));
  4365. };
  4366. // Routes command-key to control-key on Mac
  4367. keyHandler.isControlDown = function (evt) {
  4368. return mxEvent.isControlDown(evt) || (mxClient.IS_MAC && evt.metaKey);
  4369. };
  4370. var thread = null;
  4371. // Helper function to move cells with the cursor keys
  4372. function nudge(keyCode, stepSize, resize) {
  4373. if (!graph.isSelectionEmpty() && graph.isEnabled()) {
  4374. stepSize = (stepSize != null) ? stepSize : 1;
  4375. var cells = graph.getCompositeParents(graph.getSelectionCells());
  4376. var cell = (cells.length > 0) ? cells[0] : null;
  4377. if (cell != null) {
  4378. if (resize) {
  4379. // Resizes all selected vertices
  4380. graph.getModel().beginUpdate();
  4381. try {
  4382. for (var i = 0; i < cells.length; i++) {
  4383. if (graph.getModel().isVertex(cells[i]) && graph.isCellResizable(cells[i])) {
  4384. var geo = graph.getCellGeometry(cells[i]);
  4385. if (geo != null) {
  4386. geo = geo.clone();
  4387. if (keyCode == 37) {
  4388. geo.width = Math.max(0, geo.width - stepSize);
  4389. }
  4390. else if (keyCode == 38) {
  4391. geo.height = Math.max(0, geo.height - stepSize);
  4392. }
  4393. else if (keyCode == 39) {
  4394. geo.width += stepSize;
  4395. }
  4396. else if (keyCode == 40) {
  4397. geo.height += stepSize;
  4398. }
  4399. graph.getModel().setGeometry(cells[i], geo);
  4400. }
  4401. }
  4402. }
  4403. }
  4404. finally {
  4405. graph.getModel().endUpdate();
  4406. }
  4407. }
  4408. else {
  4409. // Moves vertices up/down in a stack layout
  4410. var parent = graph.model.getParent(cell);
  4411. var scale = graph.getView().scale;
  4412. var layout = null;
  4413. if (graph.getSelectionCount() == 1 && graph.model.isVertex(cell) &&
  4414. graph.layoutManager != null && !graph.isCellLocked(cell)) {
  4415. layout = graph.layoutManager.getLayout(parent);
  4416. }
  4417. if (layout != null && layout.constructor == mxStackLayout) {
  4418. var index = parent.getIndex(cell);
  4419. if (keyCode == 37 || keyCode == 38) {
  4420. graph.model.add(parent, cell, Math.max(0, index - 1));
  4421. }
  4422. else if (keyCode == 39 || keyCode == 40) {
  4423. graph.model.add(parent, cell, Math.min(graph.model.getChildCount(parent), index + 1));
  4424. }
  4425. }
  4426. else {
  4427. var handler = graph.graphHandler;
  4428. if (handler != null) {
  4429. if (handler.first == null) {
  4430. handler.start(cell, 0, 0, graph.getMovableCells(cells));
  4431. }
  4432. if (handler.first != null) {
  4433. var dx = 0;
  4434. var dy = 0;
  4435. if (keyCode == 37) {
  4436. dx = -stepSize;
  4437. }
  4438. else if (keyCode == 38) {
  4439. dy = -stepSize;
  4440. }
  4441. else if (keyCode == 39) {
  4442. dx = stepSize;
  4443. }
  4444. else if (keyCode == 40) {
  4445. dy = stepSize;
  4446. }
  4447. handler.currentDx += dx * scale;
  4448. handler.currentDy += dy * scale;
  4449. handler.checkPreview();
  4450. handler.updatePreview();
  4451. }
  4452. // Groups move steps in undoable change
  4453. if (thread != null) {
  4454. window.clearTimeout(thread);
  4455. }
  4456. thread = window.setTimeout(function () {
  4457. if (handler.first != null) {
  4458. var dx = handler.roundLength(handler.currentDx / scale);
  4459. var dy = handler.roundLength(handler.currentDy / scale);
  4460. handler.moveCells(handler.cells, dx, dy);
  4461. handler.reset();
  4462. }
  4463. }, 400);
  4464. }
  4465. }
  4466. }
  4467. }
  4468. }
  4469. };
  4470. // Overridden to handle special alt+shift+cursor keyboard shortcuts
  4471. var directions = {
  4472. 37: mxConstants.DIRECTION_WEST, 38: mxConstants.DIRECTION_NORTH,
  4473. 39: mxConstants.DIRECTION_EAST, 40: mxConstants.DIRECTION_SOUTH
  4474. };
  4475. var keyHandlerGetFunction = keyHandler.getFunction;
  4476. mxKeyHandler.prototype.getFunction = function (evt) {
  4477. if (graph.isEnabled()) {
  4478. // TODO: Add alt modifier state in core API, here are some specific cases
  4479. if (mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt)) {
  4480. var action = editorUi.actions.get(editorUi.altShiftActions[evt.keyCode]);
  4481. if (action != null) {
  4482. return action.funct;
  4483. }
  4484. }
  4485. if (directions[evt.keyCode] != null && !graph.isSelectionEmpty()) {
  4486. // On macOS, Control+Cursor is used by Expose so allow for Alt+Control to resize
  4487. if (!this.isControlDown(evt) && mxEvent.isShiftDown(evt) && mxEvent.isAltDown(evt)) {
  4488. if (graph.model.isVertex(graph.getSelectionCell())) {
  4489. return function () {
  4490. var cells = graph.connectVertex(graph.getSelectionCell(), directions[evt.keyCode],
  4491. graph.defaultEdgeLength, evt, true);
  4492. if (cells != null && cells.length > 0) {
  4493. if (cells.length == 1 && graph.model.isEdge(cells[0])) {
  4494. graph.setSelectionCell(graph.model.getTerminal(cells[0], false));
  4495. }
  4496. else {
  4497. graph.setSelectionCell(cells[cells.length - 1]);
  4498. }
  4499. graph.scrollCellToVisible(graph.getSelectionCell());
  4500. if (editorUi.hoverIcons != null) {
  4501. editorUi.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  4502. }
  4503. }
  4504. };
  4505. }
  4506. }
  4507. else {
  4508. // Avoids consuming event if no vertex is selected by returning null below
  4509. // Cursor keys move and resize (ctrl) cells
  4510. if (this.isControlDown(evt)) {
  4511. return function () {
  4512. nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null, true);
  4513. };
  4514. }
  4515. else {
  4516. return function () {
  4517. nudge(evt.keyCode, (mxEvent.isShiftDown(evt)) ? graph.gridSize : null);
  4518. };
  4519. }
  4520. }
  4521. }
  4522. }
  4523. return keyHandlerGetFunction.apply(this, arguments);
  4524. };
  4525. // Binds keystrokes to actions
  4526. keyHandler.bindAction = mxUtils.bind(this, function (code, control, key, shift) {
  4527. var action = this.actions.get(key);
  4528. if (action != null) {
  4529. var f = function () {
  4530. if (action.isEnabled()) {
  4531. action.funct.apply(this, arguments);
  4532. }
  4533. };
  4534. if (control) {
  4535. if (shift) {
  4536. keyHandler.bindControlShiftKey(code, f);
  4537. }
  4538. else {
  4539. keyHandler.bindControlKey(code, f);
  4540. }
  4541. }
  4542. else {
  4543. if (shift) {
  4544. keyHandler.bindShiftKey(code, f);
  4545. }
  4546. else {
  4547. keyHandler.bindKey(code, f);
  4548. }
  4549. }
  4550. }
  4551. });
  4552. var ui = this;
  4553. var keyHandlerEscape = keyHandler.escape;
  4554. keyHandler.escape = function (evt) {
  4555. keyHandlerEscape.apply(this, arguments);
  4556. };
  4557. // Ignores enter keystroke. Remove this line if you want the
  4558. // enter keystroke to stop editing. N, W, T are reserved.
  4559. keyHandler.enter = function () { };
  4560. keyHandler.bindControlShiftKey(36, function () { graph.exitGroup(); }); // Ctrl+Shift+Home
  4561. keyHandler.bindControlShiftKey(35, function () { graph.enterGroup(); }); // Ctrl+Shift+End
  4562. keyHandler.bindShiftKey(36, function () { graph.home(); }); // Ctrl+Shift+Home
  4563. keyHandler.bindKey(35, function () { graph.refresh(); }); // End
  4564. keyHandler.bindAction(107, true, 'zoomIn'); // Ctrl+Plus
  4565. keyHandler.bindAction(109, true, 'zoomOut'); // Ctrl+Minus
  4566. keyHandler.bindAction(80, true, 'print'); // Ctrl+P
  4567. if (!this.editor.chromeless || this.editor.editable) {
  4568. keyHandler.bindAction(79, true, 'outline', true); // Ctrl+Shift+O
  4569. keyHandler.bindControlKey(36, function () { if (graph.isEnabled()) { graph.foldCells(true); } }); // Ctrl+Home
  4570. keyHandler.bindControlKey(35, function () { if (graph.isEnabled()) { graph.foldCells(false); } }); // Ctrl+End
  4571. keyHandler.bindControlKey(13, function () { ui.ctrlEnter(); }); // Ctrl+Enter
  4572. keyHandler.bindAction(8, false, 'delete'); // Backspace
  4573. keyHandler.bindAction(8, true, 'deleteAll'); // Ctrl+Backspace
  4574. keyHandler.bindAction(8, false, 'deleteLabels', true); // Shift+Backspace
  4575. keyHandler.bindAction(46, false, 'delete'); // Delete
  4576. keyHandler.bindAction(46, true, 'deleteAll'); // Ctrl+Delete
  4577. keyHandler.bindAction(46, false, 'deleteLabels', true); // Shift+Delete
  4578. keyHandler.bindAction(36, false, 'resetView'); // Home
  4579. keyHandler.bindAction(72, true, 'fitWindow', true); // Ctrl+Shift+H
  4580. keyHandler.bindAction(74, true, 'fitPage'); // Ctrl+J
  4581. keyHandler.bindAction(74, true, 'fitTwoPages', true); // Ctrl+Shift+J
  4582. keyHandler.bindAction(48, true, 'customZoom'); // Ctrl+0
  4583. keyHandler.bindAction(82, true, 'turn'); // Ctrl+R
  4584. keyHandler.bindAction(82, true, 'clearDefaultStyle', true); // Ctrl+Shift+R
  4585. keyHandler.bindAction(83, true, 'save'); // Ctrl+S
  4586. keyHandler.bindAction(83, true, 'saveAs', true); // Ctrl+Shift+S
  4587. keyHandler.bindAction(65, true, 'selectAll'); // Ctrl+A
  4588. keyHandler.bindAction(65, true, 'selectNone', true); // Ctrl+A
  4589. keyHandler.bindAction(73, true, 'selectVertices', true); // Ctrl+Shift+I
  4590. keyHandler.bindAction(69, true, 'selectEdges', true); // Ctrl+Shift+E
  4591. keyHandler.bindAction(69, true, 'editStyle'); // Ctrl+E
  4592. keyHandler.bindAction(66, true, 'bold'); // Ctrl+B
  4593. keyHandler.bindAction(66, true, 'toBack', true); // Ctrl+Shift+B
  4594. keyHandler.bindAction(70, true, 'toFront', true); // Ctrl+Shift+F
  4595. keyHandler.bindAction(68, true, 'duplicate'); // Ctrl+D
  4596. keyHandler.bindAction(68, true, 'setAsDefaultStyle', true); // Ctrl+Shift+D
  4597. keyHandler.bindAction(90, true, 'undo'); // Ctrl+Z
  4598. keyHandler.bindAction(89, true, 'autosize', true); // Ctrl+Shift+Y
  4599. keyHandler.bindAction(88, true, 'cut'); // Ctrl+X
  4600. keyHandler.bindAction(67, true, 'copy'); // Ctrl+C
  4601. keyHandler.bindAction(86, true, 'paste'); // Ctrl+V
  4602. keyHandler.bindAction(71, true, 'group'); // Ctrl+G
  4603. keyHandler.bindAction(77, true, 'editData'); // Ctrl+M
  4604. keyHandler.bindAction(71, true, 'grid', true); // Ctrl+Shift+G
  4605. keyHandler.bindAction(73, true, 'italic'); // Ctrl+I
  4606. keyHandler.bindAction(76, true, 'lockUnlock'); // Ctrl+L
  4607. keyHandler.bindAction(76, true, 'layers', true); // Ctrl+Shift+L
  4608. keyHandler.bindAction(80, true, 'format', true); // Ctrl+Shift+P
  4609. keyHandler.bindAction(85, true, 'underline'); // Ctrl+U
  4610. keyHandler.bindAction(85, true, 'ungroup', true); // Ctrl+Shift+U
  4611. keyHandler.bindAction(109, true, 'decreaseFontSize', true); // Ctrl+Shift+Minus
  4612. keyHandler.bindAction(107, true, 'increaseFontSize', true); // Ctrl+Shift+Plus
  4613. keyHandler.bindAction(219, true, 'decreaseFontSize', true); // Ctrl+{
  4614. keyHandler.bindAction(221, true, 'increaseFontSize', true); // Ctrl+}
  4615. keyHandler.bindAction(190, true, 'superscript'); // Ctrl+.
  4616. keyHandler.bindAction(188, true, 'subscript'); // Ctrl+,
  4617. keyHandler.bindAction(13, false, 'keyPressEnter'); // Enter
  4618. keyHandler.bindKey(113, function () { if (graph.isEnabled()) { graph.startEditingAtCell(); } }); // F2
  4619. }
  4620. if (!mxClient.IS_WIN) {
  4621. keyHandler.bindAction(90, true, 'redo', true); // Ctrl+Shift+Z
  4622. }
  4623. else {
  4624. keyHandler.bindAction(89, true, 'redo'); // Ctrl+Y
  4625. }
  4626. return keyHandler;
  4627. };
  4628. /**
  4629. * Creates the keyboard event handler for the current graph and history.
  4630. */
  4631. EditorUi.prototype.destroy = function () {
  4632. var graph = this.editor.graph;
  4633. if (graph != null && this.selectionStateListener != null) {
  4634. graph.getSelectionModel().removeListener(mxEvent.CHANGE, this.selectionStateListener);
  4635. graph.getModel().removeListener(mxEvent.CHANGE, this.selectionStateListener);
  4636. graph.removeListener(mxEvent.EDITING_STARTED, this.selectionStateListener);
  4637. graph.removeListener(mxEvent.EDITING_STOPPED, this.selectionStateListener);
  4638. graph.getView().removeListener('unitChanged', this.selectionStateListener);
  4639. this.selectionStateListener = null;
  4640. }
  4641. if (this.editor != null) {
  4642. this.editor.destroy();
  4643. this.editor = null;
  4644. }
  4645. if (this.menubar != null) {
  4646. this.menubar.destroy();
  4647. this.menubar = null;
  4648. }
  4649. if (this.toolbar != null) {
  4650. this.toolbar.destroy();
  4651. this.toolbar = null;
  4652. }
  4653. if (this.sidebar != null) {
  4654. this.sidebar.destroy();
  4655. this.sidebar = null;
  4656. }
  4657. if (this.keyHandler != null) {
  4658. this.keyHandler.destroy();
  4659. this.keyHandler = null;
  4660. }
  4661. if (this.keydownHandler != null) {
  4662. mxEvent.removeListener(document, 'keydown', this.keydownHandler);
  4663. this.keydownHandler = null;
  4664. }
  4665. if (this.keyupHandler != null) {
  4666. mxEvent.removeListener(document, 'keyup', this.keyupHandler);
  4667. this.keyupHandler = null;
  4668. }
  4669. if (this.resizeHandler != null) {
  4670. mxEvent.removeListener(window, 'resize', this.resizeHandler);
  4671. this.resizeHandler = null;
  4672. }
  4673. if (this.gestureHandler != null) {
  4674. mxEvent.removeGestureListeners(document, this.gestureHandler);
  4675. this.gestureHandler = null;
  4676. }
  4677. if (this.orientationChangeHandler != null) {
  4678. mxEvent.removeListener(window, 'orientationchange', this.orientationChangeHandler);
  4679. this.orientationChangeHandler = null;
  4680. }
  4681. if (this.scrollHandler != null) {
  4682. mxEvent.removeListener(window, 'scroll', this.scrollHandler);
  4683. this.scrollHandler = null;
  4684. }
  4685. if (this.destroyFunctions != null) {
  4686. for (var i = 0; i < this.destroyFunctions.length; i++) {
  4687. this.destroyFunctions[i]();
  4688. }
  4689. this.destroyFunctions = null;
  4690. }
  4691. var c = [this.menubarContainer, this.toolbarContainer, this.sidebarContainer,
  4692. this.formatContainer, this.diagramContainer, this.footerContainer,
  4693. this.chromelessToolbar, this.hsplit, this.layersDialog];
  4694. for (var i = 0; i < c.length; i++) {
  4695. if (c[i] != null && c[i].parentNode != null) {
  4696. c[i].parentNode.removeChild(c[i]);
  4697. }
  4698. }
  4699. };
  4700. EditorUi.prototype.exportImage = function (scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, format, exportHandler) {
  4701. format = (format != null) ? format : 'png';
  4702. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  4703. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  4704. // Caches images
  4705. if (this.thumbImageCache == null) {
  4706. this.thumbImageCache = new Object();
  4707. }
  4708. try {
  4709. this.exportToCanvas(mxUtils.bind(this, function (canvas) {
  4710. try {
  4711. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  4712. null, null, ignoreSelection) : null, format, exportHandler);
  4713. }
  4714. catch (e) {
  4715. this.handleError(e);
  4716. }
  4717. }), null, this.thumbImageCache, null, mxUtils.bind(this, function (e) {
  4718. this.handleError(e);
  4719. }), null, ignoreSelection, scale || 1, transparentBackground,
  4720. addShadow, null, null, border, noCrop);
  4721. }
  4722. catch (e) {
  4723. this.handleError(e);
  4724. }
  4725. };
  4726. EditorUi.prototype.handleError = function (error) {
  4727. throw error;
  4728. }
  4729. /**
  4730. *
  4731. */
  4732. EditorUi.prototype.exportToCanvas = function (callback, width, imageCache, background, error, limitHeight,
  4733. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop) {
  4734. limitHeight = (limitHeight != null) ? limitHeight : true;
  4735. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  4736. graph = (graph != null) ? graph : this.editor.graph;
  4737. border = (border != null) ? border : 0;
  4738. this.convertImages(graph.getSvg(null, null, null),
  4739. mxUtils.bind(this, function (svgRoot) {
  4740. var img = new Image();
  4741. img.onload = mxUtils.bind(this, function () {
  4742. try {
  4743. var canvas = document.createElement('canvas');
  4744. var w = parseInt(svgRoot.getAttribute('width'));
  4745. var h = parseInt(svgRoot.getAttribute('height'));
  4746. scale = (scale != null) ? scale : 1;
  4747. if (width != null) {
  4748. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  4749. }
  4750. w = Math.ceil(scale * w) + 2 * border;
  4751. h = Math.ceil(scale * h) + 2 * border;
  4752. canvas.setAttribute('width', w);
  4753. canvas.setAttribute('height', h);
  4754. var ctx = canvas.getContext('2d');
  4755. ctx.scale(scale, scale);
  4756. // Workaround for broken data URI images in Safari on first export
  4757. if (mxClient.IS_SF) {
  4758. window.setTimeout(function () {
  4759. ctx.drawImage(img, border / scale, border / scale);
  4760. callback(canvas);
  4761. }, 0);
  4762. }
  4763. else {
  4764. ctx.drawImage(img, border / scale, border / scale);
  4765. callback(canvas);
  4766. }
  4767. }
  4768. catch (e) {
  4769. this.handleError(e);
  4770. }
  4771. });
  4772. img.onerror = function (e) {
  4773. this.handleError(e);
  4774. };
  4775. try {
  4776. if (addShadow) {
  4777. this.editor.graph.addSvgShadow(svgRoot);
  4778. }
  4779. var done = mxUtils.bind(this, function () {
  4780. if (this.editor.resolvedFontCss != null) {
  4781. var st = document.createElement('style');
  4782. st.setAttribute('type', 'text/css');
  4783. st.innerHTML = this.editor.resolvedFontCss;
  4784. // Must be in defs section for FF to work
  4785. var defs = svgRoot.getElementsByTagName('defs');
  4786. defs[0].appendChild(st);
  4787. }
  4788. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  4789. });
  4790. this.loadFonts(done);
  4791. }
  4792. catch (e) {
  4793. //console.log('src', e, img.src);
  4794. this.handleError(e);
  4795. }
  4796. }), imageCache, converter);
  4797. };
  4798. /**
  4799. * Converts all images in the SVG output to data URIs for immediate rendering
  4800. */
  4801. EditorUi.prototype.convertImages = function (svgRoot, callback, imageCache, converter) {
  4802. // Converts images to data URLs for immediate painting
  4803. if (converter == null) {
  4804. converter = this.createImageUrlConverter();
  4805. }
  4806. // Barrier for asynchronous image loading
  4807. var counter = 0;
  4808. function inc() {
  4809. counter++;
  4810. };
  4811. function dec() {
  4812. counter--;
  4813. if (counter == 0) {
  4814. callback(svgRoot);
  4815. }
  4816. };
  4817. var cache = imageCache || new Object();
  4818. var convertImages = mxUtils.bind(this, function (tagName, srcAttr) {
  4819. var images = svgRoot.getElementsByTagName(tagName);
  4820. for (var i = 0; i < images.length; i++) {
  4821. (mxUtils.bind(this, function (img) {
  4822. var src = converter.convert(img.getAttribute(srcAttr));
  4823. console.log(src)
  4824. // Data URIs are pass-through
  4825. if (src != null && src.substring(0, 5) != 'data:') {
  4826. var tmp = cache[src];
  4827. if (tmp == null) {
  4828. inc();
  4829. this.convertImageToDataUri(src, function (uri) {
  4830. if (uri != null) {
  4831. cache[src] = uri;
  4832. img.setAttribute(srcAttr, uri);
  4833. }
  4834. dec();
  4835. });
  4836. }
  4837. else {
  4838. img.setAttribute(srcAttr, tmp);
  4839. }
  4840. }
  4841. else if (src != null) {
  4842. img.setAttribute(srcAttr, src);
  4843. }
  4844. }))(images[i]);
  4845. }
  4846. });
  4847. // Converts all known image tags in output
  4848. // LATER: Add support for images in CSS
  4849. convertImages('image', 'xlink:href');
  4850. convertImages('img', 'src');
  4851. // All from cache or no images
  4852. if (counter == 0) {
  4853. callback(svgRoot);
  4854. }
  4855. };
  4856. /**
  4857. * Converts all images in the SVG output to data URIs for immediate rendering
  4858. */
  4859. EditorUi.prototype.createImageUrlConverter = function () {
  4860. var converter = new mxUrlConverter();
  4861. converter.updateBaseUrl();
  4862. // Extends convert to avoid CORS using an image proxy server where needed
  4863. var convert = converter.convert;
  4864. var self = this;
  4865. converter.convert = function (src) {
  4866. // if (src != null)
  4867. // {
  4868. // var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  4869. // if (remote && !navigator.onLine)
  4870. // {
  4871. // src = self.svgBrokenImage.src;
  4872. // }
  4873. // else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  4874. // (!self.crossOriginImages || !self.isCorsEnabledForUrl(src)))
  4875. // {
  4876. // src = PROXY_URL + '?url=' + encodeURIComponent(src);
  4877. // }
  4878. // else if (src.substring(0, 19) != 'chrome-extension://')
  4879. // {
  4880. // src = convert.apply(this, arguments);
  4881. // }
  4882. // }
  4883. return src;
  4884. };
  4885. return converter;
  4886. };
  4887. /**
  4888. * For the fontCSS to be applied when rendering images on canvas, the actual
  4889. * font data must be made available via a data URI encoding of the file.
  4890. */
  4891. EditorUi.prototype.loadFonts = function (then) {
  4892. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null) {
  4893. var parts = this.editor.fontCss.split('url(');
  4894. var waiting = 0;
  4895. var fonts = {};
  4896. // Strips leading and trailing quotes and spaces
  4897. function trimString(str) {
  4898. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  4899. };
  4900. var finish = mxUtils.bind(this, function () {
  4901. if (waiting == 0) {
  4902. // Constructs string
  4903. var result = [parts[0]];
  4904. for (var j = 1; j < parts.length; j++) {
  4905. var idx = parts[j].indexOf(')');
  4906. result.push('url("');
  4907. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  4908. result.push('"' + parts[j].substring(idx));
  4909. }
  4910. this.editor.resolvedFontCss = result.join('');
  4911. then();
  4912. }
  4913. });
  4914. if (parts.length > 0) {
  4915. for (var i = 1; i < parts.length; i++) {
  4916. var idx = parts[i].indexOf(')');
  4917. var format = null;
  4918. // Checks if there is a format directive
  4919. var fmtIdx = parts[i].indexOf('format(', idx);
  4920. if (fmtIdx > 0) {
  4921. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  4922. }
  4923. (mxUtils.bind(this, function (url) {
  4924. if (fonts[url] == null) {
  4925. // Mark font es being fetched and fetch it
  4926. fonts[url] = url;
  4927. waiting++;
  4928. var mime = 'application/x-font-ttf';
  4929. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  4930. if (format == 'svg' || /(\.svg)($|\?)/i.test(url)) {
  4931. mime = 'image/svg+xml';
  4932. }
  4933. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url)) {
  4934. mime = 'application/x-font-opentype';
  4935. }
  4936. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url)) {
  4937. mime = 'application/font-woff';
  4938. }
  4939. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url)) {
  4940. mime = 'application/font-woff2';
  4941. }
  4942. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url)) {
  4943. mime = 'application/vnd.ms-fontobject';
  4944. }
  4945. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url)) {
  4946. mime = 'application/font-sfnt';
  4947. }
  4948. var realUrl = url;
  4949. if ((/^https?:\/\//.test(realUrl)) && !this.isCorsEnabledForUrl(realUrl)) {
  4950. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  4951. }
  4952. // LATER: Remove cache-control header
  4953. this.loadUrl(realUrl, mxUtils.bind(this, function (uri) {
  4954. fonts[url] = uri;
  4955. waiting--;
  4956. finish();
  4957. }), mxUtils.bind(this, function (err) {
  4958. // LATER: handle error
  4959. waiting--;
  4960. finish();
  4961. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  4962. }
  4963. }))(trimString(parts[i].substring(0, idx)), format);
  4964. }
  4965. }
  4966. }
  4967. else {
  4968. then();
  4969. }
  4970. };
  4971. /**
  4972. * Translates this point by the given vector.
  4973. *
  4974. * @param {number} dx X-coordinate of the translation.
  4975. * @param {number} dy Y-coordinate of the translation.
  4976. */
  4977. EditorUi.prototype.createSvgDataUri = function (svg) {
  4978. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  4979. };
  4980. /**
  4981. * Translates this point by the given vector.
  4982. *
  4983. * @param {number} dx X-coordinate of the translation.
  4984. * @param {number} dy Y-coordinate of the translation.
  4985. */
  4986. EditorUi.prototype.getFileData = function (forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file) {
  4987. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  4988. currentPage = (currentPage != null) ? currentPage : false;
  4989. node = this.editor.getGraphXml(ignoreSelection);
  4990. var graph = this.editor.graph;
  4991. var result = this.createFileData(node, graph, file, window.location.href,
  4992. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  4993. // Removes temporary graph from DOM
  4994. if (graph != this.editor.graph) {
  4995. graph.container.parentNode.removeChild(graph.container);
  4996. }
  4997. return result;
  4998. };
  4999. /**
  5000. * Translates this point by the given vector.
  5001. *
  5002. * @param {number} dx X-coordinate of the translation.
  5003. * @param {number} dy Y-coordinate of the translation.
  5004. */
  5005. EditorUi.prototype.createFileData = function (node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact) {
  5006. graph = (graph != null) ? graph : this.editor.graph;
  5007. forceXml = (forceXml != null) ? forceXml : false;
  5008. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  5009. var editLink = null;
  5010. var redirect = null;
  5011. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER) {
  5012. editLink = '_blank';
  5013. }
  5014. else {
  5015. editLink = url;
  5016. redirect = editLink;
  5017. }
  5018. if (node == null) {
  5019. return '';
  5020. }
  5021. else {
  5022. var fileNode = node;
  5023. // Ignores case for possible HTML or XML nodes
  5024. if (fileNode.nodeName.toLowerCase() != 'mxfile') {
  5025. // Removes control chars in input for correct roundtrip check
  5026. var text = graph.zapGremlins(mxUtils.getXml(node));
  5027. var data = graph.compress(text);
  5028. // Fallback to plain XML for invalid compression
  5029. // TODO: Remove this fallback with active pages
  5030. if (graph.decompress(data) != text) {
  5031. return text;
  5032. }
  5033. else {
  5034. var diagramNode = node.ownerDocument.createElement('diagram');
  5035. diagramNode.setAttribute('id', 'tapd-' + Editor.guid());
  5036. mxUtils.setTextContent(diagramNode, data);
  5037. fileNode = node.ownerDocument.createElement('mxfile');
  5038. fileNode.appendChild(diagramNode);
  5039. }
  5040. }
  5041. if (!compact) {
  5042. // Removes old metadata
  5043. fileNode.removeAttribute('userAgent');
  5044. fileNode.removeAttribute('version');
  5045. fileNode.removeAttribute('editor');
  5046. fileNode.removeAttribute('type');
  5047. // Adds new metadata
  5048. fileNode.setAttribute('modified', new Date().toISOString());
  5049. fileNode.setAttribute('host', window.location.hostname);
  5050. fileNode.setAttribute('agent', navigator.userAgent);
  5051. fileNode.setAttribute('version', EditorUi.VERSION);
  5052. fileNode.setAttribute('etag', 'tapd-' + Editor.guid());
  5053. var md = (file != null) ? file.getMode() : this.mode;
  5054. if (md != null) {
  5055. fileNode.setAttribute('type', md);
  5056. }
  5057. }
  5058. else {
  5059. fileNode = fileNode.cloneNode(true);
  5060. fileNode.removeAttribute('userAgent');
  5061. fileNode.removeAttribute('version');
  5062. fileNode.removeAttribute('editor');
  5063. fileNode.removeAttribute('type');
  5064. }
  5065. var xml = mxUtils.getXml(fileNode);
  5066. return xml;
  5067. }
  5068. };
  5069. /**
  5070. *
  5071. */
  5072. EditorUi.prototype.saveCanvas = function (canvas, xml, format, exportHandler) {
  5073. var ext = ((format == 'jpeg') ? 'jpg' : format);
  5074. var filename = this.getBaseFilename() + '.' + ext;
  5075. var data = this.createImageDataUri(canvas, xml, format);
  5076. if (exportHandler && typeof exportHandler === 'function') {
  5077. exportHandler(data, filename);
  5078. } else {
  5079. this.doDownloadFile(data.substring(data.lastIndexOf(',') + 1), filename, 'image/' + format, true, format);
  5080. }
  5081. };
  5082. EditorUi.prototype.getBaseFilename = function () {
  5083. return this.editor.getFilename();
  5084. };
  5085. EditorUi.prototype.convertImageToDataUri = function (src, call) {
  5086. let img = new Image();
  5087. img.src = src;
  5088. img.onload = function() {
  5089. let canvas = document.createElement('canvas');
  5090. canvas.width = img.width;
  5091. canvas.height = img.height;
  5092. let ctx = canvas.getContext('2d');
  5093. ctx.drawImage(img, 0, 0);
  5094. let base64 = canvas.toDataURL('image/png');
  5095. call(base64)
  5096. };
  5097. }
  5098. EditorUi.prototype.createImageDataUri = function (canvas, xml, format) {
  5099. var data = canvas.toDataURL('image/' + format);
  5100. // Checks if output is invalid or empty
  5101. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format)) {
  5102. throw { message: 'Invalid image' };
  5103. }
  5104. if (xml != null) {
  5105. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(this.editor.graph.compress(xml)));
  5106. }
  5107. return data;
  5108. };
  5109. /**
  5110. * Adds the given text to the compressed or non-compressed text chunk.
  5111. */
  5112. EditorUi.prototype.writeGraphModelToPng = function (data, type, key, value, error) {
  5113. var base64 = data.substring(data.indexOf(',') + 1);
  5114. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  5115. var pos = 0;
  5116. function fread(d, count) {
  5117. var start = pos;
  5118. pos += count;
  5119. return d.substring(start, pos);
  5120. };
  5121. // Reads unsigned long 32 bit big endian
  5122. function _freadint(d) {
  5123. var bytes = fread(d, 4);
  5124. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  5125. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  5126. };
  5127. function writeInt(num) {
  5128. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  5129. (num >> 8) & 0x000000ff, num & 0x000000ff);
  5130. };
  5131. // Checks signature
  5132. if (fread(f, 8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10)) {
  5133. if (error != null) {
  5134. error();
  5135. }
  5136. return;
  5137. }
  5138. // Reads header chunk
  5139. fread(f, 4);
  5140. if (fread(f, 4) != 'IHDR') {
  5141. if (error != null) {
  5142. error();
  5143. }
  5144. return;
  5145. }
  5146. fread(f, 17);
  5147. var result = f.substring(0, pos);
  5148. do {
  5149. var n = _freadint(f);
  5150. var chunk = fread(f, 4);
  5151. if (chunk == 'IDAT') {
  5152. result = f.substring(0, pos - 8);
  5153. var chunkData = key + String.fromCharCode(0) +
  5154. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  5155. value;
  5156. // FIXME: Wrong crc
  5157. var crc = 0xffffffff;
  5158. crc = this.updateCRC(crc, type, 0, 4);
  5159. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  5160. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  5161. result += f.substring(pos - 8, f.length);
  5162. break;
  5163. }
  5164. result += f.substring(pos - 8, pos - 4 + n);
  5165. fread(f, n);
  5166. fread(f, 4);
  5167. }
  5168. while (n);
  5169. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  5170. };
  5171. EditorUi.prototype.crcTable = [];
  5172. for (var n = 0; n < 256; n++) {
  5173. var c = n;
  5174. for (var k = 0; k < 8; k++) {
  5175. if ((c & 1) == 1) {
  5176. c = 0xedb88320 ^ (c >>> 1);
  5177. }
  5178. else {
  5179. c >>>= 1;
  5180. }
  5181. EditorUi.prototype.crcTable[n] = c;
  5182. }
  5183. }
  5184. EditorUi.prototype.updateCRC = function (crc, data, off, len) {
  5185. var c = crc;
  5186. for (var n = 0; n < len; n++) {
  5187. c = EditorUi.prototype.crcTable[(c ^ data[off + n]) & 0xff] ^ (c >>> 8);
  5188. }
  5189. return c;
  5190. };