EditorUi.js 323 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. (function()
  6. {
  7. /**
  8. * Version
  9. */
  10. EditorUi.VERSION = '@DRAWIO-VERSION@';
  11. /**
  12. * Overrides compact UI setting.
  13. */
  14. EditorUi.compactUi = uiTheme != 'atlas';
  15. /**
  16. * Switch to disable logging for mode and search terms.
  17. */
  18. EditorUi.enableLogging = urlParams['stealth'] != '1' &&
  19. /.*\.draw\.io$/.test(window.location.hostname) &&
  20. window.location.hostname != 'support.draw.io';
  21. /**
  22. * Protocol and hostname to use for embedded files. Default is https://www.draw.io
  23. */
  24. EditorUi.drawHost = 'https://www.draw.io';
  25. /**
  26. * Switch to disable logging for mode and search terms.
  27. */
  28. EditorUi.lastErrorMessage = null;
  29. /**
  30. * Switch to disable logging for mode and search terms.
  31. */
  32. EditorUi.ignoredAnonymizedChars = '\n\t`~!@#$%^&*()_+{}|:"<>?-=[]\;\'.\/,\n\t';
  33. /**
  34. * Updates action states depending on the selection.
  35. */
  36. EditorUi.logError = function(message, url, linenumber, colno, err)
  37. {
  38. if (urlParams['dev'] == '1')
  39. {
  40. EditorUi.debug('logError', message, url, linenumber, colno, err);
  41. }
  42. else if (EditorUi.enableLogging)
  43. {
  44. try
  45. {
  46. if (message == EditorUi.lastErrorMessage || (message != null && url != null &&
  47. ((message.indexOf('Script error') != -1) || (message.indexOf('extension') != -1))))
  48. {
  49. // TODO log external domain script failure "Script error." is
  50. // reported when the error occurs in a script that is hosted
  51. // on a domain other than the domain of the current page
  52. }
  53. // DocumentClosedError seems to be an FF bug an can be ignored for now
  54. else if (message != null && message.indexOf('DocumentClosedError') < 0)
  55. {
  56. EditorUi.lastErrorMessage = message;
  57. var severity = (message.indexOf('NetworkError') >= 0 || message.indexOf('SecurityError') >= 0 ||
  58. message.indexOf('NS_ERROR_FAILURE') >= 0 || message.indexOf('out of memory') >= 0) ?
  59. 'CONFIG' : 'SEVERE';
  60. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  61. err = (err != null) ? err : new Error(message);
  62. var img = new Image();
  63. img.src = logDomain + '/log?severity=' + severity + '&v=' + encodeURIComponent(EditorUi.VERSION) +
  64. '&msg=clientError:' + encodeURIComponent(message) + ':url:' + encodeURIComponent(window.location.href) +
  65. ':lnum:' + encodeURIComponent(linenumber) + ((colno != null) ? ':colno:' + encodeURIComponent(colno) : '') +
  66. ((err != null && err.stack != null) ? '&stack=' + encodeURIComponent(err.stack) : '');
  67. }
  68. }
  69. catch (err)
  70. {
  71. // do nothing
  72. }
  73. }
  74. };
  75. /**
  76. * Updates action states depending on the selection.
  77. */
  78. EditorUi.logEvent = function(data)
  79. {
  80. if (urlParams['dev'] == '1')
  81. {
  82. EditorUi.debug('logEvent', data);
  83. }
  84. else if (EditorUi.enableLogging)
  85. {
  86. try
  87. {
  88. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  89. var img = new Image();
  90. img.src = logDomain + '/images/1x1.png?' +
  91. 'v=' + encodeURIComponent(EditorUi.VERSION) +
  92. ((data != null) ? '&data=' + encodeURIComponent(JSON.stringify(data)) : '');
  93. }
  94. catch (e)
  95. {
  96. // ignore
  97. }
  98. }
  99. };
  100. /**
  101. * Sending error reports.
  102. */
  103. EditorUi.sendReport = function(data, maxLength)
  104. {
  105. if (urlParams['dev'] == '1')
  106. {
  107. EditorUi.debug('sendReport', data);
  108. }
  109. else if (EditorUi.enableLogging)
  110. {
  111. try
  112. {
  113. maxLength = (maxLength != null) ? maxLength : 50000;
  114. if (data.length > maxLength)
  115. {
  116. data = data.substring(0, maxLength) + '\n...[SHORTENED]'
  117. }
  118. mxUtils.post('/email', 'version=' + encodeURIComponent(EditorUi.VERSION) +
  119. '&url=' + encodeURIComponent(window.location.href) +
  120. '&data=' + encodeURIComponent(data));
  121. }
  122. catch (e)
  123. {
  124. // ignore
  125. }
  126. }
  127. };
  128. /**
  129. * Adds the listener for automatically saving the diagram for local changes.
  130. */
  131. EditorUi.debug = function()
  132. {
  133. try
  134. {
  135. if (window.console != null && urlParams['dev'] == '1')
  136. {
  137. var args = [new Date().toISOString()];
  138. for (var i = 0; i < arguments.length; i++)
  139. {
  140. args.push(arguments[i]);
  141. }
  142. console.log.apply(console, args);
  143. }
  144. }
  145. catch (e)
  146. {
  147. // ignore
  148. }
  149. };
  150. /**
  151. * Specifies the URL for the templates index file.
  152. */
  153. EditorUi.templateFile = TEMPLATE_PATH + '/index.xml';
  154. /**
  155. * Specifies the URL for the diffsync cache.
  156. */
  157. EditorUi.cacheUrl = (urlParams['dev'] == '1') ? '/cache' : 'https://rt.draw.io/cache';
  158. /**
  159. * Switch to enable PlantUML in the insert from text dialog.
  160. * NOTE: This must also be enabled on the server-side.
  161. */
  162. EditorUi.enablePlantUml = EditorUi.enableLogging;
  163. /**
  164. * https://github.com/electron/electron/issues/2288
  165. */
  166. EditorUi.isElectronApp = window != null && window.process != null &&
  167. window.process.versions != null && window.process.versions['electron'] != null;
  168. /**
  169. * Link for scratchpad help.
  170. */
  171. EditorUi.scratchpadHelpLink = 'https://desk.draw.io/support/solutions/articles/16000042367';
  172. /**
  173. * Contains the default XML for an empty diagram.
  174. */
  175. EditorUi.prototype.emptyDiagramXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
  176. /**
  177. *
  178. */
  179. EditorUi.prototype.emptyLibraryXml = '<mxlibrary>[]</mxlibrary>';
  180. /**
  181. * Sets the delay for autosave in milliseconds. Default is 2000.
  182. */
  183. EditorUi.prototype.mode = null;
  184. /**
  185. * General timeout is 25 seconds.
  186. */
  187. EditorUi.prototype.timeout = 25000;
  188. /**
  189. * Allows for two buttons in the sidebar footer.
  190. */
  191. EditorUi.prototype.sidebarFooterHeight = 38;
  192. /**
  193. * Specifies the default custom shape style.
  194. */
  195. EditorUi.prototype.defaultCustomShapeStyle = 'shape=stencil(tZRtTsQgEEBPw1+DJR7AoN6DbWftpAgE0Ortd/jYRGq72R+YNE2YgTePloEJGWblgA18ZuKFDcMj5/Sm8boZq+BgjCX4pTyqk6ZlKROitwusOMXKQDODx5iy4pXxZ5qTHiFHawxB0JrQZH7lCabQ0Fr+XWC1/E8zcsT/gAi+Subo2/3Mh6d/oJb5nU1b5tW7r2knautaa3T+U32o7f7vZwpJkaNDLORJjcu7t59m2jXxqX9un+tt022acsfmoKaQZ+vhhswZtS6Ne/ThQGt0IV0N3Yyv6P3CeT9/tHO0XFI5cAE=);whiteSpace=wrap;html=1;';
  196. /**
  197. * Broken image symbol for offline SVG.
  198. */
  199. EditorUi.prototype.svgBrokenImage = Graph.createSvgImage(10, 10, '<rect x="0" y="0" width="10" height="10" stroke="#000" fill="transparent"/><path d="m 0 0 L 10 10 L 0 10 L 10 0" stroke="#000" fill="transparent"/>');
  200. /**
  201. * Specifies if img.crossOrigin is supported. This is true for all browsers except IE10 and earlier.
  202. */
  203. EditorUi.prototype.crossOriginImages = !mxClient.IS_IE;
  204. /**
  205. * Defines the maximum size for images.
  206. */
  207. EditorUi.prototype.maxBackgroundSize = 1600;
  208. /**
  209. * Defines the maximum size for images.
  210. */
  211. EditorUi.prototype.maxImageSize = 520;
  212. /**
  213. * Images above 100K should be resampled.
  214. */
  215. EditorUi.prototype.resampleThreshold = 100000;
  216. /**
  217. * Maximum allowed size for images is 1 MB.
  218. */
  219. EditorUi.prototype.maxImageBytes = 1000000;
  220. /**
  221. * Maximum size for background images is 2.5 MB.
  222. */
  223. EditorUi.prototype.maxBackgroundBytes = 2500000;
  224. /**
  225. * Holds the current file.
  226. */
  227. EditorUi.prototype.currentFile = null;
  228. /**
  229. * Specifies if PDF export should be done via print dialog. Default is
  230. * false which uses the PhantomJS backend to create the PDF.
  231. */
  232. EditorUi.prototype.printPdfExport = false;
  233. /**
  234. * Specifies if PDF export with pages is enabled.
  235. */
  236. EditorUi.prototype.pdfPageExport = true;
  237. /**
  238. * Restores app defaults for UI
  239. */
  240. EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
  241. /**
  242. * Whether template action should be shown in insert menu.
  243. */
  244. EditorUi.prototype.insertTemplateEnabled = true;
  245. /**
  246. * Restores app defaults for UI
  247. */
  248. EditorUi.prototype.closableScratchpad = true;
  249. /**
  250. * Capability check for canvas export
  251. */
  252. (function()
  253. {
  254. EditorUi.prototype.useCanvasForExport = false;
  255. EditorUi.prototype.jpgSupported = false;
  256. // Checks if canvas is supported
  257. try
  258. {
  259. var cnv = document.createElement('canvas');
  260. EditorUi.prototype.canvasSupported = !!(cnv.getContext && cnv.getContext('2d'));
  261. }
  262. catch (e)
  263. {
  264. // ignore
  265. }
  266. try
  267. {
  268. var canvas = document.createElement('canvas');
  269. var img = new Image();
  270. // LATER: Capability check should not be async
  271. img.onload = function()
  272. {
  273. try
  274. {
  275. var ctx = canvas.getContext('2d');
  276. ctx.drawImage(img, 0, 0);
  277. // Works in Chrome, Firefox, Edge, Safari and Opera
  278. var result = canvas.toDataURL('image/png');
  279. EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
  280. }
  281. catch (e)
  282. {
  283. // ignore
  284. }
  285. };
  286. // Checks if SVG with foreignObject can be exported
  287. var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1px" height="1px" version="1.1"><foreignObject pointer-events="all" width="1" height="1"><div xmlns="http://www.w3.org/1999/xhtml"></div></foreignObject></svg>';
  288. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  289. }
  290. catch (e)
  291. {
  292. // ignore
  293. }
  294. // Checks for client-side JPG support
  295. try
  296. {
  297. var canvas = document.createElement('canvas');
  298. canvas.width = canvas.height = 1;
  299. var uri = canvas.toDataURL('image/jpeg');
  300. EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
  301. }
  302. catch (e)
  303. {
  304. // ignore
  305. }
  306. })();
  307. /**
  308. * Hook for subclassers.
  309. */
  310. EditorUi.prototype.openLink = function(url, target, allowOpener)
  311. {
  312. // LATER: Replace this with direct calls to graph
  313. return this.editor.graph.openLink(url, target, allowOpener);
  314. };
  315. /**
  316. * Hook for subclassers.
  317. */
  318. EditorUi.prototype.showSplash = function(force) { };
  319. /**
  320. * Abstraction for local storage access.
  321. */
  322. EditorUi.prototype.getLocalData = function(key, fn)
  323. {
  324. fn(localStorage.getItem(key));
  325. };
  326. /**
  327. * Abstraction for local storage access.
  328. */
  329. EditorUi.prototype.setLocalData = function(key, data, fn)
  330. {
  331. localStorage.setItem(key, data);
  332. if (fn != null)
  333. {
  334. fn();
  335. }
  336. };
  337. /**
  338. * Abstraction for local storage access.
  339. */
  340. EditorUi.prototype.removeLocalData = function(key, fn)
  341. {
  342. localStorage.removeItem(key)
  343. fn();
  344. };
  345. EditorUi.prototype.setMathEnabled = function(value)
  346. {
  347. this.editor.graph.mathEnabled = value;
  348. this.editor.updateGraphComponents();
  349. this.editor.graph.refresh();
  350. this.fireEvent(new mxEventObject('mathEnabledChanged'));
  351. };
  352. EditorUi.prototype.isMathEnabled = function(value)
  353. {
  354. return this.editor.graph.mathEnabled;
  355. };
  356. /**
  357. * Returns true if using application cache
  358. */
  359. EditorUi.prototype.isAppCache = function()
  360. {
  361. return (urlParams['appcache'] == '1' || this.isOfflineApp());
  362. };
  363. /**
  364. * Returns true if offline app, which isn't a defined thing
  365. */
  366. EditorUi.prototype.isOfflineApp = function()
  367. {
  368. return (urlParams['offline'] == '1');
  369. };
  370. /**
  371. * Returns true if no external comms allowed or possible
  372. */
  373. EditorUi.prototype.isOffline = function()
  374. {
  375. return this.isOfflineApp() || !navigator.onLine || urlParams['stealth'] == '1';
  376. };
  377. /**
  378. * Translates this point by the given vector.
  379. *
  380. * @param {number} dx X-coordinate of the translation.
  381. * @param {number} dy Y-coordinate of the translation.
  382. */
  383. EditorUi.prototype.createSpinner = function(x, y, size)
  384. {
  385. size = (size != null) ? size : 24;
  386. var spinner = new Spinner({
  387. lines: 12, // The number of lines to draw
  388. length: size, // The length of each line
  389. width: Math.round(size / 3), // The line thickness
  390. radius: Math.round(size / 2), // The radius of the inner circle
  391. rotate: 0, // The rotation offset
  392. color: (uiTheme == 'dark') ? '#c0c0c0' : '#000', // #rgb or #rrggbb
  393. speed: 1.5, // Rounds per second
  394. trail: 60, // Afterglow percentage
  395. shadow: false, // Whether to render a shadow
  396. hwaccel: false, // Whether to use hardware acceleration
  397. zIndex: 2e9 // The z-index (defaults to 2000000000)
  398. });
  399. // Extends spin method to include an optional label
  400. var oldSpin = spinner.spin;
  401. spinner.spin = function(container, label)
  402. {
  403. var result = false;
  404. if (!this.active)
  405. {
  406. oldSpin.call(this, container);
  407. this.active = true;
  408. if (label != null)
  409. {
  410. var status = document.createElement('div');
  411. status.style.position = 'absolute';
  412. status.style.whiteSpace = 'nowrap';
  413. status.style.background = '#4B4243';
  414. status.style.color = 'white';
  415. status.style.fontFamily = 'Helvetica, Arial';
  416. status.style.fontSize = '9pt';
  417. status.style.padding = '6px';
  418. status.style.paddingLeft = '10px';
  419. status.style.paddingRight = '10px';
  420. status.style.zIndex = 2e9;
  421. status.style.left = Math.max(0, x) + 'px';
  422. status.style.top = Math.max(0, y + 70) + 'px';
  423. mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
  424. mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
  425. if (uiTheme != 'dark')
  426. {
  427. mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
  428. }
  429. if (label.substring(label.length - 3, label.length) != '...' &&
  430. label.charAt(label.length - 1) != '!')
  431. {
  432. label = label + '...';
  433. }
  434. status.innerHTML = label;
  435. container.appendChild(status);
  436. spinner.status = status;
  437. // Centers the label in older IE versions
  438. if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
  439. {
  440. status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
  441. status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
  442. }
  443. }
  444. // Pause returns a function to resume the spinner
  445. this.pause = mxUtils.bind(this, function()
  446. {
  447. var fn = function() { };
  448. if (this.active)
  449. {
  450. fn = mxUtils.bind(this, function()
  451. {
  452. this.spin(container, label);
  453. });
  454. }
  455. this.stop();
  456. return fn;
  457. });
  458. result = true;
  459. }
  460. return result;
  461. };
  462. // Extends stop method to remove the optional label
  463. var oldStop = spinner.stop;
  464. spinner.stop = function()
  465. {
  466. oldStop.call(this);
  467. this.active = false;
  468. if (spinner.status != null)
  469. {
  470. spinner.status.parentNode.removeChild(spinner.status);
  471. spinner.status = null;
  472. }
  473. };
  474. spinner.pause = function()
  475. {
  476. return function() {};
  477. };
  478. return spinner;
  479. };
  480. /**
  481. * Static method for pasing PNG files.
  482. */
  483. EditorUi.parsePng = function(f, fn, error)
  484. {
  485. var pos = 0;
  486. function fread(d, count)
  487. {
  488. var start = pos;
  489. pos += count;
  490. return d.substring(start, pos);
  491. };
  492. // Reads unsigned long 32 bit big endian
  493. function _freadint(d)
  494. {
  495. var bytes = fread(d, 4);
  496. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  497. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  498. };
  499. // Checks signature
  500. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  501. {
  502. if (error != null)
  503. {
  504. error();
  505. }
  506. return;
  507. }
  508. // Reads header chunk
  509. fread(f,4);
  510. if (fread(f,4) != 'IHDR')
  511. {
  512. if (error != null)
  513. {
  514. error();
  515. }
  516. return;
  517. }
  518. fread(f, 17);
  519. do
  520. {
  521. var n = _freadint(f);
  522. var type = fread(f,4);
  523. if (fn != null)
  524. {
  525. if (fn(pos - 8, type, n))
  526. {
  527. break;
  528. }
  529. }
  530. value = fread(f,n);
  531. fread(f,4);
  532. if (type == 'IEND')
  533. {
  534. break;
  535. }
  536. }
  537. while (n);
  538. };
  539. /**
  540. * Returns true if the given string contains a compatible graph model.
  541. */
  542. EditorUi.prototype.isCompatibleString = function(data)
  543. {
  544. try
  545. {
  546. var doc = mxUtils.parseXml(data);
  547. var node = this.editor.extractGraphModel(doc.documentElement, true);
  548. return node != null && node.getElementsByTagName('parsererror').length == 0;
  549. }
  550. catch (e)
  551. {
  552. // ignore
  553. }
  554. return false;
  555. };
  556. /**
  557. * Returns true if the given binary data is a Visio file.
  558. */
  559. EditorUi.prototype.isVisioData = function(data)
  560. {
  561. return data.length > 8 && (data.charCodeAt(0) == 0xD0 && data.charCodeAt(1) == 0xCF &&
  562. data.charCodeAt(2) == 0x11 && data.charCodeAt(3) == 0xE0 && data.charCodeAt(4) == 0xA1 && data.charCodeAt(5) == 0xB1 &&
  563. data.charCodeAt(6) == 0x1A && data.charCodeAt(7) == 0xE1) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  564. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x04) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  565. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x06);
  566. };
  567. /**
  568. * Returns true if the given binary data is a PNG file.
  569. */
  570. EditorUi.prototype.isPngData = function(data)
  571. {
  572. return data.length > 8 && data.charCodeAt(0) == 137 && data.charCodeAt(1) == 80 &&
  573. data.charCodeAt(2) == 78 && data.charCodeAt(3) == 71 && data.charCodeAt(4) == 13 &&
  574. data.charCodeAt(5) == 10 && data.charCodeAt(6) == 26 && data.charCodeAt(7) == 10;
  575. };
  576. /**
  577. * Extracts the mxfile from the given HTML data from a data transfer event.
  578. */
  579. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  580. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  581. {
  582. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  583. if (result == null)
  584. {
  585. try
  586. {
  587. var idx = data.indexOf('&lt;mxfile ');
  588. if (idx >= 0)
  589. {
  590. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  591. if (idx2 > idx)
  592. {
  593. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  594. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  595. }
  596. }
  597. else
  598. {
  599. // Gets compressed data from mxgraph element in HTML document
  600. var doc = mxUtils.parseXml(data);
  601. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null ||
  602. this.diagramContainer.style.visibility == 'hidden');
  603. result = (node != null) ? mxUtils.getXml(node) : '';
  604. }
  605. }
  606. catch (e)
  607. {
  608. // ignore
  609. }
  610. }
  611. return result;
  612. };
  613. /**
  614. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  615. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  616. */
  617. EditorUi.prototype.validateFileData = function(data)
  618. {
  619. if (data != null && data.length > 0)
  620. {
  621. var index = data.indexOf('<meta charset="utf-8">');
  622. if (index >= 0)
  623. {
  624. var replaceString = '<meta charset="utf-8"/>';
  625. var replaceStrLen = replaceString.length;
  626. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  627. }
  628. data = Graph.zapGremlins(data);
  629. }
  630. return data;
  631. };
  632. /**
  633. *
  634. */
  635. EditorUi.prototype.replaceFileData = function(data)
  636. {
  637. data = this.validateFileData(data);
  638. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  639. // Some nodes must be extracted here to find the mxfile node
  640. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  641. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  642. if (tmp != null)
  643. {
  644. node = tmp;
  645. }
  646. if (node != null)
  647. {
  648. var graph = this.editor.graph;
  649. graph.model.beginUpdate();
  650. try
  651. {
  652. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  653. var nodes = node.getElementsByTagName('diagram');
  654. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  655. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  656. {
  657. this.fileNode = node;
  658. this.pages = (this.pages != null) ? this.pages : [];
  659. // Wraps page nodes
  660. for (var i = nodes.length - 1; i >= 0; i--)
  661. {
  662. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  663. // Checks for invalid page names
  664. if (page.getName() == null)
  665. {
  666. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  667. }
  668. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  669. }
  670. }
  671. else
  672. {
  673. // Creates tabbed file structure if enforced by URL
  674. if (urlParams['pages'] != '0' && this.fileNode == null)
  675. {
  676. this.fileNode = node.ownerDocument.createElement('mxfile');
  677. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  678. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  679. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  680. }
  681. // Avoids scroll offset when switching page
  682. this.editor.setGraphXml(node);
  683. // Avoids duplicate parsing of the XML stored in the node
  684. if (this.currentPage != null)
  685. {
  686. this.currentPage.root = this.editor.graph.model.root;
  687. }
  688. }
  689. if (oldPages != null)
  690. {
  691. for (var i = 0; i < oldPages.length; i++)
  692. {
  693. graph.model.execute(new ChangePage(this, oldPages[i], null));
  694. }
  695. }
  696. }
  697. finally
  698. {
  699. graph.model.endUpdate();
  700. }
  701. }
  702. };
  703. /**
  704. * Translates this point by the given vector.
  705. *
  706. * @param {number} dx X-coordinate of the translation.
  707. * @param {number} dy Y-coordinate of the translation.
  708. */
  709. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  710. {
  711. graph = (graph != null) ? graph : this.editor.graph;
  712. forceXml = (forceXml != null) ? forceXml : false;
  713. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  714. var editLink = null;
  715. var redirect = null;
  716. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  717. {
  718. editLink = '_blank';
  719. }
  720. else
  721. {
  722. editLink = url;
  723. redirect = editLink;
  724. }
  725. if (node == null)
  726. {
  727. return '';
  728. }
  729. else
  730. {
  731. var fileNode = node;
  732. // Ignores case for possible HTML or XML nodes
  733. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  734. {
  735. // Removes control chars in input for correct roundtrip check
  736. var text = Graph.zapGremlins(mxUtils.getXml(node));
  737. var data = Graph.compress(text);
  738. // Fallback to plain XML for invalid compression
  739. // TODO: Remove this fallback with active pages
  740. if (Graph.decompress(data) != text)
  741. {
  742. return text;
  743. }
  744. else
  745. {
  746. var diagramNode = node.ownerDocument.createElement('diagram');
  747. diagramNode.setAttribute('id', Editor.guid());
  748. mxUtils.setTextContent(diagramNode, data);
  749. fileNode = node.ownerDocument.createElement('mxfile');
  750. fileNode.appendChild(diagramNode);
  751. }
  752. }
  753. if (!compact)
  754. {
  755. // Removes old metadata
  756. fileNode.removeAttribute('userAgent');
  757. fileNode.removeAttribute('version');
  758. fileNode.removeAttribute('editor');
  759. fileNode.removeAttribute('type');
  760. // Adds new metadata
  761. fileNode.setAttribute('modified', new Date().toISOString());
  762. fileNode.setAttribute('host', window.location.hostname);
  763. fileNode.setAttribute('agent', navigator.userAgent);
  764. fileNode.setAttribute('version', EditorUi.VERSION);
  765. fileNode.setAttribute('etag', Editor.guid());
  766. var md = (file != null) ? file.getMode() : this.mode;
  767. if (md != null)
  768. {
  769. fileNode.setAttribute('type', md);
  770. }
  771. }
  772. else
  773. {
  774. fileNode = fileNode.cloneNode(true);
  775. fileNode.removeAttribute('userAgent');
  776. fileNode.removeAttribute('version');
  777. fileNode.removeAttribute('editor');
  778. fileNode.removeAttribute('type');
  779. }
  780. var xml = mxUtils.getXml(fileNode);
  781. // Writes the file as an embedded HTML file
  782. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  783. {
  784. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  785. }
  786. // Maps the XML data to the content attribute in the SVG node
  787. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  788. {
  789. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  790. {
  791. url = null;
  792. }
  793. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  794. }
  795. return xml;
  796. }
  797. };
  798. /**
  799. * Translates this point by the given vector.
  800. *
  801. * @param {number} dx X-coordinate of the translation.
  802. * @param {number} dy Y-coordinate of the translation.
  803. */
  804. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  805. {
  806. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  807. currentPage = (currentPage != null) ? currentPage : false;
  808. var node = this.editor.getGraphXml(ignoreSelection);
  809. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  810. {
  811. var data = Graph.compressNode(node);
  812. mxUtils.setTextContent(this.currentPage.node, data);
  813. node = this.fileNode.cloneNode(false);
  814. if (currentPage)
  815. {
  816. node.appendChild(this.currentPage.node);
  817. }
  818. else
  819. {
  820. // Restores order of pages
  821. for (var i = 0; i < this.pages.length; i++)
  822. {
  823. if (this.currentPage != this.pages[i] && this.pages[i].needsUpdate)
  824. {
  825. var enc = new mxCodec(mxUtils.createXmlDocument());
  826. var temp = enc.encode(new mxGraphModel(this.pages[i].root));
  827. this.editor.graph.saveViewState(this.pages[i].viewState, temp);
  828. mxUtils.setTextContent(this.pages[i].node, Graph.compressNode(temp));
  829. // Marks the page as up-to-date
  830. delete this.pages[i].needsUpdate;
  831. }
  832. node.appendChild(this.pages[i].node);
  833. }
  834. }
  835. }
  836. return node;
  837. };
  838. /**
  839. * Removes any values, styles and geometries from the given XML node.
  840. */
  841. EditorUi.prototype.anonymizeString = function(text, zeros)
  842. {
  843. var result = [];
  844. for (var i = 0; i < text.length; i++)
  845. {
  846. var c = text.charAt(i);
  847. if (EditorUi.ignoredAnonymizedChars.indexOf(c) >= 0)
  848. {
  849. result.push(c);
  850. }
  851. else if (!isNaN(parseInt(c)))
  852. {
  853. result.push((zeros) ? '0' : Math.round(Math.random() * 9));
  854. }
  855. else if (c.toLowerCase() != c)
  856. {
  857. result.push(String.fromCharCode(65 + Math.round(Math.random() * 25)));
  858. }
  859. else if (c.toUpperCase() != c)
  860. {
  861. result.push(String.fromCharCode(97 + Math.round(Math.random() * 25)));
  862. }
  863. else if (/\s/.test(c))
  864. {
  865. /* any whitespace */
  866. result.push(' ');
  867. }
  868. else
  869. {
  870. result.push('?');
  871. }
  872. }
  873. return result.join('');
  874. };
  875. /**
  876. * Removes any values, styles and geometries from the given XML node.
  877. */
  878. EditorUi.prototype.anonymizePatch = function(patch)
  879. {
  880. if (patch[EditorUi.DIFF_INSERT] != null)
  881. {
  882. for (var i = 0; i < patch[EditorUi.DIFF_INSERT].length; i++)
  883. {
  884. try
  885. {
  886. var data = patch[EditorUi.DIFF_INSERT][i].data;
  887. var doc = mxUtils.parseXml(data);
  888. var clone = doc.documentElement.cloneNode(false);
  889. if (clone.getAttribute('name') != null)
  890. {
  891. clone.setAttribute('name', this.anonymizeString(clone.getAttribute('name')));
  892. }
  893. patch[EditorUi.DIFF_INSERT][i].data = mxUtils.getXml(clone);
  894. }
  895. catch (e)
  896. {
  897. patch[EditorUi.DIFF_INSERT][i].data = e.message;
  898. }
  899. }
  900. }
  901. if (patch[EditorUi.DIFF_UPDATE] != null)
  902. {
  903. for (var pageId in patch[EditorUi.DIFF_UPDATE])
  904. {
  905. var diff = patch[EditorUi.DIFF_UPDATE][pageId];
  906. if (diff.name != null)
  907. {
  908. diff.name = this.anonymizeString(diff.name);
  909. }
  910. if (diff.cells != null)
  911. {
  912. var anonymizeCellDiffs = mxUtils.bind(this, function(key)
  913. {
  914. var cellDiffs = diff.cells[key];
  915. if (cellDiffs != null)
  916. {
  917. for (var cellId in cellDiffs)
  918. {
  919. if (cellDiffs[cellId].value != null)
  920. {
  921. cellDiffs[cellId].value = '[' +
  922. cellDiffs[cellId].value.length + ']';
  923. }
  924. if (cellDiffs[cellId].xmlValue != null)
  925. {
  926. cellDiffs[cellId].xmlValue = '[' +
  927. cellDiffs[cellId].xmlValue.length + ']';
  928. }
  929. if (cellDiffs[cellId].style != null)
  930. {
  931. cellDiffs[cellId].style = '[' +
  932. cellDiffs[cellId].style.length + ']';
  933. }
  934. if (Object.keys(cellDiffs[cellId]).length == 0)
  935. {
  936. delete cellDiffs[cellId];
  937. }
  938. }
  939. if (Object.keys(cellDiffs).length == 0)
  940. {
  941. delete diff.cells[key];
  942. }
  943. }
  944. });
  945. anonymizeCellDiffs(EditorUi.DIFF_INSERT);
  946. anonymizeCellDiffs(EditorUi.DIFF_UPDATE);
  947. if (Object.keys(diff.cells).length == 0)
  948. {
  949. delete diff.cells;
  950. }
  951. }
  952. if (Object.keys(diff).length == 0)
  953. {
  954. delete patch[EditorUi.DIFF_UPDATE][pageId];
  955. }
  956. }
  957. if (Object.keys(patch[EditorUi.DIFF_UPDATE]).length == 0)
  958. {
  959. delete patch[EditorUi.DIFF_UPDATE];
  960. }
  961. }
  962. return patch;
  963. };
  964. /**
  965. * Removes any values, styles and geometries from the given XML node.
  966. */
  967. EditorUi.prototype.anonymizeAttributes = function(node, zeros)
  968. {
  969. if (node.attributes != null)
  970. {
  971. for (var i = 0; i < node.attributes.length; i++)
  972. {
  973. if (node.attributes[i].name != 'as')
  974. {
  975. node.setAttribute(node.attributes[i].name,
  976. this.anonymizeString(node.attributes[i].value, zeros));
  977. }
  978. }
  979. }
  980. if (node.childNodes != null)
  981. {
  982. for (var i = 0; i < node.childNodes.length; i++)
  983. {
  984. this.anonymizeAttributes(node.childNodes[i], zeros);
  985. }
  986. }
  987. };
  988. /**
  989. * Removes any values, styles and geometries from the given XML node.
  990. */
  991. EditorUi.prototype.anonymizeNode = function(node, zeros)
  992. {
  993. var nodes = node.getElementsByTagName('mxCell');
  994. for (var i = 0; i < nodes.length; i++)
  995. {
  996. if (nodes[i].getAttribute('value') != null)
  997. {
  998. nodes[i].setAttribute('value', '[' + nodes[i].getAttribute('value').length + ']');
  999. }
  1000. if (nodes[i].getAttribute('xmlValue') != null)
  1001. {
  1002. nodes[i].setAttribute('xmlValue', '[' + nodes[i].getAttribute('xmlValue').length + ']');
  1003. }
  1004. if (nodes[i].getAttribute('style') != null)
  1005. {
  1006. nodes[i].setAttribute('style', '[' + nodes[i].getAttribute('style').length + ']');
  1007. }
  1008. if (nodes[i].parentNode != null && nodes[i].parentNode.nodeName != 'root' &&
  1009. nodes[i].parentNode.parentNode != null)
  1010. {
  1011. nodes[i].setAttribute('id', nodes[i].parentNode.getAttribute('id'));
  1012. nodes[i].parentNode.parentNode.replaceChild(nodes[i], nodes[i].parentNode);
  1013. }
  1014. }
  1015. return node;
  1016. };
  1017. /**
  1018. * Translates this point by the given vector.
  1019. *
  1020. * @param {number} dx X-coordinate of the translation.
  1021. * @param {number} dy Y-coordinate of the translation.
  1022. */
  1023. EditorUi.prototype.synchronizeCurrentFile = function(forceReload)
  1024. {
  1025. var currentFile = this.getCurrentFile();
  1026. if (currentFile != null)
  1027. {
  1028. if (currentFile.savingFile)
  1029. {
  1030. this.handleError({message: mxResources.get('busy')});
  1031. }
  1032. else if (!forceReload && currentFile.invalidChecksum)
  1033. {
  1034. currentFile.handleFileError(null, true);
  1035. }
  1036. else if (this.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1037. {
  1038. currentFile.clearAutosave();
  1039. this.editor.setStatus('');
  1040. if (forceReload)
  1041. {
  1042. currentFile.reloadFile(mxUtils.bind(this, function()
  1043. {
  1044. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1045. }), mxUtils.bind(this, function(err)
  1046. {
  1047. currentFile.handleFileError(err, true);
  1048. }));
  1049. }
  1050. else
  1051. {
  1052. currentFile.synchronizeFile(mxUtils.bind(this, function()
  1053. {
  1054. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1055. }), mxUtils.bind(this, function(err)
  1056. {
  1057. currentFile.handleFileError(err, true);
  1058. }));
  1059. }
  1060. }
  1061. }
  1062. };
  1063. /**
  1064. * Translates this point by the given vector.
  1065. *
  1066. * @param {number} dx X-coordinate of the translation.
  1067. * @param {number} dy Y-coordinate of the translation.
  1068. */
  1069. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file)
  1070. {
  1071. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1072. currentPage = (currentPage != null) ? currentPage : false;
  1073. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  1074. file = (file != null) ? file : this.getCurrentFile();
  1075. var graph = this.editor.graph;
  1076. // Exports SVG for first page while other page is visible by creating a graph
  1077. // LATER: Add caching for the graph or SVG while not on first page
  1078. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  1079. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  1080. {
  1081. graph = this.createTemporaryGraph(graph.getStylesheet());
  1082. var graphGetGlobalVariable = graph.getGlobalVariable;
  1083. var page = this.pages[0];
  1084. graph.getGlobalVariable = function(name)
  1085. {
  1086. if (name == 'page')
  1087. {
  1088. return page.getName();
  1089. }
  1090. else if (name == 'pagenumber')
  1091. {
  1092. return 1;
  1093. }
  1094. return graphGetGlobalVariable.apply(this, arguments);
  1095. };
  1096. document.body.appendChild(graph.container);
  1097. graph.model.setRoot(page.root);
  1098. }
  1099. var result = this.createFileData(node, graph, file, window.location.href,
  1100. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  1101. // Removes temporary graph from DOM
  1102. if (graph != this.editor.graph)
  1103. {
  1104. graph.container.parentNode.removeChild(graph.container);
  1105. }
  1106. return result;
  1107. };
  1108. /**
  1109. *
  1110. */
  1111. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  1112. {
  1113. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1114. var bg = null;
  1115. var js = EditorUi.drawHost + '/js/embed-static.min.js';
  1116. // LATER: Merge common code with EmbedDialog
  1117. if (graph != null)
  1118. {
  1119. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  1120. var scale = graph.view.scale;
  1121. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  1122. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  1123. bg = graph.background;
  1124. // Embed script only used if no redirect
  1125. if (redirect == null)
  1126. {
  1127. var s = this.getBasenames().join(';');
  1128. if (s.length > 0)
  1129. {
  1130. js = EditorUi.drawHost + '/embed.js?s=' + s;
  1131. }
  1132. }
  1133. // Adds embed attributes
  1134. node.setAttribute('x0', x0);
  1135. node.setAttribute('y0', y0);
  1136. }
  1137. if (node != null)
  1138. {
  1139. node.setAttribute('pan', '1');
  1140. node.setAttribute('zoom', '1');
  1141. node.setAttribute('resize', '0');
  1142. node.setAttribute('fit', '0');
  1143. node.setAttribute('border', '20');
  1144. // Hidden attributes
  1145. node.setAttribute('links', '1');
  1146. if (editLink != null)
  1147. {
  1148. node.setAttribute('edit', editLink);
  1149. }
  1150. }
  1151. // Makes XHTML compatible
  1152. if (redirect != null)
  1153. {
  1154. redirect = redirect.replace(/&/g, '&amp;');
  1155. }
  1156. // Removes control chars in input for correct roundtrip check
  1157. var text = (node != null) ? Graph.zapGremlins(mxUtils.getXml(node)) : '';
  1158. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  1159. // embed clients that rely on this format. HTML files and export use getHtml2.
  1160. var data = Graph.compress(text);
  1161. // Fallback to URI encoded XML for invalid compression
  1162. if (Graph.decompress(data) != text)
  1163. {
  1164. data = encodeURIComponent(text);
  1165. }
  1166. var style = 'position:relative;overflow:auto;width:100%;';
  1167. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1168. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1169. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1170. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1171. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1172. '</head>\n<body' +
  1173. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  1174. '\n<div class="mxgraph" style="' + style + '">\n' +
  1175. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  1176. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1177. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1178. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1179. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1180. '\n</body>\n</html>\n';
  1181. };
  1182. /**
  1183. * Same as above but using the new embed code.
  1184. */
  1185. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  1186. {
  1187. var bg = null;
  1188. var js = EditorUi.drawHost + '/js/viewer.min.js';
  1189. var s = '';
  1190. // Makes XHTML compatible
  1191. if (redirect != null)
  1192. {
  1193. redirect = redirect.replace(/&/g, '&amp;');
  1194. }
  1195. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  1196. xml: Graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  1197. if (this.pages != null && this.currentPage != null)
  1198. {
  1199. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  1200. }
  1201. var style = 'max-width:100%;border:1px solid transparent;';
  1202. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1203. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1204. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1205. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1206. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1207. '<meta charset="utf-8"/>\n</head>\n<body>' +
  1208. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  1209. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1210. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1211. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1212. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1213. '\n</body>\n</html>\n';
  1214. };
  1215. /**
  1216. *
  1217. */
  1218. EditorUi.prototype.setFileData = function(data)
  1219. {
  1220. data = this.validateFileData(data);
  1221. this.currentPage = null;
  1222. this.fileNode = null;
  1223. this.pages = null;
  1224. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  1225. // Checks for parser errors
  1226. var errors = (node != null) ? node.getElementsByTagName('parsererror') : null;
  1227. if (errors != null && errors.length > 0)
  1228. {
  1229. var cause = mxResources.get('invalidOrMissingFile');
  1230. var divs = errors[0].getElementsByTagName('div');
  1231. if (divs.length > 0)
  1232. {
  1233. cause = mxUtils.getTextContent(divs[0]);
  1234. }
  1235. throw new Error(cause);
  1236. }
  1237. else
  1238. {
  1239. // Some nodes must be extracted here to find the mxfile node
  1240. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  1241. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  1242. if (tmp != null)
  1243. {
  1244. node = tmp;
  1245. }
  1246. if (node != null && node.nodeName == 'mxfile')
  1247. {
  1248. var nodes = node.getElementsByTagName('diagram');
  1249. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  1250. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  1251. {
  1252. var selectedPage = null;
  1253. this.fileNode = node;
  1254. this.pages = [];
  1255. // Wraps page nodes
  1256. for (var i = 0; i < nodes.length; i++)
  1257. {
  1258. // Adds page ID based on page order to match
  1259. // remote IDs given if IDs are missing here
  1260. if (nodes[i].getAttribute('id') == null)
  1261. {
  1262. nodes[i].setAttribute('id', i);
  1263. }
  1264. var page = new DiagramPage(nodes[i]);
  1265. // Checks for invalid page names
  1266. if (page.getName() == null)
  1267. {
  1268. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  1269. }
  1270. this.pages.push(page);
  1271. if (urlParams['page-id'] != null && page.getId() == urlParams['page-id'])
  1272. {
  1273. selectedPage = page;
  1274. }
  1275. }
  1276. this.currentPage = (selectedPage != null) ? selectedPage :
  1277. this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  1278. node = this.currentPage.node;
  1279. }
  1280. }
  1281. // Creates tabbed file structure if enforced by URL
  1282. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  1283. {
  1284. this.fileNode = node.ownerDocument.createElement('mxfile');
  1285. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  1286. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  1287. this.pages = [this.currentPage];
  1288. }
  1289. // Avoids scroll offset when switching page
  1290. this.editor.setGraphXml(node);
  1291. // Avoids duplicate parsing of the XML stored in the node
  1292. if (this.currentPage != null)
  1293. {
  1294. this.currentPage.root = this.editor.graph.model.root;
  1295. }
  1296. }
  1297. };
  1298. /**
  1299. * Translates this point by the given vector.
  1300. *
  1301. * @param {number} dx X-coordinate of the translation.
  1302. * @param {number} dy Y-coordinate of the translation.
  1303. */
  1304. EditorUi.prototype.getBaseFilename = function(ignorePageName)
  1305. {
  1306. var file = this.getCurrentFile();
  1307. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  1308. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
  1309. /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename) ||
  1310. /(\.drawio)$/i.test(basename))
  1311. {
  1312. basename = basename.substring(0, basename.lastIndexOf('.'));
  1313. }
  1314. if (!ignorePageName && this.pages != null && this.pages.length > 1 &&
  1315. this.currentPage != null && this.currentPage.node.getAttribute('name') != null &&
  1316. this.currentPage.getName().length > 0)
  1317. {
  1318. basename = basename + '-' + this.currentPage.getName();
  1319. }
  1320. return basename;
  1321. };
  1322. /**
  1323. * Translates this point by the given vector.
  1324. *
  1325. * @param {number} dx X-coordinate of the translation.
  1326. * @param {number} dy Y-coordinate of the translation.
  1327. */
  1328. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible, transparent)
  1329. {
  1330. try
  1331. {
  1332. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  1333. var basename = this.getBaseFilename(!currentPage);
  1334. var filename = basename + '.' + format;
  1335. if (format == 'xml')
  1336. {
  1337. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  1338. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  1339. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  1340. this.saveData(filename, format, data, 'text/xml');
  1341. }
  1342. else if (format == 'html')
  1343. {
  1344. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  1345. this.saveData(filename, format, data, 'text/html');
  1346. }
  1347. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  1348. {
  1349. var svg = null;
  1350. var saveSvg = mxUtils.bind(this, function(data)
  1351. {
  1352. if (data.length <= MAX_REQUEST_SIZE)
  1353. {
  1354. this.saveData(filename, 'svg', data, 'image/svg+xml');
  1355. }
  1356. else
  1357. {
  1358. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  1359. {
  1360. mxUtils.popup(svg);
  1361. }));
  1362. }
  1363. });
  1364. if (format == 'svg')
  1365. {
  1366. var bg = this.editor.graph.background;
  1367. if (transparent || bg == mxConstants.NONE)
  1368. {
  1369. bg = null;
  1370. }
  1371. // Sets or disables alternate text for foreignObjects. Disabling is needed
  1372. // because PhantomJS seems to ignore switch statements and paint all text.
  1373. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  1374. if (addShadow)
  1375. {
  1376. this.editor.graph.addSvgShadow(svgRoot);
  1377. }
  1378. // Embeds the images in the SVG output (async)
  1379. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  1380. {
  1381. this.spinner.stop();
  1382. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  1383. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  1384. mxUtils.getXml(svgRoot2));
  1385. })));
  1386. }
  1387. else
  1388. {
  1389. filename = basename + '.svg';
  1390. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  1391. {
  1392. this.spinner.stop();
  1393. saveSvg(svg);
  1394. }), ignoreSelection);
  1395. }
  1396. }
  1397. else
  1398. {
  1399. if (format == 'xmlpng')
  1400. {
  1401. filename = basename + '.png';
  1402. }
  1403. else if (format == 'jpeg')
  1404. {
  1405. filename = basename + '.jpg';
  1406. }
  1407. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  1408. {
  1409. try
  1410. {
  1411. var prev = this.editor.graph.pageVisible;
  1412. if (pageVisible != null)
  1413. {
  1414. this.editor.graph.pageVisible = pageVisible;
  1415. }
  1416. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64, transparent, currentPage);
  1417. this.editor.graph.pageVisible = prev;
  1418. return req;
  1419. }
  1420. catch (e)
  1421. {
  1422. this.handleError(e);
  1423. }
  1424. }));
  1425. }
  1426. }
  1427. catch (e)
  1428. {
  1429. this.handleError(e);
  1430. }
  1431. };
  1432. /**
  1433. * Translates this point by the given vector.
  1434. *
  1435. * @param {number} dx X-coordinate of the translation.
  1436. * @param {number} dy Y-coordinate of the translation.
  1437. */
  1438. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64, transparent, currentPage)
  1439. {
  1440. var bounds = this.editor.graph.getGraphBounds();
  1441. // Exports only current page for images that does not contain file data, but for
  1442. // the other formats with XML included or pdf with all pages, we need to send the complete data and use
  1443. // the from/to URL parameters to specify the page to be exported.
  1444. var data = this.getFileData(true, null, null, null, ignoreSelection, currentPage == false? false : format != 'xmlpng');
  1445. var range = '';
  1446. var allPages = '';
  1447. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  1448. {
  1449. throw {message: mxResources.get('drawingTooLarge')};
  1450. }
  1451. var embed = '0';
  1452. if (format == 'pdf' && currentPage == false)
  1453. {
  1454. allPages = '&allPages=1';
  1455. }
  1456. if (format == 'xmlpng')
  1457. {
  1458. embed = '1';
  1459. format = 'png';
  1460. // Finds the current page number
  1461. if (this.pages != null && this.currentPage != null)
  1462. {
  1463. for (var i = 0; i < this.pages.length; i++)
  1464. {
  1465. if (this.pages[i] == this.currentPage)
  1466. {
  1467. range = '&from=' + i;
  1468. break;
  1469. }
  1470. }
  1471. }
  1472. }
  1473. var bg = this.editor.graph.background;
  1474. if (format == 'png' && transparent)
  1475. {
  1476. bg = mxConstants.NONE;
  1477. }
  1478. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range + allPages +
  1479. '&bg=' + ((bg != null) ? bg : mxConstants.NONE) +
  1480. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1481. encodeURIComponent(data) + ((filename != null) ?
  1482. '&filename=' + encodeURIComponent(filename) : ''));
  1483. };
  1484. /**
  1485. * Translates this point by the given vector.
  1486. *
  1487. * @param {number} dx X-coordinate of the translation.
  1488. * @param {number} dy Y-coordinate of the translation.
  1489. */
  1490. EditorUi.prototype.setMode = function(mode, remember)
  1491. {
  1492. this.mode = mode;
  1493. };
  1494. /**
  1495. * Loads the given file descriptor. The descriptor may define the following properties:
  1496. *
  1497. * - url: The url to load the data from (proxy is used if CORS is not enabled)
  1498. * - data: The data to be inserted. If both, data and url are defined, then the data
  1499. * is preprendended to the data returned from the given URL.
  1500. * - format: Currently, only 'csv' is supported as an optional value. Default is XML.
  1501. * - update: Optional URL to fetch updates from (POST request with the page XML).
  1502. * - interval: Optional interval for fetching updates. Default is 60000 (60 seconds).
  1503. */
  1504. EditorUi.prototype.loadDescriptor = function(desc, success, error)
  1505. {
  1506. var hash = window.location.hash;
  1507. var loadData = mxUtils.bind(this, function(data)
  1508. {
  1509. var realData = (desc.data != null) ? desc.data : '';
  1510. if (data != null && data.length > 0)
  1511. {
  1512. if (realData.length > 0)
  1513. {
  1514. realData += '\n';
  1515. }
  1516. realData += data;
  1517. }
  1518. var xml = (desc.format != 'csv' && realData.length > 0) ? realData : this.emptyDiagramXml;
  1519. var tempFile = new LocalFile(this, xml, (urlParams['title'] != null) ?
  1520. decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
  1521. tempFile.getHash = function()
  1522. {
  1523. return hash;
  1524. };
  1525. this.fileLoaded(tempFile);
  1526. if (desc.format == 'csv')
  1527. {
  1528. this.importCsv(realData, mxUtils.bind(this, function(cells)
  1529. {
  1530. this.editor.undoManager.clear();
  1531. this.editor.setModified(false);
  1532. this.editor.setStatus('');
  1533. }));
  1534. }
  1535. // Installs updates
  1536. if (desc.update != null)
  1537. {
  1538. var interval = (desc.interval != null) ? parseInt(desc.interval) : 60000;
  1539. var currentThread = null;
  1540. var doUpdate = mxUtils.bind(this, function()
  1541. {
  1542. var page = this.currentPage;
  1543. mxUtils.post(desc.update, 'xml=' + encodeURIComponent(
  1544. mxUtils.getXml(this.editor.getGraphXml())),
  1545. mxUtils.bind(this, function(req)
  1546. {
  1547. if (page === this.currentPage)
  1548. {
  1549. if (req.getStatus() >= 200 && req.getStatus() <= 300)
  1550. {
  1551. var doc = this.updateDiagram(req.getText());
  1552. schedule();
  1553. }
  1554. else
  1555. {
  1556. this.handleError({message: mxResources.get('error') + ' ' + req.getStatus()});
  1557. }
  1558. }
  1559. }), mxUtils.bind(this, function(err)
  1560. {
  1561. this.handleError(err);
  1562. }));
  1563. });
  1564. var schedule = mxUtils.bind(this, function()
  1565. {
  1566. window.clearTimeout(currentThread);
  1567. currentThread = window.setTimeout(doUpdate, interval);
  1568. });
  1569. this.editor.addListener('pageSelected', mxUtils.bind(this, function()
  1570. {
  1571. schedule();
  1572. doUpdate();
  1573. }));
  1574. schedule();
  1575. doUpdate();
  1576. }
  1577. if (success != null)
  1578. {
  1579. success();
  1580. }
  1581. });
  1582. if (desc.url != null && desc.url.length > 0)
  1583. {
  1584. var realUrl = desc.url;
  1585. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  1586. {
  1587. realUrl = PROXY_URL + '?url=' + encodeURIComponent(realUrl);
  1588. }
  1589. // LATER: Remove cache-control header
  1590. this.loadUrl(realUrl, mxUtils.bind(this, function(data)
  1591. {
  1592. loadData(data);
  1593. }), mxUtils.bind(this, function(err)
  1594. {
  1595. if (error != null)
  1596. {
  1597. error(err)
  1598. }
  1599. }));
  1600. }
  1601. else
  1602. {
  1603. loadData('');
  1604. }
  1605. };
  1606. /**
  1607. * Translates this point by the given vector.
  1608. *
  1609. * @param {number} dx X-coordinate of the translation.
  1610. * @param {number} dy Y-coordinate of the translation.
  1611. */
  1612. EditorUi.prototype.updateDiagram = function(xml)
  1613. {
  1614. var doc = null;
  1615. var ui = this;
  1616. function createOverlay(desc)
  1617. {
  1618. var overlay = new mxCellOverlay(desc.image || graph.warningImage,
  1619. desc.tooltip, desc.align, desc.valign, desc.offset);
  1620. // Installs a handler for clicks on the overlay
  1621. overlay.addListener(mxEvent.CLICK, function(sender, evt)
  1622. {
  1623. ui.alert(desc.tooltip);
  1624. });
  1625. return overlay;
  1626. };
  1627. if (xml != null && xml.length > 0)
  1628. {
  1629. doc = mxUtils.parseXml(xml);
  1630. var node = (doc != null) ? doc.documentElement : null;
  1631. if (node != null && node.nodeName == 'updates')
  1632. {
  1633. var graph = this.editor.graph;
  1634. var model = graph.getModel();
  1635. model.beginUpdate();
  1636. var fit = null;
  1637. try
  1638. {
  1639. node = node.firstChild;
  1640. while (node != null)
  1641. {
  1642. if (node.nodeName == 'update')
  1643. {
  1644. // Resolves the cell ID
  1645. var cell = model.getCell(node.getAttribute('id'));
  1646. if (cell != null)
  1647. {
  1648. // Changes the value
  1649. try
  1650. {
  1651. var value = node.getAttribute('value');
  1652. if (value != null)
  1653. {
  1654. var valueNode = mxUtils.parseXml(value).documentElement;
  1655. if (valueNode != null)
  1656. {
  1657. if (valueNode.getAttribute('replace-value') == '1')
  1658. {
  1659. model.setValue(cell, valueNode);
  1660. }
  1661. else
  1662. {
  1663. var attrs = valueNode.attributes;
  1664. for (var j = 0; j < attrs.length; j++)
  1665. {
  1666. graph.setAttributeForCell(cell, attrs[j].nodeName,
  1667. (attrs[j].nodeValue.length > 0) ? attrs[j].nodeValue : null);
  1668. }
  1669. }
  1670. }
  1671. }
  1672. }
  1673. catch (e)
  1674. {
  1675. if (window.console != null)
  1676. {
  1677. console.log('Error in value for ' + cell.id + ': ' + e);
  1678. }
  1679. }
  1680. // Changes the style
  1681. try
  1682. {
  1683. var style = node.getAttribute('style');
  1684. if (style != null)
  1685. {
  1686. graph.model.setStyle(cell, style);
  1687. }
  1688. }
  1689. catch (e)
  1690. {
  1691. if (window.console != null)
  1692. {
  1693. console.log('Error in style for ' + cell.id + ': ' + e);
  1694. }
  1695. }
  1696. // Adds or removes an overlay icon
  1697. try
  1698. {
  1699. var icon = node.getAttribute('icon');
  1700. if (icon != null)
  1701. {
  1702. var desc = (icon.length > 0) ? JSON.parse(icon) : null;
  1703. if (desc == null || !desc.append)
  1704. {
  1705. graph.removeCellOverlays(cell);
  1706. }
  1707. if (desc != null)
  1708. {
  1709. graph.addCellOverlay(cell, createOverlay(desc));
  1710. }
  1711. }
  1712. }
  1713. catch (e)
  1714. {
  1715. if (window.console != null)
  1716. {
  1717. console.log('Error in icon for ' + cell.id + ': ' + e);
  1718. }
  1719. }
  1720. // Replaces the geometry
  1721. try
  1722. {
  1723. var geo = node.getAttribute('geometry');
  1724. if (geo != null)
  1725. {
  1726. geo = JSON.parse(geo);
  1727. var curr = graph.getCellGeometry(cell);
  1728. if (curr != null)
  1729. {
  1730. curr = curr.clone();
  1731. // Partially overwrites geometry
  1732. for (key in geo)
  1733. {
  1734. var val = parseFloat(geo[key]);
  1735. if (key == 'dx')
  1736. {
  1737. curr.x += val;
  1738. }
  1739. else if (key == 'dy')
  1740. {
  1741. curr.y += val;
  1742. }
  1743. else if (key == 'dw')
  1744. {
  1745. curr.width += val;
  1746. }
  1747. else if (key == 'dh')
  1748. {
  1749. curr.height += val;
  1750. }
  1751. else
  1752. {
  1753. curr[key] = parseFloat(geo[key]);
  1754. }
  1755. }
  1756. graph.model.setGeometry(cell, curr);
  1757. }
  1758. }
  1759. }
  1760. catch (e)
  1761. {
  1762. if (window.console != null)
  1763. {
  1764. console.log('Error in icon for ' + cell.id + ': ' + e);
  1765. }
  1766. }
  1767. } // if cell != null
  1768. } // if node.nodeName == 'update
  1769. else if (node.nodeName == 'model')
  1770. {
  1771. // Finds first child element
  1772. var dataNode = node.firstChild;
  1773. while (dataNode != null && dataNode.nodeType != mxConstants.NODETYPE_ELEMENT)
  1774. {
  1775. dataNode = dataNode.nextSibling;
  1776. }
  1777. if (dataNode != null)
  1778. {
  1779. var dec = new mxCodec(node.firstChild);
  1780. dec.decode(dataNode, model);
  1781. }
  1782. }
  1783. else if (node.nodeName == 'view')
  1784. {
  1785. if (node.hasAttribute('scale'))
  1786. {
  1787. graph.view.scale = parseFloat(node.getAttribute('scale'));
  1788. }
  1789. if (node.hasAttribute('dx') || node.hasAttribute('dy'))
  1790. {
  1791. graph.view.translate = new mxPoint(parseFloat(node.getAttribute('dx') || 0),
  1792. parseFloat(node.getAttribute('dy') || 0));
  1793. }
  1794. }
  1795. else if (node.nodeName == 'fit')
  1796. {
  1797. if (node.hasAttribute('max-scale'))
  1798. {
  1799. fit = parseFloat(node.getAttribute('max-scale'));
  1800. }
  1801. else
  1802. {
  1803. fit = 1;
  1804. }
  1805. }
  1806. node = node.nextSibling;
  1807. } // end of while
  1808. }
  1809. finally
  1810. {
  1811. model.endUpdate();
  1812. }
  1813. if (fit != null && this.chromelessResize)
  1814. {
  1815. this.chromelessResize(true, fit);
  1816. }
  1817. }
  1818. }
  1819. return doc;
  1820. };
  1821. /**
  1822. * Constructs a filename for a copy of the given file.
  1823. */
  1824. EditorUi.prototype.getCopyFilename = function(file, timestamp)
  1825. {
  1826. var title = (file != null && file.getTitle() != null) ?
  1827. file.getTitle() : this.defaultFilename;
  1828. // Handles extension
  1829. var extension = '';
  1830. var dot = title.lastIndexOf('.');
  1831. if (dot >= 0)
  1832. {
  1833. extension = title.substring(dot);
  1834. title = title.substring(0, dot);
  1835. }
  1836. if (timestamp)
  1837. {
  1838. function getFormattedTime()
  1839. {
  1840. var today = new Date();
  1841. var y = today.getFullYear();
  1842. // JavaScript months are 0-based.
  1843. var m = today.getMonth() + 1;
  1844. var d = today.getDate();
  1845. var h = today.getHours();
  1846. var mi = today.getMinutes();
  1847. var s = today.getSeconds();
  1848. return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
  1849. }
  1850. var ts = new Date();
  1851. title += ' ' + getFormattedTime();
  1852. }
  1853. title = mxResources.get('copyOf', [title]) + extension;
  1854. return title;
  1855. };
  1856. /**
  1857. * Translates this point by the given vector.
  1858. *
  1859. * @param {number} dx X-coordinate of the translation.
  1860. * @param {number} dy Y-coordinate of the translation.
  1861. */
  1862. EditorUi.prototype.fileLoaded = function(file, noDialogs)
  1863. {
  1864. var oldFile = this.getCurrentFile();
  1865. this.fileLoadedError = null;
  1866. this.setCurrentFile(null);
  1867. var result = false;
  1868. this.hideDialog();
  1869. if (oldFile != null)
  1870. {
  1871. oldFile.removeListener(this.descriptorChangedListener);
  1872. oldFile.close();
  1873. }
  1874. this.editor.graph.model.clear();
  1875. this.editor.undoManager.clear();
  1876. var noFile = mxUtils.bind(this, function()
  1877. {
  1878. this.setGraphEnabled(false);
  1879. this.setCurrentFile(null);
  1880. // Keeps initial title if no file existed before
  1881. if (oldFile != null)
  1882. {
  1883. this.updateDocumentTitle();
  1884. }
  1885. // File might have been loaded halfway
  1886. this.editor.graph.model.clear();
  1887. this.editor.undoManager.clear();
  1888. this.setBackgroundImage(null);
  1889. // Avoids empty hash with no value
  1890. if (!noDialogs && window.location.hash != null && window.location.hash.length > 0)
  1891. {
  1892. window.location.hash = '';
  1893. }
  1894. if (this.fname != null)
  1895. {
  1896. this.fnameWrapper.style.display = 'none';
  1897. this.fname.innerHTML = '';
  1898. this.fname.setAttribute('title', mxResources.get('rename'));
  1899. }
  1900. this.editor.setStatus('');
  1901. this.updateUi();
  1902. if (!noDialogs)
  1903. {
  1904. this.showSplash();
  1905. }
  1906. });
  1907. if (file != null)
  1908. {
  1909. try
  1910. {
  1911. // Workaround for delayed scroll repaint with min UI in Safari
  1912. if (mxClient.IS_SF && uiTheme == 'min')
  1913. {
  1914. this.diagramContainer.style.visibility = '';
  1915. }
  1916. // Order is significant, current file needed for correct
  1917. // file format for initial save after starting realtime
  1918. this.openingFile = true;
  1919. this.setCurrentFile(file);
  1920. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1921. file.addListener('contentChanged', this.descriptorChangedListener);
  1922. file.open();
  1923. delete this.openingFile;
  1924. // DescriptorChanged updates the enabled state of the graph
  1925. this.setGraphEnabled(true);
  1926. this.setMode(file.getMode());
  1927. this.editor.graph.model.prefix = Editor.guid() + '-';
  1928. this.editor.undoManager.clear();
  1929. this.descriptorChanged();
  1930. this.updateUi();
  1931. // Realtime files have a valid status message
  1932. if (!file.isEditable())
  1933. {
  1934. this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
  1935. mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
  1936. }
  1937. // Handles modified state after error of loading new file
  1938. else if (file.isModified())
  1939. {
  1940. file.addUnsavedStatus();
  1941. // Restores unsaved data
  1942. if (file.backupPatch != null)
  1943. {
  1944. file.patch([file.backupPatch]);
  1945. }
  1946. }
  1947. else
  1948. {
  1949. this.editor.setStatus('');
  1950. }
  1951. if (!this.editor.isChromelessView() || this.editor.editable)
  1952. {
  1953. this.editor.graph.selectUnlockedLayer();
  1954. this.showLayersDialog();
  1955. this.restoreLibraries();
  1956. // Workaround for no initial focus in FF
  1957. if (window.self !== window.top)
  1958. {
  1959. window.focus();
  1960. }
  1961. }
  1962. else if (this.editor.graph.isLightboxView())
  1963. {
  1964. this.lightboxFit();
  1965. }
  1966. if (this.chromelessResize)
  1967. {
  1968. this.chromelessResize();
  1969. }
  1970. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1971. result = true;
  1972. if (!this.isOffline() && file.getMode() != null)
  1973. {
  1974. EditorUi.logEvent({category: 'File', action: 'open', label:
  1975. file.getMode() + '.' + file.getSize()})
  1976. }
  1977. if (this.editor.editable && this.mode == file.getMode() &&
  1978. file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1979. {
  1980. try
  1981. {
  1982. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1983. }
  1984. catch (e)
  1985. {
  1986. // ignore
  1987. }
  1988. }
  1989. try
  1990. {
  1991. mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
  1992. mxSettings.save();
  1993. }
  1994. catch (e)
  1995. {
  1996. // ignore
  1997. }
  1998. }
  1999. catch (e)
  2000. {
  2001. this.fileLoadedError = e;
  2002. // Makes sure the file does not save the invalid UI model and overwrites anything important
  2003. if (window.console != null)
  2004. {
  2005. console.log('error in fileLoaded:', file, e);
  2006. }
  2007. if (EditorUi.enableLogging && !this.isOffline())
  2008. {
  2009. try
  2010. {
  2011. var img = new Image();
  2012. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  2013. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  2014. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  2015. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  2016. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  2017. }
  2018. catch (e)
  2019. {
  2020. // ignore
  2021. }
  2022. }
  2023. // Asynchronous handling of errors
  2024. var fn = mxUtils.bind(this, function()
  2025. {
  2026. // Removes URL parameter and reloads the page
  2027. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  2028. {
  2029. window.location.search = this.getSearch(['url']);
  2030. }
  2031. else if (oldFile != null)
  2032. {
  2033. this.fileLoaded(oldFile);
  2034. }
  2035. else
  2036. {
  2037. noFile();
  2038. }
  2039. });
  2040. if (!noDialogs)
  2041. {
  2042. this.handleError(e, mxResources.get('errorLoadingFile'), fn, true);
  2043. }
  2044. else
  2045. {
  2046. fn();
  2047. }
  2048. }
  2049. }
  2050. else
  2051. {
  2052. noFile();
  2053. }
  2054. return result;
  2055. };
  2056. /**
  2057. * Creates a hash value for the current file.
  2058. */
  2059. EditorUi.prototype.getHashValueForPages = function(pages, details)
  2060. {
  2061. // TODO: Avoid encoding to XML to make it faster
  2062. var hash = 0;
  2063. var model = new mxGraphModel();
  2064. var codec = new mxCodec();
  2065. if (details != null)
  2066. {
  2067. details.byteCount = 0;
  2068. details.attrCount = 0;
  2069. details.eltCount = 0;
  2070. details.nodeCount = 0;
  2071. }
  2072. for (var i = 0; i < pages.length; i++)
  2073. {
  2074. this.updatePageRoot(pages[i]);
  2075. var diagram = pages[i].node.cloneNode(false);
  2076. // FIXME: Check why names can be null in newer files
  2077. // ignore in hash and do not diff null names for now
  2078. diagram.removeAttribute('name');
  2079. // Model is only a holder for the root
  2080. model.root = pages[i].root;
  2081. var xmlNode = codec.encode(model);
  2082. this.editor.graph.saveViewState(pages[i].viewState, xmlNode, true);
  2083. // Local defaults may be different in files so ignore
  2084. xmlNode.removeAttribute('pageWidth');
  2085. xmlNode.removeAttribute('pageHeight');
  2086. diagram.appendChild(xmlNode);
  2087. if (details != null)
  2088. {
  2089. details.eltCount += diagram.getElementsByTagName('*').length;
  2090. details.nodeCount += diagram.getElementsByTagName('mxCell').length;
  2091. }
  2092. hash = ((hash << 5) - hash + this.hashValue(diagram, function(obj, key, value, isXml)
  2093. {
  2094. // Ignores JS machine rounding errors in known numeric attributes
  2095. // eg. 412.33333333333326 (Webkit/FF) == 412.33333333333325 (Edge/IE11)
  2096. if (isXml && (obj.nodeName == 'mxGeometry' || obj.nodeName == 'mxPoint') &&
  2097. (key == 'x' || key == 'y' || key == 'width' || key == 'height'))
  2098. {
  2099. return Math.round(value);
  2100. }
  2101. // Workaround for previous in patch written to mxCell in 10.0.23
  2102. else if (isXml && obj.nodeName == 'mxCell' && key == 'previous')
  2103. {
  2104. return null;
  2105. }
  2106. else
  2107. {
  2108. return value;
  2109. }
  2110. }, details)) << 0;
  2111. }
  2112. return hash;
  2113. };
  2114. /**
  2115. * Creates a hash value for the given object. Replacer returns the value of the
  2116. * property or attribute for the given object or XML node.
  2117. */
  2118. EditorUi.prototype.hashValue = function(obj, replacer, details)
  2119. {
  2120. var hash = 0;
  2121. // Checks for XML nodes
  2122. if (obj != null && typeof obj === 'object' && typeof obj.nodeType === 'number' &&
  2123. typeof obj.nodeName === 'string' && typeof obj.getAttribute === 'function')
  2124. {
  2125. if (obj.nodeName != null)
  2126. {
  2127. hash = hash ^ this.hashValue(obj.nodeName, replacer, details);
  2128. }
  2129. if (obj.attributes != null)
  2130. {
  2131. if (details != null)
  2132. {
  2133. details.attrCount += obj.attributes.length;
  2134. }
  2135. for (var i = 0; i < obj.attributes.length; i++)
  2136. {
  2137. var key = obj.attributes[i].name;
  2138. var value = (replacer != null) ? replacer(obj, key, obj.attributes[i].value, true) : obj.attributes[i].value;
  2139. if (value != null)
  2140. {
  2141. hash = hash ^ (this.hashValue(key, replacer, details) +
  2142. this.hashValue(value, replacer, details));
  2143. }
  2144. }
  2145. }
  2146. if (obj.childNodes != null)
  2147. {
  2148. for (var i = 0; i < obj.childNodes.length; i++)
  2149. {
  2150. hash = ((hash << 5) - hash + this.hashValue(
  2151. obj.childNodes[i], replacer, details)) << 0;
  2152. }
  2153. }
  2154. }
  2155. else if (obj != null && typeof obj !== 'function')
  2156. {
  2157. var str = String(obj);
  2158. var temp = 0;
  2159. if (details != null)
  2160. {
  2161. details.byteCount += str.length;
  2162. }
  2163. for (var i = 0; i < str.length; i++)
  2164. {
  2165. temp = ((temp << 5) - temp + str.charCodeAt(i)) << 0;
  2166. }
  2167. hash = hash ^ temp;
  2168. }
  2169. return hash;
  2170. };
  2171. /**
  2172. * Adds empty implementation
  2173. */
  2174. EditorUi.prototype.descriptorChanged = function()
  2175. {
  2176. // empty
  2177. };
  2178. /**
  2179. * Hook for subclassers.
  2180. */
  2181. EditorUi.prototype.restoreLibraries = function() { };
  2182. /**
  2183. * Hook for subclassers.
  2184. */
  2185. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn) { };
  2186. /**
  2187. *
  2188. */
  2189. EditorUi.prototype.isScratchpadEnabled = function()
  2190. {
  2191. return isLocalStorage || mxClient.IS_CHROMEAPP;
  2192. };
  2193. /**
  2194. * Shows or hides the scratchpad library.
  2195. */
  2196. EditorUi.prototype.toggleScratchpad = function()
  2197. {
  2198. if (this.isScratchpadEnabled())
  2199. {
  2200. if (this.scratchpad == null)
  2201. {
  2202. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  2203. {
  2204. if (xml == null)
  2205. {
  2206. xml = this.emptyLibraryXml;
  2207. }
  2208. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  2209. }));
  2210. }
  2211. else
  2212. {
  2213. this.closeLibrary(this.scratchpad);
  2214. }
  2215. }
  2216. };
  2217. /**
  2218. * Translates this point by the given vector.
  2219. *
  2220. * @param {number} dx X-coordinate of the translation.
  2221. * @param {number} dy Y-coordinate of the translation.
  2222. */
  2223. EditorUi.prototype.createLibraryDataFromImages = function(images)
  2224. {
  2225. var doc = mxUtils.createXmlDocument();
  2226. var library = doc.createElement('mxlibrary');
  2227. mxUtils.setTextContent(library, JSON.stringify(images));
  2228. doc.appendChild(library);
  2229. return mxUtils.getXml(doc);
  2230. };
  2231. /**
  2232. * Translates this point by the given vector.
  2233. *
  2234. * @param {number} dx X-coordinate of the translation.
  2235. * @param {number} dy Y-coordinate of the translation.
  2236. */
  2237. EditorUi.prototype.closeLibrary = function(file)
  2238. {
  2239. if (file != null)
  2240. {
  2241. this.removeLibrarySidebar(file.getHash());
  2242. if (file.constructor != LocalLibrary)
  2243. {
  2244. mxSettings.removeCustomLibrary(file.getHash());
  2245. }
  2246. if (file.title == '.scratchpad')
  2247. {
  2248. this.scratchpad = null;
  2249. }
  2250. }
  2251. };
  2252. /**
  2253. * Translates this point by the given vector.
  2254. *
  2255. * @param {number} dx X-coordinate of the translation.
  2256. * @param {number} dy Y-coordinate of the translation.
  2257. */
  2258. EditorUi.prototype.removeLibrarySidebar = function(id)
  2259. {
  2260. var elts = this.sidebar.palettes[id];
  2261. if (elts != null)
  2262. {
  2263. for (var i = 0; i < elts.length; i++)
  2264. {
  2265. elts[i].parentNode.removeChild(elts[i]);
  2266. }
  2267. delete this.sidebar.palettes[id];
  2268. }
  2269. };
  2270. /**
  2271. * Changes the position of the library in the sidebar
  2272. */
  2273. EditorUi.prototype.repositionLibrary = function(nextChild)
  2274. {
  2275. var c = this.sidebar.container;
  2276. if (nextChild == null)
  2277. {
  2278. var elts = this.sidebar.palettes['L.scratchpad'];
  2279. if (elts == null)
  2280. {
  2281. elts = this.sidebar.palettes['search'];
  2282. }
  2283. if (elts != null)
  2284. {
  2285. nextChild = elts[elts.length - 1].nextSibling;
  2286. }
  2287. }
  2288. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  2289. var content = c.lastChild;
  2290. var title = content.previousSibling;
  2291. c.insertBefore(content, nextChild);
  2292. c.insertBefore(title, content);
  2293. }
  2294. /**
  2295. * Translates this point by the given vector.
  2296. *
  2297. * @param {number} dx X-coordinate of the translation.
  2298. * @param {number} dy Y-coordinate of the translation.
  2299. */
  2300. EditorUi.prototype.loadLibrary = function(file)
  2301. {
  2302. var doc = mxUtils.parseXml(file.getData());
  2303. if (doc.documentElement.nodeName == 'mxlibrary')
  2304. {
  2305. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2306. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  2307. }
  2308. else
  2309. {
  2310. throw {message: mxResources.get('notALibraryFile')};
  2311. }
  2312. };
  2313. /**
  2314. * Translates this point by the given vector.
  2315. *
  2316. * @param {number} dx X-coordinate of the translation.
  2317. * @param {number} dy Y-coordinate of the translation.
  2318. */
  2319. EditorUi.prototype.getLibraryStorageHint = function(file)
  2320. {
  2321. return '';
  2322. };
  2323. /**
  2324. * Translates this point by the given vector.
  2325. *
  2326. * @param {number} dx X-coordinate of the translation.
  2327. * @param {number} dy Y-coordinate of the translation.
  2328. */
  2329. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  2330. {
  2331. if (this.sidebar == null)
  2332. {
  2333. return;
  2334. }
  2335. if (file.constructor != LocalLibrary)
  2336. {
  2337. mxSettings.addCustomLibrary(file.getHash());
  2338. }
  2339. if (file.title == '.scratchpad')
  2340. {
  2341. this.scratchpad = file;
  2342. }
  2343. var elts = this.sidebar.palettes[file.getHash()];
  2344. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  2345. // Removes existing sidebar entry for this library
  2346. this.removeLibrarySidebar(file.getHash());
  2347. var dropTarget = null;
  2348. var addImages = mxUtils.bind(this, function(imgs, content)
  2349. {
  2350. if (imgs.length == 0 && file.isEditable())
  2351. {
  2352. if (dropTarget == null)
  2353. {
  2354. dropTarget = document.createElement('div');
  2355. dropTarget.className = 'geDropTarget';
  2356. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  2357. }
  2358. content.appendChild(dropTarget);
  2359. }
  2360. else
  2361. {
  2362. this.addLibraryEntries(imgs, content);
  2363. }
  2364. });
  2365. // Adds entries to search index
  2366. // KNOWN: Existing entries are not replaced after edit of custom library
  2367. if (this.sidebar != null && images != null)
  2368. {
  2369. for (var i = 0; i < images.length; i++)
  2370. {
  2371. (mxUtils.bind(this, function(img)
  2372. {
  2373. var data = img.data;
  2374. if (data != null && img.title != null)
  2375. {
  2376. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2377. {
  2378. data = this.convertDataUri(data);
  2379. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2380. if (img.aspect == 'fixed')
  2381. {
  2382. s += 'aspect=fixed;'
  2383. }
  2384. return this.sidebar.createVertexTemplate(s + 'image=' +
  2385. data, img.w, img.h, '', img.title || '', false, false, true)
  2386. }));
  2387. }
  2388. else if (img.xml != null && img.title != null)
  2389. {
  2390. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2391. {
  2392. var cells = this.stringToCells(Graph.decompress(img.xml));
  2393. return this.sidebar.createVertexTemplateFromCells(
  2394. cells, img.w, img.h, img.title || '', true, false, true);
  2395. }));
  2396. }
  2397. }))(images[i]);
  2398. }
  2399. }
  2400. // Adds new sidebar entry for this library
  2401. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  2402. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  2403. {
  2404. addImages(images, content);
  2405. }));
  2406. this.repositionLibrary(nextSibling);
  2407. // Adds tooltip for backend
  2408. var title = contentDiv.parentNode.previousSibling;
  2409. var tip = title.getAttribute('title');
  2410. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  2411. {
  2412. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  2413. }
  2414. var buttons = document.createElement('div');
  2415. buttons.style.position = 'absolute';
  2416. buttons.style.right = '0px';
  2417. buttons.style.top = '0px';
  2418. buttons.style.padding = '8px'
  2419. // Workaround for CSS error in IE8 (standards and quirks)
  2420. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  2421. {
  2422. buttons.style.backgroundColor = 'inherit';
  2423. }
  2424. title.style.position = 'relative';
  2425. var btnWidth = 18;
  2426. var btn = document.createElement('img');
  2427. btn.setAttribute('src', Dialog.prototype.closeImage);
  2428. btn.setAttribute('title', mxResources.get('close'));
  2429. btn.setAttribute('valign', 'absmiddle');
  2430. btn.setAttribute('border', '0');
  2431. btn.style.margin = '0 3px';
  2432. var saveBtn = null;
  2433. if (file.title != '.scratchpad' || this.closableScratchpad)
  2434. {
  2435. buttons.appendChild(btn);
  2436. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  2437. {
  2438. // Workaround for close after any button click in IE8/quirks
  2439. if (!mxEvent.isConsumed(evt))
  2440. {
  2441. var fn = mxUtils.bind(this, function()
  2442. {
  2443. this.closeLibrary(file);
  2444. });
  2445. if (saveBtn != null)
  2446. {
  2447. this.confirm(mxResources.get('allChangesLost'), null, fn,
  2448. mxResources.get('cancel'), mxResources.get('discardChanges'));
  2449. }
  2450. else
  2451. {
  2452. fn();
  2453. }
  2454. mxEvent.consume(evt);
  2455. }
  2456. }));
  2457. }
  2458. if (file.isEditable())
  2459. {
  2460. var graph = this.editor.graph;
  2461. var spinBtn = null;
  2462. var editLibrary = mxUtils.bind(this, function(evt)
  2463. {
  2464. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  2465. mxEvent.consume(evt);
  2466. });
  2467. var saveLibrary = mxUtils.bind(this, function(evt)
  2468. {
  2469. file.setModified(true);
  2470. if (file.isAutosave())
  2471. {
  2472. if (spinBtn != null && spinBtn.parentNode != null)
  2473. {
  2474. spinBtn.parentNode.removeChild(spinBtn);
  2475. }
  2476. spinBtn = btn.cloneNode(false);
  2477. spinBtn.setAttribute('src', Editor.spinImage);
  2478. spinBtn.setAttribute('title', mxResources.get('saving'));
  2479. spinBtn.style.cursor = 'default';
  2480. spinBtn.style.marginRight = '2px';
  2481. spinBtn.style.marginTop = '-2px';
  2482. buttons.insertBefore(spinBtn, buttons.firstChild);
  2483. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2484. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  2485. {
  2486. if (spinBtn != null && spinBtn.parentNode != null)
  2487. {
  2488. spinBtn.parentNode.removeChild(spinBtn);
  2489. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2490. }
  2491. });
  2492. }
  2493. else if (saveBtn == null)
  2494. {
  2495. saveBtn = btn.cloneNode(false);
  2496. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  2497. saveBtn.setAttribute('title', mxResources.get('save'));
  2498. buttons.insertBefore(saveBtn, buttons.firstChild);
  2499. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  2500. {
  2501. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  2502. file.constructor == LocalLibrary, true, function()
  2503. {
  2504. if (saveBtn != null && !file.isModified())
  2505. {
  2506. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2507. saveBtn.parentNode.removeChild(saveBtn);
  2508. saveBtn = null;
  2509. }
  2510. });
  2511. mxEvent.consume(evt);
  2512. }));
  2513. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2514. }
  2515. });
  2516. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  2517. {
  2518. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  2519. // Translates cells to origin
  2520. for (var i = 0; i < cells.length; i++)
  2521. {
  2522. var geo = graph.getCellGeometry(cells[i]);
  2523. if (geo != null)
  2524. {
  2525. geo.translate(-bounds.x, -bounds.y);
  2526. }
  2527. }
  2528. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  2529. cells, bounds.width, bounds.height, title || '', true, false, false));
  2530. var xml = Graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  2531. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  2532. if (title != null)
  2533. {
  2534. entry.title = title;
  2535. }
  2536. images.push(entry);
  2537. saveLibrary(evt);
  2538. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2539. {
  2540. dropTarget.parentNode.removeChild(dropTarget);
  2541. dropTarget = null;
  2542. }
  2543. });
  2544. var addSelection = mxUtils.bind(this, function(evt)
  2545. {
  2546. if (!graph.isSelectionEmpty())
  2547. {
  2548. var cells = graph.getSelectionCells();
  2549. var bounds = graph.view.getBounds(cells);
  2550. var s = graph.view.scale;
  2551. bounds.x /= s;
  2552. bounds.y /= s;
  2553. bounds.width /= s;
  2554. bounds.height /= s;
  2555. bounds.x -= graph.view.translate.x;
  2556. bounds.y -= graph.view.translate.y;
  2557. addCells(cells, bounds);
  2558. }
  2559. else if (graph.getRubberband().isActive())
  2560. {
  2561. graph.getRubberband().execute(evt);
  2562. graph.getRubberband().reset();
  2563. }
  2564. else
  2565. {
  2566. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  2567. }
  2568. mxEvent.consume(evt);
  2569. });
  2570. // Adds drop handler from graph
  2571. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  2572. {
  2573. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  2574. {
  2575. graph.graphHandler.shape.node.style.visibility = 'hidden';
  2576. contentDiv.style.backgroundColor = '#f1f3f4';
  2577. contentDiv.style.cursor = 'copy';
  2578. graph.panningManager.stop();
  2579. graph.autoScroll = false;
  2580. if (graph.graphHandler.guide != null)
  2581. {
  2582. graph.graphHandler.guide.setVisible(false);
  2583. }
  2584. if (graph.graphHandler.hint != null)
  2585. {
  2586. graph.graphHandler.hint.style.visibility = 'hidden';
  2587. }
  2588. mxEvent.consume(evt);
  2589. }
  2590. }), mxUtils.bind(this, function(evt)
  2591. {
  2592. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  2593. {
  2594. contentDiv.style.backgroundColor = '';
  2595. contentDiv.style.cursor = 'default';
  2596. this.sidebar.showTooltips = true;
  2597. graph.panningManager.stop();
  2598. graph.graphHandler.reset();
  2599. graph.isMouseDown = false;
  2600. graph.autoScroll = true;
  2601. addSelection(evt);
  2602. mxEvent.consume(evt);
  2603. }
  2604. }));
  2605. // Handles mouse leaving the library and restoring move
  2606. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  2607. {
  2608. if (graph.isMouseDown && graph.graphHandler.shape != null)
  2609. {
  2610. graph.graphHandler.shape.node.style.visibility = 'visible';
  2611. contentDiv.style.backgroundColor = '';
  2612. contentDiv.style.cursor = '';
  2613. graph.autoScroll = true;
  2614. if (graph.graphHandler.guide != null)
  2615. {
  2616. graph.graphHandler.guide.setVisible(true);
  2617. }
  2618. if (graph.graphHandler.hint != null)
  2619. {
  2620. graph.graphHandler.hint.style.visibility = 'visible';
  2621. }
  2622. }
  2623. }));
  2624. // Adds drop handler from filesystem
  2625. if (Graph.fileSupport)
  2626. {
  2627. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  2628. {
  2629. contentDiv.style.backgroundColor = '#f1f3f4';
  2630. evt.dataTransfer.dropEffect = 'copy';
  2631. contentDiv.style.cursor = 'copy';
  2632. this.sidebar.hideTooltip();
  2633. evt.stopPropagation();
  2634. evt.preventDefault();
  2635. }));
  2636. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  2637. {
  2638. contentDiv.style.cursor = '';
  2639. contentDiv.style.backgroundColor = '';
  2640. if (evt.dataTransfer.files.length > 0)
  2641. {
  2642. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  2643. {
  2644. if (data != null && mimeType.substring(0, 6) == 'image/')
  2645. {
  2646. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  2647. this.convertDataUri(data);
  2648. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  2649. cells[0].vertex = true;
  2650. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  2651. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2652. {
  2653. dropTarget.parentNode.removeChild(dropTarget);
  2654. dropTarget = null;
  2655. }
  2656. }
  2657. else
  2658. {
  2659. var done = false;
  2660. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  2661. {
  2662. if (theData != null && theMimeType == 'text/xml')
  2663. {
  2664. var doc = mxUtils.parseXml(theData);
  2665. if (doc.documentElement.nodeName == 'mxlibrary')
  2666. {
  2667. try
  2668. {
  2669. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2670. addImages(temp, contentDiv);
  2671. images = images.concat(temp);
  2672. saveLibrary(evt);
  2673. this.spinner.stop();
  2674. done = true;
  2675. }
  2676. catch (e)
  2677. {
  2678. // ignore
  2679. }
  2680. }
  2681. else if (doc.documentElement.nodeName == 'mxfile')
  2682. {
  2683. try
  2684. {
  2685. var pages = doc.documentElement.getElementsByTagName('diagram');
  2686. for (var i = 0; i < pages.length; i++)
  2687. {
  2688. var temp = mxUtils.getTextContent(pages[i]);
  2689. var cells = this.stringToCells(Graph.decompress(temp));
  2690. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  2691. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  2692. }
  2693. done = true;
  2694. }
  2695. catch (e)
  2696. {
  2697. if (window.console != null)
  2698. {
  2699. console.log('error in drop handler:', e);
  2700. }
  2701. }
  2702. }
  2703. }
  2704. if (!done)
  2705. {
  2706. this.spinner.stop();
  2707. this.handleError({message: mxResources.get('errorLoadingFile')})
  2708. }
  2709. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2710. {
  2711. dropTarget.parentNode.removeChild(dropTarget);
  2712. dropTarget = null;
  2713. }
  2714. });
  2715. if (file != null && img != null && ((/(\.v(dx|sdx?))($|\?)/i.test(img)) || /(\.vs(x|sx?))($|\?)/i.test(img)))
  2716. {
  2717. this.importVisio(file, function(xml)
  2718. {
  2719. doImport(xml, 'text/xml');
  2720. }, null, img);
  2721. }
  2722. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  2723. {
  2724. this.parseFile(file, mxUtils.bind(this, function(xhr)
  2725. {
  2726. if (xhr.readyState == 4)
  2727. {
  2728. this.spinner.stop();
  2729. if (xhr.status >= 200 && xhr.status <= 299)
  2730. {
  2731. doImport(xhr.responseText, 'text/xml');
  2732. }
  2733. else
  2734. {
  2735. this.handleError({message: mxResources.get((xhr.status == 413) ?
  2736. 'drawingTooLarge' : 'invalidOrMissingFile')},
  2737. mxResources.get('errorLoadingFile'));
  2738. }
  2739. }
  2740. }));
  2741. }
  2742. else
  2743. {
  2744. doImport(data, mimeType);
  2745. }
  2746. }
  2747. }));
  2748. }
  2749. evt.stopPropagation();
  2750. evt.preventDefault();
  2751. }));
  2752. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  2753. {
  2754. contentDiv.style.cursor = '';
  2755. contentDiv.style.backgroundColor = '';
  2756. evt.stopPropagation();
  2757. evt.preventDefault();
  2758. });
  2759. }
  2760. btn = btn.cloneNode(false);
  2761. btn.setAttribute('src', Editor.editImage);
  2762. btn.setAttribute('title', mxResources.get('edit'));
  2763. buttons.insertBefore(btn, buttons.firstChild);
  2764. mxEvent.addListener(btn, 'click', editLibrary);
  2765. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  2766. {
  2767. if (mxEvent.getSource(evt) == contentDiv)
  2768. {
  2769. editLibrary(evt);
  2770. }
  2771. });
  2772. var btn2 = btn.cloneNode(false);
  2773. btn2.setAttribute('src', Editor.plusImage);
  2774. btn2.setAttribute('title', mxResources.get('add'));
  2775. buttons.insertBefore(btn2, buttons.firstChild);
  2776. mxEvent.addListener(btn2, 'click', addSelection);
  2777. if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
  2778. {
  2779. var link = document.createElement('span');
  2780. link.setAttribute('title', mxResources.get('help'));
  2781. link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
  2782. mxUtils.write(link, '?');
  2783. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  2784. {
  2785. this.openLink(EditorUi.scratchpadHelpLink);
  2786. mxEvent.consume(evt);
  2787. }));
  2788. buttons.insertBefore(link, buttons.firstChild);
  2789. }
  2790. }
  2791. title.appendChild(buttons);
  2792. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2793. };
  2794. /**
  2795. * Adds the library entries to the given DOM node.
  2796. */
  2797. EditorUi.prototype.addLibraryEntries = function(imgs, content)
  2798. {
  2799. for (var i = 0; i < imgs.length; i++)
  2800. {
  2801. var img = imgs[i];
  2802. var data = img.data;
  2803. if (data != null)
  2804. {
  2805. data = this.convertDataUri(data);
  2806. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2807. if (img.aspect == 'fixed')
  2808. {
  2809. s += 'aspect=fixed;'
  2810. }
  2811. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  2812. data, img.w, img.h, '', img.title || '', false, false, true));
  2813. }
  2814. else if (img.xml != null)
  2815. {
  2816. var cells = this.stringToCells(Graph.decompress(img.xml));
  2817. if (cells.length > 0)
  2818. {
  2819. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  2820. cells, img.w, img.h, img.title || '', true, false, true));
  2821. }
  2822. }
  2823. }
  2824. };
  2825. /**
  2826. * Extracts the resource for the current language from the given multi language
  2827. * resource object of the form {es: "...", de: "...", main: "..."} where the keys
  2828. * are country codes and main defines the fallback if no resource for the current
  2829. * country code exists.
  2830. */
  2831. EditorUi.prototype.getResource = function(obj)
  2832. {
  2833. return (obj != null) ? (obj[mxLanguage] || obj.main) : null;
  2834. };
  2835. /**
  2836. * EditorUi Overrides
  2837. */
  2838. EditorUi.prototype.footerHeight = 0;
  2839. if (urlParams['offline'] == '1' || EditorUi.isElectronApp)
  2840. {
  2841. //EditorUi.prototype.footerHeight = 4;
  2842. }
  2843. else
  2844. {
  2845. if (urlParams['savesidebar'] == '1')
  2846. {
  2847. Sidebar.prototype.thumbWidth = 64;
  2848. Sidebar.prototype.thumbHeight = 64;
  2849. }
  2850. //EditorUi.prototype.footerHeight = (screen.width >= 760 && screen.height >= 240) ? 46 : 0;
  2851. // Fetches footer from page
  2852. EditorUi.prototype.createFooter = function()
  2853. {
  2854. var footer = document.getElementById('geFooter');
  2855. if (footer != null)
  2856. {
  2857. // footer.style.visibility = 'hidden';
  2858. //
  2859. // // Adds button to hide the footer
  2860. // var img = document.createElement('img');
  2861. // img.setAttribute('border', '0');
  2862. // img.setAttribute('src', Dialog.prototype.closeImage);
  2863. // img.setAttribute('title', mxResources.get('hide'));
  2864. // footer.appendChild(img)
  2865. //
  2866. // if (mxClient.IS_QUIRKS)
  2867. // {
  2868. // img.style.position = 'relative';
  2869. // img.style.styleFloat = 'right';
  2870. // img.style.top = '-30px';
  2871. // img.style.left = '164px';
  2872. // img.style.cursor = 'pointer';
  2873. // }
  2874. //
  2875. // mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  2876. // {
  2877. // this.hideFooter();
  2878. // }));
  2879. }
  2880. return footer;
  2881. };
  2882. }
  2883. EditorUi.initTheme = function()
  2884. {
  2885. if (uiTheme == 'atlas')
  2886. {
  2887. mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
  2888. if (typeof Toolbar !== 'undefined')
  2889. {
  2890. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  2891. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  2892. }
  2893. Editor.prototype.initialTopSpacing = 3;
  2894. EditorUi.prototype.menubarHeight = 41;
  2895. EditorUi.prototype.toolbarHeight = 38;
  2896. }
  2897. else if (uiTheme == 'dark')
  2898. {
  2899. mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
  2900. Dialog.backdropColor = '#2a2a2a';
  2901. Graph.prototype.defaultThemeName = 'darkTheme';
  2902. Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
  2903. Graph.prototype.defaultPageBorderColor = '#505759';
  2904. Format.prototype.inactiveTabBackgroundColor = 'black';
  2905. BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
  2906. Sidebar.prototype.dragPreviewBorder = '1px dashed #cccccc';
  2907. mxGraphHandler.prototype.previewColor = '#cccccc';
  2908. StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
  2909. if (mxClient.IS_SVG)
  2910. {
  2911. Editor.helpImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAP1BMVEUAAAD///////////////////////////////////////////////////////////////////////////////9Du/pqAAAAFXRSTlMAT30qCJRBboyDZyCgRzUUdF46MJlgXETgAAAAeklEQVQY022O2w4DIQhEQUURda/9/28tUO2+7CQS5sgQ4F1RapX78YUwRqQjTU8ILqQfKerTKTvACJ4nLX3krt+8aS82oI8aQC4KavRgtvEW/mDvsICgA03PSGRr79MqX1YPNIxzjyqtw8ZnnRo4t5a5undtJYRywau+ds4Cyza3E6YAAAAASUVORK5CYII=';
  2912. Editor.checkmarkImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAARVBMVEUAAACZmZkICAgEBASNjY2Dg4MYGBiTk5N5eXl1dXVmZmZQUFBCQkI3NzceHh4MDAykpKSJiYl+fn5sbGxaWlo/Pz8SEhK96uPlAAAAAXRSTlMAQObYZgAAAE5JREFUGNPFzTcSgDAQQ1HJGUfy/Y9K7V1qeOUfzQifCQZai1XHaz11LFysbDbzgDSSWMZiETz3+b8yNUc/MMsktxuC8XQBSncdLwz+8gCCggGXzBcozAAAAABJRU5ErkJggg==';
  2913. }
  2914. }
  2915. };
  2916. EditorUi.initTheme();
  2917. /**
  2918. * Hides the footer.
  2919. */
  2920. EditorUi.prototype.hideFooter = function()
  2921. {
  2922. var footer = document.getElementById('geFooter');
  2923. if (footer != null)
  2924. {
  2925. this.footerHeight = 0;
  2926. footer.style.display = 'none';
  2927. this.refresh();
  2928. }
  2929. };
  2930. /**
  2931. * Shows the footer.
  2932. */
  2933. EditorUi.prototype.showFooter = function(height)
  2934. {
  2935. var footer = document.getElementById('geFooter');
  2936. if (footer != null)
  2937. {
  2938. this.footerHeight = height;
  2939. footer.style.display = 'inline';
  2940. this.refresh();
  2941. }
  2942. };
  2943. /**
  2944. * Overrides image dialog to add image search and Google+.
  2945. */
  2946. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  2947. {
  2948. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  2949. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  2950. this.showDialog(dlg.container, (Graph.fileSupport) ? 440 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
  2951. dlg.init();
  2952. };
  2953. /**
  2954. * Hides the current menu.
  2955. */
  2956. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  2957. {
  2958. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  2959. {
  2960. var change = new ChangePageSetup(this, null, image);
  2961. change.ignoreColor = true;
  2962. this.editor.graph.model.execute(change);
  2963. });
  2964. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  2965. {
  2966. apply(image);
  2967. }));
  2968. this.showDialog(dlg.container, 360, 200, true, true);
  2969. dlg.init();
  2970. };
  2971. /**
  2972. * Hides the current menu.
  2973. */
  2974. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  2975. {
  2976. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  2977. this.showDialog(dlg.container, 640, 440, true, false, mxUtils.bind(this, function(cancel)
  2978. {
  2979. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  2980. {
  2981. this.showSplash();
  2982. }
  2983. }));
  2984. dlg.init();
  2985. };
  2986. /**
  2987. * Overridden to update after view state changes.
  2988. */
  2989. var editorUiCreateFormat = EditorUi.prototype.createFormat;
  2990. EditorUi.prototype.createFormat = function(container)
  2991. {
  2992. var format = editorUiCreateFormat.apply(this, arguments);
  2993. this.editor.graph.addListener('viewStateChanged', mxUtils.bind(this, function(evt)
  2994. {
  2995. if (this.editor.graph.isSelectionEmpty())
  2996. {
  2997. format.refresh();
  2998. }
  2999. }));
  3000. return format;
  3001. };
  3002. /**
  3003. * Hook for sidebar footer container.
  3004. */
  3005. EditorUi.prototype.createSidebarFooterContainer = function()
  3006. {
  3007. var div = this.createDiv('geSidebarContainer geSidebarFooter');
  3008. div.style.position = 'absolute';
  3009. div.style.overflow = 'hidden';
  3010. var elt2 = document.createElement('a');
  3011. elt2.className = 'geTitle';
  3012. elt2.style.color = '#188038';
  3013. elt2.style.height = '100%';
  3014. elt2.style.paddingTop = '9px';
  3015. elt2.innerHTML = '<span style="font-size:18px;margin-right:5px;">+</span>';
  3016. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  3017. // Prevents focus
  3018. mxEvent.addListener(elt2, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
  3019. mxUtils.bind(this, function(evt)
  3020. {
  3021. evt.preventDefault();
  3022. }));
  3023. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  3024. {
  3025. this.actions.get('shapes').funct();
  3026. mxEvent.consume(evt);
  3027. }));
  3028. div.appendChild(elt2);
  3029. return div;
  3030. };
  3031. /**
  3032. * Translates this point by the given vector.
  3033. *
  3034. * @param {number} dx X-coordinate of the translation.
  3035. * @param {number} dy Y-coordinate of the translation.
  3036. */
  3037. EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose)
  3038. {
  3039. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3040. var e = (resp != null && resp.error != null) ? resp.error : resp;
  3041. if (e != null || title != null)
  3042. {
  3043. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  3044. var btn = mxResources.get('ok');
  3045. var retry = null;
  3046. title = (title != null) ? title : mxResources.get('error');
  3047. if (e != null)
  3048. {
  3049. if (e.retry != null)
  3050. {
  3051. btn = mxResources.get('cancel');
  3052. retry = function()
  3053. {
  3054. resume();
  3055. e.retry();
  3056. };
  3057. }
  3058. if (e.code == 404 || e.status == 404 || e.code == 403)
  3059. {
  3060. if (e.code == 403)
  3061. {
  3062. if (e.message != null)
  3063. {
  3064. msg = mxUtils.htmlEntities(e.message);
  3065. }
  3066. else
  3067. {
  3068. msg = mxUtils.htmlEntities(mxResources.get('accessDenied'));
  3069. }
  3070. }
  3071. else
  3072. {
  3073. msg = mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied'));
  3074. }
  3075. var id = window.location.hash;
  3076. if (id != null && id.substring(0, 2) == '#G' && resp != null && resp.error != null &&
  3077. resp.error.errors != null && resp.error.errors.length > 0 &&
  3078. resp.error.errors[0].reason == 'fileAccess')
  3079. {
  3080. id = id.substring(2);
  3081. // Special case where the button must have a different label and function
  3082. this.showError(title, msg, mxResources.get('cancel'), null, retry,
  3083. mxResources.get('tryOpeningViaThisPage'), mxUtils.bind(this, function()
  3084. {
  3085. this.editor.graph.openLink('https://drive.google.com/open?id=' + id);
  3086. }), null, null, 380);
  3087. return;
  3088. }
  3089. }
  3090. else if (e.message != null)
  3091. {
  3092. msg = mxUtils.htmlEntities(e.message);
  3093. }
  3094. else if (e.response != null && e.response.error != null)
  3095. {
  3096. msg = mxUtils.htmlEntities(e.response.error);
  3097. }
  3098. else if (window.App !== 'undefined')
  3099. {
  3100. if (e.code == App.ERROR_TIMEOUT)
  3101. {
  3102. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  3103. }
  3104. else if (e.code == App.ERROR_BUSY)
  3105. {
  3106. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  3107. }
  3108. }
  3109. }
  3110. this.showError(title, msg, btn, fn, retry, null, null, null, null,
  3111. null, null, null, (invokeFnOnClose) ? fn : null);
  3112. }
  3113. else if (fn != null)
  3114. {
  3115. fn();
  3116. }
  3117. };
  3118. /**
  3119. * Translates this point by the given vector.
  3120. *
  3121. * @param {number} dx X-coordinate of the translation.
  3122. * @param {number} dy Y-coordinate of the translation.
  3123. */
  3124. EditorUi.prototype.showError = function(title, msg, btn, fn, retry, btn2, fn2, btn3, fn3, w, h, hide, onClose)
  3125. {
  3126. var height = (msg != null && msg.length > 120) ? 180 : 150;
  3127. var dlg = new ErrorDialog(this, title, msg, btn || mxResources.get('ok'),
  3128. fn, retry, btn2, fn2, hide, btn3, fn3);
  3129. this.showDialog(dlg.container, w || 340, h || ((msg != null && msg.length > 120) ?
  3130. 180 : 150), true, false, onClose);
  3131. dlg.init();
  3132. };
  3133. /**
  3134. * Translates this point by the given vector.
  3135. *
  3136. * @param {number} dx X-coordinate of the translation.
  3137. * @param {number} dy Y-coordinate of the translation.
  3138. */
  3139. EditorUi.prototype.alert = function(msg, fn)
  3140. {
  3141. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  3142. this.showDialog(dlg.container, 340, 100, true, false);
  3143. dlg.init();
  3144. };
  3145. /**
  3146. * Translates this point by the given vector.
  3147. *
  3148. * @param {number} dx X-coordinate of the translation.
  3149. * @param {number} dy Y-coordinate of the translation.
  3150. */
  3151. EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel, closable)
  3152. {
  3153. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3154. var dlg = new ConfirmDialog(this, msg, function()
  3155. {
  3156. resume();
  3157. if (okFn != null)
  3158. {
  3159. okFn();
  3160. }
  3161. }, function()
  3162. {
  3163. resume();
  3164. if (cancelFn != null)
  3165. {
  3166. cancelFn();
  3167. }
  3168. }, okLabel, cancelLabel);
  3169. this.showDialog(dlg.container, 340, 90, true, closable);
  3170. dlg.init();
  3171. };
  3172. /**
  3173. * Translates this point by the given vector.
  3174. *
  3175. * @param {number} dx X-coordinate of the translation.
  3176. * @param {number} dy Y-coordinate of the translation.
  3177. */
  3178. EditorUi.prototype.setCurrentFile = function(file)
  3179. {
  3180. this.currentFile = file;
  3181. };
  3182. /**
  3183. * Translates this point by the given vector.
  3184. *
  3185. * @param {number} dx X-coordinate of the translation.
  3186. * @param {number} dy Y-coordinate of the translation.
  3187. */
  3188. EditorUi.prototype.getCurrentFile = function()
  3189. {
  3190. return this.currentFile;
  3191. };
  3192. /**
  3193. * Handling for canvas export.
  3194. */
  3195. /**
  3196. * See fixme in convertMath for client-side image generation with math.
  3197. */
  3198. EditorUi.prototype.isExportToCanvas = function()
  3199. {
  3200. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  3201. };
  3202. /**
  3203. * Translates this point by the given vector.
  3204. *
  3205. * @param {number} dx X-coordinate of the translation.
  3206. * @param {number} dy Y-coordinate of the translation.
  3207. */
  3208. EditorUi.prototype.createSvgDataUri = function(svg)
  3209. {
  3210. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  3211. };
  3212. /**
  3213. *
  3214. */
  3215. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  3216. {
  3217. var data = canvas.toDataURL('image/' + format);
  3218. // Checks if output is invalid or empty
  3219. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  3220. {
  3221. throw {message: 'Invalid image'};
  3222. }
  3223. if (xml != null)
  3224. {
  3225. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(Graph.compress(xml)));
  3226. }
  3227. return data;
  3228. };
  3229. /**
  3230. *
  3231. */
  3232. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  3233. {
  3234. var ext = ((format == 'jpeg') ? 'jpg' : format);
  3235. var filename = this.getBaseFilename() + '.' + ext;
  3236. var data = this.createImageDataUri(canvas, xml, format);
  3237. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  3238. };
  3239. /**
  3240. * Returns true if files should be saved using <saveLocalFile>.
  3241. */
  3242. EditorUi.prototype.isLocalFileSave = function()
  3243. {
  3244. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  3245. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  3246. document.documentMode != 9 && document.documentMode != 8 &&
  3247. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  3248. this.isOfflineApp() || mxClient.IS_IOS);
  3249. };
  3250. /**
  3251. * Translates this point by the given vector.
  3252. *
  3253. * @param {number} dx X-coordinate of the translation.
  3254. * @param {number} dy Y-coordinate of the translation.
  3255. */
  3256. EditorUi.prototype.showTextDialog = function(title, text)
  3257. {
  3258. var dlg = new TextareaDialog(this, title, text, null, null, mxResources.get('close'));
  3259. dlg.textarea.style.width = '600px';
  3260. dlg.textarea.style.height = '380px';
  3261. this.showDialog(dlg.container, 620, 460, true, true);
  3262. dlg.init();
  3263. document.execCommand('selectall', false, null);
  3264. };
  3265. /**
  3266. * Translates this point by the given vector.
  3267. *
  3268. * @param {number} dx X-coordinate of the translation.
  3269. * @param {number} dy Y-coordinate of the translation.
  3270. */
  3271. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  3272. {
  3273. // Newer versions of IE
  3274. if (window.Blob && navigator.msSaveOrOpenBlob)
  3275. {
  3276. var blob = (base64Encoded) ?
  3277. this.base64ToBlob(data, mimeType) :
  3278. new Blob([data], {type: mimeType})
  3279. navigator.msSaveOrOpenBlob(blob, filename);
  3280. }
  3281. // Older versions of IE (binary not supported)
  3282. else if (mxClient.IS_IE)
  3283. {
  3284. var win = window.open('about:blank', '_blank');
  3285. if (win == null)
  3286. {
  3287. mxUtils.popup(data, true);
  3288. }
  3289. else
  3290. {
  3291. win.document.write(data);
  3292. win.document.close();
  3293. win.document.execCommand('SaveAs', true, filename);
  3294. win.close();
  3295. }
  3296. }
  3297. // else if (mxClient.IS_IOS)
  3298. // {
  3299. // this.showTextDialog(filename + ':', data);
  3300. // }
  3301. else
  3302. {
  3303. var a = document.createElement('a');
  3304. // Workaround for mxXmlRequest.simulate no longer working in Safari/PaleMoon
  3305. // if this is used (ie PNG export broken after XML export in Safari/PaleMoon).
  3306. var useDownload = !mxClient.IS_SF && navigator.userAgent.indexOf("PaleMoon/") < 0 &&
  3307. typeof a.download !== 'undefined';
  3308. // Workaround for Chromium 65 cross-domain anchor download issue
  3309. if (mxClient.IS_GC)
  3310. {
  3311. var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
  3312. var vers = raw ? parseInt(raw[2], 10) : false;
  3313. useDownload = vers == 65 ? false : useDownload;
  3314. }
  3315. if (useDownload || this.isOffline())
  3316. {
  3317. a.href = URL.createObjectURL((base64Encoded) ?
  3318. this.base64ToBlob(data, mimeType) :
  3319. new Blob([data], {type: mimeType}));
  3320. if (useDownload)
  3321. {
  3322. a.download = filename;
  3323. }
  3324. else
  3325. {
  3326. // Workaround for same window in Safari
  3327. a.setAttribute('target', '_blank');
  3328. }
  3329. document.body.appendChild(a);
  3330. try
  3331. {
  3332. window.setTimeout(function()
  3333. {
  3334. URL.revokeObjectURL(a.href);
  3335. }, 0);
  3336. a.click();
  3337. a.parentNode.removeChild(a);
  3338. }
  3339. catch (e)
  3340. {
  3341. // ignore
  3342. }
  3343. }
  3344. else
  3345. {
  3346. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  3347. req.simulate(document, '_blank');
  3348. }
  3349. }
  3350. };
  3351. /**
  3352. * Translates this point by the given vector.
  3353. *
  3354. * @param {number} dx X-coordinate of the translation.
  3355. * @param {number} dy Y-coordinate of the translation.
  3356. */
  3357. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  3358. {
  3359. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  3360. 'data=' + encodeURIComponent(Graph.compress(data));
  3361. return new mxXmlRequest(SAVE_URL, param +
  3362. ((mimeType != null) ? '&mime=' + mimeType : '') +
  3363. ((format != null) ? '&format=' + format : '') +
  3364. ((base64Response != null) ? '&base64=' + base64Response : '') +
  3365. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  3366. ((base64Encoded) ? '&binary=1' : ''));
  3367. };
  3368. /**
  3369. * Translates this point by the given vector.
  3370. *
  3371. * @param {number} dx X-coordinate of the translation.
  3372. * @param {number} dy Y-coordinate of the translation.
  3373. */
  3374. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  3375. {
  3376. contentType = contentType || '';
  3377. var sliceSize = 1024;
  3378. var byteCharacters = atob(base64Data);
  3379. var bytesLength = byteCharacters.length;
  3380. var slicesCount = Math.ceil(bytesLength / sliceSize);
  3381. var byteArrays = new Array(slicesCount);
  3382. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  3383. {
  3384. var begin = sliceIndex * sliceSize;
  3385. var end = Math.min(begin + sliceSize, bytesLength);
  3386. var bytes = new Array(end - begin);
  3387. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  3388. {
  3389. bytes[i] = byteCharacters[offset].charCodeAt(0);
  3390. }
  3391. byteArrays[sliceIndex] = new Uint8Array(bytes);
  3392. }
  3393. return new Blob(byteArrays, {type: contentType});
  3394. };
  3395. /**
  3396. * Translates this point by the given vector.
  3397. *
  3398. * @param {number} dx X-coordinate of the translation.
  3399. * @param {number} dy Y-coordinate of the translation.
  3400. */
  3401. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab)
  3402. {
  3403. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  3404. allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  3405. var count = this.getServiceCount(allowBrowser);
  3406. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3407. {
  3408. try
  3409. {
  3410. // Opens a new window
  3411. if (mode == '_blank')
  3412. {
  3413. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  3414. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  3415. {
  3416. this.openInNewWindow(data, mimeType, base64Encoded);
  3417. }
  3418. else
  3419. {
  3420. var win = window.open('about:blank');
  3421. if (win == null)
  3422. {
  3423. mxUtils.popup(data, true);
  3424. }
  3425. else
  3426. {
  3427. win.document.write(mxUtils.htmlEntities(data, false));
  3428. win.document.close();
  3429. }
  3430. }
  3431. }
  3432. else if (mode == App.MODE_DEVICE || mode == 'download')
  3433. {
  3434. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  3435. }
  3436. else if (newTitle != null && newTitle.length > 0)
  3437. {
  3438. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3439. {
  3440. try
  3441. {
  3442. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  3443. }
  3444. catch (e)
  3445. {
  3446. this.handleError(e);
  3447. }
  3448. }));
  3449. }
  3450. }
  3451. catch (e)
  3452. {
  3453. this.handleError(e);
  3454. }
  3455. }), mxUtils.bind(this, function()
  3456. {
  3457. this.hideDialog();
  3458. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
  3459. null, count > 1, (count > 4 && (!allowBrowser || count < 6)) ? 3 : 4, data, mimeType, base64Encoded);
  3460. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3461. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3462. this.showDialog(dlg.container, 420, height, true, true);
  3463. dlg.init();
  3464. };
  3465. /**
  3466. *
  3467. */
  3468. EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
  3469. {
  3470. // In Google Chrome 60 the code from below produces a blank window
  3471. if (mxClient.IS_GC || mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  3472. {
  3473. var win = window.open('about:blank');
  3474. if (win == null || win.document == null)
  3475. {
  3476. mxUtils.popup(data, true);
  3477. }
  3478. else
  3479. {
  3480. // Workaround for broken images in SVG output in Chrome
  3481. if (mimeType == 'image/svg+xml')
  3482. {
  3483. win.document.write('<html>' + data + '</html>');
  3484. }
  3485. else
  3486. {
  3487. win.document.write('<html><img src="data:' +
  3488. mimeType + ((base64Encoded) ? ';base64,' +
  3489. data : ';charset=utf8,' + encodeURIComponent(data)) +
  3490. '"/></html>');
  3491. }
  3492. win.document.close();
  3493. }
  3494. }
  3495. else
  3496. {
  3497. // win.open is workaround for cleared contents in Chrome after delay
  3498. // when using location.replace
  3499. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  3500. data : ';charset=utf8,' + encodeURIComponent(data)));
  3501. if (win == null || win.document == null)
  3502. {
  3503. mxUtils.popup(data, true);
  3504. }
  3505. }
  3506. };
  3507. var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
  3508. /**
  3509. * Creates a temporary graph instance for rendering off-screen content.
  3510. */
  3511. EditorUi.prototype.addChromelessToolbarItems = function(addButton)
  3512. {
  3513. if (this.isExportToCanvas())
  3514. {
  3515. this.exportDialog = null;
  3516. var exportButton = addButton(mxUtils.bind(this, function(evt)
  3517. {
  3518. var clickHandler = mxUtils.bind(this, function()
  3519. {
  3520. mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
  3521. if (this.exportDialog != null)
  3522. {
  3523. this.exportDialog.parentNode.removeChild(this.exportDialog);
  3524. this.exportDialog = null;
  3525. }
  3526. });
  3527. if (this.exportDialog != null)
  3528. {
  3529. clickHandler.apply(this);
  3530. }
  3531. else
  3532. {
  3533. this.exportDialog = document.createElement('div');
  3534. var r = exportButton.getBoundingClientRect();
  3535. mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
  3536. this.exportDialog.style.position = 'fixed';
  3537. this.exportDialog.style.textAlign = 'center';
  3538. this.exportDialog.style.fontFamily = 'Helvetica,Arial';
  3539. this.exportDialog.style.backgroundColor = '#000000';
  3540. this.exportDialog.style.width = '50px';
  3541. this.exportDialog.style.height = '50px';
  3542. this.exportDialog.style.padding = '4px 2px 4px 2px';
  3543. this.exportDialog.style.color = '#ffffff';
  3544. mxUtils.setOpacity(this.exportDialog, 70);
  3545. this.exportDialog.style.left = r.left + 'px';
  3546. this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  3547. this.chromelessToolbar.offsetHeight + 4 + 'px';
  3548. // Puts the dialog on top of the container z-index
  3549. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  3550. this.exportDialog.style.zIndex = style.zIndex;
  3551. var spinner = new Spinner({
  3552. lines: 8, // The number of lines to draw
  3553. length: 6, // The length of each line
  3554. width: 5, // The line thickness
  3555. radius: 6, // The radius of the inner circle
  3556. rotate: 0, // The rotation offset
  3557. color: '#fff', // #rgb or #rrggbb
  3558. speed: 1.5, // Rounds per second
  3559. trail: 60, // Afterglow percentage
  3560. shadow: false, // Whether to render a shadow
  3561. hwaccel: false, // Whether to use hardware acceleration
  3562. top: '28px',
  3563. zIndex: 2e9 // The z-index (defaults to 2000000000)
  3564. });
  3565. spinner.spin(this.exportDialog);
  3566. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3567. {
  3568. spinner.stop();
  3569. this.exportDialog.style.width = 'auto';
  3570. this.exportDialog.style.height = 'auto';
  3571. this.exportDialog.style.padding = '10px';
  3572. var data = this.createImageDataUri(canvas, null, 'png');
  3573. var img = document.createElement('img');
  3574. img.style.maxWidth = '140px';
  3575. img.style.maxHeight = '140px';
  3576. img.style.cursor = 'pointer';
  3577. img.style.backgroundColor = 'white';
  3578. img.setAttribute('title', mxResources.get('openInNewWindow'));
  3579. img.setAttribute('border', '0');
  3580. img.setAttribute('src', data);
  3581. this.exportDialog.appendChild(img);
  3582. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  3583. {
  3584. this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
  3585. clickHandler.apply(this, arguments);
  3586. }));
  3587. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3588. {
  3589. this.spinner.stop();
  3590. this.handleError(e);
  3591. }));
  3592. mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
  3593. document.body.appendChild(this.exportDialog);
  3594. }
  3595. mxEvent.consume(evt);
  3596. }), Editor.cameraLargeImage, mxResources.get('export'));
  3597. }
  3598. editoUiAddChromelessToolbarItems.apply(this, arguments);
  3599. };
  3600. /**
  3601. * Translates this point by the given vector.
  3602. *
  3603. * @param {number} dx X-coordinate of the translation.
  3604. * @param {number} dy Y-coordinate of the translation.
  3605. */
  3606. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  3607. {
  3608. if (this.isLocalFileSave())
  3609. {
  3610. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  3611. }
  3612. else
  3613. {
  3614. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  3615. {
  3616. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  3617. }), data, base64Encoded, mime);
  3618. }
  3619. };
  3620. /**
  3621. * Translates this point by the given vector.
  3622. *
  3623. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  3624. * side without requiring a server roundtrip.
  3625. *
  3626. * @param {number} dx X-coordinate of the translation.
  3627. * @param {number} dy Y-coordinate of the translation.
  3628. */
  3629. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
  3630. {
  3631. allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
  3632. var count = this.getServiceCount(false);
  3633. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3634. {
  3635. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  3636. {
  3637. var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
  3638. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  3639. if (xhr != null)
  3640. {
  3641. if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
  3642. {
  3643. xhr.simulate(document, '_blank');
  3644. }
  3645. else
  3646. {
  3647. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3648. {
  3649. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  3650. 'application/pdf' : 'image/' + format);
  3651. // Workaround for no roundtrip required if data is available on client-side
  3652. // TODO: Refactor the saveData/saveRequest call chain for local data
  3653. if (data != null)
  3654. {
  3655. try
  3656. {
  3657. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  3658. }
  3659. catch (e)
  3660. {
  3661. this.handleError(e);
  3662. }
  3663. }
  3664. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  3665. {
  3666. // LATER: Catch possible mixed content error
  3667. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  3668. xhr.send(mxUtils.bind(this, function()
  3669. {
  3670. this.spinner.stop();
  3671. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  3672. {
  3673. try
  3674. {
  3675. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  3676. }
  3677. catch (e)
  3678. {
  3679. this.handleError(e);
  3680. }
  3681. }
  3682. else
  3683. {
  3684. this.handleError({message: mxResources.get('errorSavingFile')});
  3685. }
  3686. }), function(resp)
  3687. {
  3688. this.spinner.stop();
  3689. this.handleError(resp);
  3690. });
  3691. }
  3692. }));
  3693. }
  3694. }
  3695. }
  3696. }), mxUtils.bind(this, function()
  3697. {
  3698. this.hideDialog();
  3699. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
  3700. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  3701. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3702. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3703. this.showDialog(dlg.container, 380, height, true, true);
  3704. dlg.init();
  3705. };
  3706. /**
  3707. *
  3708. */
  3709. EditorUi.prototype.getEditBlankXml = function()
  3710. {
  3711. return this.getFileData(true);
  3712. };
  3713. /**
  3714. * Hook for subclassers.
  3715. */
  3716. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  3717. {
  3718. // do nothing
  3719. };
  3720. /**
  3721. * Hook for subclassers.
  3722. */
  3723. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  3724. {
  3725. fn(null);
  3726. };
  3727. /**
  3728. *
  3729. */
  3730. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow,
  3731. editable, embedImages, border, noCrop, currentPage, linkTarget)
  3732. {
  3733. if (this.spinner.spin(document.body, mxResources.get('export')))
  3734. {
  3735. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3736. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3737. var bg = (transparentBackground) ? null : this.editor.graph.background;
  3738. if (bg == mxConstants.NONE)
  3739. {
  3740. bg = null;
  3741. }
  3742. // Handles special case where background is null but transparent is false
  3743. if (bg == null && transparentBackground == false)
  3744. {
  3745. bg = '#ffffff';
  3746. }
  3747. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3748. // because PhantomJS seems to ignore switch statements and paint all text.
  3749. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null,
  3750. ignoreSelection, null, null, (linkTarget == 'blank') ? '_blank' :
  3751. ((linkTarget == 'self') ? '_top' : null));
  3752. if (addShadow)
  3753. {
  3754. this.editor.graph.addSvgShadow(svgRoot);
  3755. }
  3756. var filename = this.getBaseFilename() + '.svg';
  3757. var doSave = mxUtils.bind(this, function(svgRoot)
  3758. {
  3759. this.spinner.stop();
  3760. if (editable)
  3761. {
  3762. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  3763. }
  3764. if (this.editor.fontCss != null)
  3765. {
  3766. var svgDoc = svgRoot.ownerDocument;
  3767. var style = (svgDoc.createElementNS != null) ?
  3768. svgDoc.createElementNS(mxConstants.NS_SVG, 'style') : svgDoc.createElement('style');
  3769. style.setAttribute('type', 'text/css');
  3770. mxUtils.setTextContent(style, this.editor.fontCss);
  3771. svgRoot.getElementsByTagName('defs')[0].appendChild(style);
  3772. }
  3773. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  3774. mxUtils.getXml(svgRoot);
  3775. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  3776. {
  3777. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  3778. }
  3779. else
  3780. {
  3781. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  3782. {
  3783. mxUtils.popup(svg);
  3784. }));
  3785. }
  3786. });
  3787. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  3788. {
  3789. if (embedImages)
  3790. {
  3791. // Caches images
  3792. if (this.thumbImageCache == null)
  3793. {
  3794. this.thumbImageCache = new Object();
  3795. }
  3796. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  3797. }
  3798. else
  3799. {
  3800. doSave(svgRoot);
  3801. }
  3802. }));
  3803. }
  3804. };
  3805. EditorUi.prototype.addRadiobox = function(div, radioGroupName, label, checked, disabled, disableNewline, visible)
  3806. {
  3807. return this.addCheckbox(div, label, checked, disabled, disableNewline, visible, true, radioGroupName);
  3808. }
  3809. /**
  3810. *
  3811. */
  3812. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible, asRadio, radioGroupName)
  3813. {
  3814. visible = (visible != null) ? visible : true;
  3815. var cb = document.createElement('input');
  3816. cb.style.marginRight = '8px';
  3817. cb.style.marginTop = '16px';
  3818. cb.setAttribute('type', asRadio? 'radio' : 'checkbox');
  3819. var id = 'geCheckbox-' + Editor.guid();
  3820. cb.id = id;
  3821. if (radioGroupName != null)
  3822. {
  3823. cb.setAttribute('name', radioGroupName);
  3824. }
  3825. if (checked)
  3826. {
  3827. cb.setAttribute('checked', 'checked');
  3828. cb.defaultChecked = true;
  3829. }
  3830. if (disabled)
  3831. {
  3832. cb.setAttribute('disabled', 'disabled');
  3833. }
  3834. if (visible)
  3835. {
  3836. div.appendChild(cb);
  3837. var lbl = document.createElement('label');
  3838. mxUtils.write(lbl, label);
  3839. lbl.setAttribute('for', id);
  3840. div.appendChild(lbl);
  3841. if (!disableNewline)
  3842. {
  3843. mxUtils.br(div);
  3844. }
  3845. }
  3846. return cb;
  3847. };
  3848. /**
  3849. *
  3850. */
  3851. EditorUi.prototype.addEditButton = function(div, lightbox)
  3852. {
  3853. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  3854. edit.style.marginLeft = '24px';
  3855. var file = this.getCurrentFile();
  3856. var editUrl = '';
  3857. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  3858. {
  3859. editUrl = window.location.href;
  3860. }
  3861. var editSelect = document.createElement('select');
  3862. editSelect.style.width = '120px';
  3863. editSelect.style.marginLeft = '8px';
  3864. editSelect.style.marginRight = '10px';
  3865. editSelect.className = 'geBtn';
  3866. var blankOption = document.createElement('option');
  3867. blankOption.setAttribute('value', 'blank');
  3868. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  3869. editSelect.appendChild(blankOption);
  3870. var customOption = document.createElement('option');
  3871. customOption.setAttribute('value', 'custom');
  3872. mxUtils.write(customOption, mxResources.get('custom') + '...');
  3873. editSelect.appendChild(customOption);
  3874. div.appendChild(editSelect);
  3875. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  3876. {
  3877. if (editSelect.value == 'custom')
  3878. {
  3879. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  3880. {
  3881. if (value != null)
  3882. {
  3883. editUrl = value;
  3884. }
  3885. else
  3886. {
  3887. editSelect.value = 'blank';
  3888. }
  3889. }, mxResources.get('url'), null, null, null, null, function()
  3890. {
  3891. editSelect.value = 'blank';
  3892. });
  3893. this.showDialog(dlg2.container, 300, 80, true, false);
  3894. dlg2.init();
  3895. }
  3896. }));
  3897. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  3898. {
  3899. if (edit.checked && (lightbox == null || lightbox.checked))
  3900. {
  3901. editSelect.removeAttribute('disabled');
  3902. }
  3903. else
  3904. {
  3905. editSelect.setAttribute('disabled', 'disabled');
  3906. }
  3907. }));
  3908. mxUtils.br(div);
  3909. return {
  3910. getLink: function()
  3911. {
  3912. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  3913. },
  3914. getEditInput: function()
  3915. {
  3916. return edit;
  3917. },
  3918. getEditSelect: function()
  3919. {
  3920. return editSelect;
  3921. }
  3922. };
  3923. }
  3924. /**
  3925. *
  3926. */
  3927. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  3928. {
  3929. mxUtils.write(div, mxResources.get('links') + ':');
  3930. var linkSelect = document.createElement('select');
  3931. linkSelect.style.width = '100px';
  3932. linkSelect.style.marginLeft = '8px';
  3933. linkSelect.style.marginRight = '10px';
  3934. linkSelect.className = 'geBtn';
  3935. var autoOption = document.createElement('option');
  3936. autoOption.setAttribute('value', 'auto');
  3937. mxUtils.write(autoOption, mxResources.get('automatic'));
  3938. linkSelect.appendChild(autoOption);
  3939. var blankOption = document.createElement('option');
  3940. blankOption.setAttribute('value', 'blank');
  3941. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  3942. linkSelect.appendChild(blankOption);
  3943. var selfOption = document.createElement('option');
  3944. selfOption.setAttribute('value', 'self');
  3945. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  3946. linkSelect.appendChild(selfOption);
  3947. if (showFrameOption)
  3948. {
  3949. var frameOption = document.createElement('option');
  3950. frameOption.setAttribute('value', 'frame');
  3951. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  3952. ' (' + mxResources.get('iframe') + ')');
  3953. linkSelect.appendChild(frameOption);
  3954. }
  3955. div.appendChild(linkSelect);
  3956. mxUtils.write(div, mxResources.get('borderColor') + ':');
  3957. var linkColor = '#0000ff';
  3958. var linkButton = null;
  3959. function updateLinkColor()
  3960. {
  3961. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  3962. ((linkColor != null && linkColor != mxConstants.NONE) ?
  3963. 'border:1px solid black;background-color:' + linkColor :
  3964. 'background-position:center center;background-repeat:no-repeat;' +
  3965. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  3966. };
  3967. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  3968. {
  3969. this.pickColor(linkColor || 'none', function(color)
  3970. {
  3971. linkColor = color;
  3972. updateLinkColor();
  3973. });
  3974. mxEvent.consume(evt);
  3975. }));
  3976. updateLinkColor();
  3977. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  3978. linkButton.style.marginLeft = '4px';
  3979. linkButton.style.height = '22px';
  3980. linkButton.style.width = '22px';
  3981. linkButton.style.position = 'relative';
  3982. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  3983. linkButton.className = 'geColorBtn';
  3984. div.appendChild(linkButton);
  3985. mxUtils.br(div);
  3986. return {
  3987. getColor: function()
  3988. {
  3989. return linkColor;
  3990. },
  3991. getTarget: function()
  3992. {
  3993. return linkSelect.value;
  3994. },
  3995. focus: function()
  3996. {
  3997. linkSelect.focus();
  3998. }
  3999. };
  4000. }
  4001. /**
  4002. *
  4003. */
  4004. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  4005. {
  4006. var file = this.getCurrentFile();
  4007. var params = [];
  4008. if (lightbox)
  4009. {
  4010. params.push('lightbox=1');
  4011. if (linkTarget != 'auto')
  4012. {
  4013. params.push('target=' + linkTarget);
  4014. }
  4015. if (linkColor != null && linkColor != mxConstants.NONE)
  4016. {
  4017. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  4018. }
  4019. if (editLink != null && editLink.length > 0)
  4020. {
  4021. params.push('edit=' + encodeURIComponent(editLink));
  4022. }
  4023. if (layers)
  4024. {
  4025. params.push('layers=1');
  4026. }
  4027. if (this.editor.graph.foldingEnabled)
  4028. {
  4029. params.push('nav=1');
  4030. }
  4031. }
  4032. if (allPages && this.currentPage != null && this.pages != null &&
  4033. this.currentPage != this.pages[0])
  4034. {
  4035. params.push('page-id=' + this.currentPage.getId());
  4036. }
  4037. var data = '';
  4038. var addTitle = true;
  4039. if (url != null)
  4040. {
  4041. data = '#U' + encodeURIComponent(url);
  4042. }
  4043. else
  4044. {
  4045. var file = this.getCurrentFile();
  4046. // Fallback to non-public URL for Drive files
  4047. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  4048. {
  4049. data = '#' + file.getHash();
  4050. addTitle = false;
  4051. }
  4052. else
  4053. {
  4054. data = '#R' + encodeURIComponent((allPages) ?
  4055. this.getFileData(true, null, null, null, null, null, null, true) :
  4056. Graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  4057. }
  4058. }
  4059. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  4060. {
  4061. params.push('title=' + encodeURIComponent(file.getTitle()));
  4062. }
  4063. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || !(/.*\.draw\.io$/.test(window.location.hostname))) ?
  4064. EditorUi.drawHost : 'https://' + window.location.host + '/') +
  4065. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  4066. };
  4067. /**
  4068. *
  4069. */
  4070. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  4071. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  4072. {
  4073. var s = this.getBasenames();
  4074. var data = {};
  4075. if (linkColor != '' && linkColor != mxConstants.NONE)
  4076. {
  4077. data.highlight = linkColor;
  4078. }
  4079. if (linkTarget !== 'auto')
  4080. {
  4081. data.target = linkTarget;
  4082. }
  4083. if (!lightbox)
  4084. {
  4085. data.lightbox = false;
  4086. }
  4087. data.nav = this.editor.graph.foldingEnabled;
  4088. var zoom = parseInt(initialZoom);
  4089. if (!isNaN(zoom) && zoom != 100)
  4090. {
  4091. data.zoom = zoom / 100;
  4092. }
  4093. var tb = [];
  4094. if (allPages)
  4095. {
  4096. tb.push('pages');
  4097. data.resize = true;
  4098. if (this.pages != null && this.currentPage != null)
  4099. {
  4100. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  4101. }
  4102. }
  4103. if (zoomEnabled)
  4104. {
  4105. tb.push('zoom');
  4106. data.resize = true;
  4107. }
  4108. if (layers)
  4109. {
  4110. tb.push('layers');
  4111. }
  4112. if (tb.length > 0)
  4113. {
  4114. if (lightbox)
  4115. {
  4116. tb.push('lightbox');
  4117. }
  4118. data.toolbar = tb.join(' ');
  4119. }
  4120. if (editLink != null && editLink.length > 0)
  4121. {
  4122. data.edit = editLink;
  4123. }
  4124. if (publicUrl != null)
  4125. {
  4126. data.url = publicUrl;
  4127. }
  4128. else
  4129. {
  4130. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  4131. }
  4132. var value = '<div class="mxgraph" style="' +
  4133. ((fit) ? 'max-width:100%;' : '') +
  4134. ((tb != '') ? 'border:1px solid transparent;' : '') +
  4135. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  4136. var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
  4137. var s2 = (fetchParam.length > 0) ?
  4138. (((urlParams['dev'] == '1') ?
  4139. 'https://test.draw.io/embed2.js?dev=1' :
  4140. EditorUi.drawHost + '/embed2.js?')) + fetchParam :
  4141. (((urlParams['dev'] == '1') ?
  4142. 'https://test.draw.io/js/viewer.min.js' :
  4143. window.VIEWER_URL ? window.VIEWER_URL : EditorUi.drawHost + '/js/viewer.min.js'));
  4144. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  4145. fn(value, scr);
  4146. };
  4147. /**
  4148. *
  4149. */
  4150. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  4151. {
  4152. var div = document.createElement('div');
  4153. div.style.whiteSpace = 'nowrap';
  4154. var graph = this.editor.graph;
  4155. var hd = document.createElement('h3');
  4156. mxUtils.write(hd, mxResources.get('html'));
  4157. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4158. div.appendChild(hd);
  4159. var radioSection = document.createElement('div');
  4160. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  4161. var publicUrlRadio = document.createElement('input');
  4162. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  4163. publicUrlRadio.setAttribute('value', 'url');
  4164. publicUrlRadio.setAttribute('type', 'radio');
  4165. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  4166. var copyRadio = publicUrlRadio.cloneNode(true);
  4167. copyRadio.setAttribute('value', 'copy');
  4168. radioSection.appendChild(copyRadio);
  4169. var span = document.createElement('span');
  4170. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  4171. radioSection.appendChild(span);
  4172. mxUtils.br(radioSection);
  4173. radioSection.appendChild(publicUrlRadio);
  4174. var span = document.createElement('span');
  4175. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  4176. radioSection.appendChild(span);
  4177. var file = this.getCurrentFile();
  4178. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  4179. {
  4180. var testLink = document.createElement('a');
  4181. testLink.style.paddingLeft = '12px';
  4182. testLink.style.color = 'gray';
  4183. testLink.setAttribute('href', 'javascript:void(0);');
  4184. mxUtils.write(testLink, mxResources.get('share'));
  4185. radioSection.appendChild(testLink);
  4186. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4187. {
  4188. this.hideDialog();
  4189. this.drive.showPermissions(file.getId());
  4190. }));
  4191. }
  4192. copyRadio.setAttribute('checked', 'checked');
  4193. if (publicUrl == null)
  4194. {
  4195. publicUrlRadio.setAttribute('disabled', 'disabled');
  4196. }
  4197. div.appendChild(radioSection);
  4198. var linkSection = this.addLinkSection(div);
  4199. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  4200. mxUtils.write(div, ':');
  4201. var zoomInput = document.createElement('input');
  4202. zoomInput.setAttribute('type', 'text');
  4203. zoomInput.style.marginRight = '16px';
  4204. zoomInput.style.width = '60px';
  4205. zoomInput.style.marginLeft = '4px';
  4206. zoomInput.style.marginRight = '12px';
  4207. zoomInput.value = '100%';
  4208. div.appendChild(zoomInput);
  4209. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4210. var hasPages = this.pages != null && this.pages.length > 1;
  4211. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4212. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4213. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4214. var editSection = this.addEditButton(div, lightbox);
  4215. var edit = editSection.getEditInput();
  4216. edit.style.marginBottom = '16px';
  4217. mxEvent.addListener(lightbox, 'change', function()
  4218. {
  4219. if (lightbox.checked)
  4220. {
  4221. edit.removeAttribute('disabled');
  4222. }
  4223. else
  4224. {
  4225. edit.setAttribute('disabled', 'disabled');
  4226. }
  4227. if (edit.checked && lightbox.checked)
  4228. {
  4229. editSection.getEditSelect().removeAttribute('disabled');
  4230. }
  4231. else
  4232. {
  4233. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4234. }
  4235. });
  4236. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4237. {
  4238. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  4239. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  4240. editSection.getLink());
  4241. }), null, btnLabel, helpLink);
  4242. this.showDialog(dlg.container, 340, 384, true, true);
  4243. copyRadio.focus();
  4244. };
  4245. /**
  4246. *
  4247. */
  4248. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  4249. {
  4250. var div = document.createElement('div');
  4251. div.style.whiteSpace = 'nowrap';
  4252. var graph = this.editor.graph;
  4253. var hd = document.createElement('h3');
  4254. mxUtils.write(hd, title || mxResources.get('link'));
  4255. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4256. div.appendChild(hd);
  4257. var file = this.getCurrentFile();
  4258. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  4259. var dy = 0;
  4260. if (file != null && file.constructor == window.DriveFile && !hideShare)
  4261. {
  4262. dy = 80;
  4263. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  4264. var hintSection = document.createElement('div');
  4265. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  4266. var text = document.createElement('div');
  4267. text.style.whiteSpace = 'normal';
  4268. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  4269. hintSection.appendChild(text);
  4270. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  4271. {
  4272. this.drive.showPermissions(file.getId());
  4273. }));
  4274. shareBtn.style.marginTop = '12px';
  4275. shareBtn.className = 'geBtn';
  4276. hintSection.appendChild(shareBtn);
  4277. div.appendChild(hintSection);
  4278. var testLink = document.createElement('a');
  4279. testLink.style.paddingLeft = '12px';
  4280. testLink.style.color = 'gray';
  4281. testLink.style.fontSize = '11px';
  4282. testLink.setAttribute('href', 'javascript:void(0);');
  4283. mxUtils.write(testLink, mxResources.get('check'));
  4284. hintSection.appendChild(testLink);
  4285. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4286. {
  4287. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4288. {
  4289. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  4290. {
  4291. this.spinner.stop();
  4292. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  4293. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  4294. this.showDialog(dlg.container, 300, 80, true, false);
  4295. dlg.init();
  4296. }));
  4297. }
  4298. }));
  4299. }
  4300. var widthInput = null;
  4301. var heightInput = null;
  4302. if (width != null || height != null)
  4303. {
  4304. dy += 30;
  4305. mxUtils.write(div, mxResources.get('width') + ':');
  4306. widthInput = document.createElement('input');
  4307. widthInput.setAttribute('type', 'text');
  4308. widthInput.style.marginRight = '16px';
  4309. widthInput.style.width = '50px';
  4310. widthInput.style.marginLeft = '6px';
  4311. widthInput.style.marginRight = '16px';
  4312. widthInput.style.marginBottom = '10px';
  4313. widthInput.value = '100%';
  4314. div.appendChild(widthInput);
  4315. mxUtils.write(div, mxResources.get('height') + ':');
  4316. heightInput = document.createElement('input');
  4317. heightInput.setAttribute('type', 'text');
  4318. heightInput.style.width = '50px';
  4319. heightInput.style.marginLeft = '6px';
  4320. heightInput.style.marginBottom = '10px';
  4321. heightInput.value = height + 'px';
  4322. div.appendChild(heightInput);
  4323. mxUtils.br(div);
  4324. }
  4325. var linkSection = this.addLinkSection(div, showFrameOption);
  4326. var hasPages = this.pages != null && this.pages.length > 1;
  4327. var allPages = null;
  4328. if (file == null || file.constructor != window.DriveFile || hideShare)
  4329. {
  4330. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4331. }
  4332. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4333. var editSection = this.addEditButton(div, lightbox);
  4334. var edit = editSection.getEditInput();
  4335. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4336. layers.style.marginLeft = edit.style.marginLeft;
  4337. layers.style.marginBottom = '16px';
  4338. layers.style.marginTop = '8px';
  4339. mxEvent.addListener(lightbox, 'change', function()
  4340. {
  4341. if (lightbox.checked)
  4342. {
  4343. layers.removeAttribute('disabled');
  4344. edit.removeAttribute('disabled');
  4345. }
  4346. else
  4347. {
  4348. layers.setAttribute('disabled', 'disabled');
  4349. edit.setAttribute('disabled', 'disabled');
  4350. }
  4351. if (edit.checked && lightbox.checked)
  4352. {
  4353. editSection.getEditSelect().removeAttribute('disabled');
  4354. }
  4355. else
  4356. {
  4357. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4358. }
  4359. });
  4360. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4361. {
  4362. fn(linkSection.getTarget(), linkSection.getColor(),
  4363. (allPages == null) ? true : allPages.checked,
  4364. lightbox.checked, editSection.getLink(),
  4365. layers.checked, (widthInput != null) ? widthInput.value : null,
  4366. (heightInput != null) ? heightInput.value : null);
  4367. }), null, mxResources.get('create'), helpLink);
  4368. this.showDialog(dlg.container, 340, 254 + dy, true, true);
  4369. if (widthInput != null)
  4370. {
  4371. widthInput.focus();
  4372. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4373. {
  4374. widthInput.select();
  4375. }
  4376. else
  4377. {
  4378. document.execCommand('selectAll', false, null);
  4379. }
  4380. }
  4381. else
  4382. {
  4383. linkSection.focus();
  4384. }
  4385. };
  4386. /**
  4387. *
  4388. */
  4389. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude)
  4390. {
  4391. var div = document.createElement('div');
  4392. div.style.whiteSpace = 'nowrap';
  4393. var hd = document.createElement('h3');
  4394. mxUtils.write(hd, mxResources.get('image'));
  4395. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4396. div.appendChild(hd);
  4397. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  4398. this.editor.graph.isSelectionEmpty());
  4399. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  4400. var graph = this.editor.graph;
  4401. var transparent = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('transparentBackground'),
  4402. graph.background == mxConstants.NONE || graph.background == null);
  4403. if (transparent != null)
  4404. {
  4405. transparent.style.marginBottom = '16px';
  4406. }
  4407. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4408. {
  4409. callback(!selection.checked, (include != null) ? include.checked : false,
  4410. (transparent != null) ? transparent.checked : false);
  4411. }), null, btnLabel, helpLink);
  4412. this.showDialog(dlg.container, 300, (hideInclude) ? 100 : 186, true, true);
  4413. };
  4414. /**
  4415. *
  4416. */
  4417. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  4418. cropOption, defaultInclude, format)
  4419. {
  4420. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  4421. var div = document.createElement('div');
  4422. div.style.whiteSpace = 'nowrap';
  4423. var graph = this.editor.graph;
  4424. var height = (format == 'jpeg') ? 196 : 300;
  4425. var hd = document.createElement('h3');
  4426. mxUtils.write(hd, title);
  4427. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  4428. div.appendChild(hd);
  4429. mxUtils.write(div, mxResources.get('zoom') + ':');
  4430. var zoomInput = document.createElement('input');
  4431. zoomInput.setAttribute('type', 'text');
  4432. zoomInput.style.marginRight = '16px';
  4433. zoomInput.style.width = '60px';
  4434. zoomInput.style.marginLeft = '4px';
  4435. zoomInput.style.marginRight = '12px';
  4436. zoomInput.value = this.lastExportZoom || '100%';
  4437. div.appendChild(zoomInput);
  4438. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  4439. var borderInput = document.createElement('input');
  4440. borderInput.setAttribute('type', 'text');
  4441. borderInput.style.marginRight = '16px';
  4442. borderInput.style.width = '60px';
  4443. borderInput.style.marginLeft = '4px';
  4444. borderInput.value = this.lastExportBorder || '0';
  4445. div.appendChild(borderInput);
  4446. mxUtils.br(div);
  4447. var defaultTransparent = false; /*graph.background == mxConstants.NONE || graph.background == null*/;
  4448. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  4449. defaultTransparent, null, null, format != 'jpeg');
  4450. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  4451. false, graph.isSelectionEmpty());
  4452. var cb6 = document.createElement('input');
  4453. cb6.style.marginTop = '16px';
  4454. cb6.style.marginRight = '8px';
  4455. cb6.style.marginLeft = '24px';
  4456. cb6.setAttribute('disabled', 'disabled');
  4457. cb6.setAttribute('type', 'checkbox');
  4458. if (cropOption)
  4459. {
  4460. div.appendChild(cb6);
  4461. mxUtils.write(div, mxResources.get('crop'));
  4462. mxUtils.br(div);
  4463. height += 26;
  4464. mxEvent.addListener(selection, 'change', function()
  4465. {
  4466. if (selection.checked)
  4467. {
  4468. cb6.removeAttribute('disabled');
  4469. }
  4470. else
  4471. {
  4472. cb6.setAttribute('disabled', 'disabled');
  4473. }
  4474. });
  4475. }
  4476. if (!graph.isSelectionEmpty())
  4477. {
  4478. cb6.setAttribute('checked', 'checked');
  4479. cb6.defaultChecked = true;
  4480. }
  4481. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  4482. var cb5 = document.createElement('input');
  4483. cb5.style.marginTop = '16px';
  4484. cb5.style.marginRight = '8px';
  4485. cb5.setAttribute('type', 'checkbox');
  4486. if (this.isOffline() || !this.canvasSupported)
  4487. {
  4488. cb5.setAttribute('disabled', 'disabled');
  4489. }
  4490. if (embedOption)
  4491. {
  4492. div.appendChild(cb5);
  4493. mxUtils.write(div, mxResources.get('embedImages'));
  4494. mxUtils.br(div);
  4495. height += 26;
  4496. }
  4497. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  4498. var hasPages = this.pages != null && this.pages.length > 1;
  4499. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  4500. allPages.style.marginLeft = '24px';
  4501. allPages.style.marginBottom = '16px';
  4502. if (!hasPages)
  4503. {
  4504. allPages.style.display = 'none';
  4505. }
  4506. mxEvent.addListener(include, 'change', function()
  4507. {
  4508. if (include.checked && hasPages)
  4509. {
  4510. allPages.removeAttribute('disabled');
  4511. }
  4512. else
  4513. {
  4514. allPages.setAttribute('disabled', 'disabled');
  4515. }
  4516. });
  4517. if (!defaultInclude || !hasPages)
  4518. {
  4519. allPages.setAttribute('disabled', 'disabled');
  4520. }
  4521. var linkSelect = document.createElement('select');
  4522. linkSelect.style.maxWidth = '260px';
  4523. linkSelect.style.marginLeft = '8px';
  4524. linkSelect.style.marginRight = '10px';
  4525. linkSelect.className = 'geBtn';
  4526. var autoOption = document.createElement('option');
  4527. autoOption.setAttribute('value', 'auto');
  4528. mxUtils.write(autoOption, mxResources.get('automatic'));
  4529. linkSelect.appendChild(autoOption);
  4530. var blankOption = document.createElement('option');
  4531. blankOption.setAttribute('value', 'blank');
  4532. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  4533. linkSelect.appendChild(blankOption);
  4534. var selfOption = document.createElement('option');
  4535. selfOption.setAttribute('value', 'self');
  4536. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  4537. linkSelect.appendChild(selfOption);
  4538. if (format == 'svg')
  4539. {
  4540. mxUtils.write(div, mxResources.get('links') + ':');
  4541. div.appendChild(linkSelect);
  4542. mxUtils.br(div);
  4543. mxUtils.br(div);
  4544. height += 26;
  4545. }
  4546. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4547. {
  4548. this.lastExportBorder = borderInput.value;
  4549. this.lastExportZoom = zoomInput.value;
  4550. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  4551. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked,
  4552. linkSelect.value);
  4553. }), null, btnLabel, helpLink);
  4554. this.showDialog(dlg.container, 340, height, true, true);
  4555. zoomInput.focus();
  4556. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4557. {
  4558. zoomInput.select();
  4559. }
  4560. else
  4561. {
  4562. document.execCommand('selectAll', false, null);
  4563. }
  4564. };
  4565. /**
  4566. *
  4567. */
  4568. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  4569. {
  4570. var div = document.createElement('div');
  4571. div.style.whiteSpace = 'nowrap';
  4572. var graph = this.editor.graph;
  4573. if (title != null)
  4574. {
  4575. var hd = document.createElement('h3');
  4576. mxUtils.write(hd, title);
  4577. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4578. div.appendChild(hd);
  4579. }
  4580. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4581. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  4582. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  4583. var image = this.addCheckbox(div, imageLabel);
  4584. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4585. var editSection = this.addEditButton(div, lightbox);
  4586. var edit = editSection.getEditInput();
  4587. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  4588. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  4589. layers.style.marginLeft = edit.style.marginLeft;
  4590. layers.style.marginBottom = '12px';
  4591. layers.style.marginTop = '8px';
  4592. mxEvent.addListener(lightbox, 'change', function()
  4593. {
  4594. if (lightbox.checked)
  4595. {
  4596. if (hasLayers)
  4597. {
  4598. layers.removeAttribute('disabled');
  4599. }
  4600. edit.removeAttribute('disabled');
  4601. }
  4602. else
  4603. {
  4604. layers.setAttribute('disabled', 'disabled');
  4605. edit.setAttribute('disabled', 'disabled');
  4606. }
  4607. if (edit.checked && lightbox.checked)
  4608. {
  4609. editSection.getEditSelect().removeAttribute('disabled');
  4610. }
  4611. else
  4612. {
  4613. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4614. }
  4615. });
  4616. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4617. {
  4618. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  4619. editSection.getLink(), layers.checked);
  4620. }), null, mxResources.get('embed'), helpLink);
  4621. this.showDialog(dlg.container, 280, 280, true, true);
  4622. };
  4623. /**
  4624. *
  4625. */
  4626. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  4627. {
  4628. var bounds = this.editor.graph.getGraphBounds();
  4629. function doUpdate(dataUri)
  4630. {
  4631. var onclick = ' ';
  4632. var css = '';
  4633. // Adds double click handling
  4634. if (lightbox)
  4635. {
  4636. // KNOWN: Message passing does not seem to work in IE11
  4637. onclick = " onclick=\"(function(img){if(img.wnd!=null&&!img.wnd.closed){img.wnd.focus();}else{var r=function(evt){if(evt.data=='ready'&&evt.source==img.wnd){img.wnd.postMessage(decodeURIComponent(" +
  4638. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4639. ((edit) ? "&edit=_blank" : "") +
  4640. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4641. css += 'cursor:pointer;';
  4642. }
  4643. if (fit)
  4644. {
  4645. css += 'max-width:100%;';
  4646. }
  4647. var atts = '';
  4648. if (retina)
  4649. {
  4650. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  4651. }
  4652. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4653. };
  4654. if (this.isExportToCanvas())
  4655. {
  4656. var scale = 1;
  4657. var ignoreSelection = true;
  4658. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4659. {
  4660. var xml = (lightbox) ? this.getFileData(true) : null;
  4661. var data = this.createImageDataUri(canvas, xml, 'png');
  4662. doUpdate(data);
  4663. }), null, null, null, mxUtils.bind(this, function(e)
  4664. {
  4665. err({message: mxResources.get('unknownError')});
  4666. }), null, true, (retina) ? 2 : 1, null, shadow);
  4667. }
  4668. else
  4669. {
  4670. var data = this.getFileData(true);
  4671. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  4672. {
  4673. var size = '';
  4674. if (retina)
  4675. {
  4676. size = '&w=' + Math.round(2 * bounds.width) +
  4677. '&h=' + Math.round(2 * bounds.height);
  4678. }
  4679. var embed = (lightbox) ? '1' : '0';
  4680. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  4681. '&base64=1&embedXml=' + embed + size + '&xml=' +
  4682. encodeURIComponent(data));
  4683. // LATER: Updates on each change, add a delay
  4684. req.send(mxUtils.bind(this, function()
  4685. {
  4686. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4687. {
  4688. // Fixes possible "incorrect function" for select() on
  4689. // DOM node which is no longer in document with IE11
  4690. doUpdate('data:image/png;base64,' + req.getText());
  4691. }
  4692. else
  4693. {
  4694. err({message: mxResources.get('unknownError')});
  4695. }
  4696. }));
  4697. }
  4698. else
  4699. {
  4700. err({message: mxResources.get('drawingTooLarge')});
  4701. }
  4702. }
  4703. };
  4704. /**
  4705. *
  4706. */
  4707. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  4708. {
  4709. var svgRoot = this.editor.graph.getSvg();
  4710. // Keeps hashtag links on same page
  4711. var links = svgRoot.getElementsByTagName('a');
  4712. if (links != null)
  4713. {
  4714. for (var i = 0; i < links.length; i++)
  4715. {
  4716. var href = links[i].getAttribute('href');
  4717. if (href != null && href.charAt(0) == '#' &&
  4718. links[i].getAttribute('target') == '_blank')
  4719. {
  4720. links[i].removeAttribute('target');
  4721. }
  4722. }
  4723. }
  4724. if (lightbox)
  4725. {
  4726. svgRoot.setAttribute('content', this.getFileData(true));
  4727. }
  4728. // Adds shadow filter
  4729. if (shadow)
  4730. {
  4731. this.editor.graph.addSvgShadow(svgRoot);
  4732. }
  4733. // SVG inside image tag
  4734. if (image)
  4735. {
  4736. var onclick = ' ';
  4737. var css = '';
  4738. // Adds double click handling
  4739. if (lightbox)
  4740. {
  4741. // KNOWN: Message passing does not seem to work in IE11
  4742. onclick = "onclick=\"(function(img){if(img.wnd!=null&&!img.wnd.closed){img.wnd.focus();}else{var r=function(evt){if(evt.data=='ready'&&evt.source==img.wnd){img.wnd.postMessage(decodeURIComponent(" +
  4743. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4744. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4745. css += 'cursor:pointer;';
  4746. }
  4747. if (fit)
  4748. {
  4749. css += 'max-width:100%;';
  4750. }
  4751. // Images inside IMG don't seem to work so embed them all
  4752. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  4753. {
  4754. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  4755. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4756. }));
  4757. }
  4758. else
  4759. {
  4760. var css = '';
  4761. // Adds double click handling
  4762. if (lightbox)
  4763. {
  4764. // KNOWN: Message passing does not seem to work in IE11
  4765. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  4766. // Ignores link events
  4767. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  4768. // Focus existing lightbox
  4769. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  4770. // Message handling
  4771. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  4772. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  4773. "window.addEventListener('message',r);" +
  4774. // Opens lightbox window
  4775. "svg.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4776. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  4777. svgRoot.setAttribute('onclick', js);
  4778. css += 'cursor:pointer;';
  4779. }
  4780. // Adds responsive size
  4781. if (fit)
  4782. {
  4783. var w = parseInt(svgRoot.getAttribute('width'));
  4784. var h = parseInt(svgRoot.getAttribute('height'));
  4785. svgRoot.setAttribute('viewBox', '-0.5 -0.5 ' + w + ' ' + h);
  4786. css += 'max-width:100%;max-height:' + h + 'px;';
  4787. svgRoot.removeAttribute('height');
  4788. }
  4789. if (css != '')
  4790. {
  4791. svgRoot.setAttribute('style', css);
  4792. }
  4793. fn(mxUtils.getXml(svgRoot));
  4794. }
  4795. };
  4796. /**
  4797. * Translates this point by the given vector.
  4798. *
  4799. * @param {number} dx X-coordinate of the translation.
  4800. * @param {number} dy Y-coordinate of the translation.
  4801. */
  4802. EditorUi.prototype.timeSince = function(date)
  4803. {
  4804. var seconds = Math.floor((new Date() - date) / 1000);
  4805. var interval = Math.floor(seconds / 31536000);
  4806. if (interval > 1)
  4807. {
  4808. return interval + ' ' + mxResources.get('years');
  4809. }
  4810. interval = Math.floor(seconds / 2592000);
  4811. if (interval > 1)
  4812. {
  4813. return interval + ' ' + mxResources.get('months');
  4814. }
  4815. interval = Math.floor(seconds / 86400);
  4816. if (interval > 1)
  4817. {
  4818. return interval + ' ' + mxResources.get('days');
  4819. }
  4820. interval = Math.floor(seconds / 3600);
  4821. if (interval > 1)
  4822. {
  4823. return interval + ' ' + mxResources.get('hours');
  4824. }
  4825. interval = Math.floor(seconds / 60);
  4826. if (interval > 1)
  4827. {
  4828. return interval + ' ' + mxResources.get('minutes');
  4829. }
  4830. if (interval == 1)
  4831. {
  4832. return interval + ' ' + mxResources.get('minute');
  4833. }
  4834. return null;
  4835. };
  4836. /**
  4837. * Converts math in the given SVG
  4838. */
  4839. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  4840. {
  4841. if (graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  4842. {
  4843. // Temporarily attaches to DOM for rendering
  4844. // FIXME: If adding svgRoot to body, the text
  4845. // value of the math is appended, if not
  4846. // added to DOM then LaTeX does not work.
  4847. // This must be fixed to enable client-side export
  4848. // if math is enabled.
  4849. // document.body.appendChild(svgRoot);
  4850. Editor.MathJaxRender(svgRoot);
  4851. window.setTimeout(mxUtils.bind(this, function()
  4852. {
  4853. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  4854. {
  4855. // Removes from DOM
  4856. // svgRoot.parentNode.removeChild(svgRoot);
  4857. callback();
  4858. }));
  4859. }), 0);
  4860. }
  4861. else
  4862. {
  4863. callback();
  4864. }
  4865. };
  4866. /**
  4867. *
  4868. */
  4869. EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
  4870. {
  4871. if (node != null)
  4872. {
  4873. var diagramNode = null;
  4874. if (node.nodeName == 'diagram')
  4875. {
  4876. diagramNode = node;
  4877. }
  4878. else if (node.nodeName == 'mxfile')
  4879. {
  4880. var diagrams = node.getElementsByTagName('diagram');
  4881. if (diagrams.length > 0)
  4882. {
  4883. diagramNode = diagrams[0];
  4884. var graphGetGlobalVariable = graph.getGlobalVariable;
  4885. graph.getGlobalVariable = function(name)
  4886. {
  4887. if (name == 'page')
  4888. {
  4889. return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
  4890. }
  4891. else if (name == 'pagenumber')
  4892. {
  4893. return 1;
  4894. }
  4895. return graphGetGlobalVariable.apply(this, arguments);
  4896. };
  4897. }
  4898. }
  4899. if (diagramNode != null)
  4900. {
  4901. var tmp = Graph.decompress(mxUtils.getTextContent(diagramNode));
  4902. if (tmp != null && tmp.length > 0)
  4903. {
  4904. node = mxUtils.parseXml(tmp).documentElement;
  4905. }
  4906. }
  4907. }
  4908. // Hack to decode XML into temp graph via editor
  4909. var prev = this.editor.graph;
  4910. try
  4911. {
  4912. this.editor.graph = graph;
  4913. this.editor.setGraphXml(node);
  4914. }
  4915. catch (e)
  4916. {
  4917. // ignore
  4918. }
  4919. finally
  4920. {
  4921. this.editor.graph = prev;
  4922. }
  4923. return node;
  4924. };
  4925. /**
  4926. *
  4927. */
  4928. EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData)
  4929. {
  4930. try
  4931. {
  4932. var graph = this.editor.graph;
  4933. var diagramData = null;
  4934. // Exports PNG for given optional data
  4935. if (optionalData != null && optionalData.length > 0)
  4936. {
  4937. graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
  4938. document.body.appendChild(graph.container);
  4939. this.decodeNodeIntoGraph(this.editor.extractGraphModel(
  4940. mxUtils.parseXml(optionalData).documentElement, true), graph);
  4941. diagramData = optionalData;
  4942. }
  4943. // Exports PNG for first page while other page is showing
  4944. else if (this.pages != null && this.currentPage != this.pages[0])
  4945. {
  4946. graph = this.createTemporaryGraph(graph.getStylesheet());
  4947. var graphGetGlobalVariable = graph.getGlobalVariable;
  4948. var page = this.pages[0];
  4949. graph.getGlobalVariable = function(name)
  4950. {
  4951. if (name == 'page')
  4952. {
  4953. return page.getName();
  4954. }
  4955. else if (name == 'pagenumber')
  4956. {
  4957. return 1;
  4958. }
  4959. return graphGetGlobalVariable.apply(this, arguments);
  4960. };
  4961. document.body.appendChild(graph.container);
  4962. graph.model.setRoot(page.root);
  4963. }
  4964. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4965. {
  4966. try
  4967. {
  4968. if (diagramData == null)
  4969. {
  4970. diagramData = this.getFileData(true);
  4971. }
  4972. var data = canvas.toDataURL('image/png');
  4973. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel',
  4974. atob(Graph.compress(diagramData)));
  4975. success(data.substring(data.lastIndexOf(',') + 1));
  4976. // Removes temporary graph from DOM
  4977. if (graph != this.editor.graph)
  4978. {
  4979. graph.container.parentNode.removeChild(graph.container);
  4980. }
  4981. }
  4982. catch (e)
  4983. {
  4984. if (error != null)
  4985. {
  4986. error(e);
  4987. }
  4988. }
  4989. }), null, null, null, mxUtils.bind(this, function(e)
  4990. {
  4991. if (error != null)
  4992. {
  4993. error(e);
  4994. }
  4995. }), null, null, null, null, graph.shadowVisible, null, graph);
  4996. }
  4997. catch (e)
  4998. {
  4999. if (error != null)
  5000. {
  5001. error(e);
  5002. }
  5003. }
  5004. }
  5005. /**
  5006. * Returns the SVG of the diagram with embedded XML. If a callback function is
  5007. * used, the images are converted to data URIs.
  5008. */
  5009. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  5010. {
  5011. var bg = graph.background;
  5012. if (bg == mxConstants.NONE)
  5013. {
  5014. bg = null;
  5015. }
  5016. // Sets or disables alternate text for foreignObjects. Disabling is needed
  5017. // because PhantomJS seems to ignore switch statements and paint all text.
  5018. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  5019. if (graph.shadowVisible)
  5020. {
  5021. graph.addSvgShadow(svgRoot);
  5022. }
  5023. if (xml != null)
  5024. {
  5025. svgRoot.setAttribute('content', xml);
  5026. }
  5027. if (url != null)
  5028. {
  5029. svgRoot.setAttribute('resource', url);
  5030. }
  5031. // LATER: Click on SVG content to start editing
  5032. // if (redirect != null)
  5033. // {
  5034. // // TODO: Ignore anchor tag source for click event
  5035. // svgRoot.setAttribute('style', 'cursor:pointer;');
  5036. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  5037. // }
  5038. if (callback != null)
  5039. {
  5040. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  5041. {
  5042. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5043. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5044. mxUtils.getXml(svgRoot));
  5045. }));
  5046. }
  5047. else
  5048. {
  5049. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5050. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5051. mxUtils.getXml(svgRoot);
  5052. }
  5053. };
  5054. /**
  5055. *
  5056. */
  5057. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  5058. {
  5059. format = (format != null) ? format : 'png';
  5060. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  5061. {
  5062. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  5063. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  5064. // Caches images
  5065. if (this.thumbImageCache == null)
  5066. {
  5067. this.thumbImageCache = new Object();
  5068. }
  5069. try
  5070. {
  5071. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  5072. {
  5073. this.spinner.stop();
  5074. try
  5075. {
  5076. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  5077. null, null, ignoreSelection, currentPage) : null, format);
  5078. }
  5079. catch (e)
  5080. {
  5081. // Fallback to server-side image export
  5082. if (e.message == 'Invalid image')
  5083. {
  5084. this.downloadFile(format);
  5085. }
  5086. else
  5087. {
  5088. this.handleError(e);
  5089. }
  5090. }
  5091. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  5092. {
  5093. this.spinner.stop();
  5094. this.handleError(e);
  5095. }), null, ignoreSelection, scale || 1, transparentBackground,
  5096. addShadow, null, null, border, noCrop);
  5097. }
  5098. catch (e)
  5099. {
  5100. this.spinner.stop();
  5101. this.handleError(e);
  5102. }
  5103. }
  5104. };
  5105. /**
  5106. * For the fontCSS to be applied when rendering images on canvas, the actual
  5107. * font data must be made available via a data URI encoding of the file.
  5108. */
  5109. EditorUi.prototype.loadFonts = function(then)
  5110. {
  5111. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  5112. {
  5113. var parts = this.editor.fontCss.split('url(');
  5114. var waiting = 0;
  5115. var fonts = {};
  5116. // Strips leading and trailing quotes and spaces
  5117. function trimString(str)
  5118. {
  5119. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  5120. };
  5121. var finish = mxUtils.bind(this, function()
  5122. {
  5123. if (waiting == 0)
  5124. {
  5125. // Constructs string
  5126. var result = [parts[0]];
  5127. for (var j = 1; j < parts.length; j++)
  5128. {
  5129. var idx = parts[j].indexOf(')');
  5130. result.push('url("');
  5131. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  5132. result.push('"' + parts[j].substring(idx));
  5133. }
  5134. this.editor.resolvedFontCss = result.join('');
  5135. then();
  5136. }
  5137. });
  5138. if (parts.length > 0)
  5139. {
  5140. for (var i = 1; i < parts.length; i++)
  5141. {
  5142. var idx = parts[i].indexOf(')');
  5143. var format = null;
  5144. // Checks if there is a format directive
  5145. var fmtIdx = parts[i].indexOf('format(', idx);
  5146. if (fmtIdx > 0)
  5147. {
  5148. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  5149. }
  5150. (mxUtils.bind(this, function(url)
  5151. {
  5152. if (fonts[url] == null)
  5153. {
  5154. // Mark font es being fetched and fetch it
  5155. fonts[url] = url;
  5156. waiting++;
  5157. var mime = 'application/x-font-ttf';
  5158. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  5159. if (format == 'svg' || /(\.svg)($|\?)/i.test(url))
  5160. {
  5161. mime = 'image/svg+xml';
  5162. }
  5163. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url))
  5164. {
  5165. mime = 'application/x-font-opentype';
  5166. }
  5167. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url))
  5168. {
  5169. mime = 'application/font-woff';
  5170. }
  5171. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url))
  5172. {
  5173. mime = 'application/font-woff2';
  5174. }
  5175. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url))
  5176. {
  5177. mime = 'application/vnd.ms-fontobject';
  5178. }
  5179. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url))
  5180. {
  5181. mime = 'application/font-sfnt';
  5182. }
  5183. var realUrl = url;
  5184. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  5185. {
  5186. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  5187. }
  5188. // LATER: Remove cache-control header
  5189. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  5190. {
  5191. fonts[url] = uri;
  5192. waiting--;
  5193. finish();
  5194. }), mxUtils.bind(this, function(err)
  5195. {
  5196. // LATER: handle error
  5197. waiting--;
  5198. finish();
  5199. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  5200. }
  5201. }))(trimString(parts[i].substring(0, idx)), format);
  5202. }
  5203. }
  5204. }
  5205. else
  5206. {
  5207. then();
  5208. }
  5209. };
  5210. /**
  5211. *
  5212. */
  5213. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  5214. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  5215. {
  5216. limitHeight = (limitHeight != null) ? limitHeight : true;
  5217. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  5218. graph = (graph != null) ? graph : this.editor.graph;
  5219. border = (border != null) ? border : 0;
  5220. var bg = (transparentBackground) ? null : graph.background;
  5221. if (bg == mxConstants.NONE)
  5222. {
  5223. bg = null;
  5224. }
  5225. if (bg == null)
  5226. {
  5227. bg = background;
  5228. }
  5229. // Handles special case where background is null but transparent is false
  5230. if (bg == null && transparentBackground == false)
  5231. {
  5232. bg = '#ffffff';
  5233. }
  5234. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection, null, null, null, addShadow),
  5235. mxUtils.bind(this, function(svgRoot)
  5236. {
  5237. var img = new Image();
  5238. img.onload = mxUtils.bind(this, function()
  5239. {
  5240. try
  5241. {
  5242. var canvas = document.createElement('canvas');
  5243. var w = parseInt(svgRoot.getAttribute('width'));
  5244. var h = parseInt(svgRoot.getAttribute('height'));
  5245. scale = (scale != null) ? scale : 1;
  5246. if (width != null)
  5247. {
  5248. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  5249. }
  5250. w = Math.ceil(scale * w) + 2 * border;
  5251. h = Math.ceil(scale * h) + 2 * border;
  5252. canvas.setAttribute('width', w);
  5253. canvas.setAttribute('height', h);
  5254. var ctx = canvas.getContext('2d');
  5255. if (bg != null)
  5256. {
  5257. ctx.beginPath();
  5258. ctx.rect(0, 0, w, h);
  5259. ctx.fillStyle = bg;
  5260. ctx.fill();
  5261. }
  5262. ctx.scale(scale, scale);
  5263. // Workaround for broken data URI images in Safari on first export
  5264. if (mxClient.IS_SF)
  5265. {
  5266. window.setTimeout(function()
  5267. {
  5268. ctx.drawImage(img, border / scale, border / scale);
  5269. callback(canvas);
  5270. }, 0);
  5271. }
  5272. else
  5273. {
  5274. ctx.drawImage(img, border / scale, border / scale);
  5275. callback(canvas);
  5276. }
  5277. }
  5278. catch (e)
  5279. {
  5280. if (error != null)
  5281. {
  5282. error(e);
  5283. }
  5284. }
  5285. });
  5286. img.onerror = function(e)
  5287. {
  5288. //console.log('img', e, img.src);
  5289. if (error != null)
  5290. {
  5291. error(e);
  5292. }
  5293. };
  5294. try
  5295. {
  5296. if (addShadow)
  5297. {
  5298. this.editor.graph.addSvgShadow(svgRoot);
  5299. }
  5300. var done = mxUtils.bind(this, function()
  5301. {
  5302. if (this.editor.resolvedFontCss != null)
  5303. {
  5304. var st = document.createElement('style');
  5305. st.setAttribute('type', 'text/css');
  5306. st.innerHTML = this.editor.resolvedFontCss;
  5307. // Must be in defs section for FF to work
  5308. var defs = svgRoot.getElementsByTagName('defs');
  5309. defs[0].appendChild(st);
  5310. }
  5311. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  5312. {
  5313. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5314. }));
  5315. });
  5316. this.loadFonts(done);
  5317. }
  5318. catch (e)
  5319. {
  5320. //console.log('src', e, img.src);
  5321. if (error != null)
  5322. {
  5323. error(e);
  5324. }
  5325. }
  5326. }), imageCache, converter);
  5327. };
  5328. /**
  5329. * Converts all images in the SVG output to data URIs for immediate rendering
  5330. */
  5331. EditorUi.prototype.createImageUrlConverter = function()
  5332. {
  5333. var converter = new mxUrlConverter();
  5334. converter.updateBaseUrl();
  5335. // Extends convert to avoid CORS using an image proxy server where needed
  5336. var convert = converter.convert;
  5337. var self = this;
  5338. converter.convert = function(src)
  5339. {
  5340. if (src != null)
  5341. {
  5342. var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  5343. if (remote && !navigator.onLine)
  5344. {
  5345. src = self.svgBrokenImage.src;
  5346. }
  5347. else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  5348. (!self.crossOriginImages || !self.editor.isCorsEnabledForUrl(src)))
  5349. {
  5350. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  5351. }
  5352. else if (src.substring(0, 19) != 'chrome-extension://')
  5353. {
  5354. src = convert.apply(this, arguments);
  5355. }
  5356. }
  5357. return src;
  5358. };
  5359. return converter;
  5360. };
  5361. /**
  5362. * Converts all images in the SVG output to data URIs for immediate rendering
  5363. */
  5364. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  5365. {
  5366. // Converts images to data URLs for immediate painting
  5367. if (converter == null)
  5368. {
  5369. converter = this.createImageUrlConverter();
  5370. }
  5371. // Barrier for asynchronous image loading
  5372. var counter = 0;
  5373. function inc()
  5374. {
  5375. counter++;
  5376. };
  5377. function dec()
  5378. {
  5379. counter--;
  5380. if (counter == 0)
  5381. {
  5382. callback(svgRoot);
  5383. }
  5384. };
  5385. var cache = imageCache || new Object();
  5386. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  5387. {
  5388. var images = svgRoot.getElementsByTagName(tagName);
  5389. for (var i = 0; i < images.length; i++)
  5390. {
  5391. (mxUtils.bind(this, function(img)
  5392. {
  5393. var src = converter.convert(img.getAttribute(srcAttr));
  5394. // Data URIs are pass-through
  5395. if (src != null && src.substring(0, 5) != 'data:')
  5396. {
  5397. var tmp = cache[src];
  5398. if (tmp == null)
  5399. {
  5400. inc();
  5401. this.convertImageToDataUri(src, function(uri)
  5402. {
  5403. if (uri != null)
  5404. {
  5405. cache[src] = uri;
  5406. img.setAttribute(srcAttr, uri);
  5407. }
  5408. dec();
  5409. });
  5410. }
  5411. else
  5412. {
  5413. img.setAttribute(srcAttr, tmp);
  5414. }
  5415. }
  5416. else if (src != null)
  5417. {
  5418. img.setAttribute(srcAttr, src);
  5419. }
  5420. }))(images[i]);
  5421. }
  5422. });
  5423. // Converts all known image tags in output
  5424. // LATER: Add support for images in CSS
  5425. convertImages('image', 'xlink:href');
  5426. convertImages('img', 'src');
  5427. // All from cache or no images
  5428. if (counter == 0)
  5429. {
  5430. callback(svgRoot);
  5431. }
  5432. };
  5433. /**
  5434. * Checks if the client is authorized and calls the next step.
  5435. */
  5436. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix, noBinary)
  5437. {
  5438. try
  5439. {
  5440. var binary = !noBinary && (forceBinary || /(\.png)($|\?)/i.test(url) ||
  5441. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url));
  5442. retry = (retry != null) ? retry : true;
  5443. var fn = mxUtils.bind(this, function()
  5444. {
  5445. mxUtils.get(url, mxUtils.bind(this, function(req)
  5446. {
  5447. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  5448. {
  5449. if (success != null)
  5450. {
  5451. var data = req.getText();
  5452. // Returns PNG as base64 encoded data URI
  5453. if (binary)
  5454. {
  5455. // NOTE: This requires BinaryToArray VB script in the page
  5456. if ((document.documentMode == 9 || document.documentMode == 10) &&
  5457. typeof window.mxUtilsBinaryToArray !== 'undefined')
  5458. {
  5459. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  5460. var tmp = new Array(bin.length);
  5461. for (var i = 0; i < bin.length; i++)
  5462. {
  5463. tmp[i] = String.fromCharCode(bin[i]);
  5464. }
  5465. data = tmp.join('');
  5466. }
  5467. // LATER: Could be JPG but modern browsers
  5468. // ignore the mime type in the data URI
  5469. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  5470. data = dataUriPrefix + this.base64Encode(data);
  5471. }
  5472. success(data);
  5473. }
  5474. }
  5475. else if (error != null)
  5476. {
  5477. error({message: mxResources.get('error') + ' ' + req.getStatus()}, req);
  5478. }
  5479. }), function(req)
  5480. {
  5481. if (error != null)
  5482. {
  5483. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  5484. }
  5485. }, binary, this.timeout, function()
  5486. {
  5487. if (retry && error != null)
  5488. {
  5489. error({code: App.ERROR_TIMEOUT, retry: fn});
  5490. }
  5491. });
  5492. });
  5493. fn();
  5494. }
  5495. catch (e)
  5496. {
  5497. if (error != null)
  5498. {
  5499. error(e);
  5500. }
  5501. }
  5502. };
  5503. /**
  5504. * Returns true if the given URL is known to have CORS headers.
  5505. */
  5506. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  5507. {
  5508. return this.editor.isCorsEnabledForUrl(url);
  5509. };
  5510. /**
  5511. * Translates this point by the given vector.
  5512. *
  5513. * @param {number} dx X-coordinate of the translation.
  5514. * @param {number} dy Y-coordinate of the translation.
  5515. */
  5516. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  5517. {
  5518. if (/(\.svg)$/i.test(url))
  5519. {
  5520. mxUtils.get(url, mxUtils.bind(this, function(req)
  5521. {
  5522. callback(this.createSvgDataUri(req.getText()));
  5523. }),
  5524. function()
  5525. {
  5526. callback(this.svgBrokenImage.src);
  5527. });
  5528. }
  5529. else
  5530. {
  5531. var img = new Image();
  5532. var self = this;
  5533. if (this.crossOriginImages)
  5534. {
  5535. img.crossOrigin = 'anonymous';
  5536. }
  5537. img.onload = function()
  5538. {
  5539. var canvas = document.createElement('canvas');
  5540. var ctx = canvas.getContext('2d');
  5541. canvas.height = img.height;
  5542. canvas.width = img.width;
  5543. ctx.drawImage(img, 0, 0);
  5544. try
  5545. {
  5546. callback(canvas.toDataURL());
  5547. }
  5548. catch (e)
  5549. {
  5550. callback(self.svgBrokenImage.src);
  5551. }
  5552. };
  5553. img.onerror = function()
  5554. {
  5555. callback(self.svgBrokenImage.src);
  5556. };
  5557. img.src = url;
  5558. }
  5559. };
  5560. /**
  5561. * Handling drag and drop and import.
  5562. */
  5563. /**
  5564. * Imports the given XML into the existing diagram.
  5565. */
  5566. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  5567. {
  5568. dx = (dx != null) ? dx : 0;
  5569. dy = (dy != null) ? dy : 0;
  5570. var cells = []
  5571. try
  5572. {
  5573. var graph = this.editor.graph;
  5574. if (xml != null && xml.length > 0)
  5575. {
  5576. // Adds pages
  5577. graph.model.beginUpdate();
  5578. try
  5579. {
  5580. var doc = mxUtils.parseXml(xml);
  5581. // Checks for mxfile with multiple pages
  5582. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  5583. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  5584. {
  5585. var diagrams = node.getElementsByTagName('diagram');
  5586. if (diagrams.length == 1)
  5587. {
  5588. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5589. }
  5590. else if (diagrams.length > 1)
  5591. {
  5592. var i0 = 0;
  5593. // Adds first page to current page if current page is only page and empty
  5594. if (this.pages != null && this.pages.length == 1 && this.isDiagramEmpty())
  5595. {
  5596. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5597. crop = false;
  5598. i0 = 1;
  5599. }
  5600. for (var i = i0; i < diagrams.length; i++)
  5601. {
  5602. // Imported pages must obtain a new ID
  5603. diagrams[i].removeAttribute('id');
  5604. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  5605. var index = this.pages.length;
  5606. // Checks for invalid page names
  5607. if (page.getName() == null)
  5608. {
  5609. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  5610. }
  5611. graph.model.execute(new ChangePage(this, page, page, index, true));
  5612. }
  5613. }
  5614. }
  5615. if (node != null && node.nodeName === 'mxGraphModel')
  5616. {
  5617. cells = graph.importGraphModel(node, dx, dy, crop);
  5618. }
  5619. }
  5620. finally
  5621. {
  5622. graph.model.endUpdate();
  5623. }
  5624. }
  5625. }
  5626. catch (e)
  5627. {
  5628. if (!noErrorHandling)
  5629. {
  5630. this.handleError(e);
  5631. }
  5632. else
  5633. {
  5634. throw e;
  5635. }
  5636. }
  5637. return cells;
  5638. };
  5639. /**
  5640. * Returns true for VSD, VDX and VSS, VSX files.
  5641. */
  5642. EditorUi.prototype.isRemoteVisioFormat = function(filename)
  5643. {
  5644. return /(\.v(sd|dx))($|\?)/i.test(filename) || /(\.vs(s|x))($|\?)/i.test(filename);
  5645. };
  5646. /**
  5647. * Imports the given Visio file
  5648. */
  5649. EditorUi.prototype.importVisio = function(file, done, onerror, filename)
  5650. {
  5651. filename = (filename != null) ? filename : file.name;
  5652. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5653. {
  5654. this.handleError(e);
  5655. });
  5656. var delayed = mxUtils.bind(this, function()
  5657. {
  5658. this.loadingExtensions = false;
  5659. if (this.doImportVisio)
  5660. {
  5661. if (this.isRemoteVisioFormat(filename) && VSD_CONVERT_URL != null)
  5662. {
  5663. var formData = new FormData();
  5664. formData.append('file1', file, filename);
  5665. var xhr = new XMLHttpRequest();
  5666. xhr.open('POST', VSD_CONVERT_URL);
  5667. xhr.responseType = 'blob';
  5668. xhr.onreadystatechange = mxUtils.bind(this, function()
  5669. {
  5670. if (xhr.readyState == 4)
  5671. {
  5672. if (xhr.status >= 200 && xhr.status <= 299)
  5673. {
  5674. try
  5675. {
  5676. //add back the file name
  5677. xhr.response.name = filename;
  5678. this.doImportVisio(xhr.response, done, onerror);
  5679. }
  5680. catch (e)
  5681. {
  5682. onerror(e);
  5683. }
  5684. }
  5685. else
  5686. {
  5687. onerror({});
  5688. }
  5689. }
  5690. });
  5691. xhr.send(formData);
  5692. }
  5693. else
  5694. {
  5695. try
  5696. {
  5697. this.doImportVisio(file, done, onerror);
  5698. }
  5699. catch (e)
  5700. {
  5701. onerror(e);
  5702. }
  5703. }
  5704. }
  5705. });
  5706. if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline())
  5707. {
  5708. this.loadingExtensions = true;
  5709. mxscript('js/extensions.min.js', delayed);
  5710. }
  5711. else
  5712. {
  5713. delayed();
  5714. }
  5715. };
  5716. /**
  5717. * Imports the given GraphML (yEd) file
  5718. */
  5719. EditorUi.prototype.importGraphML = function(xmlData, done, onerror)
  5720. {
  5721. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5722. {
  5723. this.handleError(e);
  5724. });
  5725. var delayed = mxUtils.bind(this, function()
  5726. {
  5727. this.loadingExtensions = false;
  5728. if (this.doImportGraphML)
  5729. {
  5730. try
  5731. {
  5732. this.doImportGraphML(xmlData, done, onerror);
  5733. }
  5734. catch (e)
  5735. {
  5736. onerror(e);
  5737. }
  5738. }
  5739. });
  5740. if (!this.doImportGraphML && !this.loadingExtensions && !this.isOffline())
  5741. {
  5742. this.loadingExtensions = true;
  5743. mxscript('js/extensions.min.js', delayed);
  5744. }
  5745. else
  5746. {
  5747. delayed();
  5748. }
  5749. };
  5750. /**
  5751. * Export the diagram to VSDX
  5752. */
  5753. EditorUi.prototype.exportVisio = function()
  5754. {
  5755. var delayed = mxUtils.bind(this, function()
  5756. {
  5757. this.loadingExtensions = false;
  5758. if (typeof VsdxExport !== 'undefined')
  5759. {
  5760. try
  5761. {
  5762. var expSuccess = new VsdxExport(this).exportCurrentDiagrams();
  5763. if (!expSuccess)
  5764. {
  5765. this.handleError({message: mxResources.get('unknownError')});
  5766. }
  5767. }
  5768. catch (e)
  5769. {
  5770. this.handleError(e);
  5771. }
  5772. }
  5773. });
  5774. if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline())
  5775. {
  5776. this.loadingExtensions = true;
  5777. mxscript('js/extensions.min.js', delayed);
  5778. }
  5779. else
  5780. {
  5781. delayed();
  5782. }
  5783. };
  5784. /**
  5785. * Imports the given Lucidchart data.
  5786. */
  5787. EditorUi.prototype.convertLucidChart = function(data, success, error)
  5788. {
  5789. var delayed = mxUtils.bind(this, function()
  5790. {
  5791. this.loadingExtensions = false;
  5792. // Checks for signature method
  5793. if (typeof window.LucidImporter !== 'undefined')
  5794. {
  5795. try
  5796. {
  5797. success(LucidImporter.importState(JSON.parse(data)));
  5798. }
  5799. catch (e)
  5800. {
  5801. error(e);
  5802. }
  5803. }
  5804. else
  5805. {
  5806. error({message: mxResources.get('serviceUnavailableOrBlocked')});
  5807. }
  5808. });
  5809. if (typeof window.LucidImporter === 'undefined' &&
  5810. !this.loadingExtensions && !this.isOffline())
  5811. {
  5812. this.loadingExtensions = true;
  5813. if (urlParams['dev'] == '1')
  5814. {
  5815. mxscript('js/diagramly/Extensions.js', delayed);
  5816. }
  5817. else
  5818. {
  5819. mxscript('js/extensions.min.js', delayed);
  5820. }
  5821. }
  5822. else
  5823. {
  5824. // Async needed for selection
  5825. window.setTimeout(delayed, 0);
  5826. }
  5827. };
  5828. /**
  5829. * Inserts the given text as a preformatted HTML text.
  5830. */
  5831. EditorUi.prototype.insertAsPreText = function(text, x, y)
  5832. {
  5833. var graph = this.editor.graph;
  5834. var cell = null;
  5835. graph.getModel().beginUpdate();
  5836. try
  5837. {
  5838. cell = graph.insertVertex(null, null, '<pre>' + text + '</pre>',
  5839. x, y, 1, 1, 'text;html=1;align=center;verticalAlign=middle;');
  5840. graph.updateCellSize(cell, true);
  5841. }
  5842. finally
  5843. {
  5844. graph.getModel().endUpdate();
  5845. }
  5846. return cell;
  5847. };
  5848. /**
  5849. * Imports the given XML into the existing diagram.
  5850. * TODO: Make this function asynchronous
  5851. */
  5852. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages)
  5853. {
  5854. crop = (crop != null) ? crop : true;
  5855. resizeImages = (resizeImages != null) ? resizeImages : true;
  5856. // Handles special case for Gliffy data which requires async server-side for parsing
  5857. if (text != null)
  5858. {
  5859. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  5860. {
  5861. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  5862. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  5863. {
  5864. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  5865. {
  5866. this.editor.graph.setSelectionCells(this.insertTextAt(
  5867. xhr.responseText, dx, dy, true));
  5868. }
  5869. }));
  5870. // Returns empty cells array as it is aysynchronous
  5871. return [];
  5872. }
  5873. // Handles special case of data URI which requires async loading for finding size
  5874. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() &&
  5875. (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  5876. {
  5877. var graph = this.editor.graph;
  5878. // Checks for embedded XML in PNG
  5879. if (text.substring(0, 22) == 'data:image/png;base64,')
  5880. {
  5881. var xml = this.extractGraphModelFromPng(text);
  5882. var result = this.importXml(xml, dx, dy, crop, true);
  5883. if (result.length > 0)
  5884. {
  5885. return result;
  5886. }
  5887. }
  5888. // Tries to extract embedded XML from SVG data URI
  5889. if (text.substring(0, 19) == 'data:image/svg+xml;')
  5890. {
  5891. try
  5892. {
  5893. var xml = null;
  5894. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  5895. {
  5896. xml = text.substring(text.indexOf(',') + 1);
  5897. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  5898. }
  5899. else
  5900. {
  5901. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  5902. }
  5903. var result = this.importXml(xml, dx, dy, crop, true);
  5904. if (result.length > 0)
  5905. {
  5906. return result;
  5907. }
  5908. }
  5909. catch (e)
  5910. {
  5911. // Ignore
  5912. }
  5913. }
  5914. this.loadImage(text, mxUtils.bind(this, function(img)
  5915. {
  5916. if (text.substring(0, 5) == 'data:')
  5917. {
  5918. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  5919. {
  5920. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5921. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5922. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  5923. }), resizeImages, this.maxImageSize);
  5924. }
  5925. else
  5926. {
  5927. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  5928. var w = Math.round(img.width * s);
  5929. var h = Math.round(img.height * s);
  5930. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  5931. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  5932. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  5933. }
  5934. }), mxUtils.bind(this, function()
  5935. {
  5936. var cell = null;
  5937. // Inserts invalid data URIs as text
  5938. graph.getModel().beginUpdate();
  5939. try
  5940. {
  5941. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  5942. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  5943. graph.updateCellSize(cell);
  5944. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  5945. }
  5946. finally
  5947. {
  5948. graph.getModel().endUpdate();
  5949. }
  5950. graph.setSelectionCell(cell);
  5951. }));
  5952. return [];
  5953. }
  5954. else
  5955. {
  5956. text = Graph.zapGremlins(mxUtils.trim(text));
  5957. if (this.isCompatibleString(text))
  5958. {
  5959. return this.importXml(text, dx, dy, crop);
  5960. }
  5961. else if (text.length > 0)
  5962. {
  5963. if (this.isLucidChartData(text))
  5964. {
  5965. this.convertLucidChart(text, mxUtils.bind(this, function(xml)
  5966. {
  5967. this.editor.graph.setSelectionCells(
  5968. this.importXml(xml, dx, dy, crop));
  5969. }), mxUtils.bind(this, function(e)
  5970. {
  5971. this.handleError(e);
  5972. }));
  5973. }
  5974. else
  5975. {
  5976. var graph = this.editor.graph;
  5977. var cell = null;
  5978. graph.getModel().beginUpdate();
  5979. try
  5980. {
  5981. // Fires cellsInserted to apply the current style to the inserted text.
  5982. // This requires the value to be empty when the event is fired.
  5983. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  5984. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  5985. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  5986. // Single tag is converted
  5987. if (text.charAt(0) == '<' && text.indexOf('>') == text.length - 1)
  5988. {
  5989. text = mxUtils.htmlEntities(text);
  5990. }
  5991. // Apply value and updates the cell size to fit the text block
  5992. cell.value = text;
  5993. graph.updateCellSize(cell);
  5994. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  5995. var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
  5996. if (regexp.test(cell.value))
  5997. {
  5998. graph.setLinkForCell(cell, cell.value);
  5999. }
  6000. // Adds spacing
  6001. cell.geometry.width += graph.gridSize;
  6002. cell.geometry.height += graph.gridSize;
  6003. }
  6004. finally
  6005. {
  6006. graph.getModel().endUpdate();
  6007. }
  6008. return [cell];
  6009. }
  6010. }
  6011. }
  6012. }
  6013. return [];
  6014. };
  6015. /**
  6016. * Formats the given file size.
  6017. */
  6018. EditorUi.prototype.formatFileSize = function(size)
  6019. {
  6020. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  6021. var i = -1;
  6022. do
  6023. {
  6024. size = size / 1024;
  6025. i++;
  6026. } while (size > 1024);
  6027. return Math.max(size, 0.1).toFixed(1) + units[i];
  6028. };
  6029. /**
  6030. * Imports the given XML into the existing diagram.
  6031. */
  6032. EditorUi.prototype.convertDataUri = function(uri)
  6033. {
  6034. // Handles special case of data URI which needs to be rewritten
  6035. // to be used in a cell style to remove the semicolon
  6036. if (uri.substring(0, 5) == 'data:')
  6037. {
  6038. var semi = uri.indexOf(';');
  6039. if (semi > 0)
  6040. {
  6041. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  6042. }
  6043. }
  6044. return uri;
  6045. };
  6046. /**
  6047. * Returns true for Gliffy data.
  6048. */
  6049. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  6050. {
  6051. return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
  6052. };
  6053. /**
  6054. * Returns true for Gliffy
  6055. */
  6056. EditorUi.prototype.isLucidChartData = function(data)
  6057. {
  6058. return data != null && data.substring(0, 26) == '{"state":"{\\"Properties\\":';
  6059. };
  6060. /**
  6061. * Imports a local file from the device or local storage.
  6062. */
  6063. EditorUi.prototype.importLocalFile = function(device, noSplash)
  6064. {
  6065. // input.click does not work in IE on Windows 7
  6066. if (device && Graph.fileSupport && ((!mxClient.IS_IE && !mxClient.IS_IE11) ||
  6067. navigator.appVersion.indexOf('Windows NT 6.1') < 0))
  6068. {
  6069. var input = document.createElement('input');
  6070. input.setAttribute('type', 'file');
  6071. mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
  6072. {
  6073. if (input.files != null)
  6074. {
  6075. // Using null for position will disable crop of input file
  6076. this.importFiles(input.files, null, null, this.maxImageSize);
  6077. }
  6078. }));
  6079. input.click();
  6080. }
  6081. else
  6082. {
  6083. window.openNew = false;
  6084. window.openKey = 'import';
  6085. if (!noSplash)
  6086. {
  6087. var prevValue = Editor.useLocalStorage;
  6088. Editor.useLocalStorage = !device;
  6089. }
  6090. // Closes dialog after open
  6091. window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
  6092. {
  6093. this.hideDialog(cancel);
  6094. }));
  6095. window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
  6096. {
  6097. if (filename != null && Graph.fileSupport && /(\.v(dx|sdx?))($|\?)/i.test(filename))
  6098. {
  6099. // "Not a UTF 8 file" when opening VSDX in IE so this is never called
  6100. var file = new Blob([xml], {type: 'application/octet-stream'})
  6101. this.importVisio(file, mxUtils.bind(this, function(xml)
  6102. {
  6103. this.importXml(xml, 0, 0, true);
  6104. }), null, filename);
  6105. }
  6106. else
  6107. {
  6108. this.editor.graph.setSelectionCells(this.importXml(xml, 0, 0, true));
  6109. }
  6110. }));
  6111. // Removes openFile if dialog is closed
  6112. this.showDialog(new OpenDialog(this).container, 360, 220, true, true, function()
  6113. {
  6114. window.openFile = null;
  6115. });
  6116. // Extends dialog close to show splash screen
  6117. if (!noSplash)
  6118. {
  6119. var dlg = this.dialog;
  6120. var dlgClose = dlg.close;
  6121. this.dialog.close = mxUtils.bind(this, function(cancel)
  6122. {
  6123. Editor.useLocalStorage = prevValue;
  6124. dlgClose.apply(dlg, arguments);
  6125. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  6126. {
  6127. this.showSplash();
  6128. }
  6129. });
  6130. }
  6131. }
  6132. };
  6133. /**
  6134. * Imports the given XML into the existing diagram.
  6135. */
  6136. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  6137. {
  6138. crop = (crop != null) ? crop : true;
  6139. var async = false;
  6140. var cells = null;
  6141. var handleResult = mxUtils.bind(this, function(xml)
  6142. {
  6143. var importedCells = null;
  6144. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  6145. {
  6146. this.loadLibrary(new LocalLibrary(this, xml, filename));
  6147. }
  6148. else
  6149. {
  6150. importedCells = this.importXml(xml, dx, dy, crop);
  6151. }
  6152. if (done != null)
  6153. {
  6154. done(importedCells);
  6155. }
  6156. });
  6157. if (mimeType.substring(0, 5) == 'image')
  6158. {
  6159. var containsModel = false;
  6160. if (mimeType.substring(0, 9) == 'image/png')
  6161. {
  6162. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  6163. if (xml != null && xml.length > 0)
  6164. {
  6165. cells = this.importXml(xml, dx, dy, crop);
  6166. containsModel = true;
  6167. }
  6168. }
  6169. if (!containsModel)
  6170. {
  6171. var graph = this.editor.graph;
  6172. // Strips encoding bit (eg. ;base64,) for cell style
  6173. var semi = data.indexOf(';');
  6174. if (semi > 0)
  6175. {
  6176. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6177. }
  6178. if (crop && graph.isGridEnabled())
  6179. {
  6180. dx = graph.snap(dx);
  6181. dy = graph.snap(dy);
  6182. }
  6183. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  6184. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6185. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  6186. }
  6187. }
  6188. else if (/(\.*<graphml )/.test(data))
  6189. {
  6190. async = true;
  6191. this.importGraphML(data, handleResult);
  6192. }
  6193. else if (file != null && filename != null && ((/(\.v(dx|sdx?))($|\?)/i.test(filename)) || /(\.vs(x|sx?))($|\?)/i.test(filename)))
  6194. {
  6195. // LATER: done and async are a hack before making this asynchronous
  6196. async = true;
  6197. this.importVisio(file, handleResult);
  6198. }
  6199. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  6200. {
  6201. // LATER: done and async are a hack before making this asynchronous
  6202. async = true;
  6203. // Returns empty cells array as it is aysynchronous
  6204. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  6205. {
  6206. if (xhr.readyState == 4)
  6207. {
  6208. if (xhr.status >= 200 && xhr.status <= 299)
  6209. {
  6210. handleResult(xhr.responseText);
  6211. }
  6212. else if (done != null)
  6213. {
  6214. done(null);
  6215. }
  6216. }
  6217. }), filename);
  6218. }
  6219. else if (!/(\.v(sd|dx))($|\?)/i.test(filename) && !/(\.vs(s|x))($|\?)/i.test(filename))
  6220. {
  6221. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  6222. }
  6223. if (!async && done != null)
  6224. {
  6225. done(cells);
  6226. }
  6227. return cells;
  6228. };
  6229. /**
  6230. * Base64 encodes the given string. This method seems to be more
  6231. * robust for encoding PNG from binary AJAX responses.
  6232. */
  6233. EditorUi.prototype.base64Encode = function(str)
  6234. {
  6235. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6236. var out = "", i = 0, len = str.length, c1, c2, c3;
  6237. while (i < len)
  6238. {
  6239. c1 = str.charCodeAt(i++) & 0xff;
  6240. if (i == len)
  6241. {
  6242. out += CHARS.charAt(c1 >> 2);
  6243. out += CHARS.charAt((c1 & 0x3) << 4);
  6244. out += "==";
  6245. break;
  6246. }
  6247. c2 = str.charCodeAt(i++);
  6248. if (i == len)
  6249. {
  6250. out += CHARS.charAt(c1 >> 2);
  6251. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  6252. out += CHARS.charAt((c2 & 0xF) << 2);
  6253. out += "=";
  6254. break;
  6255. }
  6256. c3 = str.charCodeAt(i++);
  6257. out += CHARS.charAt(c1 >> 2);
  6258. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  6259. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  6260. out += CHARS.charAt(c3 & 0x3F);
  6261. }
  6262. return out;
  6263. };
  6264. /**
  6265. *
  6266. */
  6267. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  6268. {
  6269. x = (x != null) ? x : 0;
  6270. y = (y != null) ? y : 0;
  6271. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6272. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  6273. var crop = x != null && y != null;
  6274. var resizeImages = true;
  6275. // Checks if large images are imported
  6276. var largeImages = false;
  6277. if (!mxClient.IS_CHROMEAPP && files != null)
  6278. {
  6279. var thresh = resampleThreshold || this.resampleThreshold;
  6280. for (var i = 0; i < files.length; i++)
  6281. {
  6282. if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
  6283. {
  6284. largeImages = true;
  6285. break;
  6286. }
  6287. }
  6288. }
  6289. var doImportFiles = mxUtils.bind(this, function()
  6290. {
  6291. var graph = this.editor.graph;
  6292. var gs = graph.gridSize;
  6293. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  6294. {
  6295. if (data != null && data.substring(0, 10) == '<mxlibrary')
  6296. {
  6297. this.spinner.stop();
  6298. this.loadLibrary(new LocalLibrary(this, data, filename));
  6299. return null;
  6300. }
  6301. else
  6302. {
  6303. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  6304. }
  6305. });
  6306. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  6307. {
  6308. graph.setSelectionCells(cells);
  6309. });
  6310. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6311. {
  6312. var count = files.length;
  6313. var remain = count;
  6314. var queue = [];
  6315. // Barrier waits for all files to be loaded asynchronously
  6316. var barrier = mxUtils.bind(this, function(index, fnc)
  6317. {
  6318. queue[index] = fnc;
  6319. if (--remain == 0)
  6320. {
  6321. this.spinner.stop();
  6322. if (barrierFn != null)
  6323. {
  6324. barrierFn(queue);
  6325. }
  6326. else
  6327. {
  6328. var cells = [];
  6329. graph.getModel().beginUpdate();
  6330. try
  6331. {
  6332. for (var j = 0; j < queue.length; j++)
  6333. {
  6334. var tmp = queue[j]();
  6335. if (tmp != null)
  6336. {
  6337. cells = cells.concat(tmp);
  6338. }
  6339. }
  6340. }
  6341. finally
  6342. {
  6343. graph.getModel().endUpdate();
  6344. }
  6345. }
  6346. resultFn(cells);
  6347. }
  6348. });
  6349. for (var i = 0; i < count; i++)
  6350. {
  6351. (mxUtils.bind(this, function(index)
  6352. {
  6353. var file = files[index];
  6354. if (file != null)
  6355. {
  6356. var reader = new FileReader();
  6357. reader.onload = mxUtils.bind(this, function(e)
  6358. {
  6359. if (filterFn == null || filterFn(file))
  6360. {
  6361. if (file.type.substring(0, 6) == 'image/')
  6362. {
  6363. if (file.type.substring(0, 9) == 'image/svg')
  6364. {
  6365. // Checks if SVG contains content attribute
  6366. var data = e.target.result;
  6367. var comma = data.indexOf(',');
  6368. var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
  6369. var root = mxUtils.parseXml(svgText);
  6370. var svgs = root.getElementsByTagName('svg');
  6371. if (svgs.length > 0)
  6372. {
  6373. var svgRoot = svgs[0];
  6374. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  6375. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  6376. {
  6377. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  6378. }
  6379. if (cont != null && cont.charAt(0) == '%')
  6380. {
  6381. cont = decodeURIComponent(cont);
  6382. }
  6383. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  6384. cont.substring(0, 14) === '<mxGraphModel '))
  6385. {
  6386. barrier(index, mxUtils.bind(this, function()
  6387. {
  6388. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  6389. }));
  6390. }
  6391. else
  6392. {
  6393. // SVG needs special handling to add viewbox if missing and
  6394. // find initial size from SVG attributes (only for IE11)
  6395. barrier(index, mxUtils.bind(this, function()
  6396. {
  6397. try
  6398. {
  6399. var prefix = data.substring(0, comma + 1);
  6400. // Parses SVG and find width and height
  6401. if (root != null)
  6402. {
  6403. var svgs = root.getElementsByTagName('svg');
  6404. if (svgs.length > 0)
  6405. {
  6406. var svgRoot = svgs[0];
  6407. var w = parseFloat(svgRoot.getAttribute('width'));
  6408. var h = parseFloat(svgRoot.getAttribute('height'));
  6409. // Check if viewBox attribute already exists
  6410. var vb = svgRoot.getAttribute('viewBox');
  6411. if (vb == null || vb.length == 0)
  6412. {
  6413. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6414. }
  6415. // Uses width and height from viewbox for
  6416. // missing width and height attributes
  6417. else if (isNaN(w) || isNaN(h))
  6418. {
  6419. var tokens = vb.split(' ');
  6420. if (tokens.length > 3)
  6421. {
  6422. w = parseFloat(tokens[2]);
  6423. h = parseFloat(tokens[3]);
  6424. }
  6425. }
  6426. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6427. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6428. var cells = fn(data, file.type, x + index * gs, y + index * gs, Math.max(
  6429. 1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  6430. // Hack to fix width and height asynchronously
  6431. if (isNaN(w) || isNaN(h))
  6432. {
  6433. var img = new Image();
  6434. img.onload = mxUtils.bind(this, function()
  6435. {
  6436. w = Math.max(1, img.width);
  6437. h = Math.max(1, img.height);
  6438. cells[0].geometry.width = w;
  6439. cells[0].geometry.height = h;
  6440. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6441. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6442. var semi = data.indexOf(';');
  6443. if (semi > 0)
  6444. {
  6445. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6446. }
  6447. graph.setCellStyles('image', data, [cells[0]]);
  6448. });
  6449. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6450. }
  6451. return cells;
  6452. }
  6453. }
  6454. }
  6455. catch (e)
  6456. {
  6457. // ignores any SVG parsing errors
  6458. }
  6459. return null;
  6460. }));
  6461. }
  6462. }
  6463. else
  6464. {
  6465. barrier(index, mxUtils.bind(this, function()
  6466. {
  6467. return null;
  6468. }));
  6469. }
  6470. }
  6471. else
  6472. {
  6473. // Checks if PNG+XML is available to bypass code below
  6474. var containsModel = false;
  6475. if (file.type == 'image/png')
  6476. {
  6477. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  6478. if (xml != null && xml.length > 0)
  6479. {
  6480. var img = new Image();
  6481. img.src = e.target.result;
  6482. barrier(index, mxUtils.bind(this, function()
  6483. {
  6484. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  6485. img.width, img.height, file.name);
  6486. }));
  6487. containsModel = true;
  6488. }
  6489. }
  6490. // Additional asynchronous step for finding image size
  6491. if (!containsModel)
  6492. {
  6493. // Cannot load local files in Chrome App
  6494. if (mxClient.IS_CHROMEAPP)
  6495. {
  6496. this.spinner.stop();
  6497. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  6498. mxResources.get('cancel'), mxUtils.bind(this, function()
  6499. {
  6500. // Hides the dialog
  6501. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  6502. {
  6503. // Redirects to import function
  6504. this.actions.get('import').funct();
  6505. })
  6506. );
  6507. }
  6508. else
  6509. {
  6510. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  6511. {
  6512. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  6513. {
  6514. barrier(index, mxUtils.bind(this, function()
  6515. {
  6516. // Refuses to insert images above a certain size as they kill the app
  6517. if (data2 != null && data2.length < maxBytes)
  6518. {
  6519. var s = (!resizeImages || !this.isResampleImage(e.target.result, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  6520. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  6521. }
  6522. else
  6523. {
  6524. this.handleError({message: mxResources.get('imageTooBig')});
  6525. return null;
  6526. }
  6527. }));
  6528. }), resizeImages, maxSize, resampleThreshold);
  6529. }), mxUtils.bind(this, function()
  6530. {
  6531. this.handleError({message: mxResources.get('invalidOrMissingFile')});
  6532. }));
  6533. }
  6534. }
  6535. }
  6536. }
  6537. else
  6538. {
  6539. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6540. {
  6541. barrier(index, function()
  6542. {
  6543. return cells;
  6544. });
  6545. });
  6546. }
  6547. }
  6548. });
  6549. // Handles special cases
  6550. if (/(\.v(dx|sdx?))($|\?)/i.test(file.name) || /(\.vs(x|sx?))($|\?)/i.test(file.name))
  6551. {
  6552. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6553. {
  6554. barrier(index, function()
  6555. {
  6556. return cells;
  6557. });
  6558. }, file);
  6559. }
  6560. else if (file.type.substring(0, 5) == 'image')
  6561. {
  6562. reader.readAsDataURL(file);
  6563. }
  6564. else
  6565. {
  6566. reader.readAsText(file);
  6567. }
  6568. }
  6569. }))(i);
  6570. }
  6571. }
  6572. });
  6573. if (largeImages)
  6574. {
  6575. this.confirmImageResize(function(doResize)
  6576. {
  6577. resizeImages = doResize;
  6578. doImportFiles();
  6579. }, resizeDialog);
  6580. }
  6581. else
  6582. {
  6583. doImportFiles();
  6584. }
  6585. };
  6586. /**
  6587. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6588. * Filename is an optional parameter for blobs (that do not have a filename).
  6589. */
  6590. EditorUi.prototype.confirmImageResize = function(fn, force)
  6591. {
  6592. force = (force != null) ? force : false;
  6593. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  6594. var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
  6595. var wrapper = function(remember, resize)
  6596. {
  6597. if (remember || force)
  6598. {
  6599. mxSettings.setResizeImages((remember) ? resize : null);
  6600. mxSettings.save();
  6601. }
  6602. resume();
  6603. fn(resize);
  6604. };
  6605. if (resizeImages != null && !force)
  6606. {
  6607. wrapper(false, resizeImages);
  6608. }
  6609. else
  6610. {
  6611. this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
  6612. function(remember)
  6613. {
  6614. wrapper(remember, true);
  6615. },
  6616. function(remember)
  6617. {
  6618. wrapper(remember, false);
  6619. }, mxResources.get('resize'), mxResources.get('actualSize'),
  6620. '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
  6621. '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
  6622. isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
  6623. (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
  6624. }
  6625. };
  6626. /**
  6627. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6628. * Filename is an optional parameter for blobs (that do not have a filename).
  6629. */
  6630. EditorUi.prototype.parseFile = function(file, fn, filename)
  6631. {
  6632. filename = (filename != null) ? filename : file.name;
  6633. var formData = new FormData();
  6634. formData.append('format', 'xml');
  6635. formData.append('upfile', file, filename);
  6636. var xhr = new XMLHttpRequest();
  6637. xhr.open('POST', OPEN_URL);
  6638. xhr.onreadystatechange = function()
  6639. {
  6640. fn(xhr);
  6641. };
  6642. xhr.send(formData);
  6643. };
  6644. /**
  6645. *
  6646. */
  6647. EditorUi.prototype.isResampleImage = function(data, thresh)
  6648. {
  6649. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  6650. return data.length > thresh;
  6651. };
  6652. /**
  6653. * Resizes the given image if <maxImageBytes> is not null.
  6654. */
  6655. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  6656. {
  6657. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6658. var w = Math.max(1, img.width);
  6659. var h = Math.max(1, img.height);
  6660. if (enabled && this.isResampleImage(data, thresh))
  6661. {
  6662. try
  6663. {
  6664. var factor = Math.max(w / maxSize, h / maxSize);
  6665. if (factor > 1)
  6666. {
  6667. var w2 = Math.round(w / factor);
  6668. var h2 = Math.round(h / factor);
  6669. var canvas = document.createElement('canvas');
  6670. canvas.width = w2;
  6671. canvas.height = h2;
  6672. var ctx = canvas.getContext('2d');
  6673. ctx.drawImage(img, 0, 0, w2, h2);
  6674. var tmp = canvas.toDataURL();
  6675. // Uses new image if smaller
  6676. if (tmp.length < data.length)
  6677. {
  6678. // Checks if the image is empty by comparing
  6679. // with an empty image of the same size
  6680. var canvas2 = document.createElement('canvas');
  6681. canvas2.width = w2;
  6682. canvas2.height = h2;
  6683. var tmp2 = canvas2.toDataURL();
  6684. if (tmp !== tmp2)
  6685. {
  6686. data = tmp;
  6687. w = w2;
  6688. h = h2;
  6689. }
  6690. }
  6691. }
  6692. }
  6693. catch (e)
  6694. {
  6695. // ignores image scaling errors
  6696. }
  6697. }
  6698. fn(data, w, h);
  6699. };
  6700. EditorUi.prototype.crcTable = [];
  6701. for (var n = 0; n < 256; n++)
  6702. {
  6703. var c = n;
  6704. for (var k = 0; k < 8; k++)
  6705. {
  6706. if ((c & 1) == 1)
  6707. {
  6708. c = 0xedb88320 ^ (c >>> 1);
  6709. }
  6710. else
  6711. {
  6712. c >>>= 1;
  6713. }
  6714. EditorUi.prototype.crcTable[n] = c;
  6715. }
  6716. }
  6717. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  6718. {
  6719. var c = crc;
  6720. for (var n = 0; n < len; n++)
  6721. {
  6722. c = EditorUi.prototype.crcTable[(c ^ data.charCodeAt(off + n)) & 0xff] ^ (c >>> 8);
  6723. }
  6724. return c;
  6725. };
  6726. EditorUi.prototype.crc32 = function(str)
  6727. {
  6728. this.crcTable = this.crcTable || this.createCrcTable();
  6729. var crc = 0 ^ (-1);
  6730. for (var i = 0; i < str.length; i++ )
  6731. {
  6732. crc = (crc >>> 8) ^ this.crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
  6733. }
  6734. return (crc ^ (-1)) >>> 0;
  6735. };
  6736. /**
  6737. * Adds the given text to the compressed or non-compressed text chunk.
  6738. */
  6739. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  6740. {
  6741. var base64 = data.substring(data.indexOf(',') + 1);
  6742. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  6743. var pos = 0;
  6744. function fread(d, count)
  6745. {
  6746. var start = pos;
  6747. pos += count;
  6748. return d.substring(start, pos);
  6749. };
  6750. // Reads unsigned long 32 bit big endian
  6751. function _freadint(d)
  6752. {
  6753. var bytes = fread(d, 4);
  6754. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  6755. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  6756. };
  6757. function writeInt(num)
  6758. {
  6759. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  6760. (num >> 8) & 0x000000ff, num & 0x000000ff);
  6761. };
  6762. // Checks signature
  6763. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  6764. {
  6765. if (error != null)
  6766. {
  6767. error();
  6768. }
  6769. return;
  6770. }
  6771. // Reads header chunk
  6772. fread(f,4);
  6773. if (fread(f,4) != 'IHDR')
  6774. {
  6775. if (error != null)
  6776. {
  6777. error();
  6778. }
  6779. return;
  6780. }
  6781. fread(f, 17);
  6782. var result = f.substring(0, pos);
  6783. do
  6784. {
  6785. var n = _freadint(f);
  6786. var chunk = fread(f,4);
  6787. if (chunk == 'IDAT')
  6788. {
  6789. result = f.substring(0, pos - 8);
  6790. var chunkData = key + String.fromCharCode(0) +
  6791. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  6792. value;
  6793. var crc = 0xffffffff;
  6794. crc = this.updateCRC(crc, type, 0, 4);
  6795. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  6796. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  6797. result += f.substring(pos - 8, f.length);
  6798. break;
  6799. }
  6800. result += f.substring(pos - 8, pos - 4 + n);
  6801. fread(f,n);
  6802. fread(f,4);
  6803. }
  6804. while (n);
  6805. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  6806. }
  6807. /**
  6808. * Extracts the XML from the compressed or non-compressed text chunk.
  6809. */
  6810. EditorUi.prototype.extractGraphModelFromPng = function(data)
  6811. {
  6812. var result = null;
  6813. try
  6814. {
  6815. var base64 = data.substring(data.indexOf(',') + 1);
  6816. // Workaround for invalid character error in Safari
  6817. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  6818. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  6819. {
  6820. var value = binary.substring(pos + 8, pos + 8 + length);
  6821. if (type == 'zTXt')
  6822. {
  6823. var idx = value.indexOf(String.fromCharCode(0));
  6824. if (value.substring(0, idx) == 'mxGraphModel')
  6825. {
  6826. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  6827. var xmlData = Graph.bytesToString(pako.inflateRaw(
  6828. value.substring(idx + 2))).replace(/\+/g,' ');
  6829. if (xmlData != null && xmlData.length > 0)
  6830. {
  6831. result = xmlData;
  6832. }
  6833. }
  6834. }
  6835. // Uncompressed section is normally not used
  6836. else if (type == 'tEXt')
  6837. {
  6838. var vals = value.split(String.fromCharCode(0));
  6839. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  6840. {
  6841. result = vals[1];
  6842. }
  6843. }
  6844. if (result != null || type == 'IDAT')
  6845. {
  6846. // Stops processing the file as our text chunks
  6847. // are always placed before the data section
  6848. return true;
  6849. }
  6850. }));
  6851. }
  6852. catch (e)
  6853. {
  6854. // ignores decoding errors
  6855. }
  6856. if (result != null && result.charAt(0) == '%')
  6857. {
  6858. result = decodeURIComponent(result);
  6859. }
  6860. // Workaround for double encoded content
  6861. if (result != null && result.charAt(0) == '%')
  6862. {
  6863. result = decodeURIComponent(result);
  6864. }
  6865. return result;
  6866. };
  6867. /**
  6868. * Loads the image from the given URI.
  6869. *
  6870. * @param {number} dx X-coordinate of the translation.
  6871. * @param {number} dy Y-coordinate of the translation.
  6872. */
  6873. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  6874. {
  6875. try
  6876. {
  6877. var img = new Image();
  6878. img.onload = function()
  6879. {
  6880. onload(img);
  6881. }
  6882. if (onerror != null)
  6883. {
  6884. img.onerror = onerror;
  6885. }
  6886. img.src = uri;
  6887. }
  6888. catch (e)
  6889. {
  6890. if (onerror != null)
  6891. {
  6892. onerror(e);
  6893. }
  6894. else
  6895. {
  6896. throw e;
  6897. }
  6898. }
  6899. };
  6900. // Initializes the user interface
  6901. var editorUiInit = EditorUi.prototype.init;
  6902. EditorUi.prototype.init = function()
  6903. {
  6904. mxStencilRegistry.allowEval = mxStencilRegistry.allowEval && !this.isOfflineApp();
  6905. // Must be set before UI is created in superclass
  6906. if (typeof window.mxSettings !== 'undefined')
  6907. {
  6908. this.formatWidth = mxSettings.getFormatWidth();
  6909. }
  6910. var ui = this;
  6911. var graph = this.editor.graph;
  6912. // Redirects custom link title via UI for page links
  6913. graph.getLinkTitle = function(href)
  6914. {
  6915. return ui.getLinkTitle(href);
  6916. };
  6917. // Redirects custom link via UI for page link handling
  6918. graph.customLinkClicked = function(link)
  6919. {
  6920. var done = false;
  6921. try
  6922. {
  6923. ui.handleCustomLink(link);
  6924. done = true;
  6925. }
  6926. catch (e)
  6927. {
  6928. ui.handleError(e);
  6929. }
  6930. return done;
  6931. };
  6932. // Extends clear default style to clear persisted settings
  6933. var clearDefaultStyle = this.clearDefaultStyle;
  6934. this.clearDefaultStyle = function()
  6935. {
  6936. clearDefaultStyle.apply(this, arguments);
  6937. };
  6938. // Sets help link for placeholders
  6939. if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
  6940. {
  6941. EditDataDialog.placeholderHelpLink = 'https://desk.draw.io/support/solutions/articles/16000051979';
  6942. }
  6943. // Passes current page to editor window
  6944. var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
  6945. this.editor.getEditBlankUrl = function(params)
  6946. {
  6947. params = (params != null) ? params : '';
  6948. if (ui.pages != null && ui.currentPage != null)
  6949. {
  6950. for (var i = 0; i < ui.pages.length; i++)
  6951. {
  6952. if (ui.pages[i] == ui.currentPage)
  6953. {
  6954. if (i > 0)
  6955. {
  6956. params += ((params.length > 0) ? '&' : '?') + 'page=' + i;
  6957. }
  6958. break;
  6959. }
  6960. }
  6961. }
  6962. if (urlParams['dev'] == '1')
  6963. {
  6964. params += ((params.length > 0) ? '&' : '?') + 'dev=1&drawdev=1';
  6965. }
  6966. return editorGetEditBlankUrl.apply(this, arguments);
  6967. };
  6968. // For chromeless mode and lightbox mode in viewer
  6969. // Must be overridden before supercall to be applied
  6970. // in case of chromeless initialization
  6971. var graphAddClickHandler = graph.addClickHandler;
  6972. graph.addClickHandler = function(highlight, beforeClick, onClick)
  6973. {
  6974. var tmp = beforeClick;
  6975. beforeClick = function(evt, href)
  6976. {
  6977. if (href == null)
  6978. {
  6979. var source = mxEvent.getSource(evt);
  6980. if (source.nodeName.toLowerCase() == 'a')
  6981. {
  6982. href = source.getAttribute('href');
  6983. }
  6984. }
  6985. if (href != null && graph.isCustomLink(href) &&
  6986. (mxEvent.isTouchEvent(evt) ||
  6987. !mxEvent.isPopupTrigger(evt)) &&
  6988. graph.customLinkClicked(href))
  6989. {
  6990. mxEvent.consume(evt);
  6991. }
  6992. if (tmp != null)
  6993. {
  6994. tmp(evt, href);
  6995. }
  6996. };
  6997. // For some reason, local argument override is not enough in this case...
  6998. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  6999. };
  7000. editorUiInit.apply(this, arguments);
  7001. if (mxClient.IS_SVG)
  7002. {
  7003. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  7004. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  7005. }
  7006. // Overrides print dialog size
  7007. ui.actions.get('print').funct = function()
  7008. {
  7009. ui.showDialog(new PrintDialog(ui).container, 360,
  7010. (ui.pages != null && ui.pages.length > 1) ?
  7011. 420 : 360, true, true);
  7012. };
  7013. // Specifies the default filename
  7014. this.defaultFilename = mxResources.get('untitledDiagram');
  7015. // Adds placeholder for %page% and %pagenumber%
  7016. var graphGetGlobalVariable = graph.getGlobalVariable;
  7017. graph.getGlobalVariable = function(name)
  7018. {
  7019. if (name == 'page' && ui.currentPage != null)
  7020. {
  7021. return ui.currentPage.getName();
  7022. }
  7023. else if (name == 'pagenumber')
  7024. {
  7025. if (ui.currentPage != null && ui.pages != null)
  7026. {
  7027. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  7028. }
  7029. else
  7030. {
  7031. return 1;
  7032. }
  7033. }
  7034. return graphGetGlobalVariable.apply(this, arguments);
  7035. };
  7036. var graphLabelLinkClicked = graph.labelLinkClicked;
  7037. graph.labelLinkClicked = function(state, elt, evt)
  7038. {
  7039. var href = elt.getAttribute('href');
  7040. if (href != null && graph.isCustomLink(href) &&
  7041. (mxEvent.isTouchEvent(evt) ||
  7042. !mxEvent.isPopupTrigger(evt)))
  7043. {
  7044. // Active links are moved to the hint
  7045. if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
  7046. {
  7047. graph.customLinkClicked(href);
  7048. // Resets rubberband after click on locked cell
  7049. graph.getRubberband().reset();
  7050. }
  7051. mxEvent.consume(evt);
  7052. }
  7053. else
  7054. {
  7055. graphLabelLinkClicked.apply(this, arguments);
  7056. }
  7057. };
  7058. // Overrides editor filename
  7059. this.editor.getOrCreateFilename = function()
  7060. {
  7061. var filename = ui.defaultFilename;
  7062. var file = ui.getCurrentFile();
  7063. if (file != null)
  7064. {
  7065. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  7066. }
  7067. return filename;
  7068. };
  7069. // Disables print action for standalone apps on iOS
  7070. // because there is no way to close the new window
  7071. // LATER: Use iframe for print, disable preview
  7072. var printAction = this.actions.get('print');
  7073. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  7074. printAction.visible = printAction.isEnabled();
  7075. // Scales pages/graph to fit available size
  7076. if (!this.editor.chromeless || this.editor.editable)
  7077. {
  7078. // Defines additional hotkeys
  7079. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  7080. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  7081. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  7082. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  7083. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  7084. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  7085. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  7086. if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp)
  7087. {
  7088. this.altShiftActions[83] = 'synchronize'; // Alt+Shift+S
  7089. }
  7090. // Handles copy paste of images from clipboard
  7091. if (!mxClient.IS_IE)
  7092. {
  7093. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  7094. {
  7095. var graph = this.editor.graph;
  7096. if (!mxEvent.isConsumed(evt))
  7097. {
  7098. try
  7099. {
  7100. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  7101. var containsText = false;
  7102. // Workaround for asynchronous paste event processing in textInput
  7103. // is to ignore this event if it contains text/html/rtf (see below).
  7104. // NOTE: Image is not pasted into textInput so can't listen there.
  7105. for (var i = 0; i < data.types.length; i++)
  7106. {
  7107. if (data.types[i].substring(0, 5) === 'text/')
  7108. {
  7109. containsText = true;
  7110. break;
  7111. }
  7112. }
  7113. if (!containsText)
  7114. {
  7115. var items = data.items;
  7116. for (index in items)
  7117. {
  7118. var item = items[index];
  7119. if (item.kind === 'file')
  7120. {
  7121. if (graph.isEditing())
  7122. {
  7123. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7124. {
  7125. // Inserts image into current text box
  7126. graph.insertImage(data, w, h);
  7127. }, function()
  7128. {
  7129. // No post processing
  7130. }, function(file)
  7131. {
  7132. // Handles only images
  7133. return file.type.substring(0, 6) == 'image/';
  7134. }, function(queue)
  7135. {
  7136. // Invokes elements of queue in order
  7137. for (var i = 0; i < queue.length; i++)
  7138. {
  7139. queue[i]();
  7140. }
  7141. });
  7142. }
  7143. else
  7144. {
  7145. var pt = this.editor.graph.getInsertPoint();
  7146. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  7147. mxEvent.consume(evt);
  7148. }
  7149. break;
  7150. }
  7151. }
  7152. }
  7153. }
  7154. catch (e)
  7155. {
  7156. // ignore
  7157. }
  7158. }
  7159. }), false);
  7160. }
  7161. // Focused but invisible textarea during control or meta key events
  7162. var textInput = document.createElement('div');
  7163. textInput.style.position = 'absolute';
  7164. textInput.style.whiteSpace = 'nowrap';
  7165. textInput.style.overflow = 'hidden';
  7166. textInput.style.display = 'block';
  7167. textInput.contentEditable = true;
  7168. mxUtils.setOpacity(textInput, 0);
  7169. textInput.style.width = '1px';
  7170. textInput.style.height = '1px';
  7171. textInput.innerHTML = '&nbsp;';
  7172. var restoreFocus = false;
  7173. // Disables built-in cut, copy and paste shortcuts
  7174. this.keyHandler.bindControlKey(88, null);
  7175. this.keyHandler.bindControlKey(67, null);
  7176. this.keyHandler.bindControlKey(86, null);
  7177. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  7178. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  7179. {
  7180. // No dialog visible
  7181. var source = mxEvent.getSource(evt);
  7182. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  7183. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  7184. {
  7185. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  7186. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  7187. {
  7188. // Cannot use parentNode for check in IE
  7189. if (!restoreFocus)
  7190. {
  7191. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  7192. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  7193. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  7194. graph.container.appendChild(textInput);
  7195. restoreFocus = true;
  7196. // Workaround for selected document content in quirks mode
  7197. if (mxClient.IS_QUIRKS)
  7198. {
  7199. window.setTimeout(function()
  7200. {
  7201. textInput.focus();
  7202. document.execCommand('selectAll', false, null);
  7203. }, 0);
  7204. }
  7205. else
  7206. {
  7207. textInput.focus();
  7208. document.execCommand('selectAll', false, null);
  7209. }
  7210. }
  7211. }
  7212. }
  7213. }));
  7214. // Clears input and restores focus and selection
  7215. function clearInput()
  7216. {
  7217. window.setTimeout(function()
  7218. {
  7219. textInput.innerHTML = '&nbsp;';
  7220. textInput.focus();
  7221. document.execCommand('selectAll', false, null);
  7222. }, 0);
  7223. };
  7224. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  7225. {
  7226. // Workaround for asynchronous event read invalid in IE quirks mode
  7227. var keyCode = evt.keyCode;
  7228. // Asynchronous workaround for scroll to origin after paste if the
  7229. // Ctrl-key is not pressed for long enough in FF on Windows
  7230. window.setTimeout(mxUtils.bind(this, function()
  7231. {
  7232. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  7233. keyCode == 91 /* Meta */))
  7234. {
  7235. restoreFocus = false;
  7236. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  7237. {
  7238. graph.container.focus();
  7239. }
  7240. textInput.parentNode.removeChild(textInput);
  7241. // Workaround for lost cursor in focused element
  7242. if (this.dialog == null)
  7243. {
  7244. mxUtils.clearSelection();
  7245. }
  7246. }
  7247. }), 0);
  7248. }));
  7249. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  7250. {
  7251. if (graph.isEnabled())
  7252. {
  7253. mxClipboard.copy(graph);
  7254. this.copyCells(textInput);
  7255. clearInput();
  7256. }
  7257. }));
  7258. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  7259. {
  7260. if (graph.isEnabled())
  7261. {
  7262. mxClipboard.copy(graph);
  7263. this.copyCells(textInput, true);
  7264. clearInput();
  7265. }
  7266. }));
  7267. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  7268. {
  7269. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  7270. {
  7271. textInput.innerHTML = '&nbsp;';
  7272. textInput.focus();
  7273. window.setTimeout(mxUtils.bind(this, function()
  7274. {
  7275. this.pasteCells(evt, textInput);
  7276. textInput.innerHTML = '&nbsp;';
  7277. }), 0);
  7278. }
  7279. }), true);
  7280. // Needed for IE11
  7281. var isSelectionAllowed2 = this.isSelectionAllowed;
  7282. this.isSelectionAllowed = function(evt)
  7283. {
  7284. if (mxEvent.getSource(evt) == textInput)
  7285. {
  7286. return true;
  7287. }
  7288. return isSelectionAllowed2.apply(this, arguments);
  7289. };
  7290. };
  7291. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  7292. var x = document.body.clientWidth / 2 - 2;
  7293. // Holds the x-coordinate of the point
  7294. this.spinner = this.createSpinner(x, y, 24);
  7295. // Installs drag and drop handler for rich text editor
  7296. if (Graph.fileSupport)
  7297. {
  7298. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  7299. {
  7300. // Setup the dnd listeners
  7301. var graph = this.editor.graph;
  7302. var textElt = graph.cellEditor.text2;
  7303. var dropElt = null;
  7304. if (textElt != null)
  7305. {
  7306. mxEvent.addListener(textElt, 'dragleave', function(evt)
  7307. {
  7308. if (dropElt != null)
  7309. {
  7310. dropElt.parentNode.removeChild(dropElt);
  7311. dropElt = null;
  7312. }
  7313. evt.stopPropagation();
  7314. evt.preventDefault();
  7315. });
  7316. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  7317. {
  7318. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7319. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7320. {
  7321. dropElt = this.highlightElement(textElt);
  7322. }
  7323. evt.stopPropagation();
  7324. evt.preventDefault();
  7325. }));
  7326. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  7327. {
  7328. if (dropElt != null)
  7329. {
  7330. dropElt.parentNode.removeChild(dropElt);
  7331. dropElt = null;
  7332. }
  7333. if (evt.dataTransfer.files.length > 0)
  7334. {
  7335. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7336. {
  7337. // Inserts image into current text box
  7338. graph.insertImage(data, w, h);
  7339. }, function()
  7340. {
  7341. // No post processing
  7342. }, function(file)
  7343. {
  7344. // Handles only images
  7345. return file.type.substring(0, 6) == 'image/';
  7346. }, function(queue)
  7347. {
  7348. // Invokes elements of queue in order
  7349. for (var i = 0; i < queue.length; i++)
  7350. {
  7351. queue[i]();
  7352. }
  7353. }, mxEvent.isControlDown(evt));
  7354. }
  7355. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  7356. {
  7357. var uri = evt.dataTransfer.getData('text/uri-list');
  7358. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7359. {
  7360. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7361. {
  7362. var w = Math.max(1, img.width);
  7363. var h = Math.max(1, img.height);
  7364. var maxSize = this.maxImageSize;
  7365. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7366. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  7367. }));
  7368. }
  7369. else
  7370. {
  7371. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7372. }
  7373. }
  7374. else
  7375. {
  7376. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7377. {
  7378. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  7379. }
  7380. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7381. {
  7382. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7383. }
  7384. }
  7385. evt.stopPropagation();
  7386. evt.preventDefault();
  7387. }));
  7388. }
  7389. }));
  7390. }
  7391. //Add ruler in test mode only
  7392. //TODO add the ruler containers correctly and make the vertical one dynamic as the side panel size can change
  7393. if (urlParams['ruler'] == '1' && typeof mxRuler !== 'undefined')
  7394. {
  7395. var hRulerDiv = document.createElement('div');
  7396. hRulerDiv.style.position = 'absolute';
  7397. hRulerDiv.style.top = '95px';
  7398. hRulerDiv.style.left = '250px';
  7399. hRulerDiv.style.width = '2000px';
  7400. hRulerDiv.style.height = '30px';
  7401. hRulerDiv.style.background = 'whiteSmoke';
  7402. document.body.appendChild(hRulerDiv);
  7403. var vRulerDiv = document.createElement('div');
  7404. vRulerDiv.style.position = 'absolute';
  7405. vRulerDiv.style.top = '125px';
  7406. vRulerDiv.style.left = '220px';
  7407. vRulerDiv.style.width = '30px';
  7408. vRulerDiv.style.height = '1000px';
  7409. vRulerDiv.style.background = 'whiteSmoke';
  7410. document.body.appendChild(vRulerDiv);
  7411. var square = document.createElement('div');
  7412. square.style.position = 'absolute';
  7413. square.style.top = '95px';
  7414. square.style.left = '220px';
  7415. square.style.width = '30px';
  7416. square.style.height = '30px';
  7417. square.style.background = 'whiteSmoke';
  7418. document.body.appendChild(square);
  7419. this.vRuler = new mxRuler(this.editor.graph, vRulerDiv, true);
  7420. this.hRuler = new mxRuler(this.editor.graph, hRulerDiv, false);
  7421. }
  7422. // Adds an element to edit the style in the footer in test mode
  7423. if (urlParams['styledev'] == '1')
  7424. {
  7425. var footer = document.getElementById('geFooter');
  7426. if (footer != null)
  7427. {
  7428. this.styleInput = document.createElement('input');
  7429. this.styleInput.setAttribute('type', 'text');
  7430. this.styleInput.style.position = 'absolute';
  7431. this.styleInput.style.top = '14px';
  7432. this.styleInput.style.left = '2px';
  7433. // Workaround for ignore right CSS property in FF
  7434. this.styleInput.style.width = '98%';
  7435. this.styleInput.style.visibility = 'hidden';
  7436. this.styleInput.style.opacity = '0.9';
  7437. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  7438. {
  7439. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  7440. }));
  7441. footer.appendChild(this.styleInput);
  7442. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  7443. {
  7444. if (this.editor.graph.getSelectionCount() > 0)
  7445. {
  7446. var cell = this.editor.graph.getSelectionCell();
  7447. var style = this.editor.graph.getModel().getStyle(cell);
  7448. this.styleInput.value = style || '';
  7449. this.styleInput.style.visibility = 'visible';
  7450. } else
  7451. {
  7452. this.styleInput.style.visibility = 'hidden';
  7453. }
  7454. }));
  7455. }
  7456. var isSelectionAllowed = this.isSelectionAllowed;
  7457. this.isSelectionAllowed = function(evt)
  7458. {
  7459. if (mxEvent.getSource(evt) == this.styleInput)
  7460. {
  7461. return true;
  7462. }
  7463. return isSelectionAllowed.apply(this, arguments);
  7464. };
  7465. }
  7466. // Removes info text in page
  7467. var info = document.getElementById('geInfo');
  7468. if (info != null)
  7469. {
  7470. info.parentNode.removeChild(info);
  7471. }
  7472. // Installs drag and drop handler for files
  7473. // Enables dropping files
  7474. if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
  7475. {
  7476. // Setup the dnd listeners
  7477. var dropElt = null;
  7478. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  7479. {
  7480. if (graph.isEnabled())
  7481. {
  7482. if (dropElt != null)
  7483. {
  7484. dropElt.parentNode.removeChild(dropElt);
  7485. dropElt = null;
  7486. }
  7487. evt.stopPropagation();
  7488. evt.preventDefault();
  7489. }
  7490. });
  7491. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  7492. {
  7493. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7494. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7495. {
  7496. dropElt = this.highlightElement(graph.container);
  7497. }
  7498. if (this.sidebar != null)
  7499. {
  7500. this.sidebar.hideTooltip();
  7501. }
  7502. evt.stopPropagation();
  7503. evt.preventDefault();
  7504. }));
  7505. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  7506. {
  7507. if (dropElt != null)
  7508. {
  7509. dropElt.parentNode.removeChild(dropElt);
  7510. dropElt = null;
  7511. }
  7512. if (graph.isEnabled())
  7513. {
  7514. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  7515. var tr = graph.view.translate;
  7516. var scale = graph.view.scale;
  7517. var x = pt.x / scale - tr.x;
  7518. var y = pt.y / scale - tr.y;
  7519. if (mxEvent.isAltDown(evt))
  7520. {
  7521. x = 0;
  7522. y = 0;
  7523. }
  7524. if (evt.dataTransfer.files.length > 0)
  7525. {
  7526. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  7527. mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  7528. }
  7529. else
  7530. {
  7531. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  7532. evt.dataTransfer.getData('text/uri-list') : null;
  7533. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  7534. if (data != null)
  7535. {
  7536. graph.setSelectionCells(this.importXml(data, x, y, true));
  7537. }
  7538. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7539. {
  7540. var html = evt.dataTransfer.getData('text/html');
  7541. var div = document.createElement('div');
  7542. div.innerHTML = html;
  7543. // The default is based on the extension
  7544. var asImage = null;
  7545. // Extracts single image
  7546. var imgs = div.getElementsByTagName('img');
  7547. if (imgs != null && imgs.length == 1)
  7548. {
  7549. html = imgs[0].getAttribute('src');
  7550. // Handles special case where the src attribute has no valid extension
  7551. // in which case the text would be inserted as text with a link
  7552. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  7553. {
  7554. asImage = true;
  7555. }
  7556. }
  7557. else
  7558. {
  7559. // Extracts single link
  7560. var a = div.getElementsByTagName('a');
  7561. if (a != null && a.length == 1)
  7562. {
  7563. html = a[0].getAttribute('href');
  7564. }
  7565. }
  7566. var resizeImages = true;
  7567. var doInsert = mxUtils.bind(this, function()
  7568. {
  7569. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage, null, resizeImages));
  7570. });
  7571. if (asImage && html.length > this.resampleThreshold)
  7572. {
  7573. this.confirmImageResize(function(doResize)
  7574. {
  7575. resizeImages = doResize;
  7576. doInsert();
  7577. }, mxEvent.isControlDown(evt));
  7578. }
  7579. else
  7580. {
  7581. doInsert();
  7582. }
  7583. }
  7584. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7585. {
  7586. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7587. {
  7588. var w = Math.max(1, img.width);
  7589. var h = Math.max(1, img.height);
  7590. var maxSize = this.maxImageSize;
  7591. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7592. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  7593. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  7594. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  7595. }), mxUtils.bind(this, function(img)
  7596. {
  7597. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  7598. }));
  7599. }
  7600. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7601. {
  7602. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  7603. }
  7604. }
  7605. }
  7606. evt.stopPropagation();
  7607. evt.preventDefault();
  7608. }), false);
  7609. }
  7610. this.initPages();
  7611. // Installs listener for fixing references in undo history in
  7612. // collaborative editing where terminals may have vanished
  7613. // Undo/Redo listener to update edit's references before executing undo/redo
  7614. this.editUpdateListener = mxUtils.bind(this, function(sender, evt)
  7615. {
  7616. var edit = evt.getProperty('edit');
  7617. if (edit != null)
  7618. {
  7619. this.updateEditReferences(edit);
  7620. }
  7621. });
  7622. this.editor.undoManager.addListener(mxEvent.BEFORE_UNDO, this.editUpdateListener);
  7623. this.editor.undoManager.addListener(mxEvent.BEFORE_REDO, this.editUpdateListener);
  7624. // Embedded mode
  7625. if (urlParams['embed'] == '1')
  7626. {
  7627. this.initializeEmbedMode();
  7628. }
  7629. this.installSettings();
  7630. };
  7631. /**
  7632. *
  7633. */
  7634. EditorUi.prototype.getLinkTitle = function(href)
  7635. {
  7636. var title = Graph.prototype.getLinkTitle.apply(this, arguments);
  7637. if (href.substring(0, 13) == 'data:page/id,')
  7638. {
  7639. var comma = href.indexOf(',');
  7640. if (comma > 0)
  7641. {
  7642. var page = this.getPageById(href.substring(comma + 1));
  7643. if (page != null)
  7644. {
  7645. title = page.getName();
  7646. }
  7647. else
  7648. {
  7649. title = mxResources.get('pageNotFound');
  7650. }
  7651. }
  7652. }
  7653. else if (href.substring(0, 5) == 'data:')
  7654. {
  7655. title = mxResources.get('action');
  7656. }
  7657. return title;
  7658. };
  7659. /**
  7660. *
  7661. */
  7662. EditorUi.prototype.handleCustomLink = function(href)
  7663. {
  7664. if (href.substring(0, 13) == 'data:page/id,')
  7665. {
  7666. var comma = href.indexOf(',');
  7667. var page = this.getPageById(href.substring(comma + 1));
  7668. if (page)
  7669. {
  7670. this.selectPage(page)
  7671. }
  7672. else
  7673. {
  7674. // Needs fallback for missing resource in case of viewer lightbox
  7675. throw new Error(mxResources.get('pageNotFound') || 'Page not found');
  7676. }
  7677. }
  7678. else
  7679. {
  7680. this.editor.graph.handleCustomLink(href);
  7681. }
  7682. };
  7683. /**
  7684. *
  7685. */
  7686. EditorUi.prototype.isSettingsEnabled = function()
  7687. {
  7688. return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
  7689. };
  7690. /**
  7691. * Creates the format panel and adds overrides.
  7692. */
  7693. EditorUi.prototype.installSettings = function()
  7694. {
  7695. if (this.isSettingsEnabled())
  7696. {
  7697. // Gets recent colors from settings
  7698. ColorDialog.recentColors = mxSettings.getRecentColors();
  7699. // Updates UI to reflect current edge style
  7700. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  7701. /**
  7702. * Persists copy on connect switch.
  7703. */
  7704. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  7705. this.fireEvent(new mxEventObject('copyConnectChanged'));
  7706. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  7707. {
  7708. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  7709. mxSettings.save();
  7710. }));
  7711. /**
  7712. * Persists default page format.
  7713. */
  7714. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  7715. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  7716. {
  7717. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  7718. mxSettings.save();
  7719. }));
  7720. /**
  7721. * Persists default grid color.
  7722. */
  7723. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  7724. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  7725. {
  7726. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  7727. mxSettings.save();
  7728. }));
  7729. /**
  7730. * Persists autosave switch in Chrome app.
  7731. */
  7732. if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
  7733. {
  7734. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  7735. {
  7736. mxSettings.setAutosave(this.editor.autosave);
  7737. mxSettings.save();
  7738. }));
  7739. this.editor.autosave = mxSettings.getAutosave();
  7740. }
  7741. /**
  7742. *
  7743. */
  7744. if (this.sidebar != null)
  7745. {
  7746. this.sidebar.showPalette('search', mxSettings.settings.search);
  7747. }
  7748. /**
  7749. * Shows scratchpad if never shown.
  7750. */
  7751. if ((!this.editor.chromeless || this.editor.editable) &&
  7752. this.sidebar != null && (mxSettings.settings.isNew ||
  7753. parseInt(mxSettings.settings.version || 0) <= 8))
  7754. {
  7755. this.toggleScratchpad();
  7756. mxSettings.save();
  7757. }
  7758. // Saves app defaults for UI
  7759. this.addListener('formatWidthChanged', function()
  7760. {
  7761. mxSettings.setFormatWidth(this.formatWidth);
  7762. mxSettings.save();
  7763. });
  7764. }
  7765. };
  7766. /**
  7767. * Creates the format panel and adds overrides.
  7768. */
  7769. EditorUi.prototype.copyCells = function(elt, removeCells)
  7770. {
  7771. var graph = this.editor.graph;
  7772. if (!graph.isSelectionEmpty())
  7773. {
  7774. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  7775. // LATER: Add span with XML in data attribute
  7776. // var span = document.createElement('span');
  7777. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  7778. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  7779. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  7780. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  7781. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  7782. if (removeCells)
  7783. {
  7784. graph.removeCells(cells, false);
  7785. graph.lastPasteXml = null;
  7786. }
  7787. else
  7788. {
  7789. graph.lastPasteXml = xml;
  7790. graph.pasteCounter = 0;
  7791. }
  7792. elt.focus();
  7793. document.execCommand('selectAll', false, null);
  7794. }
  7795. else
  7796. {
  7797. // Disables copy on focused element
  7798. elt.innerHTML = '';
  7799. }
  7800. };
  7801. /**
  7802. * Creates the format panel and adds overrides.
  7803. */
  7804. EditorUi.prototype.pasteCells = function(evt, elt)
  7805. {
  7806. if (!mxEvent.isConsumed(evt))
  7807. {
  7808. var spans = elt.getElementsByTagName('span');
  7809. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  7810. 'application/vnd.lucid.chart.objects')
  7811. {
  7812. var content = spans[0].getAttribute('data-lucid-content');
  7813. if (content != null && content.length > 0)
  7814. {
  7815. this.convertLucidChart(content, mxUtils.bind(this, function(xml)
  7816. {
  7817. var graph = this.editor.graph;
  7818. graph.setSelectionCells(this.importXml(xml, 0, 0));
  7819. graph.scrollCellToVisible(graph.getSelectionCell());
  7820. }), mxUtils.bind(this, function(e)
  7821. {
  7822. this.handleError(e);
  7823. }));
  7824. mxEvent.consume(evt);
  7825. }
  7826. }
  7827. else
  7828. {
  7829. var graph = this.editor.graph;
  7830. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  7831. mxUtils.getTextContent(elt) : elt.textContent);
  7832. var compat = false;
  7833. // Workaround for junk after XML in VM
  7834. try
  7835. {
  7836. var idx = xml.lastIndexOf('%3E');
  7837. if (idx >= 0 && idx < xml.length - 3)
  7838. {
  7839. xml = xml.substring(0, idx + 3);
  7840. }
  7841. }
  7842. catch (e)
  7843. {
  7844. // ignore
  7845. }
  7846. // Checks for embedded XML content
  7847. try
  7848. {
  7849. var spans = elt.getElementsByTagName('span');
  7850. var tmp = (spans != null && spans.length > 0) ?
  7851. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  7852. decodeURIComponent(xml);
  7853. if (this.isCompatibleString(tmp))
  7854. {
  7855. compat = true;
  7856. xml = tmp;
  7857. }
  7858. }
  7859. catch (e)
  7860. {
  7861. // ignore
  7862. }
  7863. if (graph.lastPasteXml == xml)
  7864. {
  7865. graph.pasteCounter++;
  7866. }
  7867. else
  7868. {
  7869. graph.lastPasteXml = xml;
  7870. graph.pasteCounter = 0;
  7871. }
  7872. var dx = graph.pasteCounter * graph.gridSize;
  7873. if (xml != null && xml.length > 0)
  7874. {
  7875. if (compat || this.isCompatibleString(xml))
  7876. {
  7877. graph.setSelectionCells(this.importXml(xml, dx, dx));
  7878. }
  7879. else
  7880. {
  7881. var pt = graph.getInsertPoint();
  7882. if (graph.isMouseInsertPoint())
  7883. {
  7884. dx = 0;
  7885. // No offset for insert at mouse position
  7886. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  7887. {
  7888. graph.pasteCounter--;
  7889. }
  7890. }
  7891. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  7892. }
  7893. if (!graph.isSelectionEmpty())
  7894. {
  7895. graph.scrollCellToVisible(graph.getSelectionCell());
  7896. if (this.hoverIcons != null)
  7897. {
  7898. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  7899. }
  7900. try
  7901. {
  7902. mxEvent.consume(evt);
  7903. }
  7904. catch (e)
  7905. {
  7906. // ignore event no longer exists in async handler in IE8-
  7907. }
  7908. }
  7909. }
  7910. }
  7911. }
  7912. };
  7913. /**
  7914. * Adds a file drop handler for opening local files.
  7915. */
  7916. EditorUi.prototype.addFileDropHandler = function(elts)
  7917. {
  7918. // Installs drag and drop handler for files
  7919. if (Graph.fileSupport)
  7920. {
  7921. var dropElt = null;
  7922. for (var i = 0; i < elts.length; i++)
  7923. {
  7924. // Setup the dnd listeners
  7925. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  7926. {
  7927. if (dropElt != null)
  7928. {
  7929. dropElt.parentNode.removeChild(dropElt);
  7930. dropElt = null;
  7931. }
  7932. evt.stopPropagation();
  7933. evt.preventDefault();
  7934. });
  7935. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  7936. {
  7937. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7938. {
  7939. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7940. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  7941. {
  7942. dropElt = this.highlightElement();
  7943. }
  7944. }
  7945. evt.stopPropagation();
  7946. evt.preventDefault();
  7947. }));
  7948. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  7949. {
  7950. if (dropElt != null)
  7951. {
  7952. dropElt.parentNode.removeChild(dropElt);
  7953. dropElt = null;
  7954. }
  7955. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  7956. {
  7957. if (evt.dataTransfer.files.length > 0)
  7958. {
  7959. this.hideDialog();
  7960. // Never open files in embed mode
  7961. if (urlParams['embed'] == '1')
  7962. {
  7963. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  7964. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  7965. }
  7966. else
  7967. {
  7968. this.openFiles(evt.dataTransfer.files, true);
  7969. }
  7970. }
  7971. else
  7972. {
  7973. // Handles open special files via text drag and drop
  7974. var data = this.extractGraphModelFromEvent(evt);
  7975. // Tries additional and async parsing of text content such as HTML, Gliffy data
  7976. if (data == null)
  7977. {
  7978. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  7979. if (provider != null)
  7980. {
  7981. if (document.documentMode == 10 || document.documentMode == 11)
  7982. {
  7983. data = provider.getData('Text');
  7984. }
  7985. else
  7986. {
  7987. var data = null;
  7988. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  7989. {
  7990. var data = evt.dataTransfer.getData('text/uri-list');
  7991. }
  7992. else
  7993. {
  7994. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  7995. }
  7996. if (data != null && data.length > 0)
  7997. {
  7998. var div = document.createElement('div');
  7999. div.innerHTML = data;
  8000. // Extracts single image
  8001. var imgs = div.getElementsByTagName('img');
  8002. if (imgs.length > 0)
  8003. {
  8004. data = imgs[0].getAttribute('src');
  8005. }
  8006. }
  8007. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  8008. {
  8009. data = provider.getData('text/plain');
  8010. }
  8011. }
  8012. if (data != null)
  8013. {
  8014. // Checks for embedded XML in PNG
  8015. if (data.substring(0, 22) == 'data:image/png;base64,')
  8016. {
  8017. var xml = this.extractGraphModelFromPng(data);
  8018. if (xml != null && xml.length > 0)
  8019. {
  8020. this.openLocalFile(xml, null, true);
  8021. }
  8022. }
  8023. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  8024. {
  8025. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  8026. {
  8027. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8028. {
  8029. this.openLocalFile(req.getText(), null, true);
  8030. }
  8031. }));
  8032. }
  8033. else if (/^https?:\/\//.test(data))
  8034. {
  8035. if (this.getCurrentFile() == null)
  8036. {
  8037. window.location.hash = '#U' + encodeURIComponent(data);
  8038. }
  8039. else
  8040. {
  8041. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  8042. (EditorUi.drawHost + '/') : 'https://' + location.host + '/') +
  8043. window.location.search + '#U' + encodeURIComponent(data));
  8044. }
  8045. }
  8046. }
  8047. }
  8048. }
  8049. else
  8050. {
  8051. this.openLocalFile(data, null, true);
  8052. }
  8053. }
  8054. }
  8055. evt.stopPropagation();
  8056. evt.preventDefault();
  8057. }));
  8058. }
  8059. }
  8060. };
  8061. /**
  8062. * Highlights the given element
  8063. */
  8064. EditorUi.prototype.highlightElement = function(elt)
  8065. {
  8066. var x = 0;
  8067. var y = 0;
  8068. var w = 0;
  8069. var h = 0;
  8070. if (elt == null)
  8071. {
  8072. var b = document.body;
  8073. var d = document.documentElement;
  8074. w = (b.clientWidth || d.clientWidth) - 3;
  8075. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  8076. }
  8077. else
  8078. {
  8079. x = elt.offsetTop;
  8080. y = elt.offsetLeft;
  8081. w = elt.clientWidth;
  8082. h = elt.clientHeight;
  8083. }
  8084. var hl = document.createElement('div');
  8085. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  8086. hl.style.border = '3px dotted rgb(254, 137, 12)';
  8087. hl.style.pointerEvents = 'none';
  8088. hl.style.position = 'absolute';
  8089. hl.style.top = x + 'px';
  8090. hl.style.left = y + 'px';
  8091. hl.style.width = Math.max(0, w - 3) + 'px';
  8092. hl.style.height = Math.max(0, h - 3) + 'px';
  8093. if (elt != null && elt.parentNode == this.editor.graph.container)
  8094. {
  8095. this.editor.graph.container.appendChild(hl);
  8096. }
  8097. else
  8098. {
  8099. document.body.appendChild(hl);
  8100. }
  8101. return hl;
  8102. };
  8103. /**
  8104. * Highlights the given element
  8105. */
  8106. EditorUi.prototype.stringToCells = function(xml)
  8107. {
  8108. var doc = mxUtils.parseXml(xml);
  8109. var node = this.editor.extractGraphModel(doc.documentElement);
  8110. var cells = [];
  8111. if (node != null)
  8112. {
  8113. var codec = new mxCodec(node.ownerDocument);
  8114. var model = new mxGraphModel();
  8115. codec.decode(node, model);
  8116. var parent = model.getChildAt(model.getRoot(), 0);
  8117. for (var j = 0; j < model.getChildCount(parent); j++)
  8118. {
  8119. cells.push(model.getChildAt(parent, j));
  8120. }
  8121. }
  8122. return cells;
  8123. };
  8124. /**
  8125. * Opens the given files in the editor.
  8126. */
  8127. EditorUi.prototype.openFiles = function(files, temp)
  8128. {
  8129. if (this.spinner.spin(document.body, mxResources.get('loading')))
  8130. {
  8131. for (var i = 0; i < files.length; i++)
  8132. {
  8133. (mxUtils.bind(this, function(file)
  8134. {
  8135. var reader = new FileReader();
  8136. reader.onload = mxUtils.bind(this, function(e)
  8137. {
  8138. try
  8139. {
  8140. var data = e.target.result;
  8141. var name = file.name;
  8142. if (name != null && name.length > 0)
  8143. {
  8144. if (!this.useCanvasForExport && /(\.png)$/i.test(name))
  8145. {
  8146. name = name.substring(0, name.length - 4) + '.xml';
  8147. }
  8148. var handleResult = mxUtils.bind(this, function(xml)
  8149. {
  8150. var dot = name.lastIndexOf('.');
  8151. if (dot >= 0)
  8152. {
  8153. name = name.substring(0, name.lastIndexOf('.')) + '.xml';
  8154. }
  8155. else
  8156. {
  8157. name = name + '.xml';
  8158. }
  8159. if (xml.substring(0, 10) == '<mxlibrary')
  8160. {
  8161. // Creates new temporary file if library is dropped in splash screen
  8162. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8163. {
  8164. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8165. }
  8166. try
  8167. {
  8168. this.loadLibrary(new LocalLibrary(this, xml, name));
  8169. }
  8170. catch (e)
  8171. {
  8172. this.handleError(e, mxResources.get('errorLoadingFile'));
  8173. }
  8174. }
  8175. else
  8176. {
  8177. this.openLocalFile(xml, name, temp);
  8178. }
  8179. });
  8180. if (/(\.v(dx|sdx?))($|\?)/i.test(name) || /(\.vs(x|sx?))($|\?)/i.test(name))
  8181. {
  8182. this.importVisio(file, mxUtils.bind(this, function(xml)
  8183. {
  8184. this.spinner.stop();
  8185. handleResult(xml);
  8186. }));
  8187. }
  8188. else if (/(\.*<graphml )/.test(data))
  8189. {
  8190. this.importGraphML(data, mxUtils.bind(this, function(xml)
  8191. {
  8192. this.spinner.stop();
  8193. handleResult(xml);
  8194. }));
  8195. }
  8196. else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  8197. this.isRemoteFileFormat(data, name))
  8198. {
  8199. this.parseFile(file, mxUtils.bind(this, function(xhr)
  8200. {
  8201. if (xhr.readyState == 4)
  8202. {
  8203. this.spinner.stop();
  8204. if (xhr.status >= 200 && xhr.status <= 299)
  8205. {
  8206. handleResult(xhr.responseText);
  8207. }
  8208. else
  8209. {
  8210. this.handleError({message: mxResources.get((xhr.status == 413) ?
  8211. 'drawingTooLarge' : 'invalidOrMissingFile')},
  8212. mxResources.get('errorLoadingFile'));
  8213. }
  8214. }
  8215. }));
  8216. }
  8217. else if (this.isLucidChartData(data))
  8218. {
  8219. if (/(\.json)$/i.test(name))
  8220. {
  8221. name = name.substring(0, name.length - 5) + '.xml';
  8222. }
  8223. // LATER: Add import step that produces cells and use callback
  8224. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  8225. {
  8226. this.spinner.stop();
  8227. this.openLocalFile(xml, name, temp);
  8228. }), mxUtils.bind(this, function(e)
  8229. {
  8230. this.spinner.stop();
  8231. this.handleError(e);
  8232. }));
  8233. }
  8234. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  8235. {
  8236. this.spinner.stop();
  8237. // Creates new temporary file if library is dropped in splash screen
  8238. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8239. {
  8240. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8241. }
  8242. try
  8243. {
  8244. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  8245. }
  8246. catch (e)
  8247. {
  8248. this.handleError(e, mxResources.get('errorLoadingFile'));
  8249. }
  8250. }
  8251. else
  8252. {
  8253. if (file.type.substring(0, 9) == 'image/png')
  8254. {
  8255. data = this.extractGraphModelFromPng(data);
  8256. }
  8257. this.spinner.stop();
  8258. this.openLocalFile(data, name, temp);
  8259. }
  8260. }
  8261. }
  8262. catch (e)
  8263. {
  8264. this.handleError(e);
  8265. }
  8266. });
  8267. reader.onerror = mxUtils.bind(this, function(e)
  8268. {
  8269. this.spinner.stop();
  8270. this.handleError(e);
  8271. window.openFile = null;
  8272. });
  8273. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  8274. {
  8275. reader.readAsDataURL(file);
  8276. }
  8277. else
  8278. {
  8279. reader.readAsText(file);
  8280. }
  8281. }))(files[i]);
  8282. }
  8283. }
  8284. };
  8285. /**
  8286. * Shows the layers dialog if the graph has more than one layer.
  8287. */
  8288. EditorUi.prototype.openLocalFile = function(data, name, temp)
  8289. {
  8290. var currentFile = this.getCurrentFile();
  8291. var fn = mxUtils.bind(this, function()
  8292. {
  8293. window.openFile = null;
  8294. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  8295. {
  8296. var doc = mxUtils.parseXml(data);
  8297. if (doc != null)
  8298. {
  8299. this.editor.setGraphXml(doc.documentElement);
  8300. this.editor.graph.selectAll();
  8301. }
  8302. }
  8303. else
  8304. {
  8305. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  8306. }
  8307. });
  8308. if (data != null && data.length > 0)
  8309. {
  8310. if (currentFile == null || (!currentFile.isModified() &&
  8311. (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)))
  8312. {
  8313. fn();
  8314. }
  8315. else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) &&
  8316. currentFile != null && currentFile.isModified())
  8317. {
  8318. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8319. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8320. }
  8321. else
  8322. {
  8323. window.openFile = new OpenFile(function()
  8324. {
  8325. window.openFile = null;
  8326. });
  8327. window.openFile.setData(data, name);
  8328. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  8329. {
  8330. if (currentFile != null && currentFile.isModified())
  8331. {
  8332. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8333. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8334. }
  8335. else
  8336. {
  8337. fn();
  8338. }
  8339. }));
  8340. }
  8341. }
  8342. else
  8343. {
  8344. throw new Error(mxResources.get('notADiagramFile'));
  8345. }
  8346. };
  8347. /**
  8348. * Returns a list of all shapes used in the current file.
  8349. */
  8350. EditorUi.prototype.getBasenames = function()
  8351. {
  8352. var basenames = {};
  8353. if (this.pages != null)
  8354. {
  8355. for (var i = 0; i < this.pages.length; i++)
  8356. {
  8357. this.updatePageRoot(this.pages[i]);
  8358. this.addBasenamesForCell(this.pages[i].root, basenames);
  8359. }
  8360. }
  8361. else
  8362. {
  8363. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  8364. }
  8365. var result = [];
  8366. for (var key in basenames)
  8367. {
  8368. result.push(key);
  8369. }
  8370. return result;
  8371. };
  8372. /**
  8373. * Returns a list of all shapes used in the current file.
  8374. */
  8375. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  8376. {
  8377. function addName(name)
  8378. {
  8379. if (name != null)
  8380. {
  8381. // LATER: Check if this case exists
  8382. var dot = name.lastIndexOf('.');
  8383. if (dot > 0)
  8384. {
  8385. name = name.substring(dot + 1, name.length);
  8386. }
  8387. if (basenames[name] == null)
  8388. {
  8389. basenames[name] = true;
  8390. }
  8391. }
  8392. };
  8393. var graph = this.editor.graph;
  8394. var style = graph.getCellStyle(cell);
  8395. var shape = style[mxConstants.STYLE_SHAPE];
  8396. addName(mxStencilRegistry.getBasenameForStencil(shape));
  8397. // Adds package names for markers in edges
  8398. if (graph.model.isEdge(cell))
  8399. {
  8400. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  8401. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  8402. }
  8403. var childCount = graph.model.getChildCount(cell);
  8404. for (var i = 0; i < childCount; i++)
  8405. {
  8406. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  8407. }
  8408. };
  8409. /**
  8410. * Shows the layers dialog if the graph has more than one layer.
  8411. */
  8412. EditorUi.prototype.setGraphEnabled = function(enabled)
  8413. {
  8414. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  8415. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  8416. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  8417. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  8418. this.hsplit.style.display = (enabled) ? '' : 'none';
  8419. this.editor.graph.setEnabled(enabled);
  8420. if (this.tabContainer != null)
  8421. {
  8422. this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
  8423. }
  8424. if (!enabled)
  8425. {
  8426. if (this.actions.outlineWindow != null)
  8427. {
  8428. this.actions.outlineWindow.window.setVisible(false);
  8429. }
  8430. if (this.actions.layersWindow != null)
  8431. {
  8432. this.actions.layersWindow.window.setVisible(false);
  8433. }
  8434. if (this.menus.tagsWindow != null)
  8435. {
  8436. this.menus.tagsWindow.window.setVisible(false);
  8437. }
  8438. if (this.menus.findWindow != null)
  8439. {
  8440. this.menus.findWindow.window.setVisible(false);
  8441. }
  8442. }
  8443. };
  8444. /**
  8445. * Shows the layers dialog if the graph has more than one layer.
  8446. */
  8447. EditorUi.prototype.initializeEmbedMode = function()
  8448. {
  8449. this.setGraphEnabled(false);
  8450. var parent = window.opener || window.parent;
  8451. if (parent != window)
  8452. {
  8453. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  8454. {
  8455. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  8456. {
  8457. this.spinner.stop();
  8458. this.addEmbedButtons();
  8459. this.setGraphEnabled(true);
  8460. if (xml != null && xml.length > 0)
  8461. {
  8462. this.setFileData(xml);
  8463. if (!this.editor.isChromelessView())
  8464. {
  8465. this.showLayersDialog();
  8466. }
  8467. else if (this.editor.graph.isLightboxView())
  8468. {
  8469. this.lightboxFit();
  8470. }
  8471. if (this.chromelessResize)
  8472. {
  8473. this.chromelessResize();
  8474. }
  8475. }
  8476. else
  8477. {
  8478. this.editor.graph.model.clear();
  8479. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  8480. }
  8481. this.editor.undoManager.clear();
  8482. this.editor.modified = (modified != null) ? modified : false;
  8483. this.updateUi();
  8484. // Workaround for no initial focus in FF
  8485. // (does not work in Conf Cloud with FF)
  8486. if (window.self !== window.top)
  8487. {
  8488. window.focus();
  8489. }
  8490. if (this.format != null)
  8491. {
  8492. this.format.refresh();
  8493. }
  8494. }));
  8495. }
  8496. }
  8497. };
  8498. /**
  8499. * Shows the layers dialog if the graph has more than one layer.
  8500. */
  8501. EditorUi.prototype.showLayersDialog = function()
  8502. {
  8503. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  8504. {
  8505. if (this.actions.layersWindow == null)
  8506. {
  8507. this.actions.get('layers').funct();
  8508. }
  8509. else
  8510. {
  8511. this.actions.layersWindow.window.setVisible(true);
  8512. }
  8513. }
  8514. };
  8515. /**
  8516. * Tries to find a public URL for the given file.
  8517. */
  8518. EditorUi.prototype.getPublicUrl = function(file, fn)
  8519. {
  8520. if (file != null)
  8521. {
  8522. file.getPublicUrl(fn);
  8523. }
  8524. else
  8525. {
  8526. fn(null);
  8527. }
  8528. };
  8529. /**
  8530. * Adds the buttons for embedded mode.
  8531. */
  8532. EditorUi.prototype.createLoadMessage = function(eventName)
  8533. {
  8534. var graph = this.editor.graph;
  8535. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  8536. bounds: graph.getGraphBounds(), currentPage: this.getSelectedPageIndex(),
  8537. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds()};
  8538. };
  8539. /**
  8540. * Adds the buttons for embedded mode.
  8541. */
  8542. EditorUi.prototype.installMessageHandler = function(fn)
  8543. {
  8544. var changeListener = null;
  8545. var ignoreChange = false;
  8546. var autosave = false;
  8547. var lastData = null;
  8548. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  8549. {
  8550. if (!this.editor.modified || urlParams['modified'] == '0')
  8551. {
  8552. this.editor.setStatus('');
  8553. }
  8554. else if (urlParams['modified'] != null)
  8555. {
  8556. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  8557. }
  8558. });
  8559. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  8560. // Receives XML message from opener and puts it into the graph
  8561. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  8562. {
  8563. var validSource = window.opener || window.parent;
  8564. if (evt.source != validSource)
  8565. {
  8566. return;
  8567. }
  8568. var data = evt.data;
  8569. var extractDiagramXml = mxUtils.bind(this, function(data)
  8570. {
  8571. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  8572. {
  8573. try
  8574. {
  8575. if (data.substring(0, 22) == 'data:image/png;base64,')
  8576. {
  8577. data = this.extractGraphModelFromPng(data);
  8578. }
  8579. else if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  8580. {
  8581. data = atob(data.substring(26));
  8582. }
  8583. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  8584. {
  8585. data = data.substring(24);
  8586. }
  8587. if (data != null)
  8588. {
  8589. if (data.charAt(0) == '%')
  8590. {
  8591. data = decodeURIComponent(data);
  8592. }
  8593. else if (data.charAt(0) != '<')
  8594. {
  8595. data = Graph.decompress(data);
  8596. }
  8597. }
  8598. }
  8599. catch (e)
  8600. {
  8601. // ignore compression errors and use empty data
  8602. }
  8603. }
  8604. return data;
  8605. });
  8606. if (urlParams['proto'] == 'json')
  8607. {
  8608. try
  8609. {
  8610. data = JSON.parse(data);
  8611. }
  8612. catch (e)
  8613. {
  8614. data = null;
  8615. }
  8616. if (data == null)
  8617. {
  8618. // Ignore
  8619. return;
  8620. }
  8621. else if (data.action == 'dialog')
  8622. {
  8623. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  8624. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  8625. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  8626. if (data.modified != null)
  8627. {
  8628. this.editor.modified = data.modified;
  8629. }
  8630. return;
  8631. }
  8632. else if (data.action == 'prompt')
  8633. {
  8634. this.spinner.stop();
  8635. var dlg = new FilenameDialog(this, data.defaultValue || '',
  8636. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  8637. {
  8638. if (value != null)
  8639. {
  8640. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  8641. }
  8642. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  8643. this.showDialog(dlg.container, 300, 80, true, false);
  8644. dlg.init();
  8645. return;
  8646. }
  8647. else if (data.action == 'draft')
  8648. {
  8649. var tmp = extractDiagramXml(data.xml);
  8650. this.spinner.stop();
  8651. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  8652. tmp, mxUtils.bind(this, function()
  8653. {
  8654. this.hideDialog();
  8655. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  8656. }), mxUtils.bind(this, function()
  8657. {
  8658. this.hideDialog();
  8659. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  8660. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  8661. (data.discardKey) ? mxResources.get(data.discardKey) : null,
  8662. (data.ignore) ? mxUtils.bind(this, function()
  8663. {
  8664. this.hideDialog();
  8665. parent.postMessage(JSON.stringify({event: 'draft', result: 'ignore', message: data}), '*');
  8666. }) : null);
  8667. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  8668. {
  8669. if (cancel)
  8670. {
  8671. this.actions.get('exit').funct();
  8672. }
  8673. }));
  8674. try
  8675. {
  8676. dlg.init();
  8677. }
  8678. catch (e)
  8679. {
  8680. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  8681. }
  8682. return;
  8683. }
  8684. else if (data.action == 'template')
  8685. {
  8686. this.spinner.stop();
  8687. var enableRecentDocs = data.enableRecent == 1;
  8688. var enableSearchDocs = data.enableSearch == 1;
  8689. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  8690. {
  8691. xml = xml || this.emptyDiagramXml;
  8692. // LATER: Add autosave option in template message
  8693. if (data.callback != null)
  8694. {
  8695. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  8696. blank: xml == this.emptyDiagramXml, name: name}), '*');
  8697. }
  8698. else
  8699. {
  8700. fn(xml, evt, xml != this.emptyDiagramXml);
  8701. // Workaround for status updated before modified applied
  8702. if (!this.editor.modified)
  8703. {
  8704. this.editor.setStatus('');
  8705. }
  8706. }
  8707. }), null, null, null, null, null, null, null,
  8708. enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
  8709. {
  8710. this.remoteInvoke('getRecentDiagrams', null, null, recentReadyCallback, function()
  8711. {
  8712. recentReadyCallback(null, 'Network Error!');
  8713. });
  8714. }) : null,
  8715. enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
  8716. {
  8717. this.remoteInvoke('searchDiagrams', [searchStr], null, searchReadyCallback, function()
  8718. {
  8719. searchReadyCallback(null, 'Network Error!');
  8720. });
  8721. }) : null,
  8722. function(url, info, name)
  8723. {
  8724. parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
  8725. name: name}), '*');
  8726. });
  8727. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  8728. {
  8729. if (cancel)
  8730. {
  8731. this.actions.get('exit').funct();
  8732. }
  8733. }));
  8734. dlg.init();
  8735. return;
  8736. }
  8737. else if (data.action == 'textContent')
  8738. {
  8739. //TODO Remove this message and use remove invokation instead
  8740. var allPagesTxt = this.getDiagramTextContent();
  8741. parent.postMessage(JSON.stringify({event: 'textContent', data: allPagesTxt, message: data}), '*');
  8742. return;
  8743. }
  8744. else if (data.action == 'status')
  8745. {
  8746. if (data.messageKey != null)
  8747. {
  8748. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  8749. }
  8750. else if (data.message != null)
  8751. {
  8752. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  8753. }
  8754. if (data.modified != null)
  8755. {
  8756. this.editor.modified = data.modified;
  8757. }
  8758. return;
  8759. }
  8760. else if (data.action == 'spinner')
  8761. {
  8762. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  8763. if (data.show != null && !data.show)
  8764. {
  8765. this.spinner.stop();
  8766. }
  8767. else
  8768. {
  8769. this.spinner.spin(document.body, msg)
  8770. }
  8771. return;
  8772. }
  8773. else if (data.action == 'export')
  8774. {
  8775. if (data.format == 'png' || data.format == 'xmlpng')
  8776. {
  8777. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8778. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8779. {
  8780. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  8781. this.editor.graph.setEnabled(false);
  8782. var graph = this.editor.graph;
  8783. var postDataBack = mxUtils.bind(this, function(uri)
  8784. {
  8785. this.editor.graph.setEnabled(true);
  8786. this.spinner.stop();
  8787. var msg = this.createLoadMessage('export');
  8788. msg.format = data.format;
  8789. msg.message = data;
  8790. msg.data = uri;
  8791. msg.xml = encodeURIComponent(xml);
  8792. parent.postMessage(JSON.stringify(msg), '*');
  8793. });
  8794. var processUri = mxUtils.bind(this, function(uri)
  8795. {
  8796. if (uri == null)
  8797. {
  8798. uri = Editor.blankImage;
  8799. }
  8800. if (data.format == 'xmlpng')
  8801. {
  8802. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  8803. atob(Graph.compress(xml)));
  8804. }
  8805. // Removes temporary graph from DOM
  8806. if (graph != this.editor.graph)
  8807. {
  8808. graph.container.parentNode.removeChild(graph.container);
  8809. }
  8810. postDataBack(uri);
  8811. });
  8812. // LATER: Uses external export if current page (not first page) has mathEnabled
  8813. if (this.isExportToCanvas())
  8814. {
  8815. // Exports PNG for first page while other page is visible by creating a graph
  8816. // LATER: Add caching for the graph or SVG while not on first page
  8817. if (this.pages != null && this.currentPage != this.pages[0])
  8818. {
  8819. graph = this.createTemporaryGraph(graph.getStylesheet());
  8820. var graphGetGlobalVariable = graph.getGlobalVariable;
  8821. var page = this.pages[0];
  8822. graph.getGlobalVariable = function(name)
  8823. {
  8824. if (name == 'page')
  8825. {
  8826. return page.getName();
  8827. }
  8828. else if (name == 'pagenumber')
  8829. {
  8830. return 1;
  8831. }
  8832. return graphGetGlobalVariable.apply(this, arguments);
  8833. };
  8834. document.body.appendChild(graph.container);
  8835. graph.model.setRoot(page.root);
  8836. }
  8837. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  8838. {
  8839. processUri(canvas.toDataURL('image/png'));
  8840. }), null, null, null, mxUtils.bind(this, function()
  8841. {
  8842. processUri(null);
  8843. }), null, null, null, null, null, null, graph);
  8844. }
  8845. else
  8846. {
  8847. // Data from server is base64 encoded to avoid binary XHR
  8848. // Double encoding for XML arg is needed for UTF8 encoding
  8849. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  8850. ((data.format == 'xmlpng') ? '1' : '0') + '&base64=1&xml=' +
  8851. encodeURIComponent(encodeURIComponent(xml)));
  8852. req.send(mxUtils.bind(this, function(req)
  8853. {
  8854. // Temp graph was never created at this point so we can
  8855. // skip processUri since it already contains the XML
  8856. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8857. {
  8858. postDataBack('data:image/png;base64,' + req.getText());
  8859. }
  8860. else
  8861. {
  8862. processUri(null);
  8863. }
  8864. }), mxUtils.bind(this, function()
  8865. {
  8866. processUri(null);
  8867. }));
  8868. }
  8869. }
  8870. }
  8871. else
  8872. {
  8873. // SVG is generated from graph so parse optional XML
  8874. if (data.xml != null && data.xml.length > 0)
  8875. {
  8876. this.setFileData(data.xml);
  8877. }
  8878. var msg = this.createLoadMessage('export');
  8879. // Forces new HTML format if pages exists
  8880. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  8881. (this.pages != null && this.pages.length > 1))))
  8882. {
  8883. var node = this.getXmlFileData();
  8884. msg.xml = mxUtils.getXml(node);
  8885. msg.data = this.getFileData(null, null, true, null, null, null, node);
  8886. msg.format = data.format;
  8887. }
  8888. else if (data.format == 'html')
  8889. {
  8890. var xml = this.editor.getGraphXml();
  8891. msg.data = this.getHtml(xml, this.editor.graph);
  8892. msg.xml = mxUtils.getXml(xml);
  8893. msg.format = data.format;
  8894. }
  8895. else
  8896. {
  8897. // Creates a preview with no alt text for unsupported browsers
  8898. mxSvgCanvas2D.prototype.foAltText = null;
  8899. var bg = this.editor.graph.background;
  8900. if (bg == mxConstants.NONE)
  8901. {
  8902. bg = null;
  8903. }
  8904. msg.xml = this.getFileData(true);
  8905. msg.format = 'svg';
  8906. if (data.embedImages || data.embedImages == null)
  8907. {
  8908. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8909. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8910. {
  8911. this.editor.graph.setEnabled(false);
  8912. if (data.format == 'xmlsvg')
  8913. {
  8914. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  8915. {
  8916. this.editor.graph.setEnabled(true);
  8917. this.spinner.stop();
  8918. msg.data = this.createSvgDataUri(svg);
  8919. parent.postMessage(JSON.stringify(msg), '*');
  8920. }));
  8921. }
  8922. else
  8923. {
  8924. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  8925. {
  8926. this.editor.graph.setEnabled(true);
  8927. this.spinner.stop();
  8928. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  8929. parent.postMessage(JSON.stringify(msg), '*');
  8930. }));
  8931. }
  8932. }
  8933. return;
  8934. }
  8935. else
  8936. {
  8937. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  8938. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  8939. msg.data = this.createSvgDataUri(svg);
  8940. }
  8941. }
  8942. parent.postMessage(JSON.stringify(msg), '*');
  8943. }
  8944. return;
  8945. }
  8946. else if (data.action == 'load')
  8947. {
  8948. autosave = data.autosave == 1;
  8949. this.hideDialog();
  8950. if (data.modified != null && urlParams['modified'] == null)
  8951. {
  8952. urlParams['modified'] = data.modified;
  8953. }
  8954. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  8955. {
  8956. urlParams['saveAndExit'] = data.saveAndExit;
  8957. }
  8958. if (data.title != null && this.buttonContainer != null)
  8959. {
  8960. var tmp = document.createElement('span');
  8961. mxUtils.write(tmp, data.title);
  8962. if (uiTheme == 'atlas')
  8963. {
  8964. this.buttonContainer.style.paddingRight = '12px';
  8965. this.buttonContainer.style.paddingTop = '12px';
  8966. this.buttonContainer.style.right = '25px';
  8967. }
  8968. else if (uiTheme != 'min')
  8969. {
  8970. this.buttonContainer.style.paddingRight = '38px';
  8971. this.buttonContainer.style.paddingTop = '6px';
  8972. }
  8973. if (this.embedFilenameSpan != null)
  8974. {
  8975. this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
  8976. }
  8977. this.buttonContainer.appendChild(tmp);
  8978. this.embedFilenameSpan = tmp;
  8979. }
  8980. if (data.xmlpng != null)
  8981. {
  8982. data = this.extractGraphModelFromPng(data.xmlpng);
  8983. }
  8984. else
  8985. {
  8986. data = data.xml;
  8987. }
  8988. }
  8989. else if (data.action == 'remoteInvokeReady')
  8990. {
  8991. this.handleRemoteInvokeReady(parent);
  8992. return;
  8993. }
  8994. else if (data.action == 'remoteInvoke')
  8995. {
  8996. this.handleRemoteInvoke(data);
  8997. return;
  8998. }
  8999. else if (data.action == 'remoteInvokeResponse')
  9000. {
  9001. this.handleRemoteInvokeResponse(data);
  9002. return;
  9003. }
  9004. else
  9005. {
  9006. // Unknown message must stop execution
  9007. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  9008. return;
  9009. }
  9010. }
  9011. var doLoad = mxUtils.bind(this, function(data, evt)
  9012. {
  9013. ignoreChange = true;
  9014. try
  9015. {
  9016. fn(data, evt);
  9017. }
  9018. catch (e)
  9019. {
  9020. this.handleError(e);
  9021. }
  9022. ignoreChange = false;
  9023. if (urlParams['modified'] != null)
  9024. {
  9025. this.editor.setStatus('');
  9026. }
  9027. var getData = mxUtils.bind(this, function()
  9028. {
  9029. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  9030. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  9031. });;
  9032. lastData = getData();
  9033. if (autosave && changeListener == null)
  9034. {
  9035. changeListener = mxUtils.bind(this, function(sender, eventObject)
  9036. {
  9037. var data = getData();
  9038. if (data != lastData && !ignoreChange)
  9039. {
  9040. var msg = this.createLoadMessage('autosave');
  9041. msg.xml = data;
  9042. data = JSON.stringify(msg);
  9043. var parent = window.opener || window.parent;
  9044. parent.postMessage(data, '*');
  9045. }
  9046. lastData = data;
  9047. });
  9048. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  9049. // Some options trigger autosave
  9050. this.editor.graph.addListener('gridSizeChanged', changeListener);
  9051. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  9052. this.addListener('pageFormatChanged', changeListener);
  9053. this.addListener('pageScaleChanged', changeListener);
  9054. this.addListener('backgroundColorChanged', changeListener);
  9055. this.addListener('backgroundImageChanged', changeListener);
  9056. this.addListener('foldingEnabledChanged', changeListener);
  9057. this.addListener('mathEnabledChanged', changeListener);
  9058. this.addListener('gridEnabledChanged', changeListener);
  9059. this.addListener('guidesEnabledChanged', changeListener);
  9060. this.addListener('pageViewChanged', changeListener);
  9061. }
  9062. // Sends the bounds of the graph to the host after parsing
  9063. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  9064. {
  9065. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  9066. }
  9067. });
  9068. if (data != null && typeof data.substring === 'function' && data.substring(0, 34) == 'data:application/vnd.visio;base64,')
  9069. {
  9070. // Checks VND binary magic number in base64
  9071. var filename = (data.substring(34, 45) == '0M8R4KGxGuE') ? 'raw.vsd' : 'raw.vsdx';
  9072. this.importVisio(this.base64ToBlob(data.substring(data.indexOf(',') + 1)), function(xml)
  9073. {
  9074. doLoad(xml, evt);
  9075. }, mxUtils.bind(this, function(e)
  9076. {
  9077. this.handleError(e);
  9078. }), filename);
  9079. }
  9080. else if (data != null && typeof data.substring === 'function' && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, ''))
  9081. {
  9082. // Asynchronous parsing via server
  9083. this.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  9084. {
  9085. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299 &&
  9086. xhr.responseText.substring(0, 13) == '<mxGraphModel')
  9087. {
  9088. doLoad(xhr.responseText, evt);
  9089. }
  9090. }), '');
  9091. }
  9092. else if (data != null && typeof data.substring === 'function' && this.isLucidChartData(data))
  9093. {
  9094. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  9095. {
  9096. doLoad(xml);
  9097. }), mxUtils.bind(this, function(e)
  9098. {
  9099. this.handleError(e);
  9100. }));
  9101. }
  9102. else
  9103. {
  9104. data = extractDiagramXml(data);
  9105. doLoad(data, evt);
  9106. }
  9107. }));
  9108. // Requests data from the sender. This is a workaround for not allowing
  9109. // the opener to listen for the onload event if not in the same origin.
  9110. var parent = window.opener || window.parent;
  9111. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  9112. parent.postMessage(msg, '*');
  9113. };
  9114. /**
  9115. * Adds the buttons for embedded mode.
  9116. */
  9117. EditorUi.prototype.addEmbedButtons = function()
  9118. {
  9119. if (this.menubar != null)
  9120. {
  9121. var div = document.createElement('div');
  9122. div.style.display = 'inline-block';
  9123. div.style.position = 'absolute';
  9124. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  9125. div.style.paddingLeft = '8px';
  9126. div.style.paddingBottom = '2px';
  9127. var button = document.createElement('button');
  9128. mxUtils.write(button, mxResources.get('save'));
  9129. button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
  9130. button.className = 'geBigButton';
  9131. button.style.fontSize = '12px';
  9132. button.style.padding = '4px 6px 4px 6px';
  9133. button.style.borderRadius = '3px';
  9134. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9135. {
  9136. this.actions.get('save').funct();
  9137. }));
  9138. div.appendChild(button);
  9139. if (urlParams['saveAndExit'] == '1')
  9140. {
  9141. button = document.createElement('a');
  9142. mxUtils.write(button, mxResources.get('saveAndExit'));
  9143. button.setAttribute('title', mxResources.get('saveAndExit'));
  9144. button.style.fontSize = '12px';
  9145. button.style.marginLeft = '6px';
  9146. button.style.padding = '4px';
  9147. button.style.cursor = 'pointer';
  9148. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9149. {
  9150. this.actions.get('saveAndExit').funct();
  9151. }));
  9152. div.appendChild(button);
  9153. }
  9154. button = document.createElement('a');
  9155. mxUtils.write(button, mxResources.get('exit'));
  9156. button.setAttribute('title', mxResources.get('exit'));
  9157. button.style.fontSize = '12px';
  9158. button.style.marginLeft = '6px';
  9159. button.style.marginRight = '20px';
  9160. button.style.padding = '4px';
  9161. button.style.cursor = 'pointer';
  9162. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9163. {
  9164. this.actions.get('exit').funct();
  9165. }));
  9166. div.appendChild(button);
  9167. this.toolbar.container.appendChild(div);
  9168. this.toolbar.staticElements.push(div);
  9169. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  9170. }
  9171. };
  9172. /**
  9173. *
  9174. */
  9175. EditorUi.prototype.showImportCsvDialog = function()
  9176. {
  9177. if (this.importCsvDialog == null)
  9178. {
  9179. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  9180. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  9181. {
  9182. this.importCsv(newValue);
  9183. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  9184. }
  9185. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  9186. this.importCsvDialog.init();
  9187. };
  9188. /**
  9189. * TODO: Move to Editor
  9190. */
  9191. EditorUi.prototype.importCsv = function(text, done)
  9192. {
  9193. try
  9194. {
  9195. var lines = text.split('\n');
  9196. var cells = [];
  9197. if (lines.length > 0)
  9198. {
  9199. // Internal lookup table
  9200. var lookups = {};
  9201. // Default values
  9202. var style = null;
  9203. var parentstyle = null;
  9204. var identity = null;
  9205. var parent = null;
  9206. var namespace = '';
  9207. var width = 'auto';
  9208. var height = 'auto';
  9209. var left = null;
  9210. var top = null;
  9211. var edgespacing = 40;
  9212. var nodespacing = 40;
  9213. var levelspacing = 100;
  9214. var padding = 0;
  9215. var graph = this.editor.graph;
  9216. var view = graph.view;
  9217. var bds = graph.getGraphBounds();
  9218. // Delayed after optional layout
  9219. var afterInsert = function()
  9220. {
  9221. if (done != null)
  9222. {
  9223. done(select);
  9224. }
  9225. else
  9226. {
  9227. graph.setSelectionCells(select);
  9228. graph.scrollCellToVisible(graph.getSelectionCell());
  9229. }
  9230. };
  9231. // Computes unscaled, untranslated graph bounds
  9232. var pt = graph.getFreeInsertPoint();
  9233. var x0 = pt.x;
  9234. var y0 = pt.y;
  9235. var y = y0;
  9236. // Default label value depends on column names
  9237. var label = null;
  9238. // Default layout to run.
  9239. var layout = 'auto';
  9240. // Name of the attribute that contains the parent reference
  9241. var parent = null;
  9242. // Name of the attribute that contains the references for creating edges
  9243. var edges = [];
  9244. // Name of the column for hyperlinks
  9245. var link = null;
  9246. // String array of names to remove from metadata
  9247. var ignore = null;
  9248. // Read processing instructions first
  9249. var index = 0;
  9250. while (index < lines.length && lines[index].charAt(0) == '#')
  9251. {
  9252. var text = lines[index];
  9253. index++;
  9254. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  9255. lines[index].charAt(0) == '#')
  9256. {
  9257. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  9258. index++;
  9259. }
  9260. if (text.charAt(1) != '#')
  9261. {
  9262. // Processing instruction
  9263. var idx = text.indexOf(':');
  9264. if (idx > 0)
  9265. {
  9266. var key = mxUtils.trim(text.substring(1, idx));
  9267. var value = mxUtils.trim(text.substring(idx + 1));
  9268. if (key == 'label')
  9269. {
  9270. label = graph.sanitizeHtml(value);
  9271. }
  9272. else if (key == 'style')
  9273. {
  9274. style = value;
  9275. }
  9276. else if (key == 'parentstyle')
  9277. {
  9278. parentstyle = value;
  9279. }
  9280. else if (key == 'identity' && value.length > 0 && value != '-')
  9281. {
  9282. identity = value;
  9283. }
  9284. else if (key == 'parent' && value.length > 0 && value != '-')
  9285. {
  9286. parent = value;
  9287. }
  9288. else if (key == 'namespace' && value.length > 0 && value != '-')
  9289. {
  9290. namespace = value;
  9291. }
  9292. else if (key == 'width')
  9293. {
  9294. width = value;
  9295. }
  9296. else if (key == 'height')
  9297. {
  9298. height = value;
  9299. }
  9300. else if (key == 'left' && value.length > 0)
  9301. {
  9302. left = value;
  9303. }
  9304. else if (key == 'top' && value.length > 0)
  9305. {
  9306. top = value;
  9307. }
  9308. else if (key == 'ignore')
  9309. {
  9310. ignore = value.split(',');
  9311. }
  9312. else if (key == 'connect')
  9313. {
  9314. edges.push(JSON.parse(value));
  9315. }
  9316. else if (key == 'link')
  9317. {
  9318. link = value;
  9319. }
  9320. else if (key == 'padding')
  9321. {
  9322. padding = parseFloat(value);
  9323. }
  9324. else if (key == 'edgespacing')
  9325. {
  9326. edgespacing = parseFloat(value);
  9327. }
  9328. else if (key == 'nodespacing')
  9329. {
  9330. nodespacing = parseFloat(value);
  9331. }
  9332. else if (key == 'levelspacing')
  9333. {
  9334. levelspacing = parseFloat(value);
  9335. }
  9336. else if (key == 'layout')
  9337. {
  9338. layout = value;
  9339. }
  9340. }
  9341. }
  9342. }
  9343. var keys = this.editor.csvToArray(lines[index]);
  9344. // Converts name of identity and parent to indexes of column
  9345. var identityIndex = null;
  9346. var parentIndex = null;
  9347. if (identity != null || parent != null)
  9348. {
  9349. for (var i = 0; i < keys.length; i++)
  9350. {
  9351. if (identity == keys[i])
  9352. {
  9353. identityIndex = i;
  9354. }
  9355. if (parent == keys[i])
  9356. {
  9357. parentIndex = i;
  9358. }
  9359. }
  9360. }
  9361. if (label == null)
  9362. {
  9363. label = '%' + keys[0] + '%';
  9364. }
  9365. if (edges != null)
  9366. {
  9367. for (var e = 0; e < edges.length; e++)
  9368. {
  9369. if (lookups[edges[e].to] == null)
  9370. {
  9371. lookups[edges[e].to] = {};
  9372. }
  9373. }
  9374. }
  9375. graph.model.beginUpdate();
  9376. try
  9377. {
  9378. for (var i = index + 1; i < lines.length; i++)
  9379. {
  9380. var values = this.editor.csvToArray(lines[i]);
  9381. if (values == null)
  9382. {
  9383. var short = (lines[i].length > 40) ? lines[i].substring(0, 40) + '...' : lines[i];
  9384. throw new Error(i + ' (' + short + ') ' + mxResources.get('containsValidationErrors'));
  9385. }
  9386. else if (values.length == keys.length)
  9387. {
  9388. var cell = null;
  9389. var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
  9390. if (id != null)
  9391. {
  9392. cell = graph.model.getCell(id);
  9393. }
  9394. if (cell == null)
  9395. {
  9396. var cell = new mxCell(label, new mxGeometry(x0, y,
  9397. 0, 0), style || 'whiteSpace=wrap;html=1;');
  9398. cell.vertex = true;
  9399. cell.id = id;
  9400. }
  9401. for (var j = 0; j < values.length; j++)
  9402. {
  9403. graph.setAttributeForCell(cell, keys[j], values[j]);
  9404. }
  9405. graph.setAttributeForCell(cell, 'placeholders', '1');
  9406. cell.style = graph.replacePlaceholders(cell, cell.style);
  9407. for (var e = 0; e < edges.length; e++)
  9408. {
  9409. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  9410. }
  9411. if (link != null && link != 'link')
  9412. {
  9413. graph.setLinkForCell(cell, cell.getAttribute(link));
  9414. // Removes attribute
  9415. graph.setAttributeForCell(cell, link, null);
  9416. }
  9417. // Sets the size
  9418. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
  9419. var size = this.editor.graph.getPreferredSizeForCell(cell);
  9420. if (cell.vertex)
  9421. {
  9422. if (left != null && cell.getAttribute(left) != null)
  9423. {
  9424. cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
  9425. }
  9426. if (top != null && cell.getAttribute(top) != null)
  9427. {
  9428. cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
  9429. }
  9430. if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
  9431. {
  9432. cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
  9433. }
  9434. else
  9435. {
  9436. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  9437. }
  9438. if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
  9439. {
  9440. cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
  9441. }
  9442. else
  9443. {
  9444. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  9445. }
  9446. y += cell.geometry.height + nodespacing;
  9447. }
  9448. var parent = (parentIndex != null) ? graph.model.getCell(
  9449. namespace + values[parentIndex]) : null;
  9450. if (parent != null)
  9451. {
  9452. parent.style = graph.replacePlaceholders(parent, parentstyle);
  9453. graph.addCell(cell, parent);
  9454. }
  9455. else
  9456. {
  9457. cells.push(graph.addCell(cell));
  9458. }
  9459. }
  9460. }
  9461. var roots = cells.slice();
  9462. var select = cells.slice();
  9463. for (var e = 0; e < edges.length; e++)
  9464. {
  9465. var edge = edges[e];
  9466. for (var i = 0; i < cells.length; i++)
  9467. {
  9468. var cell = cells[i];
  9469. var tmp = cell.getAttribute(edge.from);
  9470. if (tmp != null)
  9471. {
  9472. // Removes attribute
  9473. graph.setAttributeForCell(cell, edge.from, null);
  9474. var refs = tmp.split(',');
  9475. for (var j = 0; j < refs.length; j++)
  9476. {
  9477. var ref = lookups[edge.to][refs[j]];
  9478. if (ref != null)
  9479. {
  9480. var label = edge.label;
  9481. if (edge.fromlabel != null)
  9482. {
  9483. label = (cell.getAttribute(edge.fromlabel) || '') + (label || '');
  9484. }
  9485. if (edge.tolabel != null)
  9486. {
  9487. label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
  9488. }
  9489. select.push(graph.insertEdge(null, null, label || '',
  9490. (edge.invert) ? ref : cell, (edge.invert) ? cell : ref,
  9491. edge.style || graph.createCurrentEdgeStyle()));
  9492. mxUtils.remove((edge.invert) ? cell : ref, roots);
  9493. }
  9494. }
  9495. }
  9496. }
  9497. }
  9498. // Removes ignored attributes after processing above
  9499. if (ignore != null)
  9500. {
  9501. for (var i = 0; i < cells.length; i++)
  9502. {
  9503. var cell = cells[i];
  9504. for (var j = 0; j < ignore.length; j++)
  9505. {
  9506. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  9507. }
  9508. }
  9509. }
  9510. var edgeLayout = new mxParallelEdgeLayout(graph);
  9511. edgeLayout.spacing = edgespacing;
  9512. var postProcess = function()
  9513. {
  9514. edgeLayout.execute(graph.getDefaultParent());
  9515. // Aligns cells to grid and/or rounds positions
  9516. for (var i = 0; i < cells.length; i++)
  9517. {
  9518. var geo = graph.getCellGeometry(cells[i]);
  9519. geo.x = Math.round(graph.snap(geo.x));
  9520. geo.y = Math.round(graph.snap(geo.y));
  9521. if (width == 'auto')
  9522. {
  9523. geo.width = Math.round(graph.snap(geo.width));
  9524. }
  9525. if (height == 'auto')
  9526. {
  9527. geo.height = Math.round(graph.snap(geo.height));
  9528. }
  9529. }
  9530. };
  9531. if (layout == 'circle')
  9532. {
  9533. var circleLayout = new mxCircleLayout(graph);
  9534. circleLayout.resetEdges = false;
  9535. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  9536. // Ignore other cells
  9537. circleLayout.isVertexIgnored = function(vertex)
  9538. {
  9539. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  9540. mxUtils.indexOf(cells, vertex) < 0;
  9541. };
  9542. this.executeLayout(function()
  9543. {
  9544. circleLayout.execute(graph.getDefaultParent());
  9545. postProcess();
  9546. }, true, afterInsert);
  9547. afterInsert = null;
  9548. }
  9549. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  9550. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  9551. {
  9552. // Required for layouts to work with new cells
  9553. graph.view.validate();
  9554. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  9555. treeLayout.levelDistance = nodespacing;
  9556. treeLayout.edgeRouting = false;
  9557. treeLayout.resetEdges = false;
  9558. this.executeLayout(function()
  9559. {
  9560. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  9561. }, true, afterInsert);
  9562. afterInsert = null;
  9563. }
  9564. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  9565. (layout == 'auto' && roots.length == 1))
  9566. {
  9567. // Required for layouts to work with new cells
  9568. graph.view.validate();
  9569. var flowLayout = new mxHierarchicalLayout(graph,
  9570. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  9571. flowLayout.intraCellSpacing = nodespacing;
  9572. flowLayout.parallelEdgeSpacing = edgespacing;
  9573. flowLayout.interRankCellSpacing = levelspacing;
  9574. flowLayout.disableEdgeStyle = false;
  9575. this.executeLayout(function()
  9576. {
  9577. flowLayout.execute(graph.getDefaultParent(), select);
  9578. // Workaround for flow layout moving cells to origin
  9579. graph.moveCells(select, x0, y0);
  9580. }, true, afterInsert);
  9581. afterInsert = null;
  9582. }
  9583. else if (layout == 'organic' || (layout == 'auto' &&
  9584. select.length > cells.length))
  9585. {
  9586. // Required for layouts to work with new cells
  9587. graph.view.validate();
  9588. var organicLayout = new mxFastOrganicLayout(graph);
  9589. organicLayout.forceConstant = nodespacing * 3;
  9590. organicLayout.resetEdges = false;
  9591. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  9592. // Ignore other cells
  9593. organicLayout.isVertexIgnored = function(vertex)
  9594. {
  9595. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  9596. mxUtils.indexOf(cells, vertex) < 0;
  9597. };
  9598. var edgeLayout = new mxParallelEdgeLayout(graph);
  9599. edgeLayout.spacing = edgespacing;
  9600. this.executeLayout(function()
  9601. {
  9602. organicLayout.execute(graph.getDefaultParent());
  9603. postProcess();
  9604. }, true, afterInsert);
  9605. afterInsert = null;
  9606. }
  9607. this.hideDialog();
  9608. }
  9609. finally
  9610. {
  9611. graph.model.endUpdate();
  9612. }
  9613. if (afterInsert != null)
  9614. {
  9615. afterInsert();
  9616. }
  9617. }
  9618. }
  9619. catch (e)
  9620. {
  9621. this.handleError(e);
  9622. }
  9623. };
  9624. /**
  9625. * Translates this point by the given vector.
  9626. *
  9627. * @param {number} dx X-coordinate of the translation.
  9628. * @param {number} dy Y-coordinate of the translation.
  9629. */
  9630. EditorUi.prototype.getSearch = function(exclude)
  9631. {
  9632. var result = '';
  9633. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  9634. {
  9635. var amp = '?';
  9636. for (var key in urlParams)
  9637. {
  9638. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  9639. {
  9640. result += amp + key + '=' + urlParams[key];
  9641. amp = '&';
  9642. }
  9643. }
  9644. }
  9645. else
  9646. {
  9647. result = window.location.search;
  9648. }
  9649. return result;
  9650. };
  9651. /**
  9652. * Returns the URL for a copy of this editor with no state.
  9653. */
  9654. EditorUi.prototype.getUrl = function(pathname)
  9655. {
  9656. var href = (pathname != null) ? pathname : window.location.pathname;
  9657. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  9658. if (urlParams['offline'] == '1')
  9659. {
  9660. href += window.location.search;
  9661. }
  9662. else
  9663. {
  9664. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  9665. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  9666. // Removes template URL parameter for new blank diagram
  9667. for (var key in urlParams)
  9668. {
  9669. if (mxUtils.indexOf(ignored, key) < 0)
  9670. {
  9671. if (parms == 0)
  9672. {
  9673. href += '?';
  9674. }
  9675. else
  9676. {
  9677. href += '&';
  9678. }
  9679. if (urlParams[key] != null)
  9680. {
  9681. href += key + '=' + urlParams[key];
  9682. parms++;
  9683. }
  9684. }
  9685. }
  9686. }
  9687. return href;
  9688. };
  9689. /**
  9690. * Overrides link dialog.
  9691. */
  9692. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  9693. {
  9694. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  9695. this.showDialog(dlg.container, 480, 130, true, true);
  9696. dlg.init();
  9697. };
  9698. /**
  9699. * Overrides createOutline
  9700. */
  9701. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  9702. EditorUi.prototype.createOutline = function(wnd)
  9703. {
  9704. var outline = editorUiCreateOutline.apply(this, arguments);
  9705. var graph = this.editor.graph;
  9706. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  9707. outline.getSourceGraphBounds = function()
  9708. {
  9709. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  9710. {
  9711. var pb = this.source.getPagePadding();
  9712. var s = this.source.view.scale;
  9713. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  9714. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  9715. return result;
  9716. }
  9717. return outlineGetSourceGraphBounds.apply(this, arguments);
  9718. };
  9719. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  9720. outline.getSourceContainerSize = function()
  9721. {
  9722. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9723. {
  9724. var pad = this.source.getPagePadding();
  9725. var s = this.source.view.scale;
  9726. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  9727. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  9728. }
  9729. return outlineGetSourceContainerSize.apply(this, arguments);
  9730. };
  9731. outline.getOutlineOffset = function(scale)
  9732. {
  9733. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9734. {
  9735. var pb = this.source.getPagePadding();
  9736. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  9737. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  9738. // Why is vertical offset negative relative to dy
  9739. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  9740. }
  9741. return new mxPoint(8 / scale, 8 / scale);
  9742. };
  9743. var outlineInit = outline.init;
  9744. outline.init = function()
  9745. {
  9746. outlineInit.apply(this, arguments);
  9747. // Problem: Need to override a function in the view but the view is created
  9748. // with the graph so a refresh of the page is needed to see this change.
  9749. outline.outline.view.getBackgroundPageBounds = function()
  9750. {
  9751. var layout = graph.getPageLayout();
  9752. var page = graph.getPageSize();
  9753. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  9754. this.scale * (this.translate.y + layout.y * page.height),
  9755. this.scale * layout.width * page.width,
  9756. this.scale * layout.height * page.height);
  9757. };
  9758. outline.outline.view.validateBackgroundPage();
  9759. };
  9760. this.editor.addListener('pageSelected', function(sender, evt)
  9761. {
  9762. var change = evt.getProperty('change');
  9763. var graph = outline.source;
  9764. var g = outline.outline;
  9765. g.pageScale = graph.pageScale;
  9766. g.pageFormat = graph.pageFormat;
  9767. g.background = graph.background;
  9768. g.pageVisible = graph.pageVisible;
  9769. g.background = graph.background;
  9770. var current = mxUtils.getCurrentStyle(graph.container);
  9771. g.container.style.backgroundColor = current.backgroundColor;
  9772. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  9773. {
  9774. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  9775. }
  9776. outline.outline.view.clear(change.previousPage.root, true);
  9777. outline.outline.view.validate();
  9778. });
  9779. return outline;
  9780. };
  9781. /**
  9782. * Returns the number of storage options enabled
  9783. */
  9784. EditorUi.prototype.getServiceCount = function(allowBrowser, splash)
  9785. {
  9786. var serviceCount = 0;
  9787. if (this.drive != null || typeof window.DriveClient === 'function')
  9788. {
  9789. serviceCount++
  9790. }
  9791. if (!splash && (this.dropbox != null || typeof window.DropboxClient === 'function'))
  9792. {
  9793. serviceCount++
  9794. }
  9795. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  9796. {
  9797. serviceCount++
  9798. }
  9799. if (!splash && (this.gitHub != null))
  9800. {
  9801. serviceCount++
  9802. }
  9803. if (!splash && (this.trello != null || typeof window.TrelloClient === 'function'))
  9804. {
  9805. serviceCount++
  9806. }
  9807. if (allowBrowser && isLocalStorage && urlParams['browser'] == '1')
  9808. {
  9809. serviceCount++
  9810. }
  9811. else
  9812. {
  9813. serviceCount++
  9814. }
  9815. return serviceCount;
  9816. }
  9817. /**
  9818. * Updates action and menu states depending on the file.
  9819. */
  9820. EditorUi.prototype.updateUi = function()
  9821. {
  9822. this.updateButtonContainer();
  9823. this.updateActionStates();
  9824. // Action states that only need update for new files
  9825. var file = this.getCurrentFile();
  9826. var active = file != null || (urlParams['embed'] == '1' &&
  9827. this.editor.graph.isEnabled());
  9828. this.menus.get('viewPanels').setEnabled(active);
  9829. this.menus.get('viewZoom').setEnabled(active);
  9830. var restricted = (urlParams['embed'] != '1' ||
  9831. !this.editor.graph.isEnabled()) &&
  9832. (file == null || file.isRestricted());
  9833. this.actions.get('makeCopy').setEnabled(!restricted);
  9834. this.actions.get('print').setEnabled(!restricted);
  9835. this.menus.get('exportAs').setEnabled(!restricted);
  9836. this.menus.get('embed').setEnabled(!restricted);
  9837. // Disables libraries and extras menu in embed mode
  9838. // while waiting for file data
  9839. var libsEnabled = urlParams['embed'] != '1' ||
  9840. this.editor.graph.isEnabled();
  9841. this.menus.get('extras').setEnabled(libsEnabled);
  9842. if (Editor.enableCustomLibraries)
  9843. {
  9844. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  9845. this.menus.get('newLibrary').setEnabled(libsEnabled);
  9846. }
  9847. // Disables actions in the toolbar
  9848. var editable = (urlParams['embed'] == '1' &&
  9849. this.editor.graph.isEnabled()) ||
  9850. (file != null && file.isEditable());
  9851. this.actions.get('image').setEnabled(active);
  9852. this.actions.get('zoomIn').setEnabled(active);
  9853. this.actions.get('zoomOut').setEnabled(active);
  9854. this.actions.get('resetView').setEnabled(active);
  9855. // Updates undo history states
  9856. this.actions.get('undo').setEnabled(this.canUndo() && editable);
  9857. this.actions.get('redo').setEnabled(this.canRedo() && editable);
  9858. // Disables menus
  9859. this.menus.get('edit').setEnabled(active);
  9860. this.menus.get('view').setEnabled(active);
  9861. this.menus.get('importFrom').setEnabled(editable);
  9862. this.menus.get('arrange').setEnabled(editable);
  9863. // Disables connection drop downs in toolbar
  9864. if (this.toolbar != null)
  9865. {
  9866. if (this.toolbar.edgeShapeMenu != null)
  9867. {
  9868. this.toolbar.edgeShapeMenu.setEnabled(editable);
  9869. }
  9870. if (this.toolbar.edgeStyleMenu != null)
  9871. {
  9872. this.toolbar.edgeStyleMenu.setEnabled(editable);
  9873. }
  9874. }
  9875. if (this.isAppCache())
  9876. {
  9877. var appCache = applicationCache;
  9878. // NOTE: HTML5 Cache is deprecated
  9879. if (appCache != null && this.offlineStatus == null)
  9880. {
  9881. this.offlineStatus = document.createElement('div');
  9882. this.offlineStatus.className = 'geItem';
  9883. this.offlineStatus.style.position = 'absolute';
  9884. this.offlineStatus.style.fontSize = '8pt';
  9885. this.offlineStatus.style.top = '2px';
  9886. this.offlineStatus.style.right = '12px';
  9887. this.offlineStatus.style.color = '#666';
  9888. this.offlineStatus.style.margin = '4px';
  9889. this.offlineStatus.style.padding = '2px';
  9890. this.offlineStatus.style.verticalAlign = 'middle';
  9891. this.offlineStatus.innerHTML = '';
  9892. this.menubarContainer.appendChild(this.offlineStatus);
  9893. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  9894. {
  9895. var img = this.offlineStatus.getElementsByTagName('img');
  9896. if (img != null && img.length > 0)
  9897. {
  9898. this.alert(img[0].getAttribute('title'));
  9899. }
  9900. }));
  9901. var appCache = window.applicationCache;
  9902. var lastStatus = null;
  9903. var updateStatus = mxUtils.bind(this, function()
  9904. {
  9905. var newStatus = appCache.status;
  9906. var html = '';
  9907. if (newStatus == appCache.CHECKING)
  9908. {
  9909. newStatus = appCache.DOWNLOADING;
  9910. }
  9911. switch (newStatus)
  9912. {
  9913. case appCache.UNCACHED: // UNCACHED == 0
  9914. html = '';
  9915. break;
  9916. case appCache.IDLE: // IDLE == 1
  9917. html = (uiTheme == 'min') ? '' : '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  9918. break;
  9919. case appCache.DOWNLOADING: // DOWNLOADING == 3
  9920. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  9921. break;
  9922. case appCache.UPDATEREADY: // UPDATEREADY == 4
  9923. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  9924. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  9925. break;
  9926. case appCache.OBSOLETE: // OBSOLETE == 5
  9927. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9928. break;
  9929. default:
  9930. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  9931. break;
  9932. }
  9933. if (newStatus != lastStatus)
  9934. {
  9935. this.offlineStatus.innerHTML = html;
  9936. lastStatus = newStatus;
  9937. }
  9938. });
  9939. mxEvent.addListener(appCache, 'checking', updateStatus);
  9940. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  9941. mxEvent.addListener(appCache, 'downloading', updateStatus);
  9942. mxEvent.addListener(appCache, 'progress', updateStatus);
  9943. mxEvent.addListener(appCache, 'cached', updateStatus);
  9944. mxEvent.addListener(appCache, 'updateready', updateStatus);
  9945. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  9946. mxEvent.addListener(appCache, 'error', updateStatus);
  9947. updateStatus();
  9948. }
  9949. }
  9950. else
  9951. {
  9952. this.updateUserElement();
  9953. }
  9954. };
  9955. /**
  9956. * Hook for subclassers
  9957. */
  9958. EditorUi.prototype.updateButtonContainer = function()
  9959. {
  9960. // do nothing
  9961. };
  9962. /**
  9963. * Hook for subclassers
  9964. */
  9965. EditorUi.prototype.updateUserElement = function()
  9966. {
  9967. // do nothing
  9968. };
  9969. /**
  9970. * Returns true if a diagram is cative and editable.
  9971. */
  9972. EditorUi.prototype.isDiagramActive = function()
  9973. {
  9974. var file = this.getCurrentFile();
  9975. return (file != null && file.isEditable()) ||
  9976. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  9977. };
  9978. /**
  9979. * Updates action states depending on the selection.
  9980. */
  9981. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  9982. EditorUi.prototype.updateActionStates = function()
  9983. {
  9984. editorUiUpdateActionStates.apply(this, arguments);
  9985. var graph = this.editor.graph;
  9986. var active = this.isDiagramActive();
  9987. var file = this.getCurrentFile();
  9988. var enabled = file != null || urlParams['embed'] == '1';
  9989. this.actions.get('pageSetup').setEnabled(active);
  9990. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  9991. this.actions.get('guides').setEnabled(active);
  9992. this.actions.get('editData').setEnabled(active);
  9993. this.actions.get('shadowVisible').setEnabled(active);
  9994. this.actions.get('connectionArrows').setEnabled(active);
  9995. this.actions.get('connectionPoints').setEnabled(active);
  9996. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  9997. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  9998. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  9999. this.actions.get('createShape').setEnabled(active);
  10000. this.actions.get('createRevision').setEnabled(active);
  10001. this.actions.get('moveToFolder').setEnabled(file != null);
  10002. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  10003. this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
  10004. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  10005. this.actions.get('tags').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10006. this.actions.get('find').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10007. this.actions.get('layers').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10008. this.actions.get('outline').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10009. this.actions.get('rename').setEnabled((file != null && file.isRenamable()) || urlParams['embed'] == '1');
  10010. this.actions.get('close').setEnabled(file != null);
  10011. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  10012. var state = graph.view.getState(graph.getSelectionCell());
  10013. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  10014. };
  10015. /**
  10016. * Overridden to remove export dialog in chromeless lightbox.
  10017. */
  10018. var editoUiDestroy = EditorUi.prototype.destroy;
  10019. EditorUi.prototype.destroy = function()
  10020. {
  10021. if (this.editUpdateListener)
  10022. {
  10023. this.editor.undoManager.removeListener(this.editUpdateListener);
  10024. this.editUpdateListener = null;
  10025. }
  10026. if (this.exportDialog != null)
  10027. {
  10028. this.exportDialog.parentNode.removeChild(this.exportDialog);
  10029. this.exportDialog = null;
  10030. }
  10031. editoUiDestroy.apply(this, arguments);
  10032. };
  10033. /**
  10034. * Overrides export dialog for using ui functions for save and setting global switches.
  10035. */
  10036. if (window.ExportDialog != null)
  10037. {
  10038. ExportDialog.showXmlOption = false;
  10039. ExportDialog.showGifOption = false;
  10040. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  10041. {
  10042. var graph = editorUi.editor.graph;
  10043. if (format == 'xml')
  10044. {
  10045. editorUi.hideDialog();
  10046. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  10047. }
  10048. else if (format == 'svg')
  10049. {
  10050. editorUi.hideDialog();
  10051. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  10052. }
  10053. else
  10054. {
  10055. var data = editorUi.getFileData(true, null, null, null, null, true);
  10056. var bounds = graph.getGraphBounds();
  10057. var w = Math.floor(bounds.width * s / graph.view.scale);
  10058. var h = Math.floor(bounds.height * s / graph.view.scale);
  10059. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  10060. {
  10061. editorUi.hideDialog();
  10062. editorUi.saveRequest(name, format,
  10063. function(newTitle, base64)
  10064. {
  10065. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  10066. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  10067. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  10068. '&border=' + b + '&xml=' + encodeURIComponent(data));
  10069. });
  10070. }
  10071. else
  10072. {
  10073. mxUtils.alert(mxResources.get('drawingTooLarge'));
  10074. }
  10075. }
  10076. };
  10077. }
  10078. /*********************************************************************************************
  10079. * This section is a fix for undo/redo edits having stale 1st- and 2nd-order references *
  10080. * The code might be reworked or even thrown out when a conceptually nicer solution is found *
  10081. *********************************************************************************************/
  10082. /**
  10083. * Updates all references in all edits and their changes in order to correspond to current model
  10084. */
  10085. EditorUi.prototype.updateEditReferences = function(edit)
  10086. {
  10087. for (var i = 0; i < edit.changes.length; i++)
  10088. {
  10089. var change = edit.changes[i];
  10090. if (change != null && change.constructor == mxChildChange)
  10091. {
  10092. if (change.child != null)
  10093. {
  10094. var child = change.child;
  10095. if (child.source != null && child.source.id != null)
  10096. {
  10097. var modelSource = this.getFutureCellForEdit(change.model, edit, child.source.id);
  10098. if (modelSource != child.source)
  10099. {
  10100. child.source = modelSource
  10101. }
  10102. }
  10103. if (child.target != null && child.target.id != null)
  10104. {
  10105. var modelTarget = this.getFutureCellForEdit(change.model, edit, child.target.id);
  10106. if (modelTarget != child.target)
  10107. {
  10108. child.target = modelTarget
  10109. }
  10110. }
  10111. }
  10112. }
  10113. }
  10114. };
  10115. /**
  10116. * Looks ahead in edit's changes to see if the last child change containing ID is one that creates a cell, then returns it.
  10117. * If cell already exists in a model, returns it first.
  10118. */
  10119. EditorUi.prototype.getFutureCellForEdit = function(model, edit, id)
  10120. {
  10121. var result = model.getCell(id);
  10122. if (result == null)
  10123. {
  10124. // Scans changes backwards
  10125. for (var i = edit.changes.length - 1; i >= 0; i--)
  10126. {
  10127. var change = edit.changes[i];
  10128. if (change.constructor == mxChildChange)
  10129. {
  10130. // Checks if child is being added in this change
  10131. if (change.child != null && change.child.id == id)
  10132. {
  10133. // Checks if cell is being removed
  10134. if (model.contains(change.previous))
  10135. {
  10136. result = change.child;
  10137. }
  10138. // Stops scan in any case, at the end of the edit
  10139. // the cell will be either added or deleted
  10140. break;
  10141. }
  10142. }
  10143. }
  10144. }
  10145. return result;
  10146. };
  10147. EditorUi.prototype.getDiagramTextContent = function()
  10148. {
  10149. this.editor.graph.setEnabled(false);
  10150. var graph = this.editor.graph;
  10151. var allPagesTxt = '';
  10152. if (this.pages != null)
  10153. {
  10154. for (var i = 0; i < this.pages.length; i++)
  10155. {
  10156. var pageGraph = graph;
  10157. if (this.currentPage != this.pages[i])
  10158. {
  10159. pageGraph = this.createTemporaryGraph(graph.getStylesheet());
  10160. pageGraph.model.setRoot(this.pages[i].root);
  10161. }
  10162. allPagesTxt += this.pages[i].getName() + ' ' + pageGraph.getIndexableText() + ' ';
  10163. }
  10164. }
  10165. else
  10166. {
  10167. allPagesTxt = graph.getIndexableText();
  10168. }
  10169. this.editor.graph.setEnabled(true);
  10170. return allPagesTxt;
  10171. };
  10172. EditorUi.prototype.showRemotelyStoredLibrary = function(title)
  10173. {
  10174. var selectedLibs = {};
  10175. var div = document.createElement('div');
  10176. div.style.whiteSpace = 'nowrap';
  10177. var graph = this.editor.graph;
  10178. var hd = document.createElement('h3');
  10179. mxUtils.write(hd, mxUtils.htmlEntities(title));
  10180. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  10181. div.appendChild(hd);
  10182. var libsSection = document.createElement('div');
  10183. libsSection.style.cssText = 'border:1px solid lightGray;overflow: auto;height:300px';
  10184. libsSection.innerHTML = '<img src="/images/spin.gif">';
  10185. var loadedLibs = {};
  10186. try
  10187. {
  10188. var custLibs = mxSettings.getCustomLibraries();
  10189. for (var j = 0; j < custLibs.length; j++)
  10190. {
  10191. var l = custLibs[j];
  10192. if (l.substring(0, 1) == 'R')
  10193. {
  10194. var libDesc = JSON.parse(decodeURIComponent(l.substring(1)));
  10195. loadedLibs[libDesc[0]] = {
  10196. id: libDesc[0],
  10197. title: libDesc[1],
  10198. downloadUrl: libDesc[2]
  10199. };
  10200. }
  10201. }
  10202. }
  10203. catch(e){}
  10204. this.remoteInvoke('getCustomLibraries', null, null, function(libsList)
  10205. {
  10206. libsSection.innerHTML = '';
  10207. for (var i = 0; i < libsList.length; i++)
  10208. {
  10209. var lib = libsList[i];
  10210. if (loadedLibs[lib.id])
  10211. {
  10212. selectedLibs[lib.id] = lib;
  10213. }
  10214. var libCheck = this.addCheckbox(libsSection, lib.title, loadedLibs[lib.id]);
  10215. (function(lib2, check)
  10216. {
  10217. mxEvent.addListener(check, 'change', function()
  10218. {
  10219. if (this.checked)
  10220. {
  10221. selectedLibs[lib2.id] = lib2;
  10222. }
  10223. else
  10224. {
  10225. delete selectedLibs[lib2.id];
  10226. }
  10227. });
  10228. })(lib, libCheck)
  10229. }
  10230. }, function()
  10231. {
  10232. this.handleError(null, mxResources.get('errorGettingConfLibs', null, 'An error occured while getting Confluence libraries list'));
  10233. });
  10234. div.appendChild(libsSection);
  10235. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  10236. {
  10237. this.spinner.spin(document.body, mxResources.get('loading'));
  10238. var pendingLibs = 0;
  10239. for (var id in selectedLibs)
  10240. {
  10241. if (loadedLibs[id] != null) continue; //already loaded!
  10242. pendingLibs++;
  10243. (mxUtils.bind(this, function(lib)
  10244. {
  10245. this.remoteInvoke('getFileContent', [lib.downloadUrl], null, mxUtils.bind(this, function(libContent)
  10246. {
  10247. pendingLibs--;
  10248. if (pendingLibs == 0) this.spinner.stop();
  10249. try
  10250. {
  10251. this.loadLibrary(new RemoteLibrary(this, libContent, lib));
  10252. }
  10253. catch (e)
  10254. {
  10255. this.handleError(e, mxResources.get('errorLoadingFile'));
  10256. }
  10257. }), mxUtils.bind(this, function()
  10258. {
  10259. pendingLibs--;
  10260. if (pendingLibs == 0) this.spinner.stop();
  10261. this.handleError(null, mxResources.get('errorLoadingFile'));
  10262. }));
  10263. }))(selectedLibs[id]);
  10264. }
  10265. for (var id in loadedLibs)
  10266. {
  10267. if (!selectedLibs[id]) //Removed
  10268. {
  10269. this.closeLibrary(new RemoteLibrary(this, null, loadedLibs[id])); //create a dummy library such that we can call closeLibrary
  10270. }
  10271. }
  10272. if (pendingLibs == 0) this.spinner.stop();
  10273. }));
  10274. this.showDialog(dlg.container, 340, 375, true, true);
  10275. };
  10276. //Remote invokation, currently limited to functions in EditorUi (and its sub objects) for security reasons
  10277. //White-listed functions and some info about it
  10278. EditorUi.prototype.remoteInvokableFns = {
  10279. getDiagramTextContent: {isAsync: false}
  10280. };
  10281. EditorUi.prototype.remoteInvokeCallbacks = [];
  10282. EditorUi.prototype.remoteInvokeQueue = [];
  10283. EditorUi.prototype.handleRemoteInvokeReady = function(remoteWin)
  10284. {
  10285. this.remoteWin = remoteWin;
  10286. for (var i = 0; i < this.remoteInvokeQueue.length; i++)
  10287. {
  10288. remoteWin.postMessage(this.remoteInvokeQueue[i], '*');
  10289. }
  10290. this.remoteInvokeQueue = [];
  10291. };
  10292. EditorUi.prototype.handleRemoteInvokeResponse = function(msg)
  10293. {
  10294. var msgMarkers = msg.msgMarkers;
  10295. var callback = this.remoteInvokeCallbacks[msgMarkers.callbackId];
  10296. if (msg.error)
  10297. {
  10298. if (callback.error) callback.error(msg.error.errResp);
  10299. }
  10300. else if (callback.callback)
  10301. {
  10302. callback.callback.apply(this, msg.resp);
  10303. }
  10304. this.remoteInvokeCallbacks[msgMarkers.callbackId] = null; //set it to null only to keep the index
  10305. };
  10306. EditorUi.prototype.remoteInvoke = function(remoteFn, remoteFnArgs, msgMarkers, callback, error)
  10307. {
  10308. msgMarkers = msgMarkers || {};
  10309. msgMarkers.callbackId = this.remoteInvokeCallbacks.length;
  10310. this.remoteInvokeCallbacks.push({callback: callback, error: error});
  10311. var msg = JSON.stringify({event: 'remoteInvoke', funtionName: remoteFn, functionArgs: remoteFnArgs, msgMarkers: msgMarkers});
  10312. if (this.remoteWin != null) //remote invoke is ready
  10313. {
  10314. this.remoteWin.postMessage(msg, '*');
  10315. }
  10316. else
  10317. {
  10318. this.remoteInvokeQueue.push(msg);
  10319. }
  10320. };
  10321. EditorUi.prototype.handleRemoteInvoke = function(msg)
  10322. {
  10323. var sendResponse = mxUtils.bind(this, function(resp, error)
  10324. {
  10325. var respMsg = {event: 'remoteInvokeResponse', msgMarkers: msg.msgMarkers};
  10326. if (error != null)
  10327. {
  10328. respMsg.error = {errResp: error};
  10329. }
  10330. else if (resp != null)
  10331. {
  10332. respMsg.resp = resp;
  10333. }
  10334. this.remoteWin.postMessage(JSON.stringify(respMsg), '*');
  10335. });
  10336. try
  10337. {
  10338. //Remote invoke are allowed to call functions in AC
  10339. var funtionName = msg.funtionName;
  10340. var functionInfo = this.remoteInvokableFns[funtionName];
  10341. if (functionInfo != null && typeof this[funtionName] === 'function')
  10342. {
  10343. var functionArgs = msg.functionArgs;
  10344. //Confirm functionArgs are not null and is array, otherwise, discard it
  10345. if (!Array.isArray(functionArgs))
  10346. {
  10347. functionArgs = [];
  10348. }
  10349. //for functions with callbacks (async) we assume last two arguments are success, error
  10350. if (functionInfo.isAsync)
  10351. {
  10352. //success
  10353. functionArgs.push(function()
  10354. {
  10355. sendResponse(Array.prototype.slice.apply(arguments));
  10356. });
  10357. //error
  10358. functionArgs.push(function(err)
  10359. {
  10360. sendResponse(null, err || 'Unkown Error');
  10361. });
  10362. this[funtionName].apply(this, functionArgs);
  10363. }
  10364. else
  10365. {
  10366. var resp = this[funtionName].apply(this, functionArgs);
  10367. sendResponse([resp]);
  10368. }
  10369. }
  10370. else
  10371. {
  10372. sendResponse(null, 'Invalid Call: ' + funtionName + ' is not found.');
  10373. }
  10374. }
  10375. catch(e)
  10376. {
  10377. sendResponse(null, 'Invalid Call: An error occured, ' + e.message);
  10378. }
  10379. };
  10380. })();