EditorUi.js 357 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421
  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. * Maximum size for text files in labels is 0.5 MB.
  226. */
  227. EditorUi.prototype.maxTextBytes = 500000;
  228. /**
  229. * Holds the current file.
  230. */
  231. EditorUi.prototype.currentFile = null;
  232. /**
  233. * Specifies if PDF export should be done via print dialog. Default is
  234. * false which uses the PhantomJS backend to create the PDF.
  235. */
  236. EditorUi.prototype.printPdfExport = false;
  237. /**
  238. * Specifies if PDF export with pages is enabled.
  239. */
  240. EditorUi.prototype.pdfPageExport = true;
  241. /**
  242. * Restores app defaults for UI
  243. */
  244. EditorUi.prototype.formatEnabled = urlParams['format'] != '0';
  245. /**
  246. * Whether template action should be shown in insert menu.
  247. */
  248. EditorUi.prototype.insertTemplateEnabled = true;
  249. /**
  250. * Restores app defaults for UI
  251. */
  252. EditorUi.prototype.closableScratchpad = true;
  253. /**
  254. * Capability check for canvas export
  255. */
  256. (function()
  257. {
  258. EditorUi.prototype.useCanvasForExport = false;
  259. EditorUi.prototype.jpgSupported = false;
  260. // Checks if canvas is supported
  261. try
  262. {
  263. var cnv = document.createElement('canvas');
  264. EditorUi.prototype.canvasSupported = !!(cnv.getContext && cnv.getContext('2d'));
  265. }
  266. catch (e)
  267. {
  268. // ignore
  269. }
  270. try
  271. {
  272. var canvas = document.createElement('canvas');
  273. var img = new Image();
  274. // LATER: Capability check should not be async
  275. img.onload = function()
  276. {
  277. try
  278. {
  279. var ctx = canvas.getContext('2d');
  280. ctx.drawImage(img, 0, 0);
  281. // Works in Chrome, Firefox, Edge, Safari and Opera
  282. var result = canvas.toDataURL('image/png');
  283. EditorUi.prototype.useCanvasForExport = result != null && result.length > 6;
  284. }
  285. catch (e)
  286. {
  287. // ignore
  288. }
  289. };
  290. // Checks if SVG with foreignObject can be exported
  291. 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>';
  292. img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  293. }
  294. catch (e)
  295. {
  296. // ignore
  297. }
  298. // Checks for client-side JPG support
  299. try
  300. {
  301. var canvas = document.createElement('canvas');
  302. canvas.width = canvas.height = 1;
  303. var uri = canvas.toDataURL('image/jpeg');
  304. EditorUi.prototype.jpgSupported = (uri.match('image/jpeg') !== null);
  305. }
  306. catch (e)
  307. {
  308. // ignore
  309. }
  310. })();
  311. /**
  312. * Hook for subclassers.
  313. */
  314. EditorUi.prototype.openLink = function(url, target, allowOpener)
  315. {
  316. // LATER: Replace this with direct calls to graph
  317. return this.editor.graph.openLink(url, target, allowOpener);
  318. };
  319. /**
  320. * Hook for subclassers.
  321. */
  322. EditorUi.prototype.showSplash = function(force) { };
  323. /**
  324. * Abstraction for local storage access.
  325. */
  326. EditorUi.prototype.getLocalData = function(key, fn)
  327. {
  328. fn(localStorage.getItem(key));
  329. };
  330. /**
  331. * Abstraction for local storage access.
  332. */
  333. EditorUi.prototype.setLocalData = function(key, data, fn)
  334. {
  335. localStorage.setItem(key, data);
  336. if (fn != null)
  337. {
  338. fn();
  339. }
  340. };
  341. /**
  342. * Abstraction for local storage access.
  343. */
  344. EditorUi.prototype.removeLocalData = function(key, fn)
  345. {
  346. localStorage.removeItem(key)
  347. fn();
  348. };
  349. EditorUi.prototype.setMathEnabled = function(value)
  350. {
  351. this.editor.graph.mathEnabled = value;
  352. this.editor.updateGraphComponents();
  353. this.editor.graph.refresh();
  354. this.fireEvent(new mxEventObject('mathEnabledChanged'));
  355. };
  356. EditorUi.prototype.isMathEnabled = function(value)
  357. {
  358. return this.editor.graph.mathEnabled;
  359. };
  360. /**
  361. * Returns true if using application cache
  362. */
  363. EditorUi.prototype.isAppCache = function()
  364. {
  365. return (urlParams['appcache'] == '1' || this.isOfflineApp());
  366. };
  367. /**
  368. * Returns true if offline app, which isn't a defined thing
  369. */
  370. EditorUi.prototype.isOfflineApp = function()
  371. {
  372. return (urlParams['offline'] == '1');
  373. };
  374. /**
  375. * Returns true if no external comms allowed or possible
  376. */
  377. EditorUi.prototype.isOffline = function(ignoreStealth)
  378. {
  379. return this.isOfflineApp() || !navigator.onLine || (!ignoreStealth && urlParams['stealth'] == '1');
  380. };
  381. /**
  382. * Translates this point by the given vector.
  383. *
  384. * @param {number} dx X-coordinate of the translation.
  385. * @param {number} dy Y-coordinate of the translation.
  386. */
  387. EditorUi.prototype.createSpinner = function(x, y, size)
  388. {
  389. size = (size != null) ? size : 24;
  390. var spinner = new Spinner({
  391. lines: 12, // The number of lines to draw
  392. length: size, // The length of each line
  393. width: Math.round(size / 3), // The line thickness
  394. radius: Math.round(size / 2), // The radius of the inner circle
  395. rotate: 0, // The rotation offset
  396. color: (uiTheme == 'dark') ? '#c0c0c0' : '#000', // #rgb or #rrggbb
  397. speed: 1.5, // Rounds per second
  398. trail: 60, // Afterglow percentage
  399. shadow: false, // Whether to render a shadow
  400. hwaccel: false, // Whether to use hardware acceleration
  401. zIndex: 2e9 // The z-index (defaults to 2000000000)
  402. });
  403. // Extends spin method to include an optional label
  404. var oldSpin = spinner.spin;
  405. spinner.spin = function(container, label)
  406. {
  407. var result = false;
  408. if (!this.active)
  409. {
  410. oldSpin.call(this, container);
  411. this.active = true;
  412. if (label != null)
  413. {
  414. var status = document.createElement('div');
  415. status.style.position = 'absolute';
  416. status.style.whiteSpace = 'nowrap';
  417. status.style.background = '#4B4243';
  418. status.style.color = 'white';
  419. status.style.fontFamily = 'Helvetica, Arial';
  420. status.style.fontSize = '9pt';
  421. status.style.padding = '6px';
  422. status.style.paddingLeft = '10px';
  423. status.style.paddingRight = '10px';
  424. status.style.zIndex = 2e9;
  425. status.style.left = Math.max(0, x) + 'px';
  426. status.style.top = Math.max(0, y + 70) + 'px';
  427. mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
  428. mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');
  429. if (uiTheme != 'dark')
  430. {
  431. mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
  432. }
  433. if (label.substring(label.length - 3, label.length) != '...' &&
  434. label.charAt(label.length - 1) != '!')
  435. {
  436. label = label + '...';
  437. }
  438. status.innerHTML = label;
  439. container.appendChild(status);
  440. spinner.status = status;
  441. // Centers the label in older IE versions
  442. if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
  443. {
  444. status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
  445. status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
  446. }
  447. }
  448. // Pause returns a function to resume the spinner
  449. this.pause = mxUtils.bind(this, function()
  450. {
  451. var fn = function() { };
  452. if (this.active)
  453. {
  454. fn = mxUtils.bind(this, function()
  455. {
  456. this.spin(container, label);
  457. });
  458. }
  459. this.stop();
  460. return fn;
  461. });
  462. result = true;
  463. }
  464. return result;
  465. };
  466. // Extends stop method to remove the optional label
  467. var oldStop = spinner.stop;
  468. spinner.stop = function()
  469. {
  470. oldStop.call(this);
  471. this.active = false;
  472. if (spinner.status != null)
  473. {
  474. spinner.status.parentNode.removeChild(spinner.status);
  475. spinner.status = null;
  476. }
  477. };
  478. spinner.pause = function()
  479. {
  480. return function() {};
  481. };
  482. return spinner;
  483. };
  484. /**
  485. * Static method for pasing PNG files.
  486. */
  487. EditorUi.parsePng = function(f, fn, error)
  488. {
  489. var pos = 0;
  490. function fread(d, count)
  491. {
  492. var start = pos;
  493. pos += count;
  494. return d.substring(start, pos);
  495. };
  496. // Reads unsigned long 32 bit big endian
  497. function _freadint(d)
  498. {
  499. var bytes = fread(d, 4);
  500. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  501. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  502. };
  503. // Checks signature
  504. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  505. {
  506. if (error != null)
  507. {
  508. error();
  509. }
  510. return;
  511. }
  512. // Reads header chunk
  513. fread(f,4);
  514. if (fread(f,4) != 'IHDR')
  515. {
  516. if (error != null)
  517. {
  518. error();
  519. }
  520. return;
  521. }
  522. fread(f, 17);
  523. do
  524. {
  525. var n = _freadint(f);
  526. var type = fread(f,4);
  527. if (fn != null)
  528. {
  529. if (fn(pos - 8, type, n))
  530. {
  531. break;
  532. }
  533. }
  534. value = fread(f,n);
  535. fread(f,4);
  536. if (type == 'IEND')
  537. {
  538. break;
  539. }
  540. }
  541. while (n);
  542. };
  543. /**
  544. * Returns true if the given string contains a compatible graph model.
  545. */
  546. EditorUi.prototype.isCompatibleString = function(data)
  547. {
  548. try
  549. {
  550. var doc = mxUtils.parseXml(data);
  551. var node = this.editor.extractGraphModel(doc.documentElement, true);
  552. return node != null && node.getElementsByTagName('parsererror').length == 0;
  553. }
  554. catch (e)
  555. {
  556. // ignore
  557. }
  558. return false;
  559. };
  560. /**
  561. * Returns true if the given binary data is a Visio file.
  562. */
  563. EditorUi.prototype.isVisioData = function(data)
  564. {
  565. return data.length > 8 && (data.charCodeAt(0) == 0xD0 && data.charCodeAt(1) == 0xCF &&
  566. data.charCodeAt(2) == 0x11 && data.charCodeAt(3) == 0xE0 && data.charCodeAt(4) == 0xA1 && data.charCodeAt(5) == 0xB1 &&
  567. data.charCodeAt(6) == 0x1A && data.charCodeAt(7) == 0xE1) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  568. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x04) || (data.charCodeAt(0) == 0x50 && data.charCodeAt(1) == 0x4B &&
  569. data.charCodeAt(2) == 0x03 && data.charCodeAt(3) == 0x06);
  570. };
  571. /**
  572. * Returns true if the given binary data is a PNG file.
  573. */
  574. EditorUi.prototype.isPngData = function(data)
  575. {
  576. return data.length > 8 && data.charCodeAt(0) == 137 && data.charCodeAt(1) == 80 &&
  577. data.charCodeAt(2) == 78 && data.charCodeAt(3) == 71 && data.charCodeAt(4) == 13 &&
  578. data.charCodeAt(5) == 10 && data.charCodeAt(6) == 26 && data.charCodeAt(7) == 10;
  579. };
  580. /**
  581. * Extracts the mxfile from the given HTML data from a data transfer event.
  582. */
  583. var editorUiExtractGraphModelFromHtml = EditorUi.prototype.extractGraphModelFromHtml;
  584. EditorUi.prototype.extractGraphModelFromHtml = function(data)
  585. {
  586. var result = editorUiExtractGraphModelFromHtml.apply(this, arguments);
  587. if (result == null)
  588. {
  589. try
  590. {
  591. var idx = data.indexOf('&lt;mxfile ');
  592. if (idx >= 0)
  593. {
  594. var idx2 = data.lastIndexOf('&lt;/mxfile&gt;');
  595. if (idx2 > idx)
  596. {
  597. result = data.substring(idx, idx2 + 15).replace(/&gt;/g, '>').
  598. replace(/&lt;/g, '<').replace(/\\&quot;/g, '"').replace(/\n/g, '');
  599. }
  600. }
  601. else
  602. {
  603. // Gets compressed data from mxgraph element in HTML document
  604. var doc = mxUtils.parseXml(data);
  605. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null ||
  606. this.diagramContainer.style.visibility == 'hidden');
  607. result = (node != null) ? mxUtils.getXml(node) : '';
  608. }
  609. }
  610. catch (e)
  611. {
  612. // ignore
  613. }
  614. }
  615. return result;
  616. };
  617. /**
  618. * Workaround for malformed xhtml meta element bug 07.08.16. The trailing slash was missing causing
  619. * reopen to fail trying to parse. Used in replaceFileData, setFileData and importFile.
  620. */
  621. EditorUi.prototype.validateFileData = function(data)
  622. {
  623. if (data != null && data.length > 0)
  624. {
  625. var index = data.indexOf('<meta charset="utf-8">');
  626. if (index >= 0)
  627. {
  628. var replaceString = '<meta charset="utf-8"/>';
  629. var replaceStrLen = replaceString.length;
  630. data = data.slice(0, index) + replaceString + data.slice(index + replaceStrLen - 1, data.length);
  631. }
  632. data = Graph.zapGremlins(data);
  633. }
  634. return data;
  635. };
  636. /**
  637. *
  638. */
  639. EditorUi.prototype.replaceFileData = function(data)
  640. {
  641. data = this.validateFileData(data);
  642. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  643. // Some nodes must be extracted here to find the mxfile node
  644. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  645. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  646. if (tmp != null)
  647. {
  648. node = tmp;
  649. }
  650. if (node != null)
  651. {
  652. var graph = this.editor.graph;
  653. graph.model.beginUpdate();
  654. try
  655. {
  656. var oldPages = (this.pages != null) ? this.pages.slice() : null;
  657. var nodes = node.getElementsByTagName('diagram');
  658. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  659. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  660. {
  661. this.fileNode = node;
  662. this.pages = (this.pages != null) ? this.pages : [];
  663. // Wraps page nodes
  664. for (var i = nodes.length - 1; i >= 0; i--)
  665. {
  666. var page = this.updatePageRoot(new DiagramPage(nodes[i]));
  667. // Checks for invalid page names
  668. if (page.getName() == null)
  669. {
  670. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  671. }
  672. graph.model.execute(new ChangePage(this, page, (i == 0) ? page : null, 0));
  673. }
  674. }
  675. else
  676. {
  677. // Creates tabbed file structure if enforced by URL
  678. if (urlParams['pages'] != '0' && this.fileNode == null)
  679. {
  680. this.fileNode = node.ownerDocument.createElement('mxfile');
  681. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  682. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  683. graph.model.execute(new ChangePage(this, this.currentPage, this.currentPage, 0));
  684. }
  685. // Avoids scroll offset when switching page
  686. this.editor.setGraphXml(node);
  687. // Avoids duplicate parsing of the XML stored in the node
  688. if (this.currentPage != null)
  689. {
  690. this.currentPage.root = this.editor.graph.model.root;
  691. }
  692. }
  693. if (oldPages != null)
  694. {
  695. for (var i = 0; i < oldPages.length; i++)
  696. {
  697. graph.model.execute(new ChangePage(this, oldPages[i], null));
  698. }
  699. }
  700. }
  701. finally
  702. {
  703. graph.model.endUpdate();
  704. }
  705. }
  706. };
  707. /**
  708. * Translates this point by the given vector.
  709. *
  710. * @param {number} dx X-coordinate of the translation.
  711. * @param {number} dy Y-coordinate of the translation.
  712. */
  713. EditorUi.prototype.createFileData = function(node, graph, file, url, forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact)
  714. {
  715. graph = (graph != null) ? graph : this.editor.graph;
  716. forceXml = (forceXml != null) ? forceXml : false;
  717. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  718. var editLink = null;
  719. var redirect = null;
  720. if (file == null || file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER)
  721. {
  722. editLink = '_blank';
  723. }
  724. else
  725. {
  726. editLink = url;
  727. redirect = editLink;
  728. }
  729. if (node == null)
  730. {
  731. return '';
  732. }
  733. else
  734. {
  735. var fileNode = node;
  736. // Ignores case for possible HTML or XML nodes
  737. if (fileNode.nodeName.toLowerCase() != 'mxfile')
  738. {
  739. // Removes control chars in input for correct roundtrip check
  740. var text = Graph.zapGremlins(mxUtils.getXml(node));
  741. var data = Graph.compress(text);
  742. // Fallback to plain XML for invalid compression
  743. // TODO: Remove this fallback with active pages
  744. if (Graph.decompress(data) != text)
  745. {
  746. return text;
  747. }
  748. else
  749. {
  750. var diagramNode = node.ownerDocument.createElement('diagram');
  751. diagramNode.setAttribute('id', Editor.guid());
  752. mxUtils.setTextContent(diagramNode, data);
  753. fileNode = node.ownerDocument.createElement('mxfile');
  754. fileNode.appendChild(diagramNode);
  755. }
  756. }
  757. if (!compact)
  758. {
  759. // Removes old metadata
  760. fileNode.removeAttribute('userAgent');
  761. fileNode.removeAttribute('version');
  762. fileNode.removeAttribute('editor');
  763. fileNode.removeAttribute('type');
  764. // Adds new metadata
  765. fileNode.setAttribute('modified', new Date().toISOString());
  766. fileNode.setAttribute('host', window.location.hostname);
  767. fileNode.setAttribute('agent', navigator.userAgent);
  768. fileNode.setAttribute('version', EditorUi.VERSION);
  769. fileNode.setAttribute('etag', Editor.guid());
  770. var md = (file != null) ? file.getMode() : this.mode;
  771. if (md != null)
  772. {
  773. fileNode.setAttribute('type', md);
  774. }
  775. }
  776. else
  777. {
  778. fileNode = fileNode.cloneNode(true);
  779. fileNode.removeAttribute('userAgent');
  780. fileNode.removeAttribute('version');
  781. fileNode.removeAttribute('editor');
  782. fileNode.removeAttribute('type');
  783. }
  784. var xml = mxUtils.getXml(fileNode);
  785. // Writes the file as an embedded HTML file
  786. if (!forceSvg && !forceXml && (forceHtml || (file != null && /(\.html)$/i.test(file.getTitle()))))
  787. {
  788. xml = this.getHtml2(mxUtils.getXml(fileNode), graph, (file != null) ? file.getTitle() : null, editLink, redirect);
  789. }
  790. // Maps the XML data to the content attribute in the SVG node
  791. else if (forceSvg || (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle())))
  792. {
  793. if (file != null && (file.getMode() == App.MODE_DEVICE || file.getMode() == App.MODE_BROWSER))
  794. {
  795. url = null;
  796. }
  797. xml = this.getEmbeddedSvg(xml, graph, url, null, embeddedCallback, ignoreSelection, redirect);
  798. }
  799. return xml;
  800. }
  801. };
  802. /**
  803. * Translates this point by the given vector.
  804. *
  805. * @param {number} dx X-coordinate of the translation.
  806. * @param {number} dy Y-coordinate of the translation.
  807. */
  808. EditorUi.prototype.getXmlFileData = function(ignoreSelection, currentPage)
  809. {
  810. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  811. currentPage = (currentPage != null) ? currentPage : false;
  812. var node = this.editor.getGraphXml(ignoreSelection);
  813. if (ignoreSelection && this.fileNode != null && this.currentPage != null)
  814. {
  815. var data = Graph.compressNode(node);
  816. mxUtils.setTextContent(this.currentPage.node, data);
  817. node = this.fileNode.cloneNode(false);
  818. if (currentPage)
  819. {
  820. node.appendChild(this.currentPage.node);
  821. }
  822. else
  823. {
  824. // Restores order of pages
  825. for (var i = 0; i < this.pages.length; i++)
  826. {
  827. if (this.currentPage != this.pages[i] && this.pages[i].needsUpdate)
  828. {
  829. var enc = new mxCodec(mxUtils.createXmlDocument());
  830. var temp = enc.encode(new mxGraphModel(this.pages[i].root));
  831. this.editor.graph.saveViewState(this.pages[i].viewState, temp);
  832. mxUtils.setTextContent(this.pages[i].node, Graph.compressNode(temp));
  833. // Marks the page as up-to-date
  834. delete this.pages[i].needsUpdate;
  835. }
  836. node.appendChild(this.pages[i].node);
  837. }
  838. }
  839. }
  840. return node;
  841. };
  842. /**
  843. * Removes any values, styles and geometries from the given XML node.
  844. */
  845. EditorUi.prototype.anonymizeString = function(text, zeros)
  846. {
  847. var result = [];
  848. for (var i = 0; i < text.length; i++)
  849. {
  850. var c = text.charAt(i);
  851. if (EditorUi.ignoredAnonymizedChars.indexOf(c) >= 0)
  852. {
  853. result.push(c);
  854. }
  855. else if (!isNaN(parseInt(c)))
  856. {
  857. result.push((zeros) ? '0' : Math.round(Math.random() * 9));
  858. }
  859. else if (c.toLowerCase() != c)
  860. {
  861. result.push(String.fromCharCode(65 + Math.round(Math.random() * 25)));
  862. }
  863. else if (c.toUpperCase() != c)
  864. {
  865. result.push(String.fromCharCode(97 + Math.round(Math.random() * 25)));
  866. }
  867. else if (/\s/.test(c))
  868. {
  869. /* any whitespace */
  870. result.push(' ');
  871. }
  872. else
  873. {
  874. result.push('?');
  875. }
  876. }
  877. return result.join('');
  878. };
  879. /**
  880. * Removes any values, styles and geometries from the given XML node.
  881. */
  882. EditorUi.prototype.anonymizePatch = function(patch)
  883. {
  884. if (patch[EditorUi.DIFF_INSERT] != null)
  885. {
  886. for (var i = 0; i < patch[EditorUi.DIFF_INSERT].length; i++)
  887. {
  888. try
  889. {
  890. var data = patch[EditorUi.DIFF_INSERT][i].data;
  891. var doc = mxUtils.parseXml(data);
  892. var clone = doc.documentElement.cloneNode(false);
  893. if (clone.getAttribute('name') != null)
  894. {
  895. clone.setAttribute('name', this.anonymizeString(clone.getAttribute('name')));
  896. }
  897. patch[EditorUi.DIFF_INSERT][i].data = mxUtils.getXml(clone);
  898. }
  899. catch (e)
  900. {
  901. patch[EditorUi.DIFF_INSERT][i].data = e.message;
  902. }
  903. }
  904. }
  905. if (patch[EditorUi.DIFF_UPDATE] != null)
  906. {
  907. for (var pageId in patch[EditorUi.DIFF_UPDATE])
  908. {
  909. var diff = patch[EditorUi.DIFF_UPDATE][pageId];
  910. if (diff.name != null)
  911. {
  912. diff.name = this.anonymizeString(diff.name);
  913. }
  914. if (diff.cells != null)
  915. {
  916. var anonymizeCellDiffs = mxUtils.bind(this, function(key)
  917. {
  918. var cellDiffs = diff.cells[key];
  919. if (cellDiffs != null)
  920. {
  921. for (var cellId in cellDiffs)
  922. {
  923. if (cellDiffs[cellId].value != null)
  924. {
  925. cellDiffs[cellId].value = '[' +
  926. cellDiffs[cellId].value.length + ']';
  927. }
  928. if (cellDiffs[cellId].xmlValue != null)
  929. {
  930. cellDiffs[cellId].xmlValue = '[' +
  931. cellDiffs[cellId].xmlValue.length + ']';
  932. }
  933. if (cellDiffs[cellId].style != null)
  934. {
  935. cellDiffs[cellId].style = '[' +
  936. cellDiffs[cellId].style.length + ']';
  937. }
  938. if (Object.keys(cellDiffs[cellId]).length == 0)
  939. {
  940. delete cellDiffs[cellId];
  941. }
  942. }
  943. if (Object.keys(cellDiffs).length == 0)
  944. {
  945. delete diff.cells[key];
  946. }
  947. }
  948. });
  949. anonymizeCellDiffs(EditorUi.DIFF_INSERT);
  950. anonymizeCellDiffs(EditorUi.DIFF_UPDATE);
  951. if (Object.keys(diff.cells).length == 0)
  952. {
  953. delete diff.cells;
  954. }
  955. }
  956. if (Object.keys(diff).length == 0)
  957. {
  958. delete patch[EditorUi.DIFF_UPDATE][pageId];
  959. }
  960. }
  961. if (Object.keys(patch[EditorUi.DIFF_UPDATE]).length == 0)
  962. {
  963. delete patch[EditorUi.DIFF_UPDATE];
  964. }
  965. }
  966. return patch;
  967. };
  968. /**
  969. * Removes any values, styles and geometries from the given XML node.
  970. */
  971. EditorUi.prototype.anonymizeAttributes = function(node, zeros)
  972. {
  973. if (node.attributes != null)
  974. {
  975. for (var i = 0; i < node.attributes.length; i++)
  976. {
  977. if (node.attributes[i].name != 'as')
  978. {
  979. node.setAttribute(node.attributes[i].name,
  980. this.anonymizeString(node.attributes[i].value, zeros));
  981. }
  982. }
  983. }
  984. if (node.childNodes != null)
  985. {
  986. for (var i = 0; i < node.childNodes.length; i++)
  987. {
  988. this.anonymizeAttributes(node.childNodes[i], zeros);
  989. }
  990. }
  991. };
  992. /**
  993. * Removes any values, styles and geometries from the given XML node.
  994. */
  995. EditorUi.prototype.anonymizeNode = function(node, zeros)
  996. {
  997. var nodes = node.getElementsByTagName('mxCell');
  998. for (var i = 0; i < nodes.length; i++)
  999. {
  1000. if (nodes[i].getAttribute('value') != null)
  1001. {
  1002. nodes[i].setAttribute('value', '[' + nodes[i].getAttribute('value').length + ']');
  1003. }
  1004. if (nodes[i].getAttribute('xmlValue') != null)
  1005. {
  1006. nodes[i].setAttribute('xmlValue', '[' + nodes[i].getAttribute('xmlValue').length + ']');
  1007. }
  1008. if (nodes[i].getAttribute('style') != null)
  1009. {
  1010. nodes[i].setAttribute('style', '[' + nodes[i].getAttribute('style').length + ']');
  1011. }
  1012. if (nodes[i].parentNode != null && nodes[i].parentNode.nodeName != 'root' &&
  1013. nodes[i].parentNode.parentNode != null)
  1014. {
  1015. nodes[i].setAttribute('id', nodes[i].parentNode.getAttribute('id'));
  1016. nodes[i].parentNode.parentNode.replaceChild(nodes[i], nodes[i].parentNode);
  1017. }
  1018. }
  1019. return node;
  1020. };
  1021. /**
  1022. * Translates this point by the given vector.
  1023. *
  1024. * @param {number} dx X-coordinate of the translation.
  1025. * @param {number} dy Y-coordinate of the translation.
  1026. */
  1027. EditorUi.prototype.synchronizeCurrentFile = function(forceReload)
  1028. {
  1029. var currentFile = this.getCurrentFile();
  1030. if (currentFile != null)
  1031. {
  1032. if (currentFile.savingFile)
  1033. {
  1034. this.handleError({message: mxResources.get('busy')});
  1035. }
  1036. else if (!forceReload && currentFile.invalidChecksum)
  1037. {
  1038. currentFile.handleFileError(null, true);
  1039. }
  1040. else if (this.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1041. {
  1042. currentFile.clearAutosave();
  1043. this.editor.setStatus('');
  1044. if (forceReload)
  1045. {
  1046. currentFile.reloadFile(mxUtils.bind(this, function()
  1047. {
  1048. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1049. }), mxUtils.bind(this, function(err)
  1050. {
  1051. currentFile.handleFileError(err, true);
  1052. }));
  1053. }
  1054. else
  1055. {
  1056. currentFile.synchronizeFile(mxUtils.bind(this, function()
  1057. {
  1058. currentFile.handleFileSuccess(DrawioFile.SYNC == 'manual');
  1059. }), mxUtils.bind(this, function(err)
  1060. {
  1061. currentFile.handleFileError(err, true);
  1062. }));
  1063. }
  1064. }
  1065. }
  1066. };
  1067. /**
  1068. * Translates this point by the given vector.
  1069. *
  1070. * @param {number} dx X-coordinate of the translation.
  1071. * @param {number} dy Y-coordinate of the translation.
  1072. */
  1073. EditorUi.prototype.getFileData = function(forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, currentPage, node, compact, file)
  1074. {
  1075. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1076. currentPage = (currentPage != null) ? currentPage : false;
  1077. node = (node != null) ? node : this.getXmlFileData(ignoreSelection, currentPage);
  1078. file = (file != null) ? file : this.getCurrentFile();
  1079. var graph = this.editor.graph;
  1080. // Exports SVG for first page while other page is visible by creating a graph
  1081. // LATER: Add caching for the graph or SVG while not on first page
  1082. if (this.pages != null && this.currentPage != this.pages[0] && (forceSvg ||
  1083. (!forceXml && file != null && /(\.svg)$/i.test(file.getTitle()))))
  1084. {
  1085. graph = this.createTemporaryGraph(graph.getStylesheet());
  1086. var graphGetGlobalVariable = graph.getGlobalVariable;
  1087. var page = this.pages[0];
  1088. graph.getGlobalVariable = function(name)
  1089. {
  1090. if (name == 'page')
  1091. {
  1092. return page.getName();
  1093. }
  1094. else if (name == 'pagenumber')
  1095. {
  1096. return 1;
  1097. }
  1098. return graphGetGlobalVariable.apply(this, arguments);
  1099. };
  1100. document.body.appendChild(graph.container);
  1101. graph.model.setRoot(page.root);
  1102. }
  1103. var result = this.createFileData(node, graph, file, window.location.href,
  1104. forceXml, forceSvg, forceHtml, embeddedCallback, ignoreSelection, compact);
  1105. // Removes temporary graph from DOM
  1106. if (graph != this.editor.graph)
  1107. {
  1108. graph.container.parentNode.removeChild(graph.container);
  1109. }
  1110. return result;
  1111. };
  1112. /**
  1113. *
  1114. */
  1115. EditorUi.prototype.getHtml = function(node, graph, title, editLink, redirect, ignoreSelection)
  1116. {
  1117. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  1118. var bg = null;
  1119. var js = EditorUi.drawHost + '/js/embed-static.min.js';
  1120. // LATER: Merge common code with EmbedDialog
  1121. if (graph != null)
  1122. {
  1123. var bounds = (ignoreSelection) ? graph.getGraphBounds() : graph.getBoundingBox(graph.getSelectionCells());
  1124. var scale = graph.view.scale;
  1125. var x0 = Math.floor(bounds.x / scale - graph.view.translate.x);
  1126. var y0 = Math.floor(bounds.y / scale - graph.view.translate.y);
  1127. bg = graph.background;
  1128. // Embed script only used if no redirect
  1129. if (redirect == null)
  1130. {
  1131. var s = this.getBasenames().join(';');
  1132. if (s.length > 0)
  1133. {
  1134. js = EditorUi.drawHost + '/embed.js?s=' + s;
  1135. }
  1136. }
  1137. // Adds embed attributes
  1138. node.setAttribute('x0', x0);
  1139. node.setAttribute('y0', y0);
  1140. }
  1141. if (node != null)
  1142. {
  1143. node.setAttribute('pan', '1');
  1144. node.setAttribute('zoom', '1');
  1145. node.setAttribute('resize', '0');
  1146. node.setAttribute('fit', '0');
  1147. node.setAttribute('border', '20');
  1148. // Hidden attributes
  1149. node.setAttribute('links', '1');
  1150. if (editLink != null)
  1151. {
  1152. node.setAttribute('edit', editLink);
  1153. }
  1154. }
  1155. // Makes XHTML compatible
  1156. if (redirect != null)
  1157. {
  1158. redirect = redirect.replace(/&/g, '&amp;');
  1159. }
  1160. // Removes control chars in input for correct roundtrip check
  1161. var text = (node != null) ? Graph.zapGremlins(mxUtils.getXml(node)) : '';
  1162. // Double compression for mxfile not fixed since it may cause imcompatibilites with
  1163. // embed clients that rely on this format. HTML files and export use getHtml2.
  1164. var data = Graph.compress(text);
  1165. // Fallback to URI encoded XML for invalid compression
  1166. if (Graph.decompress(data) != text)
  1167. {
  1168. data = encodeURIComponent(text);
  1169. }
  1170. var style = 'position:relative;overflow:auto;width:100%;';
  1171. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1172. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1173. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1174. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1175. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1176. '</head>\n<body' +
  1177. (((redirect == null && bg != null && bg != mxConstants.NONE) ? ' style="background-color:' + bg + ';">' : '>')) +
  1178. '\n<div class="mxgraph" style="' + style + '">\n' +
  1179. '<div style="width:1px;height:1px;overflow:hidden;">' + data + '</div>\n</div>\n' +
  1180. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1181. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1182. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1183. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1184. '\n</body>\n</html>\n';
  1185. };
  1186. /**
  1187. * Same as above but using the new embed code.
  1188. */
  1189. EditorUi.prototype.getHtml2 = function(xml, graph, title, editLink, redirect)
  1190. {
  1191. var bg = null;
  1192. var js = EditorUi.drawHost + '/js/viewer.min.js';
  1193. var s = '';
  1194. // Makes XHTML compatible
  1195. if (redirect != null)
  1196. {
  1197. redirect = redirect.replace(/&/g, '&amp;');
  1198. }
  1199. var data = {highlight: '#0000ff', nav: this.editor.graph.foldingEnabled, resize: true,
  1200. xml: Graph.zapGremlins(xml), toolbar: 'pages zoom layers lightbox'};
  1201. if (this.pages != null && this.currentPage != null)
  1202. {
  1203. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  1204. }
  1205. var style = 'max-width:100%;border:1px solid transparent;';
  1206. return ((redirect == null) ? '<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=5,IE=9" ><![endif]-->\n' : '') +
  1207. '<!DOCTYPE html>\n<html' + ((redirect != null) ? ' xmlns="http://www.w3.org/1999/xhtml">' : '>') +
  1208. '\n<head>\n' + ((redirect == null) ? ((title != null) ? '<title>' + mxUtils.htmlEntities(title) +
  1209. '</title>\n' : '') : '<title>Draw.io Diagram</title>\n') +
  1210. ((redirect != null) ? '<meta http-equiv="refresh" content="0;URL=\'' + redirect + '\'"/>\n' : '') +
  1211. '<meta charset="utf-8"/>\n</head>\n<body>' +
  1212. '\n<div class="mxgraph" style="' + style + '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>\n' +
  1213. ((redirect == null) ? '<script type="text/javascript" src="' + js + '"></script>' :
  1214. '<a style="position:absolute;top:50%;left:50%;margin-top:-128px;margin-left:-64px;" ' +
  1215. 'href="' + redirect + '" target="_blank"><img border="0" ' +
  1216. 'src="' + EditorUi.drawHost + '/images/drawlogo128.png"/></a>') +
  1217. '\n</body>\n</html>\n';
  1218. };
  1219. /**
  1220. *
  1221. */
  1222. EditorUi.prototype.setFileData = function(data)
  1223. {
  1224. data = this.validateFileData(data);
  1225. this.currentPage = null;
  1226. this.fileNode = null;
  1227. this.pages = null;
  1228. var node = (data != null && data.length > 0) ? mxUtils.parseXml(data).documentElement : null;
  1229. // Checks for parser errors
  1230. var errors = (node != null) ? node.getElementsByTagName('parsererror') : null;
  1231. if (errors != null && errors.length > 0)
  1232. {
  1233. var cause = mxResources.get('invalidOrMissingFile');
  1234. var divs = errors[0].getElementsByTagName('div');
  1235. if (divs.length > 0)
  1236. {
  1237. cause = mxUtils.getTextContent(divs[0]);
  1238. }
  1239. throw new Error(cause);
  1240. }
  1241. else
  1242. {
  1243. // Some nodes must be extracted here to find the mxfile node
  1244. // LATER: Remove duplicate call to extractGraphModel in overridden setGraphXml
  1245. var tmp = (node != null) ? this.editor.extractGraphModel(node, true) : null;
  1246. if (tmp != null)
  1247. {
  1248. node = tmp;
  1249. }
  1250. if (node != null && node.nodeName == 'mxfile')
  1251. {
  1252. var nodes = node.getElementsByTagName('diagram');
  1253. if (urlParams['pages'] != '0' || nodes.length > 1 ||
  1254. (nodes.length == 1 && nodes[0].hasAttribute('name')))
  1255. {
  1256. var selectedPage = null;
  1257. this.fileNode = node;
  1258. this.pages = [];
  1259. // Wraps page nodes
  1260. for (var i = 0; i < nodes.length; i++)
  1261. {
  1262. // Adds page ID based on page order to match
  1263. // remote IDs given if IDs are missing here
  1264. if (nodes[i].getAttribute('id') == null)
  1265. {
  1266. nodes[i].setAttribute('id', i);
  1267. }
  1268. var page = new DiagramPage(nodes[i]);
  1269. // Checks for invalid page names
  1270. if (page.getName() == null)
  1271. {
  1272. page.setName(mxResources.get('pageWithNumber', [i + 1]));
  1273. }
  1274. this.pages.push(page);
  1275. if (urlParams['page-id'] != null && page.getId() == urlParams['page-id'])
  1276. {
  1277. selectedPage = page;
  1278. }
  1279. }
  1280. this.currentPage = (selectedPage != null) ? selectedPage :
  1281. this.pages[Math.max(0, Math.min(this.pages.length - 1, urlParams['page'] || 0))];
  1282. node = this.currentPage.node;
  1283. }
  1284. }
  1285. // Creates tabbed file structure if enforced by URL
  1286. if (urlParams['pages'] != '0' && this.fileNode == null && node != null)
  1287. {
  1288. this.fileNode = node.ownerDocument.createElement('mxfile');
  1289. this.currentPage = new DiagramPage(node.ownerDocument.createElement('diagram'));
  1290. this.currentPage.setName(mxResources.get('pageWithNumber', [1]));
  1291. this.pages = [this.currentPage];
  1292. }
  1293. // Avoids scroll offset when switching page
  1294. this.editor.setGraphXml(node);
  1295. // Avoids duplicate parsing of the XML stored in the node
  1296. if (this.currentPage != null)
  1297. {
  1298. this.currentPage.root = this.editor.graph.model.root;
  1299. }
  1300. }
  1301. };
  1302. /**
  1303. * Translates this point by the given vector.
  1304. *
  1305. * @param {number} dx X-coordinate of the translation.
  1306. * @param {number} dy Y-coordinate of the translation.
  1307. */
  1308. EditorUi.prototype.getBaseFilename = function(ignorePageName)
  1309. {
  1310. var file = this.getCurrentFile();
  1311. var basename = (file != null && file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
  1312. if (/(\.xml)$/i.test(basename) || /(\.html)$/i.test(basename) ||
  1313. /(\.svg)$/i.test(basename) || /(\.png)$/i.test(basename) ||
  1314. /(\.drawio)$/i.test(basename))
  1315. {
  1316. basename = basename.substring(0, basename.lastIndexOf('.'));
  1317. }
  1318. if (!ignorePageName && this.pages != null && this.pages.length > 1 &&
  1319. this.currentPage != null && this.currentPage.node.getAttribute('name') != null &&
  1320. this.currentPage.getName().length > 0)
  1321. {
  1322. basename = basename + '-' + this.currentPage.getName();
  1323. }
  1324. return basename;
  1325. };
  1326. /**
  1327. * Translates this point by the given vector.
  1328. *
  1329. * @param {number} dx X-coordinate of the translation.
  1330. * @param {number} dy Y-coordinate of the translation.
  1331. */
  1332. EditorUi.prototype.downloadFile = function(format, nonCompressed, addShadow, ignoreSelection, currentPage, pageVisible, transparent, scale, border)
  1333. {
  1334. try
  1335. {
  1336. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : this.editor.graph.isSelectionEmpty();
  1337. var basename = this.getBaseFilename(!currentPage);
  1338. var filename = basename + '.' + format;
  1339. if (format == 'xml')
  1340. {
  1341. var data = '<?xml version="1.0" encoding="UTF-8"?>\n' +
  1342. ((nonCompressed) ? mxUtils.getXml(this.editor.getGraphXml(ignoreSelection)) :
  1343. this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  1344. this.saveData(filename, format, data, 'text/xml');
  1345. }
  1346. else if (format == 'html')
  1347. {
  1348. var data = this.getHtml2(this.getFileData(true), this.editor.graph, basename);
  1349. this.saveData(filename, format, data, 'text/html');
  1350. }
  1351. else if ((format == 'svg' || format == 'xmlsvg') && this.spinner.spin(document.body, mxResources.get('export')))
  1352. {
  1353. var svg = null;
  1354. var saveSvg = mxUtils.bind(this, function(data)
  1355. {
  1356. if (data.length <= MAX_REQUEST_SIZE)
  1357. {
  1358. this.saveData(filename, 'svg', data, 'image/svg+xml');
  1359. }
  1360. else
  1361. {
  1362. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  1363. {
  1364. mxUtils.popup(svg);
  1365. }));
  1366. }
  1367. });
  1368. if (format == 'svg')
  1369. {
  1370. var bg = this.editor.graph.background;
  1371. if (transparent || bg == mxConstants.NONE)
  1372. {
  1373. bg = null;
  1374. }
  1375. // Sets or disables alternate text for foreignObjects. Disabling is needed
  1376. // because PhantomJS seems to ignore switch statements and paint all text.
  1377. var svgRoot = this.editor.graph.getSvg(bg, null, null, null, null, ignoreSelection);
  1378. if (addShadow)
  1379. {
  1380. this.editor.graph.addSvgShadow(svgRoot);
  1381. }
  1382. // Embeds the images in the SVG output (async)
  1383. this.convertImages(svgRoot, mxUtils.bind(this, mxUtils.bind(this, function(svgRoot2)
  1384. {
  1385. this.spinner.stop();
  1386. saveSvg('<?xml version="1.0" encoding="UTF-8"?>\n' +
  1387. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  1388. mxUtils.getXml(svgRoot2));
  1389. })));
  1390. }
  1391. else
  1392. {
  1393. filename = basename + '.svg';
  1394. svg = this.getFileData(false, true, null, mxUtils.bind(this, function(svg)
  1395. {
  1396. this.spinner.stop();
  1397. saveSvg(svg);
  1398. }), ignoreSelection);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. if (format == 'xmlpng')
  1404. {
  1405. filename = basename + '.png';
  1406. }
  1407. else if (format == 'jpeg')
  1408. {
  1409. filename = basename + '.jpg';
  1410. }
  1411. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  1412. {
  1413. try
  1414. {
  1415. var prev = this.editor.graph.pageVisible;
  1416. if (pageVisible != null)
  1417. {
  1418. this.editor.graph.pageVisible = pageVisible;
  1419. }
  1420. var req = this.createDownloadRequest(newTitle, format, ignoreSelection, base64, transparent, currentPage, scale, border);
  1421. this.editor.graph.pageVisible = prev;
  1422. return req;
  1423. }
  1424. catch (e)
  1425. {
  1426. this.handleError(e);
  1427. }
  1428. }));
  1429. }
  1430. }
  1431. catch (e)
  1432. {
  1433. this.handleError(e);
  1434. }
  1435. };
  1436. /**
  1437. * Translates this point by the given vector.
  1438. *
  1439. * @param {number} dx X-coordinate of the translation.
  1440. * @param {number} dy Y-coordinate of the translation.
  1441. */
  1442. EditorUi.prototype.createDownloadRequest = function(filename, format, ignoreSelection, base64, transparent, currentPage, scale, border)
  1443. {
  1444. var bounds = this.editor.graph.getGraphBounds();
  1445. // Exports only current page for images that does not contain file data, but for
  1446. // the other formats with XML included or pdf with all pages, we need to send the complete data and use
  1447. // the from/to URL parameters to specify the page to be exported.
  1448. var data = this.getFileData(true, null, null, null, ignoreSelection, currentPage == false? false : format != 'xmlpng');
  1449. var range = '';
  1450. var allPages = '';
  1451. if (bounds.width * bounds.height > MAX_AREA || data.length > MAX_REQUEST_SIZE)
  1452. {
  1453. throw {message: mxResources.get('drawingTooLarge')};
  1454. }
  1455. var embed = '0';
  1456. if (format == 'pdf' && currentPage == false)
  1457. {
  1458. allPages = '&allPages=1';
  1459. }
  1460. if (format == 'xmlpng')
  1461. {
  1462. embed = '1';
  1463. format = 'png';
  1464. // Finds the current page number
  1465. if (this.pages != null && this.currentPage != null)
  1466. {
  1467. for (var i = 0; i < this.pages.length; i++)
  1468. {
  1469. if (this.pages[i] == this.currentPage)
  1470. {
  1471. range = '&from=' + i;
  1472. break;
  1473. }
  1474. }
  1475. }
  1476. }
  1477. var bg = this.editor.graph.background;
  1478. if (format == 'png' && transparent)
  1479. {
  1480. bg = mxConstants.NONE;
  1481. }
  1482. else if (!transparent && (bg == null || bg == mxConstants.NONE))
  1483. {
  1484. bg = '#ffffff';
  1485. }
  1486. return new mxXmlRequest(EXPORT_URL, 'format=' + format + range + allPages +
  1487. '&bg=' + ((bg != null) ? bg : mxConstants.NONE) +
  1488. '&base64=' + base64 + '&embedXml=' + embed + '&xml=' +
  1489. encodeURIComponent(data) + ((filename != null) ?
  1490. '&filename=' + encodeURIComponent(filename) : '') +
  1491. (scale != null? '&scale=' + scale : '') +
  1492. (border != null? '&border=' + border : ''));
  1493. };
  1494. /**
  1495. * Translates this point by the given vector.
  1496. *
  1497. * @param {number} dx X-coordinate of the translation.
  1498. * @param {number} dy Y-coordinate of the translation.
  1499. */
  1500. EditorUi.prototype.setMode = function(mode, remember)
  1501. {
  1502. this.mode = mode;
  1503. };
  1504. /**
  1505. * Loads the given file descriptor. The descriptor may define the following properties:
  1506. *
  1507. * - url: The url to load the data from (proxy is used if CORS is not enabled)
  1508. * - data: The data to be inserted. If both, data and url are defined, then the data
  1509. * is preprendended to the data returned from the given URL.
  1510. * - format: Currently, only 'csv' is supported as an optional value. Default is XML.
  1511. * - update: Optional URL to fetch updates from (POST request with the page XML).
  1512. * - interval: Optional interval for fetching updates. Default is 60000 (60 seconds).
  1513. */
  1514. EditorUi.prototype.loadDescriptor = function(desc, success, error)
  1515. {
  1516. var hash = window.location.hash;
  1517. var loadData = mxUtils.bind(this, function(data)
  1518. {
  1519. var realData = (desc.data != null) ? desc.data : '';
  1520. if (data != null && data.length > 0)
  1521. {
  1522. if (realData.length > 0)
  1523. {
  1524. realData += '\n';
  1525. }
  1526. realData += data;
  1527. }
  1528. var xml = (desc.format != 'csv' && realData.length > 0) ? realData : this.emptyDiagramXml;
  1529. var tempFile = new LocalFile(this, xml, (urlParams['title'] != null) ?
  1530. decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
  1531. tempFile.getHash = function()
  1532. {
  1533. return hash;
  1534. };
  1535. this.fileLoaded(tempFile);
  1536. if (desc.format == 'csv')
  1537. {
  1538. this.importCsv(realData, mxUtils.bind(this, function(cells)
  1539. {
  1540. this.editor.undoManager.clear();
  1541. this.editor.setModified(false);
  1542. this.editor.setStatus('');
  1543. }));
  1544. }
  1545. // Installs updates
  1546. if (desc.update != null)
  1547. {
  1548. var interval = (desc.interval != null) ? parseInt(desc.interval) : 60000;
  1549. var currentThread = null;
  1550. var doUpdate = mxUtils.bind(this, function()
  1551. {
  1552. var page = this.currentPage;
  1553. mxUtils.post(desc.update, 'xml=' + encodeURIComponent(
  1554. mxUtils.getXml(this.editor.getGraphXml())),
  1555. mxUtils.bind(this, function(req)
  1556. {
  1557. if (page === this.currentPage)
  1558. {
  1559. if (req.getStatus() >= 200 && req.getStatus() <= 300)
  1560. {
  1561. var doc = this.updateDiagram(req.getText());
  1562. schedule();
  1563. }
  1564. else
  1565. {
  1566. this.handleError({message: mxResources.get('error') + ' ' + req.getStatus()});
  1567. }
  1568. }
  1569. }), mxUtils.bind(this, function(err)
  1570. {
  1571. this.handleError(err);
  1572. }));
  1573. });
  1574. var schedule = mxUtils.bind(this, function()
  1575. {
  1576. window.clearTimeout(currentThread);
  1577. currentThread = window.setTimeout(doUpdate, interval);
  1578. });
  1579. this.editor.addListener('pageSelected', mxUtils.bind(this, function()
  1580. {
  1581. schedule();
  1582. doUpdate();
  1583. }));
  1584. schedule();
  1585. doUpdate();
  1586. }
  1587. if (success != null)
  1588. {
  1589. success();
  1590. }
  1591. });
  1592. if (desc.url != null && desc.url.length > 0)
  1593. {
  1594. var realUrl = desc.url;
  1595. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  1596. {
  1597. realUrl = PROXY_URL + '?url=' + encodeURIComponent(realUrl);
  1598. }
  1599. // LATER: Remove cache-control header
  1600. this.loadUrl(realUrl, mxUtils.bind(this, function(data)
  1601. {
  1602. loadData(data);
  1603. }), mxUtils.bind(this, function(err)
  1604. {
  1605. if (error != null)
  1606. {
  1607. error(err)
  1608. }
  1609. }));
  1610. }
  1611. else
  1612. {
  1613. loadData('');
  1614. }
  1615. };
  1616. /**
  1617. * Translates this point by the given vector.
  1618. *
  1619. * @param {number} dx X-coordinate of the translation.
  1620. * @param {number} dy Y-coordinate of the translation.
  1621. */
  1622. EditorUi.prototype.updateDiagram = function(xml)
  1623. {
  1624. var doc = null;
  1625. var ui = this;
  1626. function createOverlay(desc)
  1627. {
  1628. var overlay = new mxCellOverlay(desc.image || graph.warningImage,
  1629. desc.tooltip, desc.align, desc.valign, desc.offset);
  1630. // Installs a handler for clicks on the overlay
  1631. overlay.addListener(mxEvent.CLICK, function(sender, evt)
  1632. {
  1633. ui.alert(desc.tooltip);
  1634. });
  1635. return overlay;
  1636. };
  1637. if (xml != null && xml.length > 0)
  1638. {
  1639. doc = mxUtils.parseXml(xml);
  1640. var node = (doc != null) ? doc.documentElement : null;
  1641. if (node != null && node.nodeName == 'updates')
  1642. {
  1643. var graph = this.editor.graph;
  1644. var model = graph.getModel();
  1645. model.beginUpdate();
  1646. var fit = null;
  1647. try
  1648. {
  1649. node = node.firstChild;
  1650. while (node != null)
  1651. {
  1652. if (node.nodeName == 'update')
  1653. {
  1654. // Resolves the cell ID
  1655. var cell = model.getCell(node.getAttribute('id'));
  1656. if (cell != null)
  1657. {
  1658. // Changes the value
  1659. try
  1660. {
  1661. var value = node.getAttribute('value');
  1662. if (value != null)
  1663. {
  1664. var valueNode = mxUtils.parseXml(value).documentElement;
  1665. if (valueNode != null)
  1666. {
  1667. if (valueNode.getAttribute('replace-value') == '1')
  1668. {
  1669. model.setValue(cell, valueNode);
  1670. }
  1671. else
  1672. {
  1673. var attrs = valueNode.attributes;
  1674. for (var j = 0; j < attrs.length; j++)
  1675. {
  1676. graph.setAttributeForCell(cell, attrs[j].nodeName,
  1677. (attrs[j].nodeValue.length > 0) ? attrs[j].nodeValue : null);
  1678. }
  1679. }
  1680. }
  1681. }
  1682. }
  1683. catch (e)
  1684. {
  1685. if (window.console != null)
  1686. {
  1687. console.log('Error in value for ' + cell.id + ': ' + e);
  1688. }
  1689. }
  1690. // Changes the style
  1691. try
  1692. {
  1693. var style = node.getAttribute('style');
  1694. if (style != null)
  1695. {
  1696. graph.model.setStyle(cell, style);
  1697. }
  1698. }
  1699. catch (e)
  1700. {
  1701. if (window.console != null)
  1702. {
  1703. console.log('Error in style for ' + cell.id + ': ' + e);
  1704. }
  1705. }
  1706. // Adds or removes an overlay icon
  1707. try
  1708. {
  1709. var icon = node.getAttribute('icon');
  1710. if (icon != null)
  1711. {
  1712. var desc = (icon.length > 0) ? JSON.parse(icon) : null;
  1713. if (desc == null || !desc.append)
  1714. {
  1715. graph.removeCellOverlays(cell);
  1716. }
  1717. if (desc != null)
  1718. {
  1719. graph.addCellOverlay(cell, createOverlay(desc));
  1720. }
  1721. }
  1722. }
  1723. catch (e)
  1724. {
  1725. if (window.console != null)
  1726. {
  1727. console.log('Error in icon for ' + cell.id + ': ' + e);
  1728. }
  1729. }
  1730. // Replaces the geometry
  1731. try
  1732. {
  1733. var geo = node.getAttribute('geometry');
  1734. if (geo != null)
  1735. {
  1736. geo = JSON.parse(geo);
  1737. var curr = graph.getCellGeometry(cell);
  1738. if (curr != null)
  1739. {
  1740. curr = curr.clone();
  1741. // Partially overwrites geometry
  1742. for (key in geo)
  1743. {
  1744. var val = parseFloat(geo[key]);
  1745. if (key == 'dx')
  1746. {
  1747. curr.x += val;
  1748. }
  1749. else if (key == 'dy')
  1750. {
  1751. curr.y += val;
  1752. }
  1753. else if (key == 'dw')
  1754. {
  1755. curr.width += val;
  1756. }
  1757. else if (key == 'dh')
  1758. {
  1759. curr.height += val;
  1760. }
  1761. else
  1762. {
  1763. curr[key] = parseFloat(geo[key]);
  1764. }
  1765. }
  1766. graph.model.setGeometry(cell, curr);
  1767. }
  1768. }
  1769. }
  1770. catch (e)
  1771. {
  1772. if (window.console != null)
  1773. {
  1774. console.log('Error in icon for ' + cell.id + ': ' + e);
  1775. }
  1776. }
  1777. } // if cell != null
  1778. } // if node.nodeName == 'update
  1779. else if (node.nodeName == 'model')
  1780. {
  1781. // Finds first child element
  1782. var dataNode = node.firstChild;
  1783. while (dataNode != null && dataNode.nodeType != mxConstants.NODETYPE_ELEMENT)
  1784. {
  1785. dataNode = dataNode.nextSibling;
  1786. }
  1787. if (dataNode != null)
  1788. {
  1789. var dec = new mxCodec(node.firstChild);
  1790. dec.decode(dataNode, model);
  1791. }
  1792. }
  1793. else if (node.nodeName == 'view')
  1794. {
  1795. if (node.hasAttribute('scale'))
  1796. {
  1797. graph.view.scale = parseFloat(node.getAttribute('scale'));
  1798. }
  1799. if (node.hasAttribute('dx') || node.hasAttribute('dy'))
  1800. {
  1801. graph.view.translate = new mxPoint(parseFloat(node.getAttribute('dx') || 0),
  1802. parseFloat(node.getAttribute('dy') || 0));
  1803. }
  1804. }
  1805. else if (node.nodeName == 'fit')
  1806. {
  1807. if (node.hasAttribute('max-scale'))
  1808. {
  1809. fit = parseFloat(node.getAttribute('max-scale'));
  1810. }
  1811. else
  1812. {
  1813. fit = 1;
  1814. }
  1815. }
  1816. node = node.nextSibling;
  1817. } // end of while
  1818. }
  1819. finally
  1820. {
  1821. model.endUpdate();
  1822. }
  1823. if (fit != null && this.chromelessResize)
  1824. {
  1825. this.chromelessResize(true, fit);
  1826. }
  1827. }
  1828. }
  1829. return doc;
  1830. };
  1831. /**
  1832. * Constructs a filename for a copy of the given file.
  1833. */
  1834. EditorUi.prototype.getCopyFilename = function(file, timestamp)
  1835. {
  1836. var title = (file != null && file.getTitle() != null) ?
  1837. file.getTitle() : this.defaultFilename;
  1838. // Handles extension
  1839. var extension = '';
  1840. var dot = title.lastIndexOf('.');
  1841. if (dot >= 0)
  1842. {
  1843. extension = title.substring(dot);
  1844. title = title.substring(0, dot);
  1845. }
  1846. if (timestamp)
  1847. {
  1848. function getFormattedTime()
  1849. {
  1850. var today = new Date();
  1851. var y = today.getFullYear();
  1852. // JavaScript months are 0-based.
  1853. var m = today.getMonth() + 1;
  1854. var d = today.getDate();
  1855. var h = today.getHours();
  1856. var mi = today.getMinutes();
  1857. var s = today.getSeconds();
  1858. return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
  1859. }
  1860. var ts = new Date();
  1861. title += ' ' + getFormattedTime();
  1862. }
  1863. title = mxResources.get('copyOf', [title]) + extension;
  1864. return title;
  1865. };
  1866. /**
  1867. * Translates this point by the given vector.
  1868. *
  1869. * @param {number} dx X-coordinate of the translation.
  1870. * @param {number} dy Y-coordinate of the translation.
  1871. */
  1872. EditorUi.prototype.fileLoaded = function(file, noDialogs)
  1873. {
  1874. var oldFile = this.getCurrentFile();
  1875. this.fileLoadedError = null;
  1876. this.setCurrentFile(null);
  1877. var result = false;
  1878. this.hideDialog();
  1879. if (oldFile != null)
  1880. {
  1881. oldFile.removeListener(this.descriptorChangedListener);
  1882. oldFile.close();
  1883. }
  1884. this.editor.graph.model.clear();
  1885. this.editor.undoManager.clear();
  1886. var noFile = mxUtils.bind(this, function()
  1887. {
  1888. this.setGraphEnabled(false);
  1889. this.setCurrentFile(null);
  1890. // Keeps initial title if no file existed before
  1891. if (oldFile != null)
  1892. {
  1893. this.updateDocumentTitle();
  1894. }
  1895. // File might have been loaded halfway
  1896. this.editor.graph.model.clear();
  1897. this.editor.undoManager.clear();
  1898. this.setBackgroundImage(null);
  1899. // Avoids empty hash with no value
  1900. if (!noDialogs && window.location.hash != null && window.location.hash.length > 0)
  1901. {
  1902. window.location.hash = '';
  1903. }
  1904. if (this.fname != null)
  1905. {
  1906. this.fnameWrapper.style.display = 'none';
  1907. this.fname.innerHTML = '';
  1908. this.fname.setAttribute('title', mxResources.get('rename'));
  1909. }
  1910. this.editor.setStatus('');
  1911. this.updateUi();
  1912. if (!noDialogs)
  1913. {
  1914. this.showSplash();
  1915. }
  1916. });
  1917. if (file != null)
  1918. {
  1919. try
  1920. {
  1921. // Workaround for delayed scroll repaint with min UI in Safari
  1922. if (mxClient.IS_SF && uiTheme == 'min')
  1923. {
  1924. this.diagramContainer.style.visibility = '';
  1925. }
  1926. // Order is significant, current file needed for correct
  1927. // file format for initial save after starting realtime
  1928. this.openingFile = true;
  1929. this.setCurrentFile(file);
  1930. file.addListener('descriptorChanged', this.descriptorChangedListener);
  1931. file.addListener('contentChanged', this.descriptorChangedListener);
  1932. file.open();
  1933. delete this.openingFile;
  1934. // DescriptorChanged updates the enabled state of the graph
  1935. this.setGraphEnabled(true);
  1936. this.setMode(file.getMode());
  1937. this.editor.graph.model.prefix = Editor.guid() + '-';
  1938. this.editor.undoManager.clear();
  1939. this.descriptorChanged();
  1940. this.updateUi();
  1941. // Realtime files have a valid status message
  1942. if (!file.isEditable())
  1943. {
  1944. this.editor.setStatus('<span class="geStatusAlert" style="margin-left:8px;">' +
  1945. mxUtils.htmlEntities(mxResources.get('readOnly')) + '</span>');
  1946. }
  1947. // Handles modified state after error of loading new file
  1948. else if (file.isModified())
  1949. {
  1950. file.addUnsavedStatus();
  1951. // Restores unsaved data
  1952. if (file.backupPatch != null)
  1953. {
  1954. file.patch([file.backupPatch]);
  1955. }
  1956. }
  1957. else
  1958. {
  1959. this.editor.setStatus('');
  1960. }
  1961. if (!this.editor.isChromelessView() || this.editor.editable)
  1962. {
  1963. this.editor.graph.selectUnlockedLayer();
  1964. this.showLayersDialog();
  1965. this.restoreLibraries();
  1966. // Workaround for no initial focus in FF
  1967. if (window.self !== window.top)
  1968. {
  1969. window.focus();
  1970. }
  1971. }
  1972. else if (this.editor.graph.isLightboxView())
  1973. {
  1974. this.lightboxFit();
  1975. }
  1976. if (this.chromelessResize)
  1977. {
  1978. this.chromelessResize();
  1979. }
  1980. this.editor.fireEvent(new mxEventObject('fileLoaded'));
  1981. result = true;
  1982. if (!this.isOffline() && file.getMode() != null)
  1983. {
  1984. EditorUi.logEvent({category: file.getMode().toUpperCase() + '-OPEN-FILE-' + file.getHash(),
  1985. action: 'size_' + file.getSize(),
  1986. label: 'autosave_' + ((this.editor.autosave) ? 'on' : 'off')});
  1987. }
  1988. if (this.editor.editable && this.mode == file.getMode() &&
  1989. file.getMode() != App.MODE_DEVICE && file.getMode() != null)
  1990. {
  1991. try
  1992. {
  1993. this.addRecent({id: file.getHash(), title: file.getTitle(), mode: file.getMode()});
  1994. }
  1995. catch (e)
  1996. {
  1997. // ignore
  1998. }
  1999. }
  2000. try
  2001. {
  2002. mxSettings.setOpenCounter(mxSettings.getOpenCounter() + 1);
  2003. mxSettings.save();
  2004. }
  2005. catch (e)
  2006. {
  2007. // ignore
  2008. }
  2009. }
  2010. catch (e)
  2011. {
  2012. this.fileLoadedError = e;
  2013. // Makes sure the file does not save the invalid UI model and overwrites anything important
  2014. if (window.console != null)
  2015. {
  2016. console.log('error in fileLoaded:', file, e);
  2017. }
  2018. if (EditorUi.enableLogging && !this.isOffline())
  2019. {
  2020. try
  2021. {
  2022. var img = new Image();
  2023. var logDomain = window.DRAWIO_LOG_URL != null ? window.DRAWIO_LOG_URL : '';
  2024. img.src = logDomain + '/log?v=' + encodeURIComponent(EditorUi.VERSION) +
  2025. '&msg=errorInFileLoaded:url:' + encodeURIComponent(window.location.href) +
  2026. ((e != null && e.message != null) ? ':err:' + encodeURIComponent(e.message) : '') +
  2027. ((e != null && e.stack != null) ? '&stack=' + encodeURIComponent(e.stack) : '');
  2028. }
  2029. catch (e)
  2030. {
  2031. // ignore
  2032. }
  2033. }
  2034. // Asynchronous handling of errors
  2035. var fn = mxUtils.bind(this, function()
  2036. {
  2037. // Removes URL parameter and reloads the page
  2038. if (urlParams['url'] != null && this.spinner.spin(document.body, mxResources.get('reconnecting')))
  2039. {
  2040. window.location.search = this.getSearch(['url']);
  2041. }
  2042. else if (oldFile != null)
  2043. {
  2044. this.fileLoaded(oldFile);
  2045. }
  2046. else
  2047. {
  2048. noFile();
  2049. }
  2050. });
  2051. if (!noDialogs)
  2052. {
  2053. this.handleError(e, mxResources.get('errorLoadingFile'), fn, true);
  2054. }
  2055. else
  2056. {
  2057. fn();
  2058. }
  2059. }
  2060. }
  2061. else
  2062. {
  2063. noFile();
  2064. }
  2065. return result;
  2066. };
  2067. /**
  2068. * Creates a hash value for the current file.
  2069. */
  2070. EditorUi.prototype.getHashValueForPages = function(pages, details)
  2071. {
  2072. // TODO: Avoid encoding to XML to make it faster
  2073. var hash = 0;
  2074. var model = new mxGraphModel();
  2075. var codec = new mxCodec();
  2076. if (details != null)
  2077. {
  2078. details.byteCount = 0;
  2079. details.attrCount = 0;
  2080. details.eltCount = 0;
  2081. details.nodeCount = 0;
  2082. }
  2083. for (var i = 0; i < pages.length; i++)
  2084. {
  2085. this.updatePageRoot(pages[i]);
  2086. var diagram = pages[i].node.cloneNode(false);
  2087. // FIXME: Check why names can be null in newer files
  2088. // ignore in hash and do not diff null names for now
  2089. diagram.removeAttribute('name');
  2090. // Model is only a holder for the root
  2091. model.root = pages[i].root;
  2092. var xmlNode = codec.encode(model);
  2093. this.editor.graph.saveViewState(pages[i].viewState, xmlNode, true);
  2094. // Local defaults may be different in files so ignore
  2095. xmlNode.removeAttribute('pageWidth');
  2096. xmlNode.removeAttribute('pageHeight');
  2097. diagram.appendChild(xmlNode);
  2098. if (details != null)
  2099. {
  2100. details.eltCount += diagram.getElementsByTagName('*').length;
  2101. details.nodeCount += diagram.getElementsByTagName('mxCell').length;
  2102. }
  2103. hash = ((hash << 5) - hash + this.hashValue(diagram, function(obj, key, value, isXml)
  2104. {
  2105. // Ignores JS machine rounding errors in known numeric attributes
  2106. // eg. 412.33333333333326 (Webkit/FF) == 412.33333333333325 (Edge/IE11)
  2107. if (isXml && (obj.nodeName == 'mxGeometry' || obj.nodeName == 'mxPoint') &&
  2108. (key == 'x' || key == 'y' || key == 'width' || key == 'height'))
  2109. {
  2110. return Math.round(value);
  2111. }
  2112. // Workaround for previous in patch written to mxCell in 10.0.23
  2113. else if (isXml && obj.nodeName == 'mxCell' && key == 'previous')
  2114. {
  2115. return null;
  2116. }
  2117. else
  2118. {
  2119. return value;
  2120. }
  2121. }, details)) << 0;
  2122. }
  2123. return hash;
  2124. };
  2125. /**
  2126. * Creates a hash value for the given object. Replacer returns the value of the
  2127. * property or attribute for the given object or XML node.
  2128. */
  2129. EditorUi.prototype.hashValue = function(obj, replacer, details)
  2130. {
  2131. var hash = 0;
  2132. // Checks for XML nodes
  2133. if (obj != null && typeof obj === 'object' && typeof obj.nodeType === 'number' &&
  2134. typeof obj.nodeName === 'string' && typeof obj.getAttribute === 'function')
  2135. {
  2136. if (obj.nodeName != null)
  2137. {
  2138. hash = hash ^ this.hashValue(obj.nodeName, replacer, details);
  2139. }
  2140. if (obj.attributes != null)
  2141. {
  2142. if (details != null)
  2143. {
  2144. details.attrCount += obj.attributes.length;
  2145. }
  2146. for (var i = 0; i < obj.attributes.length; i++)
  2147. {
  2148. var key = obj.attributes[i].name;
  2149. var value = (replacer != null) ? replacer(obj, key, obj.attributes[i].value, true) : obj.attributes[i].value;
  2150. if (value != null)
  2151. {
  2152. hash = hash ^ (this.hashValue(key, replacer, details) +
  2153. this.hashValue(value, replacer, details));
  2154. }
  2155. }
  2156. }
  2157. if (obj.childNodes != null)
  2158. {
  2159. for (var i = 0; i < obj.childNodes.length; i++)
  2160. {
  2161. hash = ((hash << 5) - hash + this.hashValue(
  2162. obj.childNodes[i], replacer, details)) << 0;
  2163. }
  2164. }
  2165. }
  2166. else if (obj != null && typeof obj !== 'function')
  2167. {
  2168. var str = String(obj);
  2169. var temp = 0;
  2170. if (details != null)
  2171. {
  2172. details.byteCount += str.length;
  2173. }
  2174. for (var i = 0; i < str.length; i++)
  2175. {
  2176. temp = ((temp << 5) - temp + str.charCodeAt(i)) << 0;
  2177. }
  2178. hash = hash ^ temp;
  2179. }
  2180. return hash;
  2181. };
  2182. /**
  2183. * Adds empty implementation
  2184. */
  2185. EditorUi.prototype.descriptorChanged = function()
  2186. {
  2187. // empty
  2188. };
  2189. /**
  2190. * Hook for subclassers.
  2191. */
  2192. EditorUi.prototype.restoreLibraries = function() { };
  2193. /**
  2194. * Hook for subclassers.
  2195. */
  2196. EditorUi.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn) { };
  2197. /**
  2198. *
  2199. */
  2200. EditorUi.prototype.isScratchpadEnabled = function()
  2201. {
  2202. return isLocalStorage || mxClient.IS_CHROMEAPP;
  2203. };
  2204. /**
  2205. * Shows or hides the scratchpad library.
  2206. */
  2207. EditorUi.prototype.toggleScratchpad = function()
  2208. {
  2209. if (this.isScratchpadEnabled())
  2210. {
  2211. if (this.scratchpad == null)
  2212. {
  2213. this.getLocalData('.scratchpad', mxUtils.bind(this, function(xml)
  2214. {
  2215. if (xml == null)
  2216. {
  2217. xml = this.emptyLibraryXml;
  2218. }
  2219. this.loadLibrary(new StorageLibrary(this, xml, '.scratchpad'));
  2220. }));
  2221. }
  2222. else
  2223. {
  2224. this.closeLibrary(this.scratchpad);
  2225. }
  2226. }
  2227. };
  2228. /**
  2229. * Translates this point by the given vector.
  2230. *
  2231. * @param {number} dx X-coordinate of the translation.
  2232. * @param {number} dy Y-coordinate of the translation.
  2233. */
  2234. EditorUi.prototype.createLibraryDataFromImages = function(images)
  2235. {
  2236. var doc = mxUtils.createXmlDocument();
  2237. var library = doc.createElement('mxlibrary');
  2238. mxUtils.setTextContent(library, JSON.stringify(images));
  2239. doc.appendChild(library);
  2240. return mxUtils.getXml(doc);
  2241. };
  2242. /**
  2243. * Translates this point by the given vector.
  2244. *
  2245. * @param {number} dx X-coordinate of the translation.
  2246. * @param {number} dy Y-coordinate of the translation.
  2247. */
  2248. EditorUi.prototype.closeLibrary = function(file)
  2249. {
  2250. if (file != null)
  2251. {
  2252. this.removeLibrarySidebar(file.getHash());
  2253. if (file.constructor != LocalLibrary)
  2254. {
  2255. mxSettings.removeCustomLibrary(file.getHash());
  2256. }
  2257. if (file.title == '.scratchpad')
  2258. {
  2259. this.scratchpad = null;
  2260. }
  2261. }
  2262. };
  2263. /**
  2264. * Translates this point by the given vector.
  2265. *
  2266. * @param {number} dx X-coordinate of the translation.
  2267. * @param {number} dy Y-coordinate of the translation.
  2268. */
  2269. EditorUi.prototype.removeLibrarySidebar = function(id)
  2270. {
  2271. var elts = this.sidebar.palettes[id];
  2272. if (elts != null)
  2273. {
  2274. for (var i = 0; i < elts.length; i++)
  2275. {
  2276. elts[i].parentNode.removeChild(elts[i]);
  2277. }
  2278. delete this.sidebar.palettes[id];
  2279. }
  2280. };
  2281. /**
  2282. * Changes the position of the library in the sidebar
  2283. */
  2284. EditorUi.prototype.repositionLibrary = function(nextChild)
  2285. {
  2286. var c = this.sidebar.container;
  2287. if (nextChild == null)
  2288. {
  2289. var elts = this.sidebar.palettes['L.scratchpad'];
  2290. if (elts == null)
  2291. {
  2292. elts = this.sidebar.palettes['search'];
  2293. }
  2294. if (elts != null)
  2295. {
  2296. nextChild = elts[elts.length - 1].nextSibling;
  2297. }
  2298. }
  2299. nextChild = (nextChild != null) ? nextChild : c.firstChild.nextSibling.nextSibling;
  2300. var content = c.lastChild;
  2301. var title = content.previousSibling;
  2302. c.insertBefore(content, nextChild);
  2303. c.insertBefore(title, content);
  2304. }
  2305. /**
  2306. * Translates this point by the given vector.
  2307. *
  2308. * @param {number} dx X-coordinate of the translation.
  2309. * @param {number} dy Y-coordinate of the translation.
  2310. */
  2311. EditorUi.prototype.loadLibrary = function(file)
  2312. {
  2313. var doc = mxUtils.parseXml(file.getData());
  2314. if (doc.documentElement.nodeName == 'mxlibrary')
  2315. {
  2316. var images = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2317. this.libraryLoaded(file, images, doc.documentElement.getAttribute('title'));
  2318. }
  2319. else
  2320. {
  2321. throw {message: mxResources.get('notALibraryFile')};
  2322. }
  2323. };
  2324. /**
  2325. * Translates this point by the given vector.
  2326. *
  2327. * @param {number} dx X-coordinate of the translation.
  2328. * @param {number} dy Y-coordinate of the translation.
  2329. */
  2330. EditorUi.prototype.getLibraryStorageHint = function(file)
  2331. {
  2332. return '';
  2333. };
  2334. /**
  2335. * Translates this point by the given vector.
  2336. *
  2337. * @param {number} dx X-coordinate of the translation.
  2338. * @param {number} dy Y-coordinate of the translation.
  2339. */
  2340. EditorUi.prototype.libraryLoaded = function(file, images, optionalTitle)
  2341. {
  2342. if (this.sidebar == null)
  2343. {
  2344. return;
  2345. }
  2346. if (file.constructor != LocalLibrary)
  2347. {
  2348. mxSettings.addCustomLibrary(file.getHash());
  2349. }
  2350. if (file.title == '.scratchpad')
  2351. {
  2352. this.scratchpad = file;
  2353. }
  2354. var elts = this.sidebar.palettes[file.getHash()];
  2355. var nextSibling = (elts != null) ? elts[elts.length - 1].nextSibling : null;
  2356. // Removes existing sidebar entry for this library
  2357. this.removeLibrarySidebar(file.getHash());
  2358. var dropTarget = null;
  2359. var addImages = mxUtils.bind(this, function(imgs, content)
  2360. {
  2361. if (imgs.length == 0 && file.isEditable())
  2362. {
  2363. if (dropTarget == null)
  2364. {
  2365. dropTarget = document.createElement('div');
  2366. dropTarget.className = 'geDropTarget';
  2367. mxUtils.write(dropTarget, mxResources.get('dragElementsHere'));
  2368. }
  2369. content.appendChild(dropTarget);
  2370. }
  2371. else
  2372. {
  2373. this.addLibraryEntries(imgs, content);
  2374. }
  2375. });
  2376. // Adds entries to search index
  2377. // KNOWN: Existing entries are not replaced after edit of custom library
  2378. if (this.sidebar != null && images != null)
  2379. {
  2380. for (var i = 0; i < images.length; i++)
  2381. {
  2382. (mxUtils.bind(this, function(img)
  2383. {
  2384. var data = img.data;
  2385. if (data != null && img.title != null)
  2386. {
  2387. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2388. {
  2389. data = this.convertDataUri(data);
  2390. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2391. if (img.aspect == 'fixed')
  2392. {
  2393. s += 'aspect=fixed;'
  2394. }
  2395. return this.sidebar.createVertexTemplate(s + 'image=' +
  2396. data, img.w, img.h, '', img.title || '', false, false, true)
  2397. }));
  2398. }
  2399. else if (img.xml != null && img.title != null)
  2400. {
  2401. this.sidebar.addEntry(img.title, mxUtils.bind(this, function()
  2402. {
  2403. var cells = this.stringToCells(Graph.decompress(img.xml));
  2404. return this.sidebar.createVertexTemplateFromCells(
  2405. cells, img.w, img.h, img.title || '', true, false, true);
  2406. }));
  2407. }
  2408. }))(images[i]);
  2409. }
  2410. }
  2411. // Adds new sidebar entry for this library
  2412. var tmp = (optionalTitle != null && optionalTitle.length > 0) ? optionalTitle : file.getTitle();
  2413. var contentDiv = this.sidebar.addPalette(file.getHash(), tmp, true, mxUtils.bind(this, function(content)
  2414. {
  2415. addImages(images, content);
  2416. }));
  2417. this.repositionLibrary(nextSibling);
  2418. // Adds tooltip for backend
  2419. var title = contentDiv.parentNode.previousSibling;
  2420. var tip = title.getAttribute('title');
  2421. if (tip != null && tip.length > 0 && file.title != '.scratchpad')
  2422. {
  2423. title.setAttribute('title', this.getLibraryStorageHint(file) + '\n' + tip);
  2424. }
  2425. var buttons = document.createElement('div');
  2426. buttons.style.position = 'absolute';
  2427. buttons.style.right = '0px';
  2428. buttons.style.top = '0px';
  2429. buttons.style.padding = '8px'
  2430. // Workaround for CSS error in IE8 (standards and quirks)
  2431. if (!mxClient.IS_QUIRKS && document.documentMode != 8)
  2432. {
  2433. buttons.style.backgroundColor = 'inherit';
  2434. }
  2435. title.style.position = 'relative';
  2436. var btnWidth = 18;
  2437. var btn = document.createElement('img');
  2438. btn.setAttribute('src', Dialog.prototype.closeImage);
  2439. btn.setAttribute('title', mxResources.get('close'));
  2440. btn.setAttribute('valign', 'absmiddle');
  2441. btn.setAttribute('border', '0');
  2442. btn.style.margin = '0 3px';
  2443. var saveBtn = null;
  2444. if (file.title != '.scratchpad' || this.closableScratchpad)
  2445. {
  2446. buttons.appendChild(btn);
  2447. mxEvent.addListener(btn, 'click', mxUtils.bind(this, function(evt)
  2448. {
  2449. // Workaround for close after any button click in IE8/quirks
  2450. if (!mxEvent.isConsumed(evt))
  2451. {
  2452. var fn = mxUtils.bind(this, function()
  2453. {
  2454. this.closeLibrary(file);
  2455. });
  2456. if (saveBtn != null)
  2457. {
  2458. this.confirm(mxResources.get('allChangesLost'), null, fn,
  2459. mxResources.get('cancel'), mxResources.get('discardChanges'));
  2460. }
  2461. else
  2462. {
  2463. fn();
  2464. }
  2465. mxEvent.consume(evt);
  2466. }
  2467. }));
  2468. }
  2469. if (file.isEditable())
  2470. {
  2471. var graph = this.editor.graph;
  2472. var spinBtn = null;
  2473. var editLibrary = mxUtils.bind(this, function(evt)
  2474. {
  2475. this.showLibraryDialog(file.getTitle(), contentDiv, images, file, file.getMode());
  2476. mxEvent.consume(evt);
  2477. });
  2478. var saveLibrary = mxUtils.bind(this, function(evt)
  2479. {
  2480. file.setModified(true);
  2481. if (file.isAutosave())
  2482. {
  2483. if (spinBtn != null && spinBtn.parentNode != null)
  2484. {
  2485. spinBtn.parentNode.removeChild(spinBtn);
  2486. }
  2487. spinBtn = btn.cloneNode(false);
  2488. spinBtn.setAttribute('src', Editor.spinImage);
  2489. spinBtn.setAttribute('title', mxResources.get('saving'));
  2490. spinBtn.style.cursor = 'default';
  2491. spinBtn.style.marginRight = '2px';
  2492. spinBtn.style.marginTop = '-2px';
  2493. buttons.insertBefore(spinBtn, buttons.firstChild);
  2494. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2495. this.saveLibrary(file.getTitle(), images, file, file.getMode(), true, true, function()
  2496. {
  2497. if (spinBtn != null && spinBtn.parentNode != null)
  2498. {
  2499. spinBtn.parentNode.removeChild(spinBtn);
  2500. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2501. }
  2502. });
  2503. }
  2504. else if (saveBtn == null)
  2505. {
  2506. saveBtn = btn.cloneNode(false);
  2507. saveBtn.setAttribute('src', IMAGE_PATH + '/download.png');
  2508. saveBtn.setAttribute('title', mxResources.get('save'));
  2509. buttons.insertBefore(saveBtn, buttons.firstChild);
  2510. mxEvent.addListener(saveBtn, 'click', mxUtils.bind(this, function(evt)
  2511. {
  2512. this.saveLibrary(file.getTitle(), images, file, file.getMode(),
  2513. file.constructor == LocalLibrary, true, function()
  2514. {
  2515. if (saveBtn != null && !file.isModified())
  2516. {
  2517. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2518. saveBtn.parentNode.removeChild(saveBtn);
  2519. saveBtn = null;
  2520. }
  2521. });
  2522. mxEvent.consume(evt);
  2523. }));
  2524. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2525. }
  2526. });
  2527. var addCells = mxUtils.bind(this, function(cells, bounds, evt, title)
  2528. {
  2529. cells = graph.cloneCells(mxUtils.sortCells(graph.model.getTopmostCells(cells)));
  2530. // Translates cells to origin
  2531. for (var i = 0; i < cells.length; i++)
  2532. {
  2533. var geo = graph.getCellGeometry(cells[i]);
  2534. if (geo != null)
  2535. {
  2536. geo.translate(-bounds.x, -bounds.y);
  2537. }
  2538. }
  2539. contentDiv.appendChild(this.sidebar.createVertexTemplateFromCells(
  2540. cells, bounds.width, bounds.height, title || '', true, false, false));
  2541. var xml = Graph.compress(mxUtils.getXml(this.editor.graph.encodeCells(cells)));
  2542. var entry = {xml: xml, w: bounds.width, h: bounds.height};
  2543. if (title != null)
  2544. {
  2545. entry.title = title;
  2546. }
  2547. images.push(entry);
  2548. saveLibrary(evt);
  2549. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2550. {
  2551. dropTarget.parentNode.removeChild(dropTarget);
  2552. dropTarget = null;
  2553. }
  2554. });
  2555. var addSelection = mxUtils.bind(this, function(evt)
  2556. {
  2557. if (!graph.isSelectionEmpty())
  2558. {
  2559. var cells = graph.getSelectionCells();
  2560. var bounds = graph.view.getBounds(cells);
  2561. var s = graph.view.scale;
  2562. bounds.x /= s;
  2563. bounds.y /= s;
  2564. bounds.width /= s;
  2565. bounds.height /= s;
  2566. bounds.x -= graph.view.translate.x;
  2567. bounds.y -= graph.view.translate.y;
  2568. addCells(cells, bounds);
  2569. }
  2570. else if (graph.getRubberband().isActive())
  2571. {
  2572. graph.getRubberband().execute(evt);
  2573. graph.getRubberband().reset();
  2574. }
  2575. else
  2576. {
  2577. this.showError(mxResources.get('error'), mxResources.get('nothingIsSelected'), mxResources.get('ok'));
  2578. }
  2579. mxEvent.consume(evt);
  2580. });
  2581. // Adds drop handler from graph
  2582. mxEvent.addGestureListeners(contentDiv, function(){}, mxUtils.bind(this, function(evt)
  2583. {
  2584. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler.shape != null)
  2585. {
  2586. graph.graphHandler.shape.node.style.visibility = 'hidden';
  2587. contentDiv.style.backgroundColor = '#f1f3f4';
  2588. contentDiv.style.cursor = 'copy';
  2589. graph.panningManager.stop();
  2590. graph.autoScroll = false;
  2591. if (graph.graphHandler.guide != null)
  2592. {
  2593. graph.graphHandler.guide.setVisible(false);
  2594. }
  2595. if (graph.graphHandler.hint != null)
  2596. {
  2597. graph.graphHandler.hint.style.visibility = 'hidden';
  2598. }
  2599. mxEvent.consume(evt);
  2600. }
  2601. }), mxUtils.bind(this, function(evt)
  2602. {
  2603. if (graph.isMouseDown && graph.panningManager != null && graph.graphHandler != null)
  2604. {
  2605. contentDiv.style.backgroundColor = '';
  2606. contentDiv.style.cursor = 'default';
  2607. this.sidebar.showTooltips = true;
  2608. graph.panningManager.stop();
  2609. graph.graphHandler.reset();
  2610. graph.isMouseDown = false;
  2611. graph.autoScroll = true;
  2612. addSelection(evt);
  2613. mxEvent.consume(evt);
  2614. }
  2615. }));
  2616. // Handles mouse leaving the library and restoring move
  2617. mxEvent.addListener(contentDiv, 'mouseleave', mxUtils.bind(this, function(evt)
  2618. {
  2619. if (graph.isMouseDown && graph.graphHandler.shape != null)
  2620. {
  2621. graph.graphHandler.shape.node.style.visibility = 'visible';
  2622. contentDiv.style.backgroundColor = '';
  2623. contentDiv.style.cursor = '';
  2624. graph.autoScroll = true;
  2625. if (graph.graphHandler.guide != null)
  2626. {
  2627. graph.graphHandler.guide.setVisible(true);
  2628. }
  2629. if (graph.graphHandler.hint != null)
  2630. {
  2631. graph.graphHandler.hint.style.visibility = 'visible';
  2632. }
  2633. }
  2634. }));
  2635. // Adds drop handler from filesystem
  2636. if (Graph.fileSupport)
  2637. {
  2638. mxEvent.addListener(contentDiv, 'dragover', mxUtils.bind(this, function(evt)
  2639. {
  2640. contentDiv.style.backgroundColor = '#f1f3f4';
  2641. evt.dataTransfer.dropEffect = 'copy';
  2642. contentDiv.style.cursor = 'copy';
  2643. this.sidebar.hideTooltip();
  2644. evt.stopPropagation();
  2645. evt.preventDefault();
  2646. }));
  2647. mxEvent.addListener(contentDiv, 'drop', mxUtils.bind(this, function(evt)
  2648. {
  2649. contentDiv.style.cursor = '';
  2650. contentDiv.style.backgroundColor = '';
  2651. if (evt.dataTransfer.files.length > 0)
  2652. {
  2653. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, mxUtils.bind(this, function(data, mimeType, x, y, w, h, img, doneFn, file)
  2654. {
  2655. if (data != null && mimeType.substring(0, 6) == 'image/')
  2656. {
  2657. var style = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;aspect=fixed;image=' +
  2658. this.convertDataUri(data);
  2659. var cells = [new mxCell('', new mxGeometry(0, 0, w, h), style)];
  2660. cells[0].vertex = true;
  2661. addCells(cells, new mxRectangle(0, 0, w, h), evt, (mxEvent.isAltDown(evt)) ? null : img.substring(0, img.lastIndexOf('.')).replace(/_/g, ' '));
  2662. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2663. {
  2664. dropTarget.parentNode.removeChild(dropTarget);
  2665. dropTarget = null;
  2666. }
  2667. }
  2668. else
  2669. {
  2670. var done = false;
  2671. var doImport = mxUtils.bind(this, function(theData, theMimeType)
  2672. {
  2673. if (theData != null && theMimeType == 'text/xml')
  2674. {
  2675. var doc = mxUtils.parseXml(theData);
  2676. if (doc.documentElement.nodeName == 'mxlibrary')
  2677. {
  2678. try
  2679. {
  2680. var temp = JSON.parse(mxUtils.getTextContent(doc.documentElement));
  2681. addImages(temp, contentDiv);
  2682. images = images.concat(temp);
  2683. saveLibrary(evt);
  2684. this.spinner.stop();
  2685. done = true;
  2686. }
  2687. catch (e)
  2688. {
  2689. // ignore
  2690. }
  2691. }
  2692. else if (doc.documentElement.nodeName == 'mxfile')
  2693. {
  2694. try
  2695. {
  2696. var pages = doc.documentElement.getElementsByTagName('diagram');
  2697. for (var i = 0; i < pages.length; i++)
  2698. {
  2699. var temp = mxUtils.getTextContent(pages[i]);
  2700. var cells = this.stringToCells(Graph.decompress(temp));
  2701. var size = this.editor.graph.getBoundingBoxFromGeometry(cells);
  2702. addCells(cells, new mxRectangle(0, 0, size.width, size.height), evt);
  2703. }
  2704. done = true;
  2705. }
  2706. catch (e)
  2707. {
  2708. if (window.console != null)
  2709. {
  2710. console.log('error in drop handler:', e);
  2711. }
  2712. }
  2713. }
  2714. }
  2715. if (!done)
  2716. {
  2717. this.spinner.stop();
  2718. this.handleError({message: mxResources.get('errorLoadingFile')})
  2719. }
  2720. if (dropTarget != null && dropTarget.parentNode != null && images.length > 0)
  2721. {
  2722. dropTarget.parentNode.removeChild(dropTarget);
  2723. dropTarget = null;
  2724. }
  2725. });
  2726. if (file != null && img != null && ((/(\.v(dx|sdx?))($|\?)/i.test(img)) || /(\.vs(x|sx?))($|\?)/i.test(img)))
  2727. {
  2728. this.importVisio(file, function(xml)
  2729. {
  2730. doImport(xml, 'text/xml');
  2731. }, null, img);
  2732. }
  2733. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, img) && file != null)
  2734. {
  2735. this.parseFile(file, mxUtils.bind(this, function(xhr)
  2736. {
  2737. if (xhr.readyState == 4)
  2738. {
  2739. this.spinner.stop();
  2740. if (xhr.status >= 200 && xhr.status <= 299)
  2741. {
  2742. doImport(xhr.responseText, 'text/xml');
  2743. }
  2744. else
  2745. {
  2746. this.handleError({message: mxResources.get((xhr.status == 413) ?
  2747. 'drawingTooLarge' : 'invalidOrMissingFile')},
  2748. mxResources.get('errorLoadingFile'));
  2749. }
  2750. }
  2751. }));
  2752. }
  2753. else
  2754. {
  2755. doImport(data, mimeType);
  2756. }
  2757. }
  2758. }));
  2759. }
  2760. evt.stopPropagation();
  2761. evt.preventDefault();
  2762. }));
  2763. mxEvent.addListener(contentDiv, 'dragleave', function(evt)
  2764. {
  2765. contentDiv.style.cursor = '';
  2766. contentDiv.style.backgroundColor = '';
  2767. evt.stopPropagation();
  2768. evt.preventDefault();
  2769. });
  2770. }
  2771. btn = btn.cloneNode(false);
  2772. btn.setAttribute('src', Editor.editImage);
  2773. btn.setAttribute('title', mxResources.get('edit'));
  2774. buttons.insertBefore(btn, buttons.firstChild);
  2775. mxEvent.addListener(btn, 'click', editLibrary);
  2776. mxEvent.addListener(contentDiv, 'dblclick', function(evt)
  2777. {
  2778. if (mxEvent.getSource(evt) == contentDiv)
  2779. {
  2780. editLibrary(evt);
  2781. }
  2782. });
  2783. var btn2 = btn.cloneNode(false);
  2784. btn2.setAttribute('src', Editor.plusImage);
  2785. btn2.setAttribute('title', mxResources.get('add'));
  2786. buttons.insertBefore(btn2, buttons.firstChild);
  2787. mxEvent.addListener(btn2, 'click', addSelection);
  2788. if (!this.isOffline() && file.title == '.scratchpad' && EditorUi.scratchpadHelpLink != null)
  2789. {
  2790. var link = document.createElement('span');
  2791. link.setAttribute('title', mxResources.get('help'));
  2792. link.style.cssText = 'color:#a3a3a3;text-decoration:none;margin-right:2px;';
  2793. mxUtils.write(link, '?');
  2794. mxEvent.addGestureListeners(link, mxUtils.bind(this, function(evt)
  2795. {
  2796. this.openLink(EditorUi.scratchpadHelpLink);
  2797. mxEvent.consume(evt);
  2798. }));
  2799. buttons.insertBefore(link, buttons.firstChild);
  2800. }
  2801. }
  2802. title.appendChild(buttons);
  2803. title.style.paddingRight = (buttons.childNodes.length * btnWidth) + 'px';
  2804. };
  2805. /**
  2806. * Adds the library entries to the given DOM node.
  2807. */
  2808. EditorUi.prototype.addLibraryEntries = function(imgs, content)
  2809. {
  2810. for (var i = 0; i < imgs.length; i++)
  2811. {
  2812. var img = imgs[i];
  2813. var data = img.data;
  2814. if (data != null)
  2815. {
  2816. data = this.convertDataUri(data);
  2817. var s = 'shape=image;verticalLabelPosition=bottom;verticalAlign=top;imageAspect=0;';
  2818. if (img.aspect == 'fixed')
  2819. {
  2820. s += 'aspect=fixed;'
  2821. }
  2822. content.appendChild(this.sidebar.createVertexTemplate(s + 'image=' +
  2823. data, img.w, img.h, '', img.title || '', false, false, true));
  2824. }
  2825. else if (img.xml != null)
  2826. {
  2827. var cells = this.stringToCells(Graph.decompress(img.xml));
  2828. if (cells.length > 0)
  2829. {
  2830. content.appendChild(this.sidebar.createVertexTemplateFromCells(
  2831. cells, img.w, img.h, img.title || '', true, false, true));
  2832. }
  2833. }
  2834. }
  2835. };
  2836. /**
  2837. * Extracts the resource for the current language from the given multi language
  2838. * resource object of the form {es: "...", de: "...", main: "..."} where the keys
  2839. * are country codes and main defines the fallback if no resource for the current
  2840. * country code exists.
  2841. */
  2842. EditorUi.prototype.getResource = function(obj)
  2843. {
  2844. return (obj != null) ? (obj[mxLanguage] || obj.main) : null;
  2845. };
  2846. /**
  2847. * EditorUi Overrides
  2848. */
  2849. EditorUi.prototype.footerHeight = 0;
  2850. if (urlParams['offline'] == '1' || EditorUi.isElectronApp)
  2851. {
  2852. //EditorUi.prototype.footerHeight = 4;
  2853. }
  2854. else
  2855. {
  2856. if (urlParams['savesidebar'] == '1')
  2857. {
  2858. Sidebar.prototype.thumbWidth = 64;
  2859. Sidebar.prototype.thumbHeight = 64;
  2860. }
  2861. //EditorUi.prototype.footerHeight = (screen.width >= 760 && screen.height >= 240) ? 46 : 0;
  2862. // Fetches footer from page
  2863. EditorUi.prototype.createFooter = function()
  2864. {
  2865. var footer = document.getElementById('geFooter');
  2866. if (footer != null)
  2867. {
  2868. // footer.style.visibility = 'hidden';
  2869. //
  2870. // // Adds button to hide the footer
  2871. // var img = document.createElement('img');
  2872. // img.setAttribute('border', '0');
  2873. // img.setAttribute('src', Dialog.prototype.closeImage);
  2874. // img.setAttribute('title', mxResources.get('hide'));
  2875. // footer.appendChild(img)
  2876. //
  2877. // if (mxClient.IS_QUIRKS)
  2878. // {
  2879. // img.style.position = 'relative';
  2880. // img.style.styleFloat = 'right';
  2881. // img.style.top = '-30px';
  2882. // img.style.left = '164px';
  2883. // img.style.cursor = 'pointer';
  2884. // }
  2885. //
  2886. // mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  2887. // {
  2888. // this.hideFooter();
  2889. // }));
  2890. }
  2891. return footer;
  2892. };
  2893. }
  2894. EditorUi.initTheme = function()
  2895. {
  2896. if (uiTheme == 'atlas')
  2897. {
  2898. mxClient.link('stylesheet', STYLE_PATH + '/atlas.css');
  2899. if (typeof Toolbar !== 'undefined')
  2900. {
  2901. Toolbar.prototype.unselectedBackground = (mxClient.IS_QUIRKS) ? 'none' : 'linear-gradient(rgb(255, 255, 255) 0px, rgb(242, 242, 242) 100%)';
  2902. Toolbar.prototype.selectedBackground = 'rgb(242, 242, 242)';
  2903. }
  2904. Editor.prototype.initialTopSpacing = 3;
  2905. EditorUi.prototype.menubarHeight = 41;
  2906. EditorUi.prototype.toolbarHeight = 38;
  2907. }
  2908. else if (uiTheme == 'dark')
  2909. {
  2910. mxClient.link('stylesheet', STYLE_PATH + '/dark.css');
  2911. Dialog.backdropColor = '#2a2a2a';
  2912. Graph.prototype.defaultThemeName = 'darkTheme';
  2913. Graph.prototype.defaultPageBackgroundColor = '#2a2a2a';
  2914. Graph.prototype.defaultPageBorderColor = '#505759';
  2915. Format.prototype.inactiveTabBackgroundColor = 'black';
  2916. BaseFormatPanel.prototype.buttonBackgroundColor = '#2a2a2a';
  2917. Sidebar.prototype.dragPreviewBorder = '1px dashed #cccccc';
  2918. mxGraphHandler.prototype.previewColor = '#cccccc';
  2919. StyleFormatPanel.prototype.defaultStrokeColor = '#cccccc';
  2920. if (mxClient.IS_SVG)
  2921. {
  2922. Editor.helpImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAP1BMVEUAAAD///////////////////////////////////////////////////////////////////////////////9Du/pqAAAAFXRSTlMAT30qCJRBboyDZyCgRzUUdF46MJlgXETgAAAAeklEQVQY022O2w4DIQhEQUURda/9/28tUO2+7CQS5sgQ4F1RapX78YUwRqQjTU8ILqQfKerTKTvACJ4nLX3krt+8aS82oI8aQC4KavRgtvEW/mDvsICgA03PSGRr79MqX1YPNIxzjyqtw8ZnnRo4t5a5undtJYRywau+ds4Cyza3E6YAAAAASUVORK5CYII=';
  2923. Editor.checkmarkImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAARVBMVEUAAACZmZkICAgEBASNjY2Dg4MYGBiTk5N5eXl1dXVmZmZQUFBCQkI3NzceHh4MDAykpKSJiYl+fn5sbGxaWlo/Pz8SEhK96uPlAAAAAXRSTlMAQObYZgAAAE5JREFUGNPFzTcSgDAQQ1HJGUfy/Y9K7V1qeOUfzQifCQZai1XHaz11LFysbDbzgDSSWMZiETz3+b8yNUc/MMsktxuC8XQBSncdLwz+8gCCggGXzBcozAAAAABJRU5ErkJggg==';
  2924. }
  2925. }
  2926. };
  2927. EditorUi.initTheme();
  2928. /**
  2929. * Hides the footer.
  2930. */
  2931. EditorUi.prototype.hideFooter = function()
  2932. {
  2933. var footer = document.getElementById('geFooter');
  2934. if (footer != null)
  2935. {
  2936. this.footerHeight = 0;
  2937. footer.style.display = 'none';
  2938. this.refresh();
  2939. }
  2940. };
  2941. /**
  2942. * Shows the footer.
  2943. */
  2944. EditorUi.prototype.showFooter = function(height)
  2945. {
  2946. var footer = document.getElementById('geFooter');
  2947. if (footer != null)
  2948. {
  2949. this.footerHeight = height;
  2950. footer.style.display = 'inline';
  2951. this.refresh();
  2952. }
  2953. };
  2954. /**
  2955. * Overrides image dialog to add image search and Google+.
  2956. */
  2957. EditorUi.prototype.showImageDialog = function(title, value, fn, ignoreExisting, convertDataUri)
  2958. {
  2959. // KNOWN: IE+FF don't return keyboard focus after image dialog (calling focus doesn't help)
  2960. var dlg = new ImageDialog(this, title, value, fn, ignoreExisting, convertDataUri);
  2961. this.showDialog(dlg.container, (Graph.fileSupport) ? 440 : 360, (Graph.fileSupport) ? 200 : 90, true, true);
  2962. dlg.init();
  2963. };
  2964. /**
  2965. * Hides the current menu.
  2966. */
  2967. EditorUi.prototype.showBackgroundImageDialog = function(apply)
  2968. {
  2969. apply = (apply != null) ? apply : mxUtils.bind(this, function(image)
  2970. {
  2971. var change = new ChangePageSetup(this, null, image);
  2972. change.ignoreColor = true;
  2973. this.editor.graph.model.execute(change);
  2974. });
  2975. var dlg = new BackgroundImageDialog(this, mxUtils.bind(this, function(image)
  2976. {
  2977. apply(image);
  2978. }));
  2979. this.showDialog(dlg.container, 360, 200, true, true);
  2980. dlg.init();
  2981. };
  2982. /**
  2983. * Hides the current menu.
  2984. */
  2985. EditorUi.prototype.showLibraryDialog = function(name, sidebar, images, file, mode)
  2986. {
  2987. var dlg = new LibraryDialog(this, name, sidebar, images, file, mode);
  2988. this.showDialog(dlg.container, 640, 440, true, false, mxUtils.bind(this, function(cancel)
  2989. {
  2990. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  2991. {
  2992. this.showSplash();
  2993. }
  2994. }));
  2995. dlg.init();
  2996. };
  2997. /**
  2998. * Overridden to update after view state changes.
  2999. */
  3000. var editorUiCreateFormat = EditorUi.prototype.createFormat;
  3001. EditorUi.prototype.createFormat = function(container)
  3002. {
  3003. var format = editorUiCreateFormat.apply(this, arguments);
  3004. this.editor.graph.addListener('viewStateChanged', mxUtils.bind(this, function(evt)
  3005. {
  3006. if (this.editor.graph.isSelectionEmpty())
  3007. {
  3008. format.refresh();
  3009. }
  3010. }));
  3011. return format;
  3012. };
  3013. /**
  3014. * Hook for sidebar footer container.
  3015. */
  3016. EditorUi.prototype.createSidebarFooterContainer = function()
  3017. {
  3018. var div = this.createDiv('geSidebarContainer geSidebarFooter');
  3019. div.style.position = 'absolute';
  3020. div.style.overflow = 'hidden';
  3021. var elt2 = document.createElement('a');
  3022. elt2.className = 'geTitle';
  3023. elt2.style.color = '#188038';
  3024. elt2.style.height = '100%';
  3025. elt2.style.paddingTop = '9px';
  3026. elt2.innerHTML = '<span style="font-size:18px;margin-right:5px;">+</span>';
  3027. mxUtils.write(elt2, mxResources.get('moreShapes') + '...');
  3028. // Prevents focus
  3029. mxEvent.addListener(elt2, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
  3030. mxUtils.bind(this, function(evt)
  3031. {
  3032. evt.preventDefault();
  3033. }));
  3034. mxEvent.addListener(elt2, 'click', mxUtils.bind(this, function(evt)
  3035. {
  3036. this.actions.get('shapes').funct();
  3037. mxEvent.consume(evt);
  3038. }));
  3039. div.appendChild(elt2);
  3040. return div;
  3041. };
  3042. /**
  3043. * Translates this point by the given vector.
  3044. *
  3045. * @param {number} dx X-coordinate of the translation.
  3046. * @param {number} dy Y-coordinate of the translation.
  3047. */
  3048. EditorUi.prototype.handleError = function(resp, title, fn, invokeFnOnClose, notFoundMessage)
  3049. {
  3050. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3051. var e = (resp != null && resp.error != null) ? resp.error : resp;
  3052. if (e != null || title != null)
  3053. {
  3054. var msg = mxUtils.htmlEntities(mxResources.get('unknownError'));
  3055. var btn = mxResources.get('ok');
  3056. var retry = null;
  3057. title = (title != null) ? title : mxResources.get('error');
  3058. if (e != null)
  3059. {
  3060. if (e.retry != null)
  3061. {
  3062. btn = mxResources.get('cancel');
  3063. retry = function()
  3064. {
  3065. resume();
  3066. e.retry();
  3067. };
  3068. }
  3069. if (e.code == 404 || e.status == 404 || e.code == 403)
  3070. {
  3071. if (e.code == 403)
  3072. {
  3073. if (e.message != null)
  3074. {
  3075. msg = mxUtils.htmlEntities(e.message);
  3076. }
  3077. else
  3078. {
  3079. msg = mxUtils.htmlEntities(mxResources.get('accessDenied'));
  3080. }
  3081. }
  3082. else
  3083. {
  3084. msg = (notFoundMessage != null) ? notFoundMessage :
  3085. mxUtils.htmlEntities(mxResources.get('fileNotFoundOrDenied') +
  3086. ((this.drive != null && this.drive.user != null) ? ' (' + this.drive.user.displayName +
  3087. ', ' + this.drive.user.email+ ')' : ''));
  3088. }
  3089. var id = window.location.hash;
  3090. // #U handles case where we tried to fallback to Google File and
  3091. // hash property still shows the public URL we tried to load
  3092. if (id != null && (id.substring(0, 2) == '#G' ||
  3093. id.substring(0, 45) == '#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D') &&
  3094. ((resp != null && resp.error != null && ((resp.error.errors != null &&
  3095. resp.error.errors.length > 0 && resp.error.errors[0].reason == 'fileAccess') ||
  3096. (resp.error.data != null && resp.error.data.length > 0 &&
  3097. resp.error.data[0].reason == 'fileAccess'))) ||
  3098. e.code == 404 || e.status == 404))
  3099. {
  3100. id = (id.substring(0, 2) == '#U') ? id.substring(45, id.lastIndexOf('%26ex')) : id.substring(2);
  3101. // Special case where the button must have a different label and function
  3102. this.showError(title, msg, mxResources.get('openInNewWindow'), mxUtils.bind(this, function()
  3103. {
  3104. this.editor.graph.openLink('https://drive.google.com/open?id=' + id);
  3105. this.handleError(resp, title, fn, invokeFnOnClose, notFoundMessage)
  3106. }), retry, mxResources.get('changeUser'), mxUtils.bind(this, function()
  3107. {
  3108. if (this.spinner.spin(document.body, mxResources.get('loading')))
  3109. {
  3110. this.drive.clearUserId();
  3111. gapi.auth.signOut();
  3112. // Reload page to reset client auth
  3113. window.location.reload();
  3114. }
  3115. }), mxResources.get('cancel'), mxUtils.bind(this, function()
  3116. {
  3117. window.location.hash = '';
  3118. }), 480, 150);
  3119. return;
  3120. }
  3121. }
  3122. else if (e.message != null)
  3123. {
  3124. msg = mxUtils.htmlEntities(e.message);
  3125. }
  3126. else if (e.response != null && e.response.error != null)
  3127. {
  3128. msg = mxUtils.htmlEntities(e.response.error);
  3129. }
  3130. else if (window.App !== 'undefined')
  3131. {
  3132. if (e.code == App.ERROR_TIMEOUT)
  3133. {
  3134. msg = mxUtils.htmlEntities(mxResources.get('timeout'));
  3135. }
  3136. else if (e.code == App.ERROR_BUSY)
  3137. {
  3138. msg = mxUtils.htmlEntities(mxResources.get('busy'));
  3139. }
  3140. }
  3141. }
  3142. this.showError(title, msg, btn, fn, retry, null, null, null, null,
  3143. null, null, null, (invokeFnOnClose) ? fn : null);
  3144. }
  3145. else if (fn != null)
  3146. {
  3147. fn();
  3148. }
  3149. };
  3150. /**
  3151. * Translates this point by the given vector.
  3152. *
  3153. * @param {number} dx X-coordinate of the translation.
  3154. * @param {number} dy Y-coordinate of the translation.
  3155. */
  3156. EditorUi.prototype.alert = function(msg, fn)
  3157. {
  3158. var dlg = new ErrorDialog(this, null, msg, mxResources.get('ok'), fn);
  3159. this.showDialog(dlg.container, 340, 100, true, false);
  3160. dlg.init();
  3161. };
  3162. /**
  3163. * Translates this point by the given vector.
  3164. *
  3165. * @param {number} dx X-coordinate of the translation.
  3166. * @param {number} dy Y-coordinate of the translation.
  3167. */
  3168. EditorUi.prototype.confirm = function(msg, okFn, cancelFn, okLabel, cancelLabel, closable)
  3169. {
  3170. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  3171. var dlg = new ConfirmDialog(this, msg, function()
  3172. {
  3173. resume();
  3174. if (okFn != null)
  3175. {
  3176. okFn();
  3177. }
  3178. }, function()
  3179. {
  3180. resume();
  3181. if (cancelFn != null)
  3182. {
  3183. cancelFn();
  3184. }
  3185. }, okLabel, cancelLabel);
  3186. this.showDialog(dlg.container, 340, 90, true, closable);
  3187. dlg.init();
  3188. };
  3189. /**
  3190. * Translates this point by the given vector.
  3191. *
  3192. * @param {number} dx X-coordinate of the translation.
  3193. * @param {number} dy Y-coordinate of the translation.
  3194. */
  3195. EditorUi.prototype.setCurrentFile = function(file)
  3196. {
  3197. if (file != null)
  3198. {
  3199. file.opened = new Date();
  3200. }
  3201. this.currentFile = file;
  3202. };
  3203. /**
  3204. * Translates this point by the given vector.
  3205. *
  3206. * @param {number} dx X-coordinate of the translation.
  3207. * @param {number} dy Y-coordinate of the translation.
  3208. */
  3209. EditorUi.prototype.getCurrentFile = function()
  3210. {
  3211. return this.currentFile;
  3212. };
  3213. /**
  3214. * Handling for canvas export.
  3215. */
  3216. /**
  3217. * See fixme in convertMath for client-side image generation with math.
  3218. */
  3219. EditorUi.prototype.isExportToCanvas = function()
  3220. {
  3221. return mxClient.IS_CHROMEAPP || (!this.editor.graph.mathEnabled && this.useCanvasForExport);
  3222. };
  3223. /**
  3224. * Translates this point by the given vector.
  3225. *
  3226. * @param {number} dx X-coordinate of the translation.
  3227. * @param {number} dy Y-coordinate of the translation.
  3228. */
  3229. EditorUi.prototype.createSvgDataUri = function(svg)
  3230. {
  3231. return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
  3232. };
  3233. /**
  3234. *
  3235. */
  3236. EditorUi.prototype.createImageDataUri = function(canvas, xml, format)
  3237. {
  3238. var data = canvas.toDataURL('image/' + format);
  3239. // Checks if output is invalid or empty
  3240. if (data.length <= 6 || data == canvas.cloneNode(false).toDataURL('image/' + format))
  3241. {
  3242. throw {message: 'Invalid image'};
  3243. }
  3244. if (xml != null)
  3245. {
  3246. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel', atob(Graph.compress(xml)));
  3247. }
  3248. return data;
  3249. };
  3250. /**
  3251. *
  3252. */
  3253. EditorUi.prototype.saveCanvas = function(canvas, xml, format)
  3254. {
  3255. var ext = ((format == 'jpeg') ? 'jpg' : format);
  3256. var filename = this.getBaseFilename() + '.' + ext;
  3257. var data = this.createImageDataUri(canvas, xml, format);
  3258. this.saveData(filename, ext, data.substring(data.lastIndexOf(',') + 1), 'image/' + format, true);
  3259. };
  3260. /**
  3261. * Returns true if files should be saved using <saveLocalFile>.
  3262. */
  3263. EditorUi.prototype.isLocalFileSave = function()
  3264. {
  3265. return ((urlParams['save'] != 'remote' && (mxClient.IS_IE ||
  3266. (typeof window.Blob !== 'undefined' && typeof window.URL !== 'undefined')) &&
  3267. document.documentMode != 9 && document.documentMode != 8 &&
  3268. document.documentMode != 7 && !mxClient.IS_QUIRKS) ||
  3269. this.isOfflineApp() || mxClient.IS_IOS);
  3270. };
  3271. /**
  3272. * Translates this point by the given vector.
  3273. *
  3274. * @param {number} dx X-coordinate of the translation.
  3275. * @param {number} dy Y-coordinate of the translation.
  3276. */
  3277. EditorUi.prototype.showTextDialog = function(title, text)
  3278. {
  3279. var dlg = new TextareaDialog(this, title, text, null, null, mxResources.get('close'));
  3280. dlg.textarea.style.width = '600px';
  3281. dlg.textarea.style.height = '380px';
  3282. this.showDialog(dlg.container, 620, 460, true, true);
  3283. dlg.init();
  3284. document.execCommand('selectall', false, null);
  3285. };
  3286. /**
  3287. * Translates this point by the given vector.
  3288. *
  3289. * @param {number} dx X-coordinate of the translation.
  3290. * @param {number} dy Y-coordinate of the translation.
  3291. */
  3292. EditorUi.prototype.doSaveLocalFile = function(data, filename, mimeType, base64Encoded, format)
  3293. {
  3294. // Newer versions of IE
  3295. if (window.Blob && navigator.msSaveOrOpenBlob)
  3296. {
  3297. var blob = (base64Encoded) ?
  3298. this.base64ToBlob(data, mimeType) :
  3299. new Blob([data], {type: mimeType})
  3300. navigator.msSaveOrOpenBlob(blob, filename);
  3301. }
  3302. // Older versions of IE (binary not supported)
  3303. else if (mxClient.IS_IE)
  3304. {
  3305. var win = window.open('about:blank', '_blank');
  3306. if (win == null)
  3307. {
  3308. mxUtils.popup(data, true);
  3309. }
  3310. else
  3311. {
  3312. win.document.write(data);
  3313. win.document.close();
  3314. win.document.execCommand('SaveAs', true, filename);
  3315. win.close();
  3316. }
  3317. }
  3318. // else if (mxClient.IS_IOS)
  3319. // {
  3320. // this.showTextDialog(filename + ':', data);
  3321. // }
  3322. else
  3323. {
  3324. var a = document.createElement('a');
  3325. // Workaround for mxXmlRequest.simulate no longer working in Safari/PaleMoon
  3326. // if this is used (ie PNG export broken after XML export in Safari/PaleMoon).
  3327. var useDownload = !mxClient.IS_SF && navigator.userAgent.indexOf("PaleMoon/") < 0 &&
  3328. typeof a.download !== 'undefined';
  3329. // Workaround for Chromium 65 cross-domain anchor download issue
  3330. if (mxClient.IS_GC)
  3331. {
  3332. var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)
  3333. var vers = raw ? parseInt(raw[2], 10) : false;
  3334. useDownload = vers == 65 ? false : useDownload;
  3335. }
  3336. if (useDownload || this.isOffline())
  3337. {
  3338. a.href = URL.createObjectURL((base64Encoded) ?
  3339. this.base64ToBlob(data, mimeType) :
  3340. new Blob([data], {type: mimeType}));
  3341. if (useDownload)
  3342. {
  3343. a.download = filename;
  3344. }
  3345. else
  3346. {
  3347. // Workaround for same window in Safari
  3348. a.setAttribute('target', '_blank');
  3349. }
  3350. document.body.appendChild(a);
  3351. try
  3352. {
  3353. window.setTimeout(function()
  3354. {
  3355. URL.revokeObjectURL(a.href);
  3356. }, 0);
  3357. a.click();
  3358. a.parentNode.removeChild(a);
  3359. }
  3360. catch (e)
  3361. {
  3362. // ignore
  3363. }
  3364. }
  3365. else
  3366. {
  3367. var req = this.createEchoRequest(data, filename, mimeType, base64Encoded, format);
  3368. req.simulate(document, '_blank');
  3369. }
  3370. }
  3371. };
  3372. /**
  3373. * Translates this point by the given vector.
  3374. *
  3375. * @param {number} dx X-coordinate of the translation.
  3376. * @param {number} dy Y-coordinate of the translation.
  3377. */
  3378. EditorUi.prototype.createEchoRequest = function(data, filename, mimeType, base64Encoded, format, base64Response)
  3379. {
  3380. var param = (typeof(pako) === 'undefined' || true) ? 'xml=' + encodeURIComponent(data) :
  3381. 'data=' + encodeURIComponent(Graph.compress(data));
  3382. return new mxXmlRequest(SAVE_URL, param +
  3383. ((mimeType != null) ? '&mime=' + mimeType : '') +
  3384. ((format != null) ? '&format=' + format : '') +
  3385. ((base64Response != null) ? '&base64=' + base64Response : '') +
  3386. ((filename != null) ? '&filename=' + encodeURIComponent(filename) : '') +
  3387. ((base64Encoded) ? '&binary=1' : ''));
  3388. };
  3389. /**
  3390. * Translates this point by the given vector.
  3391. *
  3392. * @param {number} dx X-coordinate of the translation.
  3393. * @param {number} dy Y-coordinate of the translation.
  3394. */
  3395. EditorUi.prototype.base64ToBlob = function(base64Data, contentType)
  3396. {
  3397. contentType = contentType || '';
  3398. var sliceSize = 1024;
  3399. var byteCharacters = atob(base64Data);
  3400. var bytesLength = byteCharacters.length;
  3401. var slicesCount = Math.ceil(bytesLength / sliceSize);
  3402. var byteArrays = new Array(slicesCount);
  3403. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex)
  3404. {
  3405. var begin = sliceIndex * sliceSize;
  3406. var end = Math.min(begin + sliceSize, bytesLength);
  3407. var bytes = new Array(end - begin);
  3408. for (var offset = begin, i = 0 ; offset < end; ++i, ++offset)
  3409. {
  3410. bytes[i] = byteCharacters[offset].charCodeAt(0);
  3411. }
  3412. byteArrays[sliceIndex] = new Uint8Array(bytes);
  3413. }
  3414. return new Blob(byteArrays, {type: contentType});
  3415. };
  3416. /**
  3417. * Translates this point by the given vector.
  3418. *
  3419. * @param {number} dx X-coordinate of the translation.
  3420. * @param {number} dy Y-coordinate of the translation.
  3421. */
  3422. EditorUi.prototype.saveLocalFile = function(data, filename, mimeType, base64Encoded, format, allowBrowser, allowTab)
  3423. {
  3424. allowBrowser = (allowBrowser != null) ? allowBrowser : false;
  3425. allowTab = (allowTab != null) ? allowTab : (format != 'vsdx') && (!mxClient.IS_IOS || !navigator.standalone);
  3426. var count = this.getServiceCount(allowBrowser);
  3427. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3428. {
  3429. try
  3430. {
  3431. // Opens a new window
  3432. if (mode == '_blank')
  3433. {
  3434. if (mimeType != null && mimeType.substring(0, 6) == 'image/' &&
  3435. (mimeType.substring(0, 9) != 'image/svg' || mxClient.IS_SVG))
  3436. {
  3437. this.openInNewWindow(data, mimeType, base64Encoded);
  3438. }
  3439. else
  3440. {
  3441. var win = window.open('about:blank');
  3442. if (win == null)
  3443. {
  3444. mxUtils.popup(data, true);
  3445. }
  3446. else
  3447. {
  3448. win.document.write(mxUtils.htmlEntities(data, false));
  3449. win.document.close();
  3450. }
  3451. }
  3452. }
  3453. else if (mode == App.MODE_DEVICE || mode == 'download')
  3454. {
  3455. this.doSaveLocalFile(data, newTitle, mimeType, base64Encoded);
  3456. }
  3457. else if (newTitle != null && newTitle.length > 0)
  3458. {
  3459. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3460. {
  3461. try
  3462. {
  3463. this.exportFile(data, newTitle, mimeType, base64Encoded, mode, folderId);
  3464. }
  3465. catch (e)
  3466. {
  3467. this.handleError(e);
  3468. }
  3469. }));
  3470. }
  3471. }
  3472. catch (e)
  3473. {
  3474. this.handleError(e);
  3475. }
  3476. }), mxUtils.bind(this, function()
  3477. {
  3478. this.hideDialog();
  3479. }), mxResources.get('saveAs'), mxResources.get('download'), false, allowBrowser, allowTab,
  3480. null, count > 1, (count > 4 && (!allowBrowser || count < 6)) ? 3 : 4, data, mimeType, base64Encoded);
  3481. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3482. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3483. this.showDialog(dlg.container, 420, height, true, true);
  3484. dlg.init();
  3485. };
  3486. /**
  3487. *
  3488. */
  3489. EditorUi.prototype.openInNewWindow = function(data, mimeType, base64Encoded)
  3490. {
  3491. // In Google Chrome 60 the code from below produces a blank window
  3492. if (mxClient.IS_GC || mxClient.IS_EDGE || document.documentMode == 11 || document.documentMode == 10)
  3493. {
  3494. var win = window.open('about:blank');
  3495. if (win == null || win.document == null)
  3496. {
  3497. mxUtils.popup(data, true);
  3498. }
  3499. else
  3500. {
  3501. // Workaround for broken images in SVG output in Chrome
  3502. if (mimeType == 'image/svg+xml')
  3503. {
  3504. win.document.write('<html>' + data + '</html>');
  3505. }
  3506. else
  3507. {
  3508. win.document.write('<html><img src="data:' +
  3509. mimeType + ((base64Encoded) ? ';base64,' +
  3510. data : ';charset=utf8,' + encodeURIComponent(data)) +
  3511. '"/></html>');
  3512. }
  3513. win.document.close();
  3514. }
  3515. }
  3516. else
  3517. {
  3518. // win.open is workaround for cleared contents in Chrome after delay
  3519. // when using location.replace
  3520. var win = window.open('data:' + mimeType + ((base64Encoded) ? ';base64,' +
  3521. data : ';charset=utf8,' + encodeURIComponent(data)));
  3522. if (win == null || win.document == null)
  3523. {
  3524. mxUtils.popup(data, true);
  3525. }
  3526. }
  3527. };
  3528. var editoUiAddChromelessToolbarItems = EditorUi.prototype.addChromelessToolbarItems;
  3529. /**
  3530. * Creates a temporary graph instance for rendering off-screen content.
  3531. */
  3532. EditorUi.prototype.addChromelessToolbarItems = function(addButton)
  3533. {
  3534. if (this.isExportToCanvas())
  3535. {
  3536. this.exportDialog = null;
  3537. var exportButton = addButton(mxUtils.bind(this, function(evt)
  3538. {
  3539. var clickHandler = mxUtils.bind(this, function()
  3540. {
  3541. mxEvent.removeListener(this.editor.graph.container, 'click', clickHandler);
  3542. if (this.exportDialog != null)
  3543. {
  3544. this.exportDialog.parentNode.removeChild(this.exportDialog);
  3545. this.exportDialog = null;
  3546. }
  3547. });
  3548. if (this.exportDialog != null)
  3549. {
  3550. clickHandler.apply(this);
  3551. }
  3552. else
  3553. {
  3554. this.exportDialog = document.createElement('div');
  3555. var r = exportButton.getBoundingClientRect();
  3556. mxUtils.setPrefixedStyle(this.exportDialog.style, 'borderRadius', '5px');
  3557. this.exportDialog.style.position = 'fixed';
  3558. this.exportDialog.style.textAlign = 'center';
  3559. this.exportDialog.style.fontFamily = 'Helvetica,Arial';
  3560. this.exportDialog.style.backgroundColor = '#000000';
  3561. this.exportDialog.style.width = '50px';
  3562. this.exportDialog.style.height = '50px';
  3563. this.exportDialog.style.padding = '4px 2px 4px 2px';
  3564. this.exportDialog.style.color = '#ffffff';
  3565. mxUtils.setOpacity(this.exportDialog, 70);
  3566. this.exportDialog.style.left = r.left + 'px';
  3567. this.exportDialog.style.bottom = parseInt(this.chromelessToolbar.style.bottom) +
  3568. this.chromelessToolbar.offsetHeight + 4 + 'px';
  3569. // Puts the dialog on top of the container z-index
  3570. var style = mxUtils.getCurrentStyle(this.editor.graph.container);
  3571. this.exportDialog.style.zIndex = style.zIndex;
  3572. var spinner = new Spinner({
  3573. lines: 8, // The number of lines to draw
  3574. length: 6, // The length of each line
  3575. width: 5, // The line thickness
  3576. radius: 6, // The radius of the inner circle
  3577. rotate: 0, // The rotation offset
  3578. color: '#fff', // #rgb or #rrggbb
  3579. speed: 1.5, // Rounds per second
  3580. trail: 60, // Afterglow percentage
  3581. shadow: false, // Whether to render a shadow
  3582. hwaccel: false, // Whether to use hardware acceleration
  3583. top: '28px',
  3584. zIndex: 2e9 // The z-index (defaults to 2000000000)
  3585. });
  3586. spinner.spin(this.exportDialog);
  3587. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  3588. {
  3589. spinner.stop();
  3590. this.exportDialog.style.width = 'auto';
  3591. this.exportDialog.style.height = 'auto';
  3592. this.exportDialog.style.padding = '10px';
  3593. var data = this.createImageDataUri(canvas, null, 'png');
  3594. var img = document.createElement('img');
  3595. img.style.maxWidth = '140px';
  3596. img.style.maxHeight = '140px';
  3597. img.style.cursor = 'pointer';
  3598. img.style.backgroundColor = 'white';
  3599. img.setAttribute('title', mxResources.get('openInNewWindow'));
  3600. img.setAttribute('border', '0');
  3601. img.setAttribute('src', data);
  3602. this.exportDialog.appendChild(img);
  3603. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  3604. {
  3605. this.openInNewWindow(data.substring(data.indexOf(',') + 1), 'image/png', true);
  3606. clickHandler.apply(this, arguments);
  3607. }));
  3608. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  3609. {
  3610. this.spinner.stop();
  3611. this.handleError(e);
  3612. }));
  3613. mxEvent.addListener(this.editor.graph.container, 'click', clickHandler);
  3614. document.body.appendChild(this.exportDialog);
  3615. }
  3616. mxEvent.consume(evt);
  3617. }), Editor.cameraLargeImage, mxResources.get('export'));
  3618. }
  3619. editoUiAddChromelessToolbarItems.apply(this, arguments);
  3620. };
  3621. /**
  3622. * Translates this point by the given vector.
  3623. *
  3624. * @param {number} dx X-coordinate of the translation.
  3625. * @param {number} dy Y-coordinate of the translation.
  3626. */
  3627. EditorUi.prototype.saveData = function(filename, format, data, mime, base64Encoded)
  3628. {
  3629. if (this.isLocalFileSave())
  3630. {
  3631. this.saveLocalFile(data, filename, mime, base64Encoded, format);
  3632. }
  3633. else
  3634. {
  3635. this.saveRequest(filename, format, mxUtils.bind(this, function(newTitle, base64)
  3636. {
  3637. return this.createEchoRequest(data, newTitle, mime, base64Encoded, format, base64);
  3638. }), data, base64Encoded, mime);
  3639. }
  3640. };
  3641. /**
  3642. * Translates this point by the given vector.
  3643. *
  3644. * Last 3 argument are optional and must only be used if the data can be stored as is on the client
  3645. * side without requiring a server roundtrip.
  3646. *
  3647. * @param {number} dx X-coordinate of the translation.
  3648. * @param {number} dy Y-coordinate of the translation.
  3649. */
  3650. EditorUi.prototype.saveRequest = function(filename, format, fn, data, base64Encoded, mimeType, allowTab)
  3651. {
  3652. allowTab = (allowTab != null) ? allowTab : !mxClient.IS_IOS || !navigator.standalone;
  3653. var count = this.getServiceCount(false);
  3654. var dlg = new CreateDialog(this, filename, mxUtils.bind(this, function(newTitle, mode)
  3655. {
  3656. if (mode == '_blank' || newTitle != null && newTitle.length > 0)
  3657. {
  3658. var base64 = (mode == App.MODE_DEVICE || mode == 'download' || mode == null || mode == '_blank') ? '0' : '1';
  3659. var xhr = fn((mode == '_blank') ? null : newTitle, base64);
  3660. if (xhr != null)
  3661. {
  3662. if (mode == App.MODE_DEVICE || mode == 'download' || mode == '_blank')
  3663. {
  3664. xhr.simulate(document, '_blank');
  3665. }
  3666. else
  3667. {
  3668. this.pickFolder(mode, mxUtils.bind(this, function(folderId)
  3669. {
  3670. mimeType = (mimeType != null) ? mimeType : ((format == 'pdf') ?
  3671. 'application/pdf' : 'image/' + format);
  3672. // Workaround for no roundtrip required if data is available on client-side
  3673. // TODO: Refactor the saveData/saveRequest call chain for local data
  3674. if (data != null)
  3675. {
  3676. try
  3677. {
  3678. this.exportFile(data, newTitle, mimeType, true, mode, folderId);
  3679. }
  3680. catch (e)
  3681. {
  3682. this.handleError(e);
  3683. }
  3684. }
  3685. else if (this.spinner.spin(document.body, mxResources.get('saving')))
  3686. {
  3687. // LATER: Catch possible mixed content error
  3688. // see http://stackoverflow.com/questions/30646417/catching-mixed-content-error
  3689. xhr.send(mxUtils.bind(this, function()
  3690. {
  3691. this.spinner.stop();
  3692. if (xhr.getStatus() >= 200 && xhr.getStatus() <= 299)
  3693. {
  3694. try
  3695. {
  3696. this.exportFile(xhr.getText(), newTitle, mimeType, true, mode, folderId);
  3697. }
  3698. catch (e)
  3699. {
  3700. this.handleError(e);
  3701. }
  3702. }
  3703. else
  3704. {
  3705. this.handleError({message: mxResources.get('errorSavingFile')});
  3706. }
  3707. }), function(resp)
  3708. {
  3709. this.spinner.stop();
  3710. this.handleError(resp);
  3711. });
  3712. }
  3713. }));
  3714. }
  3715. }
  3716. }
  3717. }), mxUtils.bind(this, function()
  3718. {
  3719. this.hideDialog();
  3720. }), mxResources.get('saveAs'), mxResources.get('download'), false, false, allowTab,
  3721. null, count > 1, (count > 4) ? 3 : 4, data, mimeType, base64Encoded);
  3722. var noServices = 1; //(mxClient.IS_IOS) ? 0 : 1;
  3723. var height = (count == noServices) ? 160 : ((count > 4) ? 390 : 270);
  3724. this.showDialog(dlg.container, 380, height, true, true);
  3725. dlg.init();
  3726. };
  3727. /**
  3728. *
  3729. */
  3730. EditorUi.prototype.getEditBlankXml = function()
  3731. {
  3732. return this.getFileData(true);
  3733. };
  3734. /**
  3735. * Hook for subclassers.
  3736. */
  3737. EditorUi.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
  3738. {
  3739. // do nothing
  3740. };
  3741. /**
  3742. * Hook for subclassers.
  3743. */
  3744. EditorUi.prototype.pickFolder = function(mode, fn, enabled)
  3745. {
  3746. fn(null);
  3747. };
  3748. /**
  3749. *
  3750. */
  3751. EditorUi.prototype.exportSvg = function(scale, transparentBackground, ignoreSelection, addShadow,
  3752. editable, embedImages, border, noCrop, currentPage, linkTarget)
  3753. {
  3754. if (this.spinner.spin(document.body, mxResources.get('export')))
  3755. {
  3756. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  3757. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  3758. var bg = (transparentBackground) ? null : this.editor.graph.background;
  3759. if (bg == mxConstants.NONE)
  3760. {
  3761. bg = null;
  3762. }
  3763. // Handles special case where background is null but transparent is false
  3764. if (bg == null && transparentBackground == false)
  3765. {
  3766. bg = '#ffffff';
  3767. }
  3768. // Sets or disables alternate text for foreignObjects. Disabling is needed
  3769. // because PhantomJS seems to ignore switch statements and paint all text.
  3770. var svgRoot = this.editor.graph.getSvg(bg, scale, border, noCrop, null,
  3771. ignoreSelection, null, null, (linkTarget == 'blank') ? '_blank' :
  3772. ((linkTarget == 'self') ? '_top' : null));
  3773. if (addShadow)
  3774. {
  3775. this.editor.graph.addSvgShadow(svgRoot);
  3776. }
  3777. var filename = this.getBaseFilename() + '.svg';
  3778. var doSave = mxUtils.bind(this, function(svgRoot)
  3779. {
  3780. this.spinner.stop();
  3781. if (editable)
  3782. {
  3783. svgRoot.setAttribute('content', this.getFileData(true, null, null, null, ignoreSelection, currentPage));
  3784. }
  3785. if (this.editor.fontCss != null)
  3786. {
  3787. var svgDoc = svgRoot.ownerDocument;
  3788. var style = (svgDoc.createElementNS != null) ?
  3789. svgDoc.createElementNS(mxConstants.NS_SVG, 'style') : svgDoc.createElement('style');
  3790. style.setAttribute('type', 'text/css');
  3791. mxUtils.setTextContent(style, this.editor.fontCss);
  3792. svgRoot.getElementsByTagName('defs')[0].appendChild(style);
  3793. }
  3794. var svg = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
  3795. mxUtils.getXml(svgRoot);
  3796. if (this.isLocalFileSave() || svg.length <= MAX_REQUEST_SIZE)
  3797. {
  3798. this.saveData(filename, 'svg', svg, 'image/svg+xml');
  3799. }
  3800. else
  3801. {
  3802. this.handleError({message: mxResources.get('drawingTooLarge')}, mxResources.get('error'), mxUtils.bind(this, function()
  3803. {
  3804. mxUtils.popup(svg);
  3805. }));
  3806. }
  3807. });
  3808. this.convertMath(this.editor.graph, svgRoot, false, mxUtils.bind(this, function()
  3809. {
  3810. if (embedImages)
  3811. {
  3812. // Caches images
  3813. if (this.thumbImageCache == null)
  3814. {
  3815. this.thumbImageCache = new Object();
  3816. }
  3817. this.convertImages(svgRoot, doSave, this.thumbImageCache);
  3818. }
  3819. else
  3820. {
  3821. doSave(svgRoot);
  3822. }
  3823. }));
  3824. }
  3825. };
  3826. EditorUi.prototype.addRadiobox = function(div, radioGroupName, label, checked, disabled, disableNewline, visible)
  3827. {
  3828. return this.addCheckbox(div, label, checked, disabled, disableNewline, visible, true, radioGroupName);
  3829. }
  3830. /**
  3831. *
  3832. */
  3833. EditorUi.prototype.addCheckbox = function(div, label, checked, disabled, disableNewline, visible, asRadio, radioGroupName)
  3834. {
  3835. visible = (visible != null) ? visible : true;
  3836. var cb = document.createElement('input');
  3837. cb.style.marginRight = '8px';
  3838. cb.style.marginTop = '16px';
  3839. cb.setAttribute('type', asRadio? 'radio' : 'checkbox');
  3840. var id = 'geCheckbox-' + Editor.guid();
  3841. cb.id = id;
  3842. if (radioGroupName != null)
  3843. {
  3844. cb.setAttribute('name', radioGroupName);
  3845. }
  3846. if (checked)
  3847. {
  3848. cb.setAttribute('checked', 'checked');
  3849. cb.defaultChecked = true;
  3850. }
  3851. if (disabled)
  3852. {
  3853. cb.setAttribute('disabled', 'disabled');
  3854. }
  3855. if (visible)
  3856. {
  3857. div.appendChild(cb);
  3858. var lbl = document.createElement('label');
  3859. mxUtils.write(lbl, label);
  3860. lbl.setAttribute('for', id);
  3861. div.appendChild(lbl);
  3862. if (!disableNewline)
  3863. {
  3864. mxUtils.br(div);
  3865. }
  3866. }
  3867. return cb;
  3868. };
  3869. /**
  3870. *
  3871. */
  3872. EditorUi.prototype.addEditButton = function(div, lightbox)
  3873. {
  3874. var edit = this.addCheckbox(div, mxResources.get('edit') + ':', true, null, true);
  3875. edit.style.marginLeft = '24px';
  3876. var file = this.getCurrentFile();
  3877. var editUrl = '';
  3878. if (file != null && file.getMode() != App.MODE_DEVICE && file.getMode() != App.MODE_BROWSER)
  3879. {
  3880. editUrl = window.location.href;
  3881. }
  3882. var editSelect = document.createElement('select');
  3883. editSelect.style.width = '120px';
  3884. editSelect.style.marginLeft = '8px';
  3885. editSelect.style.marginRight = '10px';
  3886. editSelect.className = 'geBtn';
  3887. var blankOption = document.createElement('option');
  3888. blankOption.setAttribute('value', 'blank');
  3889. mxUtils.write(blankOption, mxResources.get('makeCopy'));
  3890. editSelect.appendChild(blankOption);
  3891. var customOption = document.createElement('option');
  3892. customOption.setAttribute('value', 'custom');
  3893. mxUtils.write(customOption, mxResources.get('custom') + '...');
  3894. editSelect.appendChild(customOption);
  3895. div.appendChild(editSelect);
  3896. mxEvent.addListener(editSelect, 'change', mxUtils.bind(this, function()
  3897. {
  3898. if (editSelect.value == 'custom')
  3899. {
  3900. var dlg2 = new FilenameDialog(this, editUrl, mxResources.get('ok'), function(value)
  3901. {
  3902. if (value != null)
  3903. {
  3904. editUrl = value;
  3905. }
  3906. else
  3907. {
  3908. editSelect.value = 'blank';
  3909. }
  3910. }, mxResources.get('url'), null, null, null, null, function()
  3911. {
  3912. editSelect.value = 'blank';
  3913. });
  3914. this.showDialog(dlg2.container, 300, 80, true, false);
  3915. dlg2.init();
  3916. }
  3917. }));
  3918. mxEvent.addListener(edit, 'change', mxUtils.bind(this, function()
  3919. {
  3920. if (edit.checked && (lightbox == null || lightbox.checked))
  3921. {
  3922. editSelect.removeAttribute('disabled');
  3923. }
  3924. else
  3925. {
  3926. editSelect.setAttribute('disabled', 'disabled');
  3927. }
  3928. }));
  3929. mxUtils.br(div);
  3930. return {
  3931. getLink: function()
  3932. {
  3933. return (edit.checked) ? ((editSelect.value === 'blank') ? '_blank' : editUrl) : null;
  3934. },
  3935. getEditInput: function()
  3936. {
  3937. return edit;
  3938. },
  3939. getEditSelect: function()
  3940. {
  3941. return editSelect;
  3942. }
  3943. };
  3944. }
  3945. /**
  3946. *
  3947. */
  3948. EditorUi.prototype.addLinkSection = function(div, showFrameOption)
  3949. {
  3950. mxUtils.write(div, mxResources.get('links') + ':');
  3951. var linkSelect = document.createElement('select');
  3952. linkSelect.style.width = '100px';
  3953. linkSelect.style.marginLeft = '8px';
  3954. linkSelect.style.marginRight = '10px';
  3955. linkSelect.className = 'geBtn';
  3956. var autoOption = document.createElement('option');
  3957. autoOption.setAttribute('value', 'auto');
  3958. mxUtils.write(autoOption, mxResources.get('automatic'));
  3959. linkSelect.appendChild(autoOption);
  3960. var blankOption = document.createElement('option');
  3961. blankOption.setAttribute('value', 'blank');
  3962. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  3963. linkSelect.appendChild(blankOption);
  3964. var selfOption = document.createElement('option');
  3965. selfOption.setAttribute('value', 'self');
  3966. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  3967. linkSelect.appendChild(selfOption);
  3968. if (showFrameOption)
  3969. {
  3970. var frameOption = document.createElement('option');
  3971. frameOption.setAttribute('value', 'frame');
  3972. mxUtils.write(frameOption, mxResources.get('openInThisWindow') +
  3973. ' (' + mxResources.get('iframe') + ')');
  3974. linkSelect.appendChild(frameOption);
  3975. }
  3976. div.appendChild(linkSelect);
  3977. mxUtils.write(div, mxResources.get('borderColor') + ':');
  3978. var linkColor = '#0000ff';
  3979. var linkButton = null;
  3980. function updateLinkColor()
  3981. {
  3982. linkButton.innerHTML = '<div style="width:100%;height:100%;box-sizing:border-box;' +
  3983. ((linkColor != null && linkColor != mxConstants.NONE) ?
  3984. 'border:1px solid black;background-color:' + linkColor :
  3985. 'background-position:center center;background-repeat:no-repeat;' +
  3986. 'background-image:url(\'' + Dialog.prototype.closeImage + '\')') + ';"></div>';
  3987. };
  3988. linkButton = mxUtils.button('', mxUtils.bind(this, function(evt)
  3989. {
  3990. this.pickColor(linkColor || 'none', function(color)
  3991. {
  3992. linkColor = color;
  3993. updateLinkColor();
  3994. });
  3995. mxEvent.consume(evt);
  3996. }));
  3997. updateLinkColor();
  3998. linkButton.style.padding = (mxClient.IS_FF) ? '4px 2px 4px 2px' : '4px';
  3999. linkButton.style.marginLeft = '4px';
  4000. linkButton.style.height = '22px';
  4001. linkButton.style.width = '22px';
  4002. linkButton.style.position = 'relative';
  4003. linkButton.style.top = (mxClient.IS_IE || mxClient.IS_IE11 || mxClient.IS_EDGE) ? '6px' : '1px';
  4004. linkButton.className = 'geColorBtn';
  4005. div.appendChild(linkButton);
  4006. mxUtils.br(div);
  4007. return {
  4008. getColor: function()
  4009. {
  4010. return linkColor;
  4011. },
  4012. getTarget: function()
  4013. {
  4014. return linkSelect.value;
  4015. },
  4016. focus: function()
  4017. {
  4018. linkSelect.focus();
  4019. }
  4020. };
  4021. }
  4022. /**
  4023. *
  4024. */
  4025. EditorUi.prototype.createLink = function(linkTarget, linkColor, allPages, lightbox, editLink, layers, url, ignoreFile)
  4026. {
  4027. var file = this.getCurrentFile();
  4028. var params = [];
  4029. if (lightbox)
  4030. {
  4031. params.push('lightbox=1');
  4032. if (linkTarget != 'auto')
  4033. {
  4034. params.push('target=' + linkTarget);
  4035. }
  4036. if (linkColor != null && linkColor != mxConstants.NONE)
  4037. {
  4038. params.push('highlight=' + ((linkColor.charAt(0) == '#') ? linkColor.substring(1) : linkColor));
  4039. }
  4040. if (editLink != null && editLink.length > 0)
  4041. {
  4042. params.push('edit=' + encodeURIComponent(editLink));
  4043. }
  4044. if (layers)
  4045. {
  4046. params.push('layers=1');
  4047. }
  4048. if (this.editor.graph.foldingEnabled)
  4049. {
  4050. params.push('nav=1');
  4051. }
  4052. }
  4053. if (allPages && this.currentPage != null && this.pages != null &&
  4054. this.currentPage != this.pages[0])
  4055. {
  4056. params.push('page-id=' + this.currentPage.getId());
  4057. }
  4058. var data = '';
  4059. var addTitle = true;
  4060. if (url != null)
  4061. {
  4062. data = '#U' + encodeURIComponent(url);
  4063. }
  4064. else
  4065. {
  4066. var file = this.getCurrentFile();
  4067. // Fallback to non-public URL for Drive files
  4068. if (!ignoreFile && file != null && file.constructor == window.DriveFile)
  4069. {
  4070. data = '#' + file.getHash();
  4071. addTitle = false;
  4072. }
  4073. else
  4074. {
  4075. data = '#R' + encodeURIComponent((allPages) ?
  4076. this.getFileData(true, null, null, null, null, null, null, true) :
  4077. Graph.compress(mxUtils.getXml(this.editor.getGraphXml())))
  4078. }
  4079. }
  4080. if (addTitle && file != null && file.getTitle() != null && file.getTitle() != this.defaultFilename)
  4081. {
  4082. params.push('title=' + encodeURIComponent(file.getTitle()));
  4083. }
  4084. return ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp || !(/.*\.draw\.io$/.test(window.location.hostname))) ?
  4085. EditorUi.drawHost : 'https://' + window.location.host + '/') +
  4086. ((params.length > 0) ? '?' + params.join('&') : '') + data;
  4087. };
  4088. /**
  4089. *
  4090. */
  4091. EditorUi.prototype.createHtml = function(publicUrl, zoomEnabled, initialZoom, linkTarget,
  4092. linkColor, fit, allPages, layers, lightbox, editLink, fn)
  4093. {
  4094. var s = this.getBasenames();
  4095. var data = {};
  4096. if (linkColor != '' && linkColor != mxConstants.NONE)
  4097. {
  4098. data.highlight = linkColor;
  4099. }
  4100. if (linkTarget !== 'auto')
  4101. {
  4102. data.target = linkTarget;
  4103. }
  4104. if (!lightbox)
  4105. {
  4106. data.lightbox = false;
  4107. }
  4108. data.nav = this.editor.graph.foldingEnabled;
  4109. var zoom = parseInt(initialZoom);
  4110. if (!isNaN(zoom) && zoom != 100)
  4111. {
  4112. data.zoom = zoom / 100;
  4113. }
  4114. var tb = [];
  4115. if (allPages)
  4116. {
  4117. tb.push('pages');
  4118. data.resize = true;
  4119. if (this.pages != null && this.currentPage != null)
  4120. {
  4121. data.page = mxUtils.indexOf(this.pages, this.currentPage);
  4122. }
  4123. }
  4124. if (zoomEnabled)
  4125. {
  4126. tb.push('zoom');
  4127. data.resize = true;
  4128. }
  4129. if (layers)
  4130. {
  4131. tb.push('layers');
  4132. }
  4133. if (tb.length > 0)
  4134. {
  4135. if (lightbox)
  4136. {
  4137. tb.push('lightbox');
  4138. }
  4139. data.toolbar = tb.join(' ');
  4140. }
  4141. if (editLink != null && editLink.length > 0)
  4142. {
  4143. data.edit = editLink;
  4144. }
  4145. if (publicUrl != null)
  4146. {
  4147. data.url = publicUrl;
  4148. }
  4149. else
  4150. {
  4151. data.xml = this.getFileData(true, null, null, null, null, !allPages);
  4152. }
  4153. var value = '<div class="mxgraph" style="' +
  4154. ((fit) ? 'max-width:100%;' : '') +
  4155. ((tb != '') ? 'border:1px solid transparent;' : '') +
  4156. '" data-mxgraph="' + mxUtils.htmlEntities(JSON.stringify(data)) + '"></div>';
  4157. var fetchParam = (publicUrl != null) ? '&fetch=' + encodeURIComponent(publicUrl) : '';
  4158. var s2 = (fetchParam.length > 0) ?
  4159. (((urlParams['dev'] == '1') ?
  4160. 'https://test.draw.io/embed2.js?dev=1' :
  4161. EditorUi.drawHost + '/embed2.js?')) + fetchParam :
  4162. (((urlParams['dev'] == '1') ?
  4163. 'https://test.draw.io/js/viewer.min.js' :
  4164. window.VIEWER_URL ? window.VIEWER_URL : EditorUi.drawHost + '/js/viewer.min.js'));
  4165. var scr = '<script type="text/javascript" src="' + s2 + '"></script>';
  4166. fn(value, scr);
  4167. };
  4168. /**
  4169. *
  4170. */
  4171. EditorUi.prototype.showHtmlDialog = function(btnLabel, helpLink, publicUrl, fn)
  4172. {
  4173. var div = document.createElement('div');
  4174. div.style.whiteSpace = 'nowrap';
  4175. var graph = this.editor.graph;
  4176. var hd = document.createElement('h3');
  4177. mxUtils.write(hd, mxResources.get('html'));
  4178. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4179. div.appendChild(hd);
  4180. var radioSection = document.createElement('div');
  4181. radioSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:8px;margin-bottom:12px;';
  4182. var publicUrlRadio = document.createElement('input');
  4183. publicUrlRadio.style.cssText = 'margin-right:8px;margin-top:8px;margin-bottom:8px;';
  4184. publicUrlRadio.setAttribute('value', 'url');
  4185. publicUrlRadio.setAttribute('type', 'radio');
  4186. publicUrlRadio.setAttribute('name', 'type-embedhtmldialog');
  4187. var copyRadio = publicUrlRadio.cloneNode(true);
  4188. copyRadio.setAttribute('value', 'copy');
  4189. radioSection.appendChild(copyRadio);
  4190. var span = document.createElement('span');
  4191. mxUtils.write(span, mxResources.get('includeCopyOfMyDiagram'));
  4192. radioSection.appendChild(span);
  4193. mxUtils.br(radioSection);
  4194. radioSection.appendChild(publicUrlRadio);
  4195. var span = document.createElement('span');
  4196. mxUtils.write(span, mxResources.get('publicDiagramUrl'));
  4197. radioSection.appendChild(span);
  4198. var file = this.getCurrentFile();
  4199. if (publicUrl == null && file != null && file.constructor == window.DriveFile)
  4200. {
  4201. var testLink = document.createElement('a');
  4202. testLink.style.paddingLeft = '12px';
  4203. testLink.style.color = 'gray';
  4204. testLink.setAttribute('href', 'javascript:void(0);');
  4205. mxUtils.write(testLink, mxResources.get('share'));
  4206. radioSection.appendChild(testLink);
  4207. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4208. {
  4209. this.hideDialog();
  4210. this.drive.showPermissions(file.getId());
  4211. }));
  4212. }
  4213. copyRadio.setAttribute('checked', 'checked');
  4214. if (publicUrl == null)
  4215. {
  4216. publicUrlRadio.setAttribute('disabled', 'disabled');
  4217. }
  4218. div.appendChild(radioSection);
  4219. var linkSection = this.addLinkSection(div);
  4220. var zoom = this.addCheckbox(div, mxResources.get('zoom'), true, null, true);
  4221. mxUtils.write(div, ':');
  4222. var zoomInput = document.createElement('input');
  4223. zoomInput.setAttribute('type', 'text');
  4224. zoomInput.style.marginRight = '16px';
  4225. zoomInput.style.width = '60px';
  4226. zoomInput.style.marginLeft = '4px';
  4227. zoomInput.style.marginRight = '12px';
  4228. zoomInput.value = '100%';
  4229. div.appendChild(zoomInput);
  4230. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4231. var hasPages = this.pages != null && this.pages.length > 1;
  4232. var allPages = allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4233. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4234. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4235. var editSection = this.addEditButton(div, lightbox);
  4236. var edit = editSection.getEditInput();
  4237. edit.style.marginBottom = '16px';
  4238. mxEvent.addListener(lightbox, 'change', function()
  4239. {
  4240. if (lightbox.checked)
  4241. {
  4242. edit.removeAttribute('disabled');
  4243. }
  4244. else
  4245. {
  4246. edit.setAttribute('disabled', 'disabled');
  4247. }
  4248. if (edit.checked && lightbox.checked)
  4249. {
  4250. editSection.getEditSelect().removeAttribute('disabled');
  4251. }
  4252. else
  4253. {
  4254. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4255. }
  4256. });
  4257. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4258. {
  4259. fn((publicUrlRadio.checked) ? publicUrl : null, zoom.checked, zoomInput.value, linkSection.getTarget(),
  4260. linkSection.getColor(), fit.checked, allPages.checked, layers.checked, lightbox.checked,
  4261. editSection.getLink());
  4262. }), null, btnLabel, helpLink);
  4263. this.showDialog(dlg.container, 340, 384, true, true);
  4264. copyRadio.focus();
  4265. };
  4266. /**
  4267. *
  4268. */
  4269. EditorUi.prototype.showPublishLinkDialog = function(title, hideShare, width, height, fn, showFrameOption)
  4270. {
  4271. var div = document.createElement('div');
  4272. div.style.whiteSpace = 'nowrap';
  4273. var graph = this.editor.graph;
  4274. var hd = document.createElement('h3');
  4275. mxUtils.write(hd, title || mxResources.get('link'));
  4276. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  4277. div.appendChild(hd);
  4278. var file = this.getCurrentFile();
  4279. var helpLink = 'https://desk.draw.io/support/solutions/articles/16000051941';
  4280. var dy = 0;
  4281. if (file != null && file.constructor == window.DriveFile && !hideShare)
  4282. {
  4283. dy = 80;
  4284. helpLink = 'https://desk.draw.io/support/solutions/articles/16000039384';
  4285. var hintSection = document.createElement('div');
  4286. hintSection.style.cssText = 'border-bottom:1px solid lightGray;padding-bottom:14px;padding-top:6px;margin-bottom:14px;text-align:center;';
  4287. var text = document.createElement('div');
  4288. text.style.whiteSpace = 'normal';
  4289. mxUtils.write(text, mxResources.get('linkAccountRequired'));
  4290. hintSection.appendChild(text);
  4291. var shareBtn = mxUtils.button(mxResources.get('share'), mxUtils.bind(this, function()
  4292. {
  4293. this.drive.showPermissions(file.getId());
  4294. }));
  4295. shareBtn.style.marginTop = '12px';
  4296. shareBtn.className = 'geBtn';
  4297. hintSection.appendChild(shareBtn);
  4298. div.appendChild(hintSection);
  4299. var testLink = document.createElement('a');
  4300. testLink.style.paddingLeft = '12px';
  4301. testLink.style.color = 'gray';
  4302. testLink.style.fontSize = '11px';
  4303. testLink.setAttribute('href', 'javascript:void(0);');
  4304. mxUtils.write(testLink, mxResources.get('check'));
  4305. hintSection.appendChild(testLink);
  4306. mxEvent.addListener(testLink, 'click', mxUtils.bind(this, function()
  4307. {
  4308. if (this.spinner.spin(document.body, mxResources.get('loading')))
  4309. {
  4310. this.getPublicUrl(this.getCurrentFile(), mxUtils.bind(this, function(url)
  4311. {
  4312. this.spinner.stop();
  4313. var dlg = new ErrorDialog(this, null, mxResources.get((url != null) ?
  4314. 'diagramIsPublic' : 'diagramIsNotPublic'), mxResources.get('ok'));
  4315. this.showDialog(dlg.container, 300, 80, true, false);
  4316. dlg.init();
  4317. }));
  4318. }
  4319. }));
  4320. }
  4321. var widthInput = null;
  4322. var heightInput = null;
  4323. if (width != null || height != null)
  4324. {
  4325. dy += 30;
  4326. mxUtils.write(div, mxResources.get('width') + ':');
  4327. widthInput = document.createElement('input');
  4328. widthInput.setAttribute('type', 'text');
  4329. widthInput.style.marginRight = '16px';
  4330. widthInput.style.width = '50px';
  4331. widthInput.style.marginLeft = '6px';
  4332. widthInput.style.marginRight = '16px';
  4333. widthInput.style.marginBottom = '10px';
  4334. widthInput.value = '100%';
  4335. div.appendChild(widthInput);
  4336. mxUtils.write(div, mxResources.get('height') + ':');
  4337. heightInput = document.createElement('input');
  4338. heightInput.setAttribute('type', 'text');
  4339. heightInput.style.width = '50px';
  4340. heightInput.style.marginLeft = '6px';
  4341. heightInput.style.marginBottom = '10px';
  4342. heightInput.value = height + 'px';
  4343. div.appendChild(heightInput);
  4344. mxUtils.br(div);
  4345. }
  4346. var linkSection = this.addLinkSection(div, showFrameOption);
  4347. var hasPages = this.pages != null && this.pages.length > 1;
  4348. var allPages = null;
  4349. if (file == null || file.constructor != window.DriveFile || hideShare)
  4350. {
  4351. allPages = this.addCheckbox(div, mxResources.get('allPages'), hasPages, !hasPages);
  4352. }
  4353. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4354. var editSection = this.addEditButton(div, lightbox);
  4355. var edit = editSection.getEditInput();
  4356. var layers = this.addCheckbox(div, mxResources.get('layers'), true);
  4357. layers.style.marginLeft = edit.style.marginLeft;
  4358. layers.style.marginBottom = '16px';
  4359. layers.style.marginTop = '8px';
  4360. mxEvent.addListener(lightbox, 'change', function()
  4361. {
  4362. if (lightbox.checked)
  4363. {
  4364. layers.removeAttribute('disabled');
  4365. edit.removeAttribute('disabled');
  4366. }
  4367. else
  4368. {
  4369. layers.setAttribute('disabled', 'disabled');
  4370. edit.setAttribute('disabled', 'disabled');
  4371. }
  4372. if (edit.checked && lightbox.checked)
  4373. {
  4374. editSection.getEditSelect().removeAttribute('disabled');
  4375. }
  4376. else
  4377. {
  4378. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4379. }
  4380. });
  4381. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4382. {
  4383. fn(linkSection.getTarget(), linkSection.getColor(),
  4384. (allPages == null) ? true : allPages.checked,
  4385. lightbox.checked, editSection.getLink(),
  4386. layers.checked, (widthInput != null) ? widthInput.value : null,
  4387. (heightInput != null) ? heightInput.value : null);
  4388. }), null, mxResources.get('create'), helpLink);
  4389. this.showDialog(dlg.container, 340, 254 + dy, true, true);
  4390. if (widthInput != null)
  4391. {
  4392. widthInput.focus();
  4393. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4394. {
  4395. widthInput.select();
  4396. }
  4397. else
  4398. {
  4399. document.execCommand('selectAll', false, null);
  4400. }
  4401. }
  4402. else
  4403. {
  4404. linkSection.focus();
  4405. }
  4406. };
  4407. /**
  4408. *
  4409. */
  4410. EditorUi.prototype.showRemoteExportDialog = function(btnLabel, helpLink, callback, hideInclude, showZoomBorder)
  4411. {
  4412. var div = document.createElement('div');
  4413. div.style.whiteSpace = 'nowrap';
  4414. var hd = document.createElement('h3');
  4415. mxUtils.write(hd, mxResources.get('image'));
  4416. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:' + (showZoomBorder? '10' : '4') +'px';
  4417. div.appendChild(hd);
  4418. if (showZoomBorder)
  4419. {
  4420. mxUtils.write(div, mxResources.get('zoom') + ':');
  4421. var zoomInput = document.createElement('input');
  4422. zoomInput.setAttribute('type', 'text');
  4423. zoomInput.style.marginRight = '16px';
  4424. zoomInput.style.width = '60px';
  4425. zoomInput.style.marginLeft = '4px';
  4426. zoomInput.style.marginRight = '12px';
  4427. zoomInput.value = this.lastExportZoom || '100%';
  4428. div.appendChild(zoomInput);
  4429. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  4430. var borderInput = document.createElement('input');
  4431. borderInput.setAttribute('type', 'text');
  4432. borderInput.style.marginRight = '16px';
  4433. borderInput.style.width = '60px';
  4434. borderInput.style.marginLeft = '4px';
  4435. borderInput.value = this.lastExportBorder || '0';
  4436. div.appendChild(borderInput);
  4437. mxUtils.br(div);
  4438. }
  4439. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'), false,
  4440. this.editor.graph.isSelectionEmpty());
  4441. var include = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), true);
  4442. var graph = this.editor.graph;
  4443. var transparent = (hideInclude) ? null : this.addCheckbox(div, mxResources.get('transparentBackground'),
  4444. graph.background == mxConstants.NONE || graph.background == null);
  4445. if (transparent != null)
  4446. {
  4447. transparent.style.marginBottom = '16px';
  4448. }
  4449. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4450. {
  4451. var scale = parseInt(zoomInput.value) / 100 || 1;
  4452. var border = parseInt(borderInput.value) || 0;
  4453. callback(!selection.checked, (include != null) ? include.checked : false,
  4454. (transparent != null) ? transparent.checked : false, scale, border);
  4455. }), null, btnLabel, helpLink);
  4456. this.showDialog(dlg.container, 300, (showZoomBorder? 25 : 0) + (hideInclude ? 125 : 210), true, true);
  4457. };
  4458. /**
  4459. *
  4460. */
  4461. EditorUi.prototype.showExportDialog = function(title, embedOption, btnLabel, helpLink, callback,
  4462. cropOption, defaultInclude, format)
  4463. {
  4464. defaultInclude = (defaultInclude != null) ? defaultInclude : true;
  4465. var div = document.createElement('div');
  4466. div.style.whiteSpace = 'nowrap';
  4467. var graph = this.editor.graph;
  4468. var height = (format == 'jpeg') ? 196 : 300;
  4469. var hd = document.createElement('h3');
  4470. mxUtils.write(hd, title);
  4471. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:10px';
  4472. div.appendChild(hd);
  4473. mxUtils.write(div, mxResources.get('zoom') + ':');
  4474. var zoomInput = document.createElement('input');
  4475. zoomInput.setAttribute('type', 'text');
  4476. zoomInput.style.marginRight = '16px';
  4477. zoomInput.style.width = '60px';
  4478. zoomInput.style.marginLeft = '4px';
  4479. zoomInput.style.marginRight = '12px';
  4480. zoomInput.value = this.lastExportZoom || '100%';
  4481. div.appendChild(zoomInput);
  4482. mxUtils.write(div, mxResources.get('borderWidth') + ':');
  4483. var borderInput = document.createElement('input');
  4484. borderInput.setAttribute('type', 'text');
  4485. borderInput.style.marginRight = '16px';
  4486. borderInput.style.width = '60px';
  4487. borderInput.style.marginLeft = '4px';
  4488. borderInput.value = this.lastExportBorder || '0';
  4489. div.appendChild(borderInput);
  4490. mxUtils.br(div);
  4491. var defaultTransparent = false; /*graph.background == mxConstants.NONE || graph.background == null*/;
  4492. var transparent = this.addCheckbox(div, mxResources.get('transparentBackground'),
  4493. defaultTransparent, null, null, format != 'jpeg');
  4494. var selection = this.addCheckbox(div, mxResources.get('selectionOnly'),
  4495. false, graph.isSelectionEmpty());
  4496. var cb6 = document.createElement('input');
  4497. cb6.style.marginTop = '16px';
  4498. cb6.style.marginRight = '8px';
  4499. cb6.style.marginLeft = '24px';
  4500. cb6.setAttribute('disabled', 'disabled');
  4501. cb6.setAttribute('type', 'checkbox');
  4502. if (cropOption)
  4503. {
  4504. div.appendChild(cb6);
  4505. mxUtils.write(div, mxResources.get('crop'));
  4506. mxUtils.br(div);
  4507. height += 26;
  4508. mxEvent.addListener(selection, 'change', function()
  4509. {
  4510. if (selection.checked)
  4511. {
  4512. cb6.removeAttribute('disabled');
  4513. }
  4514. else
  4515. {
  4516. cb6.setAttribute('disabled', 'disabled');
  4517. }
  4518. });
  4519. }
  4520. if (!graph.isSelectionEmpty())
  4521. {
  4522. cb6.setAttribute('checked', 'checked');
  4523. cb6.defaultChecked = true;
  4524. }
  4525. var shadow = this.addCheckbox(div, mxResources.get('shadow'), graph.shadowVisible);
  4526. var cb5 = document.createElement('input');
  4527. cb5.style.marginTop = '16px';
  4528. cb5.style.marginRight = '8px';
  4529. cb5.setAttribute('type', 'checkbox');
  4530. if (this.isOffline() || !this.canvasSupported)
  4531. {
  4532. cb5.setAttribute('disabled', 'disabled');
  4533. }
  4534. if (embedOption)
  4535. {
  4536. div.appendChild(cb5);
  4537. mxUtils.write(div, mxResources.get('embedImages'));
  4538. mxUtils.br(div);
  4539. height += 26;
  4540. }
  4541. var include = this.addCheckbox(div, mxResources.get('includeCopyOfMyDiagram'), defaultInclude, null, null, format != 'jpeg');
  4542. var hasPages = this.pages != null && this.pages.length > 1;
  4543. var allPages = this.addCheckbox(div, (hasPages) ? mxResources.get('allPages') : '', hasPages, !hasPages, null, format != 'jpeg');
  4544. allPages.style.marginLeft = '24px';
  4545. allPages.style.marginBottom = '16px';
  4546. if (!hasPages)
  4547. {
  4548. allPages.style.display = 'none';
  4549. }
  4550. mxEvent.addListener(include, 'change', function()
  4551. {
  4552. if (include.checked && hasPages)
  4553. {
  4554. allPages.removeAttribute('disabled');
  4555. }
  4556. else
  4557. {
  4558. allPages.setAttribute('disabled', 'disabled');
  4559. }
  4560. });
  4561. if (!defaultInclude || !hasPages)
  4562. {
  4563. allPages.setAttribute('disabled', 'disabled');
  4564. }
  4565. var linkSelect = document.createElement('select');
  4566. linkSelect.style.maxWidth = '260px';
  4567. linkSelect.style.marginLeft = '8px';
  4568. linkSelect.style.marginRight = '10px';
  4569. linkSelect.className = 'geBtn';
  4570. var autoOption = document.createElement('option');
  4571. autoOption.setAttribute('value', 'auto');
  4572. mxUtils.write(autoOption, mxResources.get('automatic'));
  4573. linkSelect.appendChild(autoOption);
  4574. var blankOption = document.createElement('option');
  4575. blankOption.setAttribute('value', 'blank');
  4576. mxUtils.write(blankOption, mxResources.get('openInNewWindow'));
  4577. linkSelect.appendChild(blankOption);
  4578. var selfOption = document.createElement('option');
  4579. selfOption.setAttribute('value', 'self');
  4580. mxUtils.write(selfOption, mxResources.get('openInThisWindow'));
  4581. linkSelect.appendChild(selfOption);
  4582. if (format == 'svg')
  4583. {
  4584. mxUtils.write(div, mxResources.get('links') + ':');
  4585. div.appendChild(linkSelect);
  4586. mxUtils.br(div);
  4587. mxUtils.br(div);
  4588. height += 26;
  4589. }
  4590. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4591. {
  4592. this.lastExportBorder = borderInput.value;
  4593. this.lastExportZoom = zoomInput.value;
  4594. callback(zoomInput.value, transparent.checked, !selection.checked, shadow.checked,
  4595. include.checked, cb5.checked, borderInput.value, cb6.checked, !allPages.checked,
  4596. linkSelect.value);
  4597. }), null, btnLabel, helpLink);
  4598. this.showDialog(dlg.container, 340, height, true, true, null, null, null, null, true);
  4599. zoomInput.focus();
  4600. if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5 || mxClient.IS_QUIRKS)
  4601. {
  4602. zoomInput.select();
  4603. }
  4604. else
  4605. {
  4606. document.execCommand('selectAll', false, null);
  4607. }
  4608. };
  4609. /**
  4610. *
  4611. */
  4612. EditorUi.prototype.showEmbedImageDialog = function(fn, title, imageLabel, shadowEnabled, helpLink)
  4613. {
  4614. var div = document.createElement('div');
  4615. div.style.whiteSpace = 'nowrap';
  4616. var graph = this.editor.graph;
  4617. if (title != null)
  4618. {
  4619. var hd = document.createElement('h3');
  4620. mxUtils.write(hd, title);
  4621. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
  4622. div.appendChild(hd);
  4623. }
  4624. var fit = this.addCheckbox(div, mxResources.get('fit'), true);
  4625. var shadow = this.addCheckbox(div, mxResources.get('shadow'),
  4626. graph.shadowVisible && shadowEnabled, !shadowEnabled);
  4627. var image = this.addCheckbox(div, imageLabel);
  4628. var lightbox = this.addCheckbox(div, mxResources.get('lightbox'), true);
  4629. var editSection = this.addEditButton(div, lightbox);
  4630. var edit = editSection.getEditInput();
  4631. var hasLayers = graph.model.getChildCount(graph.model.getRoot()) > 1;
  4632. var layers = this.addCheckbox(div, mxResources.get('layers'), hasLayers, !hasLayers);
  4633. layers.style.marginLeft = edit.style.marginLeft;
  4634. layers.style.marginBottom = '12px';
  4635. layers.style.marginTop = '8px';
  4636. mxEvent.addListener(lightbox, 'change', function()
  4637. {
  4638. if (lightbox.checked)
  4639. {
  4640. if (hasLayers)
  4641. {
  4642. layers.removeAttribute('disabled');
  4643. }
  4644. edit.removeAttribute('disabled');
  4645. }
  4646. else
  4647. {
  4648. layers.setAttribute('disabled', 'disabled');
  4649. edit.setAttribute('disabled', 'disabled');
  4650. }
  4651. if (edit.checked && lightbox.checked)
  4652. {
  4653. editSection.getEditSelect().removeAttribute('disabled');
  4654. }
  4655. else
  4656. {
  4657. editSection.getEditSelect().setAttribute('disabled', 'disabled');
  4658. }
  4659. });
  4660. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  4661. {
  4662. fn(fit.checked, shadow.checked, image.checked, lightbox.checked,
  4663. editSection.getLink(), layers.checked);
  4664. }), null, mxResources.get('embed'), helpLink);
  4665. this.showDialog(dlg.container, 280, 280, true, true);
  4666. };
  4667. /**
  4668. *
  4669. */
  4670. EditorUi.prototype.createEmbedImage = function(fit, shadow, retina, lightbox, edit, layers, fn, err)
  4671. {
  4672. var bounds = this.editor.graph.getGraphBounds();
  4673. function doUpdate(dataUri)
  4674. {
  4675. var onclick = ' ';
  4676. var css = '';
  4677. // Adds double click handling
  4678. if (lightbox)
  4679. {
  4680. // KNOWN: Message passing does not seem to work in IE11
  4681. 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(" +
  4682. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4683. ((edit) ? "&edit=_blank" : "") +
  4684. ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4685. css += 'cursor:pointer;';
  4686. }
  4687. if (fit)
  4688. {
  4689. css += 'max-width:100%;';
  4690. }
  4691. var atts = '';
  4692. if (retina)
  4693. {
  4694. atts = ' width="' + Math.round(bounds.width) + '" height="' + Math.round(bounds.height) + '"';
  4695. }
  4696. fn('<img src="' + dataUri + '"' + atts + ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4697. };
  4698. if (this.isExportToCanvas())
  4699. {
  4700. var scale = 1;
  4701. var ignoreSelection = true;
  4702. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  4703. {
  4704. var xml = (lightbox) ? this.getFileData(true) : null;
  4705. var data = this.createImageDataUri(canvas, xml, 'png');
  4706. doUpdate(data);
  4707. }), null, null, null, mxUtils.bind(this, function(e)
  4708. {
  4709. err({message: mxResources.get('unknownError')});
  4710. }), null, true, (retina) ? 2 : 1, null, shadow);
  4711. }
  4712. else
  4713. {
  4714. var data = this.getFileData(true);
  4715. if (bounds.width * bounds.height <= MAX_AREA && data.length <= MAX_REQUEST_SIZE)
  4716. {
  4717. var size = '';
  4718. if (retina)
  4719. {
  4720. size = '&w=' + Math.round(2 * bounds.width) +
  4721. '&h=' + Math.round(2 * bounds.height);
  4722. }
  4723. var embed = (lightbox) ? '1' : '0';
  4724. var req = new mxXmlRequest(EXPORT_URL, 'format=png' +
  4725. '&base64=1&embedXml=' + embed + size + '&xml=' +
  4726. encodeURIComponent(data));
  4727. // LATER: Updates on each change, add a delay
  4728. req.send(mxUtils.bind(this, function()
  4729. {
  4730. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  4731. {
  4732. // Fixes possible "incorrect function" for select() on
  4733. // DOM node which is no longer in document with IE11
  4734. doUpdate('data:image/png;base64,' + req.getText());
  4735. }
  4736. else
  4737. {
  4738. err({message: mxResources.get('unknownError')});
  4739. }
  4740. }));
  4741. }
  4742. else
  4743. {
  4744. err({message: mxResources.get('drawingTooLarge')});
  4745. }
  4746. }
  4747. };
  4748. /**
  4749. *
  4750. */
  4751. EditorUi.prototype.createEmbedSvg = function(fit, shadow, image, lightbox, edit, layers, fn)
  4752. {
  4753. var svgRoot = this.editor.graph.getSvg();
  4754. // Keeps hashtag links on same page
  4755. var links = svgRoot.getElementsByTagName('a');
  4756. if (links != null)
  4757. {
  4758. for (var i = 0; i < links.length; i++)
  4759. {
  4760. var href = links[i].getAttribute('href');
  4761. if (href != null && href.charAt(0) == '#' &&
  4762. links[i].getAttribute('target') == '_blank')
  4763. {
  4764. links[i].removeAttribute('target');
  4765. }
  4766. }
  4767. }
  4768. if (lightbox)
  4769. {
  4770. svgRoot.setAttribute('content', this.getFileData(true));
  4771. }
  4772. // Adds shadow filter
  4773. if (shadow)
  4774. {
  4775. this.editor.graph.addSvgShadow(svgRoot);
  4776. }
  4777. // SVG inside image tag
  4778. if (image)
  4779. {
  4780. var onclick = ' ';
  4781. var css = '';
  4782. // Adds double click handling
  4783. if (lightbox)
  4784. {
  4785. // KNOWN: Message passing does not seem to work in IE11
  4786. 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(" +
  4787. "img.getAttribute('src')),'*');window.removeEventListener('message',r);}};window.addEventListener('message',r);img.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4788. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}})(this);\"";
  4789. css += 'cursor:pointer;';
  4790. }
  4791. if (fit)
  4792. {
  4793. css += 'max-width:100%;';
  4794. }
  4795. // Images inside IMG don't seem to work so embed them all
  4796. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  4797. {
  4798. fn('<img src="' + this.createSvgDataUri(mxUtils.getXml(svgRoot)) + '"' +
  4799. ((css != '') ? ' style="' + css + '"' : '') + onclick + '/>');
  4800. }));
  4801. }
  4802. else
  4803. {
  4804. var css = '';
  4805. // Adds double click handling
  4806. if (lightbox)
  4807. {
  4808. // KNOWN: Message passing does not seem to work in IE11
  4809. var js = "(function(svg){var src=window.event.target||window.event.srcElement;" +
  4810. // Ignores link events
  4811. "while (src!=null&&src.nodeName.toLowerCase()!='a'){src=src.parentNode;}if(src==null)" +
  4812. // Focus existing lightbox
  4813. "{if(svg.wnd!=null&&!svg.wnd.closed){svg.wnd.focus();}else{var r=function(evt){" +
  4814. // Message handling
  4815. "if(evt.data=='ready'&&evt.source==svg.wnd){svg.wnd.postMessage(decodeURIComponent(" +
  4816. "svg.getAttribute('content')),'*');window.removeEventListener('message',r);}};" +
  4817. "window.addEventListener('message',r);" +
  4818. // Opens lightbox window
  4819. "svg.wnd=window.open('" + EditorUi.drawHost + "/?client=1&lightbox=1" +
  4820. ((edit) ? "&edit=_blank" : "") + ((layers) ? '&layers=1' : '') + "');}}})(this);";
  4821. svgRoot.setAttribute('onclick', js);
  4822. css += 'cursor:pointer;';
  4823. }
  4824. // Adds responsive size
  4825. if (fit)
  4826. {
  4827. var w = parseInt(svgRoot.getAttribute('width'));
  4828. var h = parseInt(svgRoot.getAttribute('height'));
  4829. svgRoot.setAttribute('viewBox', '-0.5 -0.5 ' + w + ' ' + h);
  4830. css += 'max-width:100%;max-height:' + h + 'px;';
  4831. svgRoot.removeAttribute('height');
  4832. }
  4833. if (css != '')
  4834. {
  4835. svgRoot.setAttribute('style', css);
  4836. }
  4837. fn(mxUtils.getXml(svgRoot));
  4838. }
  4839. };
  4840. /**
  4841. * Translates this point by the given vector.
  4842. *
  4843. * @param {number} dx X-coordinate of the translation.
  4844. * @param {number} dy Y-coordinate of the translation.
  4845. */
  4846. EditorUi.prototype.timeSince = function(date)
  4847. {
  4848. var seconds = Math.floor((new Date() - date) / 1000);
  4849. var interval = Math.floor(seconds / 31536000);
  4850. if (interval > 1)
  4851. {
  4852. return interval + ' ' + mxResources.get('years');
  4853. }
  4854. interval = Math.floor(seconds / 2592000);
  4855. if (interval > 1)
  4856. {
  4857. return interval + ' ' + mxResources.get('months');
  4858. }
  4859. interval = Math.floor(seconds / 86400);
  4860. if (interval > 1)
  4861. {
  4862. return interval + ' ' + mxResources.get('days');
  4863. }
  4864. interval = Math.floor(seconds / 3600);
  4865. if (interval > 1)
  4866. {
  4867. return interval + ' ' + mxResources.get('hours');
  4868. }
  4869. interval = Math.floor(seconds / 60);
  4870. if (interval > 1)
  4871. {
  4872. return interval + ' ' + mxResources.get('minutes');
  4873. }
  4874. if (interval == 1)
  4875. {
  4876. return interval + ' ' + mxResources.get('minute');
  4877. }
  4878. return null;
  4879. };
  4880. /**
  4881. * Converts math in the given SVG
  4882. */
  4883. EditorUi.prototype.convertMath = function(graph, svgRoot, fixPosition, callback)
  4884. {
  4885. if (graph.mathEnabled && typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
  4886. {
  4887. // Temporarily attaches to DOM for rendering
  4888. // FIXME: If adding svgRoot to body, the text
  4889. // value of the math is appended, if not
  4890. // added to DOM then LaTeX does not work.
  4891. // This must be fixed to enable client-side export
  4892. // if math is enabled.
  4893. // document.body.appendChild(svgRoot);
  4894. Editor.MathJaxRender(svgRoot);
  4895. window.setTimeout(mxUtils.bind(this, function()
  4896. {
  4897. MathJax.Hub.Queue(mxUtils.bind(this, function ()
  4898. {
  4899. // Removes from DOM
  4900. // svgRoot.parentNode.removeChild(svgRoot);
  4901. callback();
  4902. }));
  4903. }), 0);
  4904. }
  4905. else
  4906. {
  4907. callback();
  4908. }
  4909. };
  4910. /**
  4911. *
  4912. */
  4913. EditorUi.prototype.decodeNodeIntoGraph = function(node, graph)
  4914. {
  4915. if (node != null)
  4916. {
  4917. var diagramNode = null;
  4918. if (node.nodeName == 'diagram')
  4919. {
  4920. diagramNode = node;
  4921. }
  4922. else if (node.nodeName == 'mxfile')
  4923. {
  4924. var diagrams = node.getElementsByTagName('diagram');
  4925. if (diagrams.length > 0)
  4926. {
  4927. diagramNode = diagrams[0];
  4928. var graphGetGlobalVariable = graph.getGlobalVariable;
  4929. graph.getGlobalVariable = function(name)
  4930. {
  4931. if (name == 'page')
  4932. {
  4933. return diagramNode.getAttribute('name') || mxResources.get('pageWithNumber', [1])
  4934. }
  4935. else if (name == 'pagenumber')
  4936. {
  4937. return 1;
  4938. }
  4939. return graphGetGlobalVariable.apply(this, arguments);
  4940. };
  4941. }
  4942. }
  4943. if (diagramNode != null)
  4944. {
  4945. var tmp = Graph.decompress(mxUtils.getTextContent(diagramNode));
  4946. if (tmp != null && tmp.length > 0)
  4947. {
  4948. node = mxUtils.parseXml(tmp).documentElement;
  4949. }
  4950. }
  4951. }
  4952. // Hack to decode XML into temp graph via editor
  4953. var prev = this.editor.graph;
  4954. try
  4955. {
  4956. this.editor.graph = graph;
  4957. this.editor.setGraphXml(node);
  4958. }
  4959. catch (e)
  4960. {
  4961. // ignore
  4962. }
  4963. finally
  4964. {
  4965. this.editor.graph = prev;
  4966. }
  4967. return node;
  4968. };
  4969. /**
  4970. *
  4971. */
  4972. EditorUi.prototype.getEmbeddedPng = function(success, error, optionalData)
  4973. {
  4974. try
  4975. {
  4976. var graph = this.editor.graph;
  4977. var diagramData = null;
  4978. // Exports PNG for given optional data
  4979. if (optionalData != null && optionalData.length > 0)
  4980. {
  4981. graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
  4982. document.body.appendChild(graph.container);
  4983. this.decodeNodeIntoGraph(this.editor.extractGraphModel(
  4984. mxUtils.parseXml(optionalData).documentElement, true), graph);
  4985. diagramData = optionalData;
  4986. }
  4987. // Exports PNG for first page while other page is showing
  4988. else if (this.pages != null && this.currentPage != this.pages[0])
  4989. {
  4990. graph = this.createTemporaryGraph(graph.getStylesheet());
  4991. var graphGetGlobalVariable = graph.getGlobalVariable;
  4992. var page = this.pages[0];
  4993. graph.getGlobalVariable = function(name)
  4994. {
  4995. if (name == 'page')
  4996. {
  4997. return page.getName();
  4998. }
  4999. else if (name == 'pagenumber')
  5000. {
  5001. return 1;
  5002. }
  5003. return graphGetGlobalVariable.apply(this, arguments);
  5004. };
  5005. document.body.appendChild(graph.container);
  5006. graph.model.setRoot(page.root);
  5007. }
  5008. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  5009. {
  5010. try
  5011. {
  5012. if (diagramData == null)
  5013. {
  5014. diagramData = this.getFileData(true);
  5015. }
  5016. var data = canvas.toDataURL('image/png');
  5017. data = this.writeGraphModelToPng(data, 'zTXt', 'mxGraphModel',
  5018. atob(Graph.compress(diagramData)));
  5019. success(data.substring(data.lastIndexOf(',') + 1));
  5020. // Removes temporary graph from DOM
  5021. if (graph != this.editor.graph)
  5022. {
  5023. graph.container.parentNode.removeChild(graph.container);
  5024. }
  5025. }
  5026. catch (e)
  5027. {
  5028. if (error != null)
  5029. {
  5030. error(e);
  5031. }
  5032. }
  5033. }), null, null, null, mxUtils.bind(this, function(e)
  5034. {
  5035. if (error != null)
  5036. {
  5037. error(e);
  5038. }
  5039. }), null, null, null, null, graph.shadowVisible, null, graph);
  5040. }
  5041. catch (e)
  5042. {
  5043. if (error != null)
  5044. {
  5045. error(e);
  5046. }
  5047. }
  5048. }
  5049. /**
  5050. * Returns the SVG of the diagram with embedded XML. If a callback function is
  5051. * used, the images are converted to data URIs.
  5052. */
  5053. EditorUi.prototype.getEmbeddedSvg = function(xml, graph, url, noHeader, callback, ignoreSelection, redirect)
  5054. {
  5055. var bg = graph.background;
  5056. if (bg == mxConstants.NONE)
  5057. {
  5058. bg = null;
  5059. }
  5060. // Sets or disables alternate text for foreignObjects. Disabling is needed
  5061. // because PhantomJS seems to ignore switch statements and paint all text.
  5062. var svgRoot = graph.getSvg(bg, null, null, null, null, ignoreSelection);
  5063. if (graph.shadowVisible)
  5064. {
  5065. graph.addSvgShadow(svgRoot);
  5066. }
  5067. if (xml != null)
  5068. {
  5069. svgRoot.setAttribute('content', xml);
  5070. }
  5071. if (url != null)
  5072. {
  5073. svgRoot.setAttribute('resource', url);
  5074. }
  5075. // LATER: Click on SVG content to start editing
  5076. // if (redirect != null)
  5077. // {
  5078. // // TODO: Ignore anchor tag source for click event
  5079. // svgRoot.setAttribute('style', 'cursor:pointer;');
  5080. // svgRoot.setAttribute('onclick', 'window.location.href=\'' + redirect + '\';');
  5081. // }
  5082. if (callback != null)
  5083. {
  5084. this.convertImages(svgRoot, mxUtils.bind(this, function(svgRoot)
  5085. {
  5086. callback(((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5087. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5088. mxUtils.getXml(svgRoot));
  5089. }));
  5090. }
  5091. else
  5092. {
  5093. return ((!noHeader) ? '<?xml version="1.0" encoding="UTF-8"?>\n' +
  5094. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' : '') +
  5095. mxUtils.getXml(svgRoot);
  5096. }
  5097. };
  5098. /**
  5099. *
  5100. */
  5101. EditorUi.prototype.exportImage = function(scale, transparentBackground, ignoreSelection, addShadow, editable, border, noCrop, currentPage, format)
  5102. {
  5103. format = (format != null) ? format : 'png';
  5104. if (this.spinner.spin(document.body, mxResources.get('exporting')))
  5105. {
  5106. var selectionEmpty = this.editor.graph.isSelectionEmpty();
  5107. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : selectionEmpty;
  5108. // Caches images
  5109. if (this.thumbImageCache == null)
  5110. {
  5111. this.thumbImageCache = new Object();
  5112. }
  5113. try
  5114. {
  5115. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  5116. {
  5117. this.spinner.stop();
  5118. try
  5119. {
  5120. this.saveCanvas(canvas, (editable) ? this.getFileData(true, null,
  5121. null, null, ignoreSelection, currentPage) : null, format);
  5122. }
  5123. catch (e)
  5124. {
  5125. // Fallback to server-side image export
  5126. if (e.message == 'Invalid image')
  5127. {
  5128. this.downloadFile(format);
  5129. }
  5130. else
  5131. {
  5132. this.handleError(e);
  5133. }
  5134. }
  5135. }), null, this.thumbImageCache, null, mxUtils.bind(this, function(e)
  5136. {
  5137. this.spinner.stop();
  5138. this.handleError(e);
  5139. }), null, ignoreSelection, scale || 1, transparentBackground,
  5140. addShadow, null, null, border, noCrop);
  5141. }
  5142. catch (e)
  5143. {
  5144. this.spinner.stop();
  5145. this.handleError(e);
  5146. }
  5147. }
  5148. };
  5149. /**
  5150. * For the fontCSS to be applied when rendering images on canvas, the actual
  5151. * font data must be made available via a data URI encoding of the file.
  5152. */
  5153. EditorUi.prototype.loadFonts = function(then)
  5154. {
  5155. if (this.editor.fontCss != null && this.editor.resolvedFontCss == null)
  5156. {
  5157. var parts = this.editor.fontCss.split('url(');
  5158. var waiting = 0;
  5159. var fonts = {};
  5160. // Strips leading and trailing quotes and spaces
  5161. function trimString(str)
  5162. {
  5163. return str.replace(new RegExp("^[\\s\"']+", "g"), "").replace(new RegExp("[\\s\"']+$", "g"), "");
  5164. };
  5165. var finish = mxUtils.bind(this, function()
  5166. {
  5167. if (waiting == 0)
  5168. {
  5169. // Constructs string
  5170. var result = [parts[0]];
  5171. for (var j = 1; j < parts.length; j++)
  5172. {
  5173. var idx = parts[j].indexOf(')');
  5174. result.push('url("');
  5175. result.push(fonts[trimString(parts[j].substring(0, idx))]);
  5176. result.push('"' + parts[j].substring(idx));
  5177. }
  5178. this.editor.resolvedFontCss = result.join('');
  5179. then();
  5180. }
  5181. });
  5182. if (parts.length > 0)
  5183. {
  5184. for (var i = 1; i < parts.length; i++)
  5185. {
  5186. var idx = parts[i].indexOf(')');
  5187. var format = null;
  5188. // Checks if there is a format directive
  5189. var fmtIdx = parts[i].indexOf('format(', idx);
  5190. if (fmtIdx > 0)
  5191. {
  5192. format = trimString(parts[i].substring(fmtIdx + 7, parts[i].indexOf(')', fmtIdx)));
  5193. }
  5194. (mxUtils.bind(this, function(url)
  5195. {
  5196. if (fonts[url] == null)
  5197. {
  5198. // Mark font es being fetched and fetch it
  5199. fonts[url] = url;
  5200. waiting++;
  5201. var mime = 'application/x-font-ttf';
  5202. // See https://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
  5203. if (format == 'svg' || /(\.svg)($|\?)/i.test(url))
  5204. {
  5205. mime = 'image/svg+xml';
  5206. }
  5207. else if (format == 'otf' || format == 'embedded-opentype' || /(\.otf)($|\?)/i.test(url))
  5208. {
  5209. mime = 'application/x-font-opentype';
  5210. }
  5211. else if (format == 'woff' || /(\.woff)($|\?)/i.test(url))
  5212. {
  5213. mime = 'application/font-woff';
  5214. }
  5215. else if (format == 'woff2' || /(\.woff2)($|\?)/i.test(url))
  5216. {
  5217. mime = 'application/font-woff2';
  5218. }
  5219. else if (format == 'eot' || /(\.eot)($|\?)/i.test(url))
  5220. {
  5221. mime = 'application/vnd.ms-fontobject';
  5222. }
  5223. else if (format == 'sfnt' || /(\.sfnt)($|\?)/i.test(url))
  5224. {
  5225. mime = 'application/font-sfnt';
  5226. }
  5227. var realUrl = url;
  5228. if ((/^https?:\/\//.test(realUrl)) && !this.editor.isCorsEnabledForUrl(realUrl))
  5229. {
  5230. realUrl = PROXY_URL + '?url=' + encodeURIComponent(url);
  5231. }
  5232. // LATER: Remove cache-control header
  5233. this.loadUrl(realUrl, mxUtils.bind(this, function(uri)
  5234. {
  5235. fonts[url] = uri;
  5236. waiting--;
  5237. finish();
  5238. }), mxUtils.bind(this, function(err)
  5239. {
  5240. // LATER: handle error
  5241. waiting--;
  5242. finish();
  5243. }), true, null, 'data:' + mime + ';charset=utf-8;base64,');
  5244. }
  5245. }))(trimString(parts[i].substring(0, idx)), format);
  5246. }
  5247. }
  5248. }
  5249. else
  5250. {
  5251. then();
  5252. }
  5253. };
  5254. /**
  5255. *
  5256. */
  5257. EditorUi.prototype.exportToCanvas = function(callback, width, imageCache, background, error, limitHeight,
  5258. ignoreSelection, scale, transparentBackground, addShadow, converter, graph, border, noCrop)
  5259. {
  5260. limitHeight = (limitHeight != null) ? limitHeight : true;
  5261. ignoreSelection = (ignoreSelection != null) ? ignoreSelection : true;
  5262. graph = (graph != null) ? graph : this.editor.graph;
  5263. border = (border != null) ? border : 0;
  5264. var bg = (transparentBackground) ? null : graph.background;
  5265. if (bg == mxConstants.NONE)
  5266. {
  5267. bg = null;
  5268. }
  5269. if (bg == null)
  5270. {
  5271. bg = background;
  5272. }
  5273. // Handles special case where background is null but transparent is false
  5274. if (bg == null && transparentBackground == false)
  5275. {
  5276. bg = '#ffffff';
  5277. }
  5278. this.convertImages(graph.getSvg(bg, null, null, noCrop, null, ignoreSelection, null, null, null, addShadow),
  5279. mxUtils.bind(this, function(svgRoot)
  5280. {
  5281. var img = new Image();
  5282. img.onload = mxUtils.bind(this, function()
  5283. {
  5284. try
  5285. {
  5286. var canvas = document.createElement('canvas');
  5287. var w = parseInt(svgRoot.getAttribute('width'));
  5288. var h = parseInt(svgRoot.getAttribute('height'));
  5289. scale = (scale != null) ? scale : 1;
  5290. if (width != null)
  5291. {
  5292. scale = (!limitHeight) ? width / w : Math.min(1, Math.min((width * 3) / (h * 4), width / w));
  5293. }
  5294. w = Math.ceil(scale * w) + 2 * border;
  5295. h = Math.ceil(scale * h) + 2 * border;
  5296. canvas.setAttribute('width', w);
  5297. canvas.setAttribute('height', h);
  5298. var ctx = canvas.getContext('2d');
  5299. if (bg != null)
  5300. {
  5301. ctx.beginPath();
  5302. ctx.rect(0, 0, w, h);
  5303. ctx.fillStyle = bg;
  5304. ctx.fill();
  5305. }
  5306. ctx.scale(scale, scale);
  5307. // Workaround for broken data URI images in Safari on first export
  5308. if (mxClient.IS_SF)
  5309. {
  5310. window.setTimeout(function()
  5311. {
  5312. ctx.drawImage(img, border / scale, border / scale);
  5313. callback(canvas);
  5314. }, 0);
  5315. }
  5316. else
  5317. {
  5318. ctx.drawImage(img, border / scale, border / scale);
  5319. callback(canvas);
  5320. }
  5321. }
  5322. catch (e)
  5323. {
  5324. if (error != null)
  5325. {
  5326. error(e);
  5327. }
  5328. }
  5329. });
  5330. img.onerror = function(e)
  5331. {
  5332. //console.log('img', e, img.src);
  5333. if (error != null)
  5334. {
  5335. error(e);
  5336. }
  5337. };
  5338. try
  5339. {
  5340. if (addShadow)
  5341. {
  5342. this.editor.graph.addSvgShadow(svgRoot);
  5343. }
  5344. var done = mxUtils.bind(this, function()
  5345. {
  5346. if (this.editor.resolvedFontCss != null)
  5347. {
  5348. var st = document.createElement('style');
  5349. st.setAttribute('type', 'text/css');
  5350. st.innerHTML = this.editor.resolvedFontCss;
  5351. // Must be in defs section for FF to work
  5352. var defs = svgRoot.getElementsByTagName('defs');
  5353. defs[0].appendChild(st);
  5354. }
  5355. this.convertMath(graph, svgRoot, true, mxUtils.bind(this, function()
  5356. {
  5357. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  5358. }));
  5359. });
  5360. this.loadFonts(done);
  5361. }
  5362. catch (e)
  5363. {
  5364. //console.log('src', e, img.src);
  5365. if (error != null)
  5366. {
  5367. error(e);
  5368. }
  5369. }
  5370. }), imageCache, converter);
  5371. };
  5372. /**
  5373. * Converts all images in the SVG output to data URIs for immediate rendering
  5374. */
  5375. EditorUi.prototype.createImageUrlConverter = function()
  5376. {
  5377. var converter = new mxUrlConverter();
  5378. converter.updateBaseUrl();
  5379. // Extends convert to avoid CORS using an image proxy server where needed
  5380. var convert = converter.convert;
  5381. var self = this;
  5382. converter.convert = function(src)
  5383. {
  5384. if (src != null)
  5385. {
  5386. var remote = src.substring(0, 7) == 'http://' || src.substring(0, 8) == 'https://';
  5387. if (remote && !navigator.onLine)
  5388. {
  5389. src = self.svgBrokenImage.src;
  5390. }
  5391. else if (remote && src.substring(0, converter.baseUrl.length) != converter.baseUrl &&
  5392. (!self.crossOriginImages || !self.editor.isCorsEnabledForUrl(src)))
  5393. {
  5394. src = PROXY_URL + '?url=' + encodeURIComponent(src);
  5395. }
  5396. else if (src.substring(0, 19) != 'chrome-extension://')
  5397. {
  5398. src = convert.apply(this, arguments);
  5399. }
  5400. }
  5401. return src;
  5402. };
  5403. return converter;
  5404. };
  5405. /**
  5406. * Converts all images in the SVG output to data URIs for immediate rendering
  5407. */
  5408. EditorUi.prototype.convertImages = function(svgRoot, callback, imageCache, converter)
  5409. {
  5410. // Converts images to data URLs for immediate painting
  5411. if (converter == null)
  5412. {
  5413. converter = this.createImageUrlConverter();
  5414. }
  5415. // Barrier for asynchronous image loading
  5416. var counter = 0;
  5417. function inc()
  5418. {
  5419. counter++;
  5420. };
  5421. function dec()
  5422. {
  5423. counter--;
  5424. if (counter == 0)
  5425. {
  5426. callback(svgRoot);
  5427. }
  5428. };
  5429. var cache = imageCache || new Object();
  5430. var convertImages = mxUtils.bind(this, function(tagName, srcAttr)
  5431. {
  5432. var images = svgRoot.getElementsByTagName(tagName);
  5433. for (var i = 0; i < images.length; i++)
  5434. {
  5435. (mxUtils.bind(this, function(img)
  5436. {
  5437. var src = converter.convert(img.getAttribute(srcAttr));
  5438. // Data URIs are pass-through
  5439. if (src != null && src.substring(0, 5) != 'data:')
  5440. {
  5441. var tmp = cache[src];
  5442. if (tmp == null)
  5443. {
  5444. inc();
  5445. this.convertImageToDataUri(src, function(uri)
  5446. {
  5447. if (uri != null)
  5448. {
  5449. cache[src] = uri;
  5450. img.setAttribute(srcAttr, uri);
  5451. }
  5452. dec();
  5453. });
  5454. }
  5455. else
  5456. {
  5457. img.setAttribute(srcAttr, tmp);
  5458. }
  5459. }
  5460. else if (src != null)
  5461. {
  5462. img.setAttribute(srcAttr, src);
  5463. }
  5464. }))(images[i]);
  5465. }
  5466. });
  5467. // Converts all known image tags in output
  5468. // LATER: Add support for images in CSS
  5469. convertImages('image', 'xlink:href');
  5470. convertImages('img', 'src');
  5471. // All from cache or no images
  5472. if (counter == 0)
  5473. {
  5474. callback(svgRoot);
  5475. }
  5476. };
  5477. /**
  5478. * Checks if the client is authorized and calls the next step.
  5479. */
  5480. EditorUi.prototype.loadUrl = function(url, success, error, forceBinary, retry, dataUriPrefix, noBinary)
  5481. {
  5482. try
  5483. {
  5484. var binary = !noBinary && (forceBinary || /(\.png)($|\?)/i.test(url) ||
  5485. /(\.jpe?g)($|\?)/i.test(url) || /(\.gif)($|\?)/i.test(url));
  5486. retry = (retry != null) ? retry : true;
  5487. var fn = mxUtils.bind(this, function()
  5488. {
  5489. mxUtils.get(url, mxUtils.bind(this, function(req)
  5490. {
  5491. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  5492. {
  5493. if (success != null)
  5494. {
  5495. var data = req.getText();
  5496. // Returns PNG as base64 encoded data URI
  5497. if (binary)
  5498. {
  5499. // NOTE: This requires BinaryToArray VB script in the page
  5500. if ((document.documentMode == 9 || document.documentMode == 10) &&
  5501. typeof window.mxUtilsBinaryToArray !== 'undefined')
  5502. {
  5503. var bin = mxUtilsBinaryToArray(req.request.responseBody).toArray();
  5504. var tmp = new Array(bin.length);
  5505. for (var i = 0; i < bin.length; i++)
  5506. {
  5507. tmp[i] = String.fromCharCode(bin[i]);
  5508. }
  5509. data = tmp.join('');
  5510. }
  5511. // LATER: Could be JPG but modern browsers
  5512. // ignore the mime type in the data URI
  5513. dataUriPrefix = (dataUriPrefix != null) ? dataUriPrefix : 'data:image/png;base64,';
  5514. data = dataUriPrefix + this.base64Encode(data);
  5515. }
  5516. success(data);
  5517. }
  5518. }
  5519. else if (error != null)
  5520. {
  5521. error({message: mxResources.get('error') + ' ' + req.getStatus()}, req);
  5522. }
  5523. }), function(req)
  5524. {
  5525. if (error != null)
  5526. {
  5527. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  5528. }
  5529. }, binary, this.timeout, function()
  5530. {
  5531. if (retry && error != null)
  5532. {
  5533. error({code: App.ERROR_TIMEOUT, retry: fn});
  5534. }
  5535. });
  5536. });
  5537. fn();
  5538. }
  5539. catch (e)
  5540. {
  5541. if (error != null)
  5542. {
  5543. error(e);
  5544. }
  5545. }
  5546. };
  5547. /**
  5548. * Returns true if the given URL is known to have CORS headers.
  5549. */
  5550. EditorUi.prototype.isCorsEnabledForUrl = function(url)
  5551. {
  5552. return this.editor.isCorsEnabledForUrl(url);
  5553. };
  5554. /**
  5555. * Translates this point by the given vector.
  5556. *
  5557. * @param {number} dx X-coordinate of the translation.
  5558. * @param {number} dy Y-coordinate of the translation.
  5559. */
  5560. EditorUi.prototype.convertImageToDataUri = function(url, callback)
  5561. {
  5562. if (/(\.svg)$/i.test(url))
  5563. {
  5564. mxUtils.get(url, mxUtils.bind(this, function(req)
  5565. {
  5566. callback(this.createSvgDataUri(req.getText()));
  5567. }),
  5568. function()
  5569. {
  5570. callback(this.svgBrokenImage.src);
  5571. });
  5572. }
  5573. else
  5574. {
  5575. var img = new Image();
  5576. var self = this;
  5577. if (this.crossOriginImages)
  5578. {
  5579. img.crossOrigin = 'anonymous';
  5580. }
  5581. img.onload = function()
  5582. {
  5583. var canvas = document.createElement('canvas');
  5584. var ctx = canvas.getContext('2d');
  5585. canvas.height = img.height;
  5586. canvas.width = img.width;
  5587. ctx.drawImage(img, 0, 0);
  5588. try
  5589. {
  5590. callback(canvas.toDataURL());
  5591. }
  5592. catch (e)
  5593. {
  5594. callback(self.svgBrokenImage.src);
  5595. }
  5596. };
  5597. img.onerror = function()
  5598. {
  5599. callback(self.svgBrokenImage.src);
  5600. };
  5601. img.src = url;
  5602. }
  5603. };
  5604. /**
  5605. * Handling drag and drop and import.
  5606. */
  5607. /**
  5608. * Imports the given XML into the existing diagram.
  5609. */
  5610. EditorUi.prototype.importXml = function(xml, dx, dy, crop, noErrorHandling)
  5611. {
  5612. dx = (dx != null) ? dx : 0;
  5613. dy = (dy != null) ? dy : 0;
  5614. var cells = []
  5615. try
  5616. {
  5617. var graph = this.editor.graph;
  5618. if (xml != null && xml.length > 0)
  5619. {
  5620. // Adds pages
  5621. graph.model.beginUpdate();
  5622. try
  5623. {
  5624. var doc = mxUtils.parseXml(xml);
  5625. // Checks for mxfile with multiple pages
  5626. var node = this.editor.extractGraphModel(doc.documentElement, this.pages != null);
  5627. if (node != null && node.nodeName == 'mxfile' && this.pages != null)
  5628. {
  5629. var diagrams = node.getElementsByTagName('diagram');
  5630. if (diagrams.length == 1)
  5631. {
  5632. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5633. }
  5634. else if (diagrams.length > 1)
  5635. {
  5636. var mapping = {};
  5637. var pages = [];
  5638. var i0 = 0;
  5639. // Adds first page to current page if current page is only page and empty
  5640. if (this.pages != null && this.pages.length == 1 && this.isDiagramEmpty())
  5641. {
  5642. node = mxUtils.parseXml(Graph.decompress(mxUtils.getTextContent(diagrams[0]))).documentElement;
  5643. crop = false;
  5644. i0 = 1;
  5645. }
  5646. for (var i = i0; i < diagrams.length; i++)
  5647. {
  5648. // Imported pages must obtain a new ID and
  5649. // all links to pages must be updated below
  5650. var oldId = diagrams[i].getAttribute('id')
  5651. diagrams[i].removeAttribute('id');
  5652. var page = this.updatePageRoot(new DiagramPage(diagrams[i]));
  5653. mapping[oldId] = diagrams[i].getAttribute('id');
  5654. var index = this.pages.length;
  5655. // Checks for invalid page names
  5656. if (page.getName() == null)
  5657. {
  5658. page.setName(mxResources.get('pageWithNumber', [index + 1]));
  5659. }
  5660. graph.model.execute(new ChangePage(this, page, page, index, true));
  5661. pages.push(page);
  5662. }
  5663. this.updatePageLinks(mapping, pages);
  5664. }
  5665. }
  5666. if (node != null && node.nodeName === 'mxGraphModel')
  5667. {
  5668. cells = graph.importGraphModel(node, dx, dy, crop);
  5669. }
  5670. }
  5671. finally
  5672. {
  5673. graph.model.endUpdate();
  5674. }
  5675. }
  5676. }
  5677. catch (e)
  5678. {
  5679. if (!noErrorHandling)
  5680. {
  5681. this.handleError(e);
  5682. }
  5683. else
  5684. {
  5685. throw e;
  5686. }
  5687. }
  5688. return cells;
  5689. };
  5690. /**
  5691. * Updates links to pages in shapes and labels.
  5692. */
  5693. EditorUi.prototype.updatePageLinks = function(mapping, pages)
  5694. {
  5695. for (var i = 0; i < pages.length; i++)
  5696. {
  5697. this.updatePageLinksForCell(mapping, pages[i].root);
  5698. }
  5699. };
  5700. /**
  5701. * Updates links to pages in shapes and labels.
  5702. */
  5703. EditorUi.prototype.updatePageLinksForCell = function(mapping, cell)
  5704. {
  5705. var temp = document.createElement('div');
  5706. var graph = this.editor.graph;
  5707. var href = graph.getLinkForCell(cell);
  5708. if (href != null && href.substring(0, 13) == 'data:page/id,')
  5709. {
  5710. graph.setLinkForCell(cell, this.updatePageLink(mapping, href));
  5711. }
  5712. if (graph.isHtmlLabel(cell))
  5713. {
  5714. temp.innerHTML = graph.getLabel(cell);
  5715. var links = temp.getElementsByTagName('a');
  5716. var changed = false;
  5717. for (var i = 0; i < links.length; i++)
  5718. {
  5719. href = links[i].getAttribute('href');
  5720. if (href != null && href.substring(0, 13) == 'data:page/id,')
  5721. {
  5722. links[i].setAttribute('href', this.updatePageLink(mapping, href));
  5723. changed = true;
  5724. }
  5725. }
  5726. if (changed)
  5727. {
  5728. graph.labelChanged(cell, temp.innerHTML);
  5729. }
  5730. }
  5731. for (var i = 0; i < graph.model.getChildCount(cell); i++)
  5732. {
  5733. this.updatePageLinksForCell(mapping, graph.model.getChildAt(cell, i));
  5734. }
  5735. };
  5736. /**
  5737. * Updates links to pages in shapes and labels.
  5738. */
  5739. EditorUi.prototype.updatePageLink = function(mapping, href)
  5740. {
  5741. var newId = mapping[href.substring(href.indexOf(',') + 1)];
  5742. return (newId != null) ? 'data:page/id,' + newId : null;
  5743. };
  5744. /**
  5745. * Returns true for VSD, VDX and VSS, VSX files.
  5746. */
  5747. EditorUi.prototype.isRemoteVisioFormat = function(filename)
  5748. {
  5749. return /(\.v(sd|dx))($|\?)/i.test(filename) || /(\.vs(s|x))($|\?)/i.test(filename);
  5750. };
  5751. /**
  5752. * Imports the given Visio file
  5753. */
  5754. EditorUi.prototype.importVisio = function(file, done, onerror, filename)
  5755. {
  5756. filename = (filename != null) ? filename : file.name;
  5757. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5758. {
  5759. this.handleError(e);
  5760. });
  5761. var delayed = mxUtils.bind(this, function()
  5762. {
  5763. this.loadingExtensions = false;
  5764. if (this.doImportVisio)
  5765. {
  5766. if (this.isRemoteVisioFormat(filename) && VSD_CONVERT_URL != null)
  5767. {
  5768. var formData = new FormData();
  5769. formData.append('file1', file, filename);
  5770. var xhr = new XMLHttpRequest();
  5771. xhr.open('POST', VSD_CONVERT_URL);
  5772. xhr.responseType = 'blob';
  5773. xhr.onreadystatechange = mxUtils.bind(this, function()
  5774. {
  5775. if (xhr.readyState == 4)
  5776. {
  5777. if (xhr.status >= 200 && xhr.status <= 299)
  5778. {
  5779. try
  5780. {
  5781. this.doImportVisio(xhr.response, done, onerror, filename);
  5782. }
  5783. catch (e)
  5784. {
  5785. onerror(e);
  5786. }
  5787. }
  5788. else
  5789. {
  5790. onerror({});
  5791. }
  5792. }
  5793. });
  5794. xhr.send(formData);
  5795. }
  5796. else
  5797. {
  5798. try
  5799. {
  5800. this.doImportVisio(file, done, onerror, filename);
  5801. }
  5802. catch (e)
  5803. {
  5804. onerror(e);
  5805. }
  5806. }
  5807. }
  5808. else
  5809. {
  5810. this.spinner.stop();
  5811. this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
  5812. }
  5813. });
  5814. if (!this.doImportVisio && !this.loadingExtensions && !this.isOffline(true))
  5815. {
  5816. this.loadingExtensions = true;
  5817. mxscript('js/extensions.min.js', delayed);
  5818. }
  5819. else
  5820. {
  5821. delayed();
  5822. }
  5823. };
  5824. /**
  5825. * Imports the given GraphML (yEd) file
  5826. */
  5827. EditorUi.prototype.importGraphML = function(xmlData, done, onerror)
  5828. {
  5829. onerror = (onerror != null) ? onerror : mxUtils.bind(this, function(e)
  5830. {
  5831. this.handleError(e);
  5832. });
  5833. var delayed = mxUtils.bind(this, function()
  5834. {
  5835. this.loadingExtensions = false;
  5836. if (this.doImportGraphML)
  5837. {
  5838. try
  5839. {
  5840. this.doImportGraphML(xmlData, done, onerror);
  5841. }
  5842. catch (e)
  5843. {
  5844. onerror(e);
  5845. }
  5846. }
  5847. else
  5848. {
  5849. this.spinner.stop();
  5850. this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
  5851. }
  5852. });
  5853. if (!this.doImportGraphML && !this.loadingExtensions && !this.isOffline(true))
  5854. {
  5855. this.loadingExtensions = true;
  5856. mxscript('js/extensions.min.js', delayed);
  5857. }
  5858. else
  5859. {
  5860. delayed();
  5861. }
  5862. };
  5863. /**
  5864. * Export the diagram to VSDX
  5865. */
  5866. EditorUi.prototype.exportVisio = function()
  5867. {
  5868. var delayed = mxUtils.bind(this, function()
  5869. {
  5870. this.loadingExtensions = false;
  5871. if (typeof VsdxExport !== 'undefined')
  5872. {
  5873. try
  5874. {
  5875. var expSuccess = new VsdxExport(this).exportCurrentDiagrams();
  5876. if (!expSuccess)
  5877. {
  5878. this.handleError({message: mxResources.get('unknownError')});
  5879. }
  5880. }
  5881. catch (e)
  5882. {
  5883. this.handleError(e);
  5884. }
  5885. }
  5886. else
  5887. {
  5888. this.spinner.stop();
  5889. this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
  5890. }
  5891. });
  5892. if (typeof VsdxExport === 'undefined' && !this.loadingExtensions && !this.isOffline(true))
  5893. {
  5894. this.loadingExtensions = true;
  5895. mxscript('js/extensions.min.js', delayed);
  5896. }
  5897. else
  5898. {
  5899. delayed();
  5900. }
  5901. };
  5902. /**
  5903. * Imports the given Lucidchart data.
  5904. */
  5905. EditorUi.prototype.convertLucidChart = function(data, success, error)
  5906. {
  5907. var delayed = mxUtils.bind(this, function()
  5908. {
  5909. this.loadingExtensions = false;
  5910. // Checks for signature method
  5911. if (typeof window.LucidImporter !== 'undefined')
  5912. {
  5913. try
  5914. {
  5915. success(LucidImporter.importState(JSON.parse(data)));
  5916. }
  5917. catch (e)
  5918. {
  5919. error(e);
  5920. }
  5921. }
  5922. else
  5923. {
  5924. error({message: mxResources.get('serviceUnavailableOrBlocked')});
  5925. }
  5926. });
  5927. if (typeof window.LucidImporter === 'undefined' &&
  5928. !this.loadingExtensions && !this.isOffline(true))
  5929. {
  5930. this.loadingExtensions = true;
  5931. if (urlParams['dev'] == '1')
  5932. {
  5933. mxscript('js/diagramly/Extensions.js', delayed);
  5934. }
  5935. else
  5936. {
  5937. mxscript('js/extensions.min.js', delayed);
  5938. }
  5939. }
  5940. else
  5941. {
  5942. // Async needed for selection
  5943. window.setTimeout(delayed, 0);
  5944. }
  5945. };
  5946. /**
  5947. * Inserts the given text as a preformatted HTML text.
  5948. */
  5949. EditorUi.prototype.insertAsPreText = function(text, x, y)
  5950. {
  5951. var graph = this.editor.graph;
  5952. var cell = null;
  5953. graph.getModel().beginUpdate();
  5954. try
  5955. {
  5956. cell = graph.insertVertex(null, null, '<pre>' + text + '</pre>',
  5957. x, y, 1, 1, 'text;html=1;align=center;verticalAlign=middle;');
  5958. graph.updateCellSize(cell, true);
  5959. }
  5960. finally
  5961. {
  5962. graph.getModel().endUpdate();
  5963. }
  5964. return cell;
  5965. };
  5966. /**
  5967. * Imports the given XML into the existing diagram.
  5968. * TODO: Make this function asynchronous
  5969. */
  5970. EditorUi.prototype.insertTextAt = function(text, dx, dy, html, asImage, crop, resizeImages)
  5971. {
  5972. crop = (crop != null) ? crop : true;
  5973. resizeImages = (resizeImages != null) ? resizeImages : true;
  5974. // Handles special case for Gliffy data which requires async server-side for parsing
  5975. if (text != null)
  5976. {
  5977. if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(text))
  5978. {
  5979. // Fixes possible parsing problems with ASCII 160 (non-breaking space)
  5980. this.parseFile(new Blob([text.replace(/\s+/g,' ')], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  5981. {
  5982. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299)
  5983. {
  5984. this.editor.graph.setSelectionCells(this.insertTextAt(
  5985. xhr.responseText, dx, dy, true));
  5986. }
  5987. }));
  5988. // Returns empty cells array as it is aysynchronous
  5989. return [];
  5990. }
  5991. // Handles special case of data URI which requires async loading for finding size
  5992. else if (text.substring(0, 5) == 'data:' || (!this.isOffline() &&
  5993. (asImage || (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(text))))
  5994. {
  5995. var graph = this.editor.graph;
  5996. // Checks for embedded XML in PNG
  5997. if (text.substring(0, 22) == 'data:image/png;base64,')
  5998. {
  5999. var xml = this.extractGraphModelFromPng(text);
  6000. var result = this.importXml(xml, dx, dy, crop, true);
  6001. if (result.length > 0)
  6002. {
  6003. return result;
  6004. }
  6005. }
  6006. // Tries to extract embedded XML from SVG data URI
  6007. if (text.substring(0, 19) == 'data:image/svg+xml;')
  6008. {
  6009. try
  6010. {
  6011. var xml = null;
  6012. if (text.substring(0, 26) == 'data:image/svg+xml;base64,')
  6013. {
  6014. xml = text.substring(text.indexOf(',') + 1);
  6015. xml = (window.atob && !mxClient.IS_SF) ? atob(xml) : Base64.decode(xml, true);
  6016. }
  6017. else
  6018. {
  6019. xml = decodeURIComponent(text.substring(text.indexOf(',') + 1));
  6020. }
  6021. var result = this.importXml(xml, dx, dy, crop, true);
  6022. if (result.length > 0)
  6023. {
  6024. return result;
  6025. }
  6026. }
  6027. catch (e)
  6028. {
  6029. // Ignore
  6030. }
  6031. }
  6032. this.loadImage(text, mxUtils.bind(this, function(img)
  6033. {
  6034. if (text.substring(0, 5) == 'data:')
  6035. {
  6036. this.resizeImage(img, text, mxUtils.bind(this, function(data2, w2, h2)
  6037. {
  6038. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  6039. w2, h2, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6040. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + this.convertDataUri(data2) + ';'));
  6041. }), resizeImages, this.maxImageSize);
  6042. }
  6043. else
  6044. {
  6045. var s = Math.min(1, Math.min(this.maxImageSize / img.width, this.maxImageSize / img.height));
  6046. var w = Math.round(img.width * s);
  6047. var h = Math.round(img.height * s);
  6048. graph.setSelectionCell(graph.insertVertex(null, null, '', graph.snap(dx), graph.snap(dy),
  6049. w, h, 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6050. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + text + ';'));
  6051. }
  6052. }), mxUtils.bind(this, function()
  6053. {
  6054. var cell = null;
  6055. // Inserts invalid data URIs as text
  6056. graph.getModel().beginUpdate();
  6057. try
  6058. {
  6059. cell = graph.insertVertex(graph.getDefaultParent(), null, text,
  6060. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  6061. graph.updateCellSize(cell);
  6062. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  6063. }
  6064. finally
  6065. {
  6066. graph.getModel().endUpdate();
  6067. }
  6068. graph.setSelectionCell(cell);
  6069. }));
  6070. return [];
  6071. }
  6072. else
  6073. {
  6074. text = Graph.zapGremlins(mxUtils.trim(text));
  6075. if (this.isCompatibleString(text))
  6076. {
  6077. return this.importXml(text, dx, dy, crop);
  6078. }
  6079. else if (text.length > 0)
  6080. {
  6081. if (this.isLucidChartData(text))
  6082. {
  6083. this.convertLucidChart(text, mxUtils.bind(this, function(xml)
  6084. {
  6085. this.editor.graph.setSelectionCells(
  6086. this.importXml(xml, dx, dy, crop));
  6087. }), mxUtils.bind(this, function(e)
  6088. {
  6089. this.handleError(e);
  6090. }));
  6091. }
  6092. else
  6093. {
  6094. var graph = this.editor.graph;
  6095. var cell = null;
  6096. graph.getModel().beginUpdate();
  6097. try
  6098. {
  6099. // Fires cellsInserted to apply the current style to the inserted text.
  6100. // This requires the value to be empty when the event is fired.
  6101. cell = graph.insertVertex(graph.getDefaultParent(), null, '',
  6102. graph.snap(dx), graph.snap(dy), 1, 1, 'text;' + ((html) ? 'html=1;' : ''));
  6103. graph.fireEvent(new mxEventObject('textInserted', 'cells', [cell]));
  6104. // Single tag is converted
  6105. if (text.charAt(0) == '<' && text.indexOf('>') == text.length - 1)
  6106. {
  6107. text = mxUtils.htmlEntities(text);
  6108. }
  6109. //TODO Refuse unsupported file types early as at this stage a lot of processing has beed done and time is wasted.
  6110. // For example, 5 MB PDF files is processed and then only 0.5 MB of meaningless text is added!
  6111. //Limit labels to maxTextBytes
  6112. if (text.length > this.maxTextBytes)
  6113. {
  6114. text = text.substring(0, this.maxTextBytes) + '...';
  6115. }
  6116. // Apply value and updates the cell size to fit the text block
  6117. cell.value = text;
  6118. graph.updateCellSize(cell);
  6119. // See http://stackoverflow.com/questions/6927719/url-regex-does-not-work-in-javascript
  6120. 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;
  6121. if (regexp.test(cell.value))
  6122. {
  6123. graph.setLinkForCell(cell, cell.value);
  6124. }
  6125. // Adds spacing
  6126. cell.geometry.width += graph.gridSize;
  6127. cell.geometry.height += graph.gridSize;
  6128. }
  6129. finally
  6130. {
  6131. graph.getModel().endUpdate();
  6132. }
  6133. return [cell];
  6134. }
  6135. }
  6136. }
  6137. }
  6138. return [];
  6139. };
  6140. /**
  6141. * Formats the given file size.
  6142. */
  6143. EditorUi.prototype.formatFileSize = function(size)
  6144. {
  6145. var units = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
  6146. var i = -1;
  6147. do
  6148. {
  6149. size = size / 1024;
  6150. i++;
  6151. } while (size > 1024);
  6152. return Math.max(size, 0.1).toFixed(1) + units[i];
  6153. };
  6154. /**
  6155. * Imports the given XML into the existing diagram.
  6156. */
  6157. EditorUi.prototype.convertDataUri = function(uri)
  6158. {
  6159. // Handles special case of data URI which needs to be rewritten
  6160. // to be used in a cell style to remove the semicolon
  6161. if (uri.substring(0, 5) == 'data:')
  6162. {
  6163. var semi = uri.indexOf(';');
  6164. if (semi > 0)
  6165. {
  6166. uri = uri.substring(0, semi) + uri.substring(uri.indexOf(',', semi + 1));
  6167. }
  6168. }
  6169. return uri;
  6170. };
  6171. /**
  6172. * Returns true for Gliffy data.
  6173. */
  6174. EditorUi.prototype.isRemoteFileFormat = function(data, filename)
  6175. {
  6176. return /(\"contentType\":\s*\"application\/gliffy\+json\")/.test(data);
  6177. };
  6178. /**
  6179. * Returns true for Gliffy
  6180. */
  6181. EditorUi.prototype.isLucidChartData = function(data)
  6182. {
  6183. return data != null && (data.substring(0, 26) ==
  6184. '{"state":"{\\"Properties\\":' ||
  6185. data.substring(0, 14) == '{"Properties":');
  6186. };
  6187. /**
  6188. * Imports a local file from the device or local storage.
  6189. */
  6190. EditorUi.prototype.importLocalFile = function(device, noSplash)
  6191. {
  6192. if (device && Graph.fileSupport)
  6193. {
  6194. if (this.importFileInputElt == null)
  6195. {
  6196. var input = document.createElement('input');
  6197. input.setAttribute('type', 'file');
  6198. mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
  6199. {
  6200. if (input.files != null)
  6201. {
  6202. // Using null for position will disable crop of input file
  6203. this.importFiles(input.files, null, null, this.maxImageSize);
  6204. // Resets input to force change event for same file (type reset required for IE)
  6205. input.type = '';
  6206. input.type = 'file';
  6207. input.value = '';
  6208. }
  6209. }));
  6210. input.style.display = 'none';
  6211. document.body.appendChild(input);
  6212. this.importFileInputElt = input;
  6213. }
  6214. this.importFileInputElt.click();
  6215. }
  6216. else
  6217. {
  6218. window.openNew = false;
  6219. window.openKey = 'import';
  6220. if (!noSplash)
  6221. {
  6222. var prevValue = Editor.useLocalStorage;
  6223. Editor.useLocalStorage = !device;
  6224. }
  6225. // Closes dialog after open
  6226. window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
  6227. {
  6228. this.hideDialog(cancel);
  6229. }));
  6230. window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
  6231. {
  6232. if (filename != null && Graph.fileSupport && /(\.v(dx|sdx?))($|\?)/i.test(filename))
  6233. {
  6234. // "Not a UTF 8 file" when opening VSDX in IE so this is never called
  6235. var file = new Blob([xml], {type: 'application/octet-stream'})
  6236. this.importVisio(file, mxUtils.bind(this, function(xml)
  6237. {
  6238. this.importXml(xml, 0, 0, true);
  6239. }), null, filename);
  6240. }
  6241. else
  6242. {
  6243. this.editor.graph.setSelectionCells(this.importXml(xml, 0, 0, true));
  6244. }
  6245. }));
  6246. // Removes openFile if dialog is closed
  6247. this.showDialog(new OpenDialog(this).container, 360, 220, true, true, function()
  6248. {
  6249. window.openFile = null;
  6250. });
  6251. // Extends dialog close to show splash screen
  6252. if (!noSplash)
  6253. {
  6254. var dlg = this.dialog;
  6255. var dlgClose = dlg.close;
  6256. this.dialog.close = mxUtils.bind(this, function(cancel)
  6257. {
  6258. Editor.useLocalStorage = prevValue;
  6259. dlgClose.apply(dlg, arguments);
  6260. if (cancel && this.getCurrentFile() == null && urlParams['embed'] != '1')
  6261. {
  6262. this.showSplash();
  6263. }
  6264. });
  6265. }
  6266. }
  6267. };
  6268. /**
  6269. * Imports the given XML into the existing diagram.
  6270. */
  6271. EditorUi.prototype.importFile = function(data, mimeType, dx, dy, w, h, filename, done, file, crop, ignoreEmbeddedXml)
  6272. {
  6273. crop = (crop != null) ? crop : true;
  6274. var async = false;
  6275. var cells = null;
  6276. var handleResult = mxUtils.bind(this, function(xml)
  6277. {
  6278. var importedCells = null;
  6279. if (xml != null && xml.substring(0, 10) == '<mxlibrary')
  6280. {
  6281. this.loadLibrary(new LocalLibrary(this, xml, filename));
  6282. }
  6283. else
  6284. {
  6285. importedCells = this.importXml(xml, dx, dy, crop);
  6286. }
  6287. if (done != null)
  6288. {
  6289. done(importedCells);
  6290. }
  6291. });
  6292. if (mimeType.substring(0, 5) == 'image')
  6293. {
  6294. var containsModel = false;
  6295. if (mimeType.substring(0, 9) == 'image/png')
  6296. {
  6297. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(data);
  6298. if (xml != null && xml.length > 0)
  6299. {
  6300. cells = this.importXml(xml, dx, dy, crop);
  6301. containsModel = true;
  6302. }
  6303. }
  6304. if (!containsModel)
  6305. {
  6306. var graph = this.editor.graph;
  6307. // Strips encoding bit (eg. ;base64,) for cell style
  6308. var semi = data.indexOf(';');
  6309. if (semi > 0)
  6310. {
  6311. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6312. }
  6313. if (crop && graph.isGridEnabled())
  6314. {
  6315. dx = graph.snap(dx);
  6316. dy = graph.snap(dy);
  6317. }
  6318. cells = [graph.insertVertex(null, null, '', dx, dy, w, h,
  6319. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  6320. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + data + ';')];
  6321. }
  6322. }
  6323. else if (/(\.*<graphml )/.test(data))
  6324. {
  6325. async = true;
  6326. this.importGraphML(data, handleResult);
  6327. }
  6328. else if (file != null && filename != null && ((/(\.v(dx|sdx?))($|\?)/i.test(filename)) || /(\.vs(x|sx?))($|\?)/i.test(filename)))
  6329. {
  6330. // LATER: done and async are a hack before making this asynchronous
  6331. async = true;
  6332. this.importVisio(file, handleResult);
  6333. }
  6334. else if (!this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, filename))
  6335. {
  6336. // LATER: done and async are a hack before making this asynchronous
  6337. async = true;
  6338. // Returns empty cells array as it is aysynchronous
  6339. this.parseFile((file != null) ? file : new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  6340. {
  6341. if (xhr.readyState == 4)
  6342. {
  6343. if (xhr.status >= 200 && xhr.status <= 299)
  6344. {
  6345. handleResult(xhr.responseText);
  6346. }
  6347. else if (done != null)
  6348. {
  6349. done(null);
  6350. }
  6351. }
  6352. }), filename);
  6353. }
  6354. else if (!/(\.v(sd|dx))($|\?)/i.test(filename) && !/(\.vs(s|x))($|\?)/i.test(filename))
  6355. {
  6356. cells = this.insertTextAt(this.validateFileData(data), dx, dy, true, null, crop);
  6357. }
  6358. if (!async && done != null)
  6359. {
  6360. done(cells);
  6361. }
  6362. return cells;
  6363. };
  6364. /**
  6365. * Base64 encodes the given string. This method seems to be more
  6366. * robust for encoding PNG from binary AJAX responses.
  6367. */
  6368. EditorUi.prototype.base64Encode = function(str)
  6369. {
  6370. var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6371. var out = "", i = 0, len = str.length, c1, c2, c3;
  6372. while (i < len)
  6373. {
  6374. c1 = str.charCodeAt(i++) & 0xff;
  6375. if (i == len)
  6376. {
  6377. out += CHARS.charAt(c1 >> 2);
  6378. out += CHARS.charAt((c1 & 0x3) << 4);
  6379. out += "==";
  6380. break;
  6381. }
  6382. c2 = str.charCodeAt(i++);
  6383. if (i == len)
  6384. {
  6385. out += CHARS.charAt(c1 >> 2);
  6386. out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  6387. out += CHARS.charAt((c2 & 0xF) << 2);
  6388. out += "=";
  6389. break;
  6390. }
  6391. c3 = str.charCodeAt(i++);
  6392. out += CHARS.charAt(c1 >> 2);
  6393. out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
  6394. out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  6395. out += CHARS.charAt(c3 & 0x3F);
  6396. }
  6397. return out;
  6398. };
  6399. /**
  6400. *
  6401. */
  6402. EditorUi.prototype.importFiles = function(files, x, y, maxSize, fn, resultFn, filterFn, barrierFn, resizeDialog, maxBytes, resampleThreshold, ignoreEmbeddedXml)
  6403. {
  6404. x = (x != null) ? x : 0;
  6405. y = (y != null) ? y : 0;
  6406. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6407. maxBytes = (maxBytes != null) ? maxBytes : this.maxImageBytes;
  6408. var crop = x != null && y != null;
  6409. var resizeImages = true;
  6410. // Checks if large images are imported
  6411. var largeImages = false;
  6412. if (!mxClient.IS_CHROMEAPP && files != null)
  6413. {
  6414. var thresh = resampleThreshold || this.resampleThreshold;
  6415. for (var i = 0; i < files.length; i++)
  6416. {
  6417. if (files[i].type.substring(0, 6) == 'image/' && files[i].size > thresh)
  6418. {
  6419. largeImages = true;
  6420. break;
  6421. }
  6422. }
  6423. }
  6424. var doImportFiles = mxUtils.bind(this, function()
  6425. {
  6426. var graph = this.editor.graph;
  6427. var gs = graph.gridSize;
  6428. fn = (fn != null) ? fn : mxUtils.bind(this, function(data, mimeType, x, y, w, h, filename, done, file)
  6429. {
  6430. if (data != null && data.substring(0, 10) == '<mxlibrary')
  6431. {
  6432. this.spinner.stop();
  6433. this.loadLibrary(new LocalLibrary(this, data, filename));
  6434. return null;
  6435. }
  6436. else
  6437. {
  6438. return this.importFile(data, mimeType, x, y, w, h, filename, done, file, crop, ignoreEmbeddedXml);
  6439. }
  6440. });
  6441. resultFn = (resultFn != null) ? resultFn : mxUtils.bind(this, function(cells)
  6442. {
  6443. graph.setSelectionCells(cells);
  6444. });
  6445. if (this.spinner.spin(document.body, mxResources.get('loading')))
  6446. {
  6447. var count = files.length;
  6448. var remain = count;
  6449. var queue = [];
  6450. // Barrier waits for all files to be loaded asynchronously
  6451. var barrier = mxUtils.bind(this, function(index, fnc)
  6452. {
  6453. queue[index] = fnc;
  6454. if (--remain == 0)
  6455. {
  6456. this.spinner.stop();
  6457. if (barrierFn != null)
  6458. {
  6459. barrierFn(queue);
  6460. }
  6461. else
  6462. {
  6463. var cells = [];
  6464. graph.getModel().beginUpdate();
  6465. try
  6466. {
  6467. for (var j = 0; j < queue.length; j++)
  6468. {
  6469. var tmp = queue[j]();
  6470. if (tmp != null)
  6471. {
  6472. cells = cells.concat(tmp);
  6473. }
  6474. }
  6475. }
  6476. finally
  6477. {
  6478. graph.getModel().endUpdate();
  6479. }
  6480. }
  6481. resultFn(cells);
  6482. }
  6483. });
  6484. for (var i = 0; i < count; i++)
  6485. {
  6486. (mxUtils.bind(this, function(index)
  6487. {
  6488. var file = files[index];
  6489. if (file != null)
  6490. {
  6491. var reader = new FileReader();
  6492. reader.onload = mxUtils.bind(this, function(e)
  6493. {
  6494. if (filterFn == null || filterFn(file))
  6495. {
  6496. if (file.type.substring(0, 6) == 'image/')
  6497. {
  6498. if (file.type.substring(0, 9) == 'image/svg')
  6499. {
  6500. // Checks if SVG contains content attribute
  6501. var data = e.target.result;
  6502. var comma = data.indexOf(',');
  6503. var svgText = decodeURIComponent(escape(atob(data.substring(comma + 1))));
  6504. var root = mxUtils.parseXml(svgText);
  6505. var svgs = root.getElementsByTagName('svg');
  6506. if (svgs.length > 0)
  6507. {
  6508. var svgRoot = svgs[0];
  6509. var cont = (ignoreEmbeddedXml) ? null : svgRoot.getAttribute('content');
  6510. if (cont != null && cont.charAt(0) != '<' && cont.charAt(0) != '%')
  6511. {
  6512. cont = unescape((window.atob) ? atob(cont) : Base64.decode(cont, true));
  6513. }
  6514. if (cont != null && cont.charAt(0) == '%')
  6515. {
  6516. cont = decodeURIComponent(cont);
  6517. }
  6518. if (cont != null && (cont.substring(0, 8) === '<mxfile ' ||
  6519. cont.substring(0, 14) === '<mxGraphModel '))
  6520. {
  6521. barrier(index, mxUtils.bind(this, function()
  6522. {
  6523. return fn(cont, 'text/xml', x + index * gs, y + index * gs, 0, 0, file.name);
  6524. }));
  6525. }
  6526. else
  6527. {
  6528. // SVG needs special handling to add viewbox if missing and
  6529. // find initial size from SVG attributes (only for IE11)
  6530. barrier(index, mxUtils.bind(this, function()
  6531. {
  6532. try
  6533. {
  6534. var prefix = data.substring(0, comma + 1);
  6535. // Parses SVG and find width and height
  6536. if (root != null)
  6537. {
  6538. var svgs = root.getElementsByTagName('svg');
  6539. if (svgs.length > 0)
  6540. {
  6541. var svgRoot = svgs[0];
  6542. var w = parseFloat(svgRoot.getAttribute('width'));
  6543. var h = parseFloat(svgRoot.getAttribute('height'));
  6544. // Check if viewBox attribute already exists
  6545. var vb = svgRoot.getAttribute('viewBox');
  6546. if (vb == null || vb.length == 0)
  6547. {
  6548. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6549. }
  6550. // Uses width and height from viewbox for
  6551. // missing width and height attributes
  6552. else if (isNaN(w) || isNaN(h))
  6553. {
  6554. var tokens = vb.split(' ');
  6555. if (tokens.length > 3)
  6556. {
  6557. w = parseFloat(tokens[2]);
  6558. h = parseFloat(tokens[3]);
  6559. }
  6560. }
  6561. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6562. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  6563. var cells = fn(data, file.type, x + index * gs, y + index * gs, Math.max(
  6564. 1, Math.round(w * s)), Math.max(1, Math.round(h * s)), file.name);
  6565. // Hack to fix width and height asynchronously
  6566. if (isNaN(w) || isNaN(h))
  6567. {
  6568. var img = new Image();
  6569. img.onload = mxUtils.bind(this, function()
  6570. {
  6571. w = Math.max(1, img.width);
  6572. h = Math.max(1, img.height);
  6573. cells[0].geometry.width = w;
  6574. cells[0].geometry.height = h;
  6575. svgRoot.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
  6576. data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6577. var semi = data.indexOf(';');
  6578. if (semi > 0)
  6579. {
  6580. data = data.substring(0, semi) + data.substring(data.indexOf(',', semi + 1));
  6581. }
  6582. graph.setCellStyles('image', data, [cells[0]]);
  6583. });
  6584. img.src = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  6585. }
  6586. return cells;
  6587. }
  6588. }
  6589. }
  6590. catch (e)
  6591. {
  6592. // ignores any SVG parsing errors
  6593. }
  6594. return null;
  6595. }));
  6596. }
  6597. }
  6598. else
  6599. {
  6600. barrier(index, mxUtils.bind(this, function()
  6601. {
  6602. return null;
  6603. }));
  6604. }
  6605. }
  6606. else
  6607. {
  6608. // Checks if PNG+XML is available to bypass code below
  6609. var containsModel = false;
  6610. if (file.type == 'image/png')
  6611. {
  6612. var xml = (ignoreEmbeddedXml) ? null : this.extractGraphModelFromPng(e.target.result);
  6613. if (xml != null && xml.length > 0)
  6614. {
  6615. var img = new Image();
  6616. img.src = e.target.result;
  6617. barrier(index, mxUtils.bind(this, function()
  6618. {
  6619. return fn(xml, 'text/xml', x + index * gs, y + index * gs,
  6620. img.width, img.height, file.name);
  6621. }));
  6622. containsModel = true;
  6623. }
  6624. }
  6625. // Additional asynchronous step for finding image size
  6626. if (!containsModel)
  6627. {
  6628. // Cannot load local files in Chrome App
  6629. if (mxClient.IS_CHROMEAPP)
  6630. {
  6631. this.spinner.stop();
  6632. this.showError(mxResources.get('error'), mxResources.get('dragAndDropNotSupported'),
  6633. mxResources.get('cancel'), mxUtils.bind(this, function()
  6634. {
  6635. // Hides the dialog
  6636. }), null, mxResources.get('ok'), mxUtils.bind(this, function()
  6637. {
  6638. // Redirects to import function
  6639. this.actions.get('import').funct();
  6640. })
  6641. );
  6642. }
  6643. else
  6644. {
  6645. this.loadImage(e.target.result, mxUtils.bind(this, function(img)
  6646. {
  6647. this.resizeImage(img, e.target.result, mxUtils.bind(this, function(data2, w2, h2)
  6648. {
  6649. barrier(index, mxUtils.bind(this, function()
  6650. {
  6651. // Refuses to insert images above a certain size as they kill the app
  6652. if (data2 != null && data2.length < maxBytes)
  6653. {
  6654. var s = (!resizeImages || !this.isResampleImage(e.target.result, resampleThreshold)) ? 1 : Math.min(1, Math.min(maxSize / w2, maxSize / h2));
  6655. return fn(data2, file.type, x + index * gs, y + index * gs, Math.round(w2 * s), Math.round(h2 * s), file.name);
  6656. }
  6657. else
  6658. {
  6659. this.handleError({message: mxResources.get('imageTooBig')});
  6660. return null;
  6661. }
  6662. }));
  6663. }), resizeImages, maxSize, resampleThreshold);
  6664. }), mxUtils.bind(this, function()
  6665. {
  6666. this.handleError({message: mxResources.get('invalidOrMissingFile')});
  6667. }));
  6668. }
  6669. }
  6670. }
  6671. }
  6672. else
  6673. {
  6674. fn(e.target.result, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6675. {
  6676. barrier(index, function()
  6677. {
  6678. return cells;
  6679. });
  6680. });
  6681. }
  6682. }
  6683. });
  6684. // Handles special cases
  6685. if (/(\.v(dx|sdx?))($|\?)/i.test(file.name) || /(\.vs(x|sx?))($|\?)/i.test(file.name))
  6686. {
  6687. fn(null, file.type, x + index * gs, y + index * gs, 240, 160, file.name, function(cells)
  6688. {
  6689. barrier(index, function()
  6690. {
  6691. return cells;
  6692. });
  6693. }, file);
  6694. }
  6695. else if (file.type.substring(0, 5) == 'image')
  6696. {
  6697. reader.readAsDataURL(file);
  6698. }
  6699. else
  6700. {
  6701. reader.readAsText(file);
  6702. }
  6703. }
  6704. }))(i);
  6705. }
  6706. }
  6707. });
  6708. if (largeImages)
  6709. {
  6710. // Workaround for lost files array in async code
  6711. var tmp = [];
  6712. for (var i = 0; i < files.length; i++)
  6713. {
  6714. tmp.push(files[i]);
  6715. }
  6716. files = tmp;
  6717. this.confirmImageResize(function(doResize)
  6718. {
  6719. resizeImages = doResize;
  6720. doImportFiles();
  6721. }, resizeDialog);
  6722. }
  6723. else
  6724. {
  6725. doImportFiles();
  6726. }
  6727. };
  6728. /**
  6729. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6730. * Filename is an optional parameter for blobs (that do not have a filename).
  6731. */
  6732. EditorUi.prototype.confirmImageResize = function(fn, force)
  6733. {
  6734. force = (force != null) ? force : false;
  6735. var resume = (this.spinner != null && this.spinner.pause != null) ? this.spinner.pause() : function() {};
  6736. var resizeImages = (isLocalStorage || mxClient.IS_CHROMEAPP) ? mxSettings.getResizeImages() : null;
  6737. var wrapper = function(remember, resize)
  6738. {
  6739. if (remember || force)
  6740. {
  6741. mxSettings.setResizeImages((remember) ? resize : null);
  6742. mxSettings.save();
  6743. }
  6744. resume();
  6745. fn(resize);
  6746. };
  6747. if (resizeImages != null && !force)
  6748. {
  6749. wrapper(false, resizeImages);
  6750. }
  6751. else
  6752. {
  6753. this.showDialog(new ConfirmDialog(this, mxResources.get('resizeLargeImages'),
  6754. function(remember)
  6755. {
  6756. wrapper(remember, true);
  6757. },
  6758. function(remember)
  6759. {
  6760. wrapper(remember, false);
  6761. }, mxResources.get('resize'), mxResources.get('actualSize'),
  6762. '<img style="margin-top:8px;" src="' + Editor.loResImage + '"/>',
  6763. '<img style="margin-top:8px;" src="' + Editor.hiResImage + '"/>',
  6764. isLocalStorage || mxClient.IS_CHROMEAPP).container, 340,
  6765. (isLocalStorage || mxClient.IS_CHROMEAPP) ? 220 : 200, true, true);
  6766. }
  6767. };
  6768. /**
  6769. * Parses the file using XHR2 via the server. File can be a blob or file object.
  6770. * Filename is an optional parameter for blobs (that do not have a filename).
  6771. */
  6772. EditorUi.prototype.parseFile = function(file, fn, filename)
  6773. {
  6774. filename = (filename != null) ? filename : file.name;
  6775. var formData = new FormData();
  6776. formData.append('format', 'xml');
  6777. formData.append('upfile', file, filename);
  6778. var xhr = new XMLHttpRequest();
  6779. xhr.open('POST', OPEN_URL);
  6780. xhr.onreadystatechange = function()
  6781. {
  6782. fn(xhr);
  6783. };
  6784. xhr.send(formData);
  6785. };
  6786. /**
  6787. *
  6788. */
  6789. EditorUi.prototype.isResampleImage = function(data, thresh)
  6790. {
  6791. thresh = (thresh != null) ? thresh : this.resampleThreshold;
  6792. return data.length > thresh;
  6793. };
  6794. /**
  6795. * Resizes the given image if <maxImageBytes> is not null.
  6796. */
  6797. EditorUi.prototype.resizeImage = function(img, data, fn, enabled, maxSize, thresh)
  6798. {
  6799. maxSize = (maxSize != null) ? maxSize : this.maxImageSize;
  6800. var w = Math.max(1, img.width);
  6801. var h = Math.max(1, img.height);
  6802. if (enabled && this.isResampleImage(data, thresh))
  6803. {
  6804. try
  6805. {
  6806. var factor = Math.max(w / maxSize, h / maxSize);
  6807. if (factor > 1)
  6808. {
  6809. var w2 = Math.round(w / factor);
  6810. var h2 = Math.round(h / factor);
  6811. var canvas = document.createElement('canvas');
  6812. canvas.width = w2;
  6813. canvas.height = h2;
  6814. var ctx = canvas.getContext('2d');
  6815. ctx.drawImage(img, 0, 0, w2, h2);
  6816. var tmp = canvas.toDataURL();
  6817. // Uses new image if smaller
  6818. if (tmp.length < data.length)
  6819. {
  6820. // Checks if the image is empty by comparing
  6821. // with an empty image of the same size
  6822. var canvas2 = document.createElement('canvas');
  6823. canvas2.width = w2;
  6824. canvas2.height = h2;
  6825. var tmp2 = canvas2.toDataURL();
  6826. if (tmp !== tmp2)
  6827. {
  6828. data = tmp;
  6829. w = w2;
  6830. h = h2;
  6831. }
  6832. }
  6833. }
  6834. }
  6835. catch (e)
  6836. {
  6837. // ignores image scaling errors
  6838. }
  6839. }
  6840. fn(data, w, h);
  6841. };
  6842. EditorUi.prototype.crcTable = [];
  6843. for (var n = 0; n < 256; n++)
  6844. {
  6845. var c = n;
  6846. for (var k = 0; k < 8; k++)
  6847. {
  6848. if ((c & 1) == 1)
  6849. {
  6850. c = 0xedb88320 ^ (c >>> 1);
  6851. }
  6852. else
  6853. {
  6854. c >>>= 1;
  6855. }
  6856. EditorUi.prototype.crcTable[n] = c;
  6857. }
  6858. }
  6859. EditorUi.prototype.updateCRC = function(crc, data, off, len)
  6860. {
  6861. var c = crc;
  6862. for (var n = 0; n < len; n++)
  6863. {
  6864. c = EditorUi.prototype.crcTable[(c ^ data.charCodeAt(off + n)) & 0xff] ^ (c >>> 8);
  6865. }
  6866. return c;
  6867. };
  6868. EditorUi.prototype.crc32 = function(str)
  6869. {
  6870. this.crcTable = this.crcTable || this.createCrcTable();
  6871. var crc = 0 ^ (-1);
  6872. for (var i = 0; i < str.length; i++ )
  6873. {
  6874. crc = (crc >>> 8) ^ this.crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
  6875. }
  6876. return (crc ^ (-1)) >>> 0;
  6877. };
  6878. /**
  6879. * Adds the given text to the compressed or non-compressed text chunk.
  6880. */
  6881. EditorUi.prototype.writeGraphModelToPng = function(data, type, key, value, error)
  6882. {
  6883. var base64 = data.substring(data.indexOf(',') + 1);
  6884. var f = (window.atob) ? atob(base64) : Base64.decode(base64, true);
  6885. var pos = 0;
  6886. function fread(d, count)
  6887. {
  6888. var start = pos;
  6889. pos += count;
  6890. return d.substring(start, pos);
  6891. };
  6892. // Reads unsigned long 32 bit big endian
  6893. function _freadint(d)
  6894. {
  6895. var bytes = fread(d, 4);
  6896. return bytes.charCodeAt(3) + (bytes.charCodeAt(2) << 8) +
  6897. (bytes.charCodeAt(1) << 16) + (bytes.charCodeAt(0) << 24);
  6898. };
  6899. function writeInt(num)
  6900. {
  6901. return String.fromCharCode((num >> 24) & 0x000000ff, (num >> 16) & 0x000000ff,
  6902. (num >> 8) & 0x000000ff, num & 0x000000ff);
  6903. };
  6904. // Checks signature
  6905. if (fread(f,8) != String.fromCharCode(137) + 'PNG' + String.fromCharCode(13, 10, 26, 10))
  6906. {
  6907. if (error != null)
  6908. {
  6909. error();
  6910. }
  6911. return;
  6912. }
  6913. // Reads header chunk
  6914. fread(f,4);
  6915. if (fread(f,4) != 'IHDR')
  6916. {
  6917. if (error != null)
  6918. {
  6919. error();
  6920. }
  6921. return;
  6922. }
  6923. fread(f, 17);
  6924. var result = f.substring(0, pos);
  6925. do
  6926. {
  6927. var n = _freadint(f);
  6928. var chunk = fread(f,4);
  6929. if (chunk == 'IDAT')
  6930. {
  6931. result = f.substring(0, pos - 8);
  6932. var chunkData = key + String.fromCharCode(0) +
  6933. ((type == 'zTXt') ? String.fromCharCode(0) : '') +
  6934. value;
  6935. var crc = 0xffffffff;
  6936. crc = this.updateCRC(crc, type, 0, 4);
  6937. crc = this.updateCRC(crc, chunkData, 0, chunkData.length);
  6938. result += writeInt(chunkData.length) + type + chunkData + writeInt(crc ^ 0xffffffff);
  6939. result += f.substring(pos - 8, f.length);
  6940. break;
  6941. }
  6942. result += f.substring(pos - 8, pos - 4 + n);
  6943. fread(f,n);
  6944. fread(f,4);
  6945. }
  6946. while (n);
  6947. return 'data:image/png;base64,' + ((window.btoa) ? btoa(result) : Base64.encode(result, true));
  6948. }
  6949. /**
  6950. * Extracts the XML from the compressed or non-compressed text chunk.
  6951. */
  6952. EditorUi.prototype.extractGraphModelFromPng = function(data)
  6953. {
  6954. var result = null;
  6955. try
  6956. {
  6957. var base64 = data.substring(data.indexOf(',') + 1);
  6958. // Workaround for invalid character error in Safari
  6959. var binary = (window.atob && !mxClient.IS_SF) ? atob(base64) : Base64.decode(base64, true);
  6960. EditorUi.parsePng(binary, mxUtils.bind(this, function(pos, type, length)
  6961. {
  6962. var value = binary.substring(pos + 8, pos + 8 + length);
  6963. if (type == 'zTXt')
  6964. {
  6965. var idx = value.indexOf(String.fromCharCode(0));
  6966. if (value.substring(0, idx) == 'mxGraphModel')
  6967. {
  6968. // Workaround for Java URL Encoder using + for spaces, which isn't compatible with JS
  6969. var xmlData = Graph.bytesToString(pako.inflateRaw(
  6970. value.substring(idx + 2))).replace(/\+/g,' ');
  6971. if (xmlData != null && xmlData.length > 0)
  6972. {
  6973. result = xmlData;
  6974. }
  6975. }
  6976. }
  6977. // Uncompressed section is normally not used
  6978. else if (type == 'tEXt')
  6979. {
  6980. var vals = value.split(String.fromCharCode(0));
  6981. if (vals.length > 1 && vals[0] == 'mxGraphModel')
  6982. {
  6983. result = vals[1];
  6984. }
  6985. }
  6986. if (result != null || type == 'IDAT')
  6987. {
  6988. // Stops processing the file as our text chunks
  6989. // are always placed before the data section
  6990. return true;
  6991. }
  6992. }));
  6993. }
  6994. catch (e)
  6995. {
  6996. // ignores decoding errors
  6997. }
  6998. if (result != null && result.charAt(0) == '%')
  6999. {
  7000. result = decodeURIComponent(result);
  7001. }
  7002. // Workaround for double encoded content
  7003. if (result != null && result.charAt(0) == '%')
  7004. {
  7005. result = decodeURIComponent(result);
  7006. }
  7007. return result;
  7008. };
  7009. /**
  7010. * Loads the image from the given URI.
  7011. *
  7012. * @param {number} dx X-coordinate of the translation.
  7013. * @param {number} dy Y-coordinate of the translation.
  7014. */
  7015. EditorUi.prototype.loadImage = function(uri, onload, onerror)
  7016. {
  7017. try
  7018. {
  7019. var img = new Image();
  7020. img.onload = function()
  7021. {
  7022. onload(img);
  7023. }
  7024. if (onerror != null)
  7025. {
  7026. img.onerror = onerror;
  7027. }
  7028. img.src = uri;
  7029. }
  7030. catch (e)
  7031. {
  7032. if (onerror != null)
  7033. {
  7034. onerror(e);
  7035. }
  7036. else
  7037. {
  7038. throw e;
  7039. }
  7040. }
  7041. };
  7042. // Initializes the user interface
  7043. var editorUiInit = EditorUi.prototype.init;
  7044. EditorUi.prototype.init = function()
  7045. {
  7046. mxStencilRegistry.allowEval = mxStencilRegistry.allowEval && !this.isOfflineApp();
  7047. // Must be set before UI is created in superclass
  7048. if (typeof window.mxSettings !== 'undefined')
  7049. {
  7050. this.formatWidth = mxSettings.getFormatWidth();
  7051. }
  7052. var ui = this;
  7053. var graph = this.editor.graph;
  7054. // Redirects custom link title via UI for page links
  7055. graph.getLinkTitle = function(href)
  7056. {
  7057. return ui.getLinkTitle(href);
  7058. };
  7059. // Redirects custom link via UI for page link handling
  7060. graph.customLinkClicked = function(link)
  7061. {
  7062. var done = false;
  7063. try
  7064. {
  7065. ui.handleCustomLink(link);
  7066. done = true;
  7067. }
  7068. catch (e)
  7069. {
  7070. ui.handleError(e);
  7071. }
  7072. return done;
  7073. };
  7074. // Extends clear default style to clear persisted settings
  7075. var clearDefaultStyle = this.clearDefaultStyle;
  7076. this.clearDefaultStyle = function()
  7077. {
  7078. clearDefaultStyle.apply(this, arguments);
  7079. };
  7080. // Sets help link for placeholders
  7081. if (!this.isOffline() && typeof window.EditDataDialog !== 'undefined')
  7082. {
  7083. EditDataDialog.placeholderHelpLink = 'https://desk.draw.io/support/solutions/articles/16000051979';
  7084. }
  7085. // Passes current page to editor window
  7086. var editorGetEditBlankUrl = ui.editor.getEditBlankUrl;
  7087. this.editor.getEditBlankUrl = function(params)
  7088. {
  7089. params = (params != null) ? params : '';
  7090. if (ui.pages != null && ui.currentPage != null)
  7091. {
  7092. for (var i = 0; i < ui.pages.length; i++)
  7093. {
  7094. if (ui.pages[i] == ui.currentPage)
  7095. {
  7096. if (i > 0)
  7097. {
  7098. params += ((params.length > 0) ? '&' : '?') + 'page=' + i;
  7099. }
  7100. break;
  7101. }
  7102. }
  7103. }
  7104. if (urlParams['dev'] == '1')
  7105. {
  7106. params += ((params.length > 0) ? '&' : '?') + 'dev=1&drawdev=1';
  7107. }
  7108. return editorGetEditBlankUrl.apply(this, arguments);
  7109. };
  7110. // For chromeless mode and lightbox mode in viewer
  7111. // Must be overridden before supercall to be applied
  7112. // in case of chromeless initialization
  7113. var graphAddClickHandler = graph.addClickHandler;
  7114. graph.addClickHandler = function(highlight, beforeClick, onClick)
  7115. {
  7116. var tmp = beforeClick;
  7117. beforeClick = function(evt, href)
  7118. {
  7119. if (href == null)
  7120. {
  7121. var source = mxEvent.getSource(evt);
  7122. if (source.nodeName.toLowerCase() == 'a')
  7123. {
  7124. href = source.getAttribute('href');
  7125. }
  7126. }
  7127. if (href != null && graph.isCustomLink(href) &&
  7128. (mxEvent.isTouchEvent(evt) ||
  7129. !mxEvent.isPopupTrigger(evt)) &&
  7130. graph.customLinkClicked(href))
  7131. {
  7132. mxEvent.consume(evt);
  7133. }
  7134. if (tmp != null)
  7135. {
  7136. tmp(evt, href);
  7137. }
  7138. };
  7139. // For some reason, local argument override is not enough in this case...
  7140. graphAddClickHandler.call(this, highlight, beforeClick, onClick);
  7141. };
  7142. editorUiInit.apply(this, arguments);
  7143. if (mxClient.IS_SVG)
  7144. {
  7145. // LATER: Add shadow for labels in graph.container (eg. math, NO_FO), scaling
  7146. this.editor.graph.addSvgShadow(graph.view.canvas.ownerSVGElement, null, true);
  7147. }
  7148. // Overrides print dialog size
  7149. ui.actions.get('print').funct = function()
  7150. {
  7151. ui.showDialog(new PrintDialog(ui).container, 360,
  7152. (ui.pages != null && ui.pages.length > 1) ?
  7153. 420 : 360, true, true);
  7154. };
  7155. // Specifies the default filename
  7156. this.defaultFilename = mxResources.get('untitledDiagram');
  7157. // Adds placeholder for %page% and %pagenumber%
  7158. var graphGetGlobalVariable = graph.getGlobalVariable;
  7159. graph.getGlobalVariable = function(name)
  7160. {
  7161. if (name == 'page' && ui.currentPage != null)
  7162. {
  7163. return ui.currentPage.getName();
  7164. }
  7165. else if (name == 'pagenumber')
  7166. {
  7167. if (ui.currentPage != null && ui.pages != null)
  7168. {
  7169. return mxUtils.indexOf(ui.pages, ui.currentPage) + 1;
  7170. }
  7171. else
  7172. {
  7173. return 1;
  7174. }
  7175. }
  7176. return graphGetGlobalVariable.apply(this, arguments);
  7177. };
  7178. var graphLabelLinkClicked = graph.labelLinkClicked;
  7179. graph.labelLinkClicked = function(state, elt, evt)
  7180. {
  7181. var href = elt.getAttribute('href');
  7182. if (href != null && graph.isCustomLink(href) &&
  7183. (mxEvent.isTouchEvent(evt) ||
  7184. !mxEvent.isPopupTrigger(evt)))
  7185. {
  7186. // Active links are moved to the hint
  7187. if (!graph.isEnabled() || (state != null && graph.isCellLocked(state.cell)))
  7188. {
  7189. graph.customLinkClicked(href);
  7190. // Resets rubberband after click on locked cell
  7191. graph.getRubberband().reset();
  7192. }
  7193. mxEvent.consume(evt);
  7194. }
  7195. else
  7196. {
  7197. graphLabelLinkClicked.apply(this, arguments);
  7198. }
  7199. };
  7200. // Overrides editor filename
  7201. this.editor.getOrCreateFilename = function()
  7202. {
  7203. var filename = ui.defaultFilename;
  7204. var file = ui.getCurrentFile();
  7205. if (file != null)
  7206. {
  7207. filename = (file.getTitle() != null) ? file.getTitle() : filename;
  7208. }
  7209. return filename;
  7210. };
  7211. // Disables print action for standalone apps on iOS
  7212. // because there is no way to close the new window
  7213. // LATER: Use iframe for print, disable preview
  7214. var printAction = this.actions.get('print');
  7215. printAction.setEnabled(!mxClient.IS_IOS || !navigator.standalone);
  7216. printAction.visible = printAction.isEnabled();
  7217. // Scales pages/graph to fit available size
  7218. if (!this.editor.chromeless || this.editor.editable)
  7219. {
  7220. // Defines additional hotkeys
  7221. this.keyHandler.bindAction(70, true, 'find'); // Ctrl+F
  7222. this.keyHandler.bindAction(67, true, 'copyStyle', true); // Ctrl+Shift+C
  7223. this.keyHandler.bindAction(86, true, 'pasteStyle', true); // Ctrl+Shift+V
  7224. this.keyHandler.bindAction(77, true, 'editGeometry', true); // Ctrl+Shift+M
  7225. this.keyHandler.bindAction(88, true, 'insertText', true); // Ctrl+Shift+X
  7226. this.keyHandler.bindAction(75, true, 'insertRectangle'); // Ctrl+K
  7227. this.keyHandler.bindAction(75, true, 'insertEllipse', true); // Ctrl+Shift+K
  7228. if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp)
  7229. {
  7230. this.altShiftActions[83] = 'synchronize'; // Alt+Shift+S
  7231. }
  7232. // Handles copy paste of images from clipboard
  7233. if (!mxClient.IS_IE)
  7234. {
  7235. graph.container.addEventListener('paste', mxUtils.bind(this, function(evt)
  7236. {
  7237. var graph = this.editor.graph;
  7238. if (!mxEvent.isConsumed(evt))
  7239. {
  7240. try
  7241. {
  7242. var data = (evt.clipboardData || evt.originalEvent.clipboardData);
  7243. var containsText = false;
  7244. // Workaround for asynchronous paste event processing in textInput
  7245. // is to ignore this event if it contains text/html/rtf (see below).
  7246. // NOTE: Image is not pasted into textInput so can't listen there.
  7247. for (var i = 0; i < data.types.length; i++)
  7248. {
  7249. if (data.types[i].substring(0, 5) === 'text/')
  7250. {
  7251. containsText = true;
  7252. break;
  7253. }
  7254. }
  7255. if (!containsText)
  7256. {
  7257. var items = data.items;
  7258. for (index in items)
  7259. {
  7260. var item = items[index];
  7261. if (item.kind === 'file')
  7262. {
  7263. if (graph.isEditing())
  7264. {
  7265. this.importFiles([item.getAsFile()], 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7266. {
  7267. // Inserts image into current text box
  7268. graph.insertImage(data, w, h);
  7269. }, function()
  7270. {
  7271. // No post processing
  7272. }, function(file)
  7273. {
  7274. // Handles only images
  7275. return file.type.substring(0, 6) == 'image/';
  7276. }, function(queue)
  7277. {
  7278. // Invokes elements of queue in order
  7279. for (var i = 0; i < queue.length; i++)
  7280. {
  7281. queue[i]();
  7282. }
  7283. });
  7284. }
  7285. else
  7286. {
  7287. var pt = this.editor.graph.getInsertPoint();
  7288. this.importFiles([item.getAsFile()], pt.x, pt.y, this.maxImageSize);
  7289. mxEvent.consume(evt);
  7290. }
  7291. break;
  7292. }
  7293. }
  7294. }
  7295. }
  7296. catch (e)
  7297. {
  7298. // ignore
  7299. }
  7300. }
  7301. }), false);
  7302. }
  7303. // Focused but invisible textarea during control or meta key events
  7304. var textInput = document.createElement('div');
  7305. textInput.style.position = 'absolute';
  7306. textInput.style.whiteSpace = 'nowrap';
  7307. textInput.style.overflow = 'hidden';
  7308. textInput.style.display = 'block';
  7309. textInput.contentEditable = true;
  7310. mxUtils.setOpacity(textInput, 0);
  7311. textInput.style.width = '1px';
  7312. textInput.style.height = '1px';
  7313. textInput.innerHTML = '&nbsp;';
  7314. var restoreFocus = false;
  7315. // Disables built-in cut, copy and paste shortcuts
  7316. this.keyHandler.bindControlKey(88, null);
  7317. this.keyHandler.bindControlKey(67, null);
  7318. this.keyHandler.bindControlKey(86, null);
  7319. // Shows a textare when control/cmd is pressed to handle native clipboard actions
  7320. mxEvent.addListener(document, 'keydown', mxUtils.bind(this, function(evt)
  7321. {
  7322. // No dialog visible
  7323. var source = mxEvent.getSource(evt);
  7324. if (graph.container != null && graph.isEnabled() && !graph.isMouseDown && !graph.isEditing() &&
  7325. this.dialog == null && source.nodeName != 'INPUT' && source.nodeName != 'TEXTAREA')
  7326. {
  7327. if (evt.keyCode == 224 /* FF */ || (!mxClient.IS_MAC && evt.keyCode == 17 /* Control */) ||
  7328. (mxClient.IS_MAC && evt.keyCode == 91 /* Meta */))
  7329. {
  7330. // Cannot use parentNode for check in IE
  7331. if (!restoreFocus)
  7332. {
  7333. // Avoid autoscroll but allow handling of all pass-through ctrl shortcuts
  7334. textInput.style.left = (graph.container.scrollLeft + 10) + 'px';
  7335. textInput.style.top = (graph.container.scrollTop + 10) + 'px';
  7336. graph.container.appendChild(textInput);
  7337. restoreFocus = true;
  7338. // Workaround for selected document content in quirks mode
  7339. if (mxClient.IS_QUIRKS)
  7340. {
  7341. window.setTimeout(function()
  7342. {
  7343. textInput.focus();
  7344. document.execCommand('selectAll', false, null);
  7345. }, 0);
  7346. }
  7347. else
  7348. {
  7349. textInput.focus();
  7350. document.execCommand('selectAll', false, null);
  7351. }
  7352. }
  7353. }
  7354. }
  7355. }));
  7356. // Clears input and restores focus and selection
  7357. function clearInput()
  7358. {
  7359. window.setTimeout(function()
  7360. {
  7361. textInput.innerHTML = '&nbsp;';
  7362. textInput.focus();
  7363. document.execCommand('selectAll', false, null);
  7364. }, 0);
  7365. };
  7366. mxEvent.addListener(document, 'keyup', mxUtils.bind(this, function(evt)
  7367. {
  7368. // Workaround for asynchronous event read invalid in IE quirks mode
  7369. var keyCode = evt.keyCode;
  7370. // Asynchronous workaround for scroll to origin after paste if the
  7371. // Ctrl-key is not pressed for long enough in FF on Windows
  7372. window.setTimeout(mxUtils.bind(this, function()
  7373. {
  7374. if (restoreFocus && (keyCode == 224 /* FF */ || keyCode == 17 /* Control */ ||
  7375. keyCode == 91 /* Meta */))
  7376. {
  7377. restoreFocus = false;
  7378. if (!graph.isEditing() && this.dialog == null && graph.container != null)
  7379. {
  7380. graph.container.focus();
  7381. }
  7382. textInput.parentNode.removeChild(textInput);
  7383. // Workaround for lost cursor in focused element
  7384. if (this.dialog == null)
  7385. {
  7386. mxUtils.clearSelection();
  7387. }
  7388. }
  7389. }), 0);
  7390. }));
  7391. mxEvent.addListener(textInput, 'copy', mxUtils.bind(this, function(evt)
  7392. {
  7393. if (graph.isEnabled())
  7394. {
  7395. try
  7396. {
  7397. mxClipboard.copy(graph);
  7398. this.copyCells(textInput);
  7399. clearInput();
  7400. }
  7401. catch (e)
  7402. {
  7403. this.handleError(e);
  7404. }
  7405. }
  7406. }));
  7407. mxEvent.addListener(textInput, 'cut', mxUtils.bind(this, function(evt)
  7408. {
  7409. if (graph.isEnabled())
  7410. {
  7411. try
  7412. {
  7413. mxClipboard.copy(graph);
  7414. this.copyCells(textInput, true);
  7415. clearInput();
  7416. }
  7417. catch (e)
  7418. {
  7419. this.handleError(e);
  7420. }
  7421. }
  7422. }));
  7423. mxEvent.addListener(textInput, 'paste', mxUtils.bind(this, function(evt)
  7424. {
  7425. if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
  7426. {
  7427. textInput.innerHTML = '&nbsp;';
  7428. textInput.focus();
  7429. window.setTimeout(mxUtils.bind(this, function()
  7430. {
  7431. this.pasteCells(evt, textInput);
  7432. textInput.innerHTML = '&nbsp;';
  7433. }), 0);
  7434. }
  7435. }), true);
  7436. // Needed for IE11
  7437. var isSelectionAllowed2 = this.isSelectionAllowed;
  7438. this.isSelectionAllowed = function(evt)
  7439. {
  7440. if (mxEvent.getSource(evt) == textInput)
  7441. {
  7442. return true;
  7443. }
  7444. return isSelectionAllowed2.apply(this, arguments);
  7445. };
  7446. };
  7447. var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
  7448. var x = document.body.clientWidth / 2 - 2;
  7449. // Holds the x-coordinate of the point
  7450. this.spinner = this.createSpinner(x, y, 24);
  7451. // Installs drag and drop handler for rich text editor
  7452. if (Graph.fileSupport)
  7453. {
  7454. this.editor.graph.addListener(mxEvent.EDITING_STARTED, mxUtils.bind(this, function(evt)
  7455. {
  7456. // Setup the dnd listeners
  7457. var graph = this.editor.graph;
  7458. var textElt = graph.cellEditor.text2;
  7459. var dropElt = null;
  7460. if (textElt != null)
  7461. {
  7462. mxEvent.addListener(textElt, 'dragleave', function(evt)
  7463. {
  7464. if (dropElt != null)
  7465. {
  7466. dropElt.parentNode.removeChild(dropElt);
  7467. dropElt = null;
  7468. }
  7469. evt.stopPropagation();
  7470. evt.preventDefault();
  7471. });
  7472. mxEvent.addListener(textElt, 'dragover', mxUtils.bind(this, function(evt)
  7473. {
  7474. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7475. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7476. {
  7477. dropElt = this.highlightElement(textElt);
  7478. }
  7479. evt.stopPropagation();
  7480. evt.preventDefault();
  7481. }));
  7482. mxEvent.addListener(textElt, 'drop', mxUtils.bind(this, function(evt)
  7483. {
  7484. if (dropElt != null)
  7485. {
  7486. dropElt.parentNode.removeChild(dropElt);
  7487. dropElt = null;
  7488. }
  7489. if (evt.dataTransfer.files.length > 0)
  7490. {
  7491. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, function(data, mimeType, x, y, w, h)
  7492. {
  7493. // Inserts image into current text box
  7494. graph.insertImage(data, w, h);
  7495. }, function()
  7496. {
  7497. // No post processing
  7498. }, function(file)
  7499. {
  7500. // Handles only images
  7501. return file.type.substring(0, 6) == 'image/';
  7502. }, function(queue)
  7503. {
  7504. // Invokes elements of queue in order
  7505. for (var i = 0; i < queue.length; i++)
  7506. {
  7507. queue[i]();
  7508. }
  7509. }, mxEvent.isControlDown(evt));
  7510. }
  7511. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0)
  7512. {
  7513. var uri = evt.dataTransfer.getData('text/uri-list');
  7514. if ((/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7515. {
  7516. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7517. {
  7518. var w = Math.max(1, img.width);
  7519. var h = Math.max(1, img.height);
  7520. var maxSize = this.maxImageSize;
  7521. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7522. graph.insertImage(decodeURIComponent(uri), w * s, h * s);
  7523. }));
  7524. }
  7525. else
  7526. {
  7527. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7528. }
  7529. }
  7530. else
  7531. {
  7532. if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7533. {
  7534. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/html'));
  7535. }
  7536. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7537. {
  7538. document.execCommand('insertHTML', false, evt.dataTransfer.getData('text/plain'));
  7539. }
  7540. }
  7541. evt.stopPropagation();
  7542. evt.preventDefault();
  7543. }));
  7544. }
  7545. }));
  7546. }
  7547. //Add ruler in test mode only
  7548. //TODO add the ruler containers correctly and make the vertical one dynamic as the side panel size can change
  7549. if (urlParams['ruler'] == '1' && typeof mxRuler !== 'undefined')
  7550. {
  7551. var hRulerDiv = document.createElement('div');
  7552. hRulerDiv.style.position = 'absolute';
  7553. hRulerDiv.style.top = '95px';
  7554. hRulerDiv.style.left = '250px';
  7555. hRulerDiv.style.width = '2000px';
  7556. hRulerDiv.style.height = '30px';
  7557. hRulerDiv.style.background = 'whiteSmoke';
  7558. document.body.appendChild(hRulerDiv);
  7559. var vRulerDiv = document.createElement('div');
  7560. vRulerDiv.style.position = 'absolute';
  7561. vRulerDiv.style.top = '125px';
  7562. vRulerDiv.style.left = '220px';
  7563. vRulerDiv.style.width = '30px';
  7564. vRulerDiv.style.height = '1000px';
  7565. vRulerDiv.style.background = 'whiteSmoke';
  7566. document.body.appendChild(vRulerDiv);
  7567. var square = document.createElement('div');
  7568. square.style.position = 'absolute';
  7569. square.style.top = '95px';
  7570. square.style.left = '220px';
  7571. square.style.width = '30px';
  7572. square.style.height = '30px';
  7573. square.style.background = 'whiteSmoke';
  7574. document.body.appendChild(square);
  7575. this.vRuler = new mxRuler(this.editor.graph, vRulerDiv, true);
  7576. this.hRuler = new mxRuler(this.editor.graph, hRulerDiv, false);
  7577. }
  7578. // Adds an element to edit the style in the footer in test mode
  7579. if (urlParams['styledev'] == '1')
  7580. {
  7581. var footer = document.getElementById('geFooter');
  7582. if (footer != null)
  7583. {
  7584. this.styleInput = document.createElement('input');
  7585. this.styleInput.setAttribute('type', 'text');
  7586. this.styleInput.style.position = 'absolute';
  7587. this.styleInput.style.top = '14px';
  7588. this.styleInput.style.left = '2px';
  7589. // Workaround for ignore right CSS property in FF
  7590. this.styleInput.style.width = '98%';
  7591. this.styleInput.style.visibility = 'hidden';
  7592. this.styleInput.style.opacity = '0.9';
  7593. mxEvent.addListener(this.styleInput, 'change', mxUtils.bind(this, function()
  7594. {
  7595. this.editor.graph.getModel().setStyle(this.editor.graph.getSelectionCell(), this.styleInput.value);
  7596. }));
  7597. footer.appendChild(this.styleInput);
  7598. this.editor.graph.getSelectionModel().addListener(mxEvent.CHANGE, mxUtils.bind(this, function(sender, evt)
  7599. {
  7600. if (this.editor.graph.getSelectionCount() > 0)
  7601. {
  7602. var cell = this.editor.graph.getSelectionCell();
  7603. var style = this.editor.graph.getModel().getStyle(cell);
  7604. this.styleInput.value = style || '';
  7605. this.styleInput.style.visibility = 'visible';
  7606. } else
  7607. {
  7608. this.styleInput.style.visibility = 'hidden';
  7609. }
  7610. }));
  7611. }
  7612. var isSelectionAllowed = this.isSelectionAllowed;
  7613. this.isSelectionAllowed = function(evt)
  7614. {
  7615. if (mxEvent.getSource(evt) == this.styleInput)
  7616. {
  7617. return true;
  7618. }
  7619. return isSelectionAllowed.apply(this, arguments);
  7620. };
  7621. }
  7622. // Removes info text in page
  7623. var info = document.getElementById('geInfo');
  7624. if (info != null)
  7625. {
  7626. info.parentNode.removeChild(info);
  7627. }
  7628. // Installs drag and drop handler for files
  7629. // Enables dropping files
  7630. if (Graph.fileSupport && (!this.editor.chromeless || this.editor.editable))
  7631. {
  7632. // Setup the dnd listeners
  7633. var dropElt = null;
  7634. mxEvent.addListener(graph.container, 'dragleave', function(evt)
  7635. {
  7636. if (graph.isEnabled())
  7637. {
  7638. if (dropElt != null)
  7639. {
  7640. dropElt.parentNode.removeChild(dropElt);
  7641. dropElt = null;
  7642. }
  7643. evt.stopPropagation();
  7644. evt.preventDefault();
  7645. }
  7646. });
  7647. mxEvent.addListener(graph.container, 'dragover', mxUtils.bind(this, function(evt)
  7648. {
  7649. // IE 10 does not implement pointer-events so it can't have a drop highlight
  7650. if (dropElt == null && (!mxClient.IS_IE || document.documentMode > 10))
  7651. {
  7652. dropElt = this.highlightElement(graph.container);
  7653. }
  7654. if (this.sidebar != null)
  7655. {
  7656. this.sidebar.hideTooltip();
  7657. }
  7658. evt.stopPropagation();
  7659. evt.preventDefault();
  7660. }));
  7661. mxEvent.addListener(graph.container, 'drop', mxUtils.bind(this, function(evt)
  7662. {
  7663. if (dropElt != null)
  7664. {
  7665. dropElt.parentNode.removeChild(dropElt);
  7666. dropElt = null;
  7667. }
  7668. if (graph.isEnabled())
  7669. {
  7670. var pt = mxUtils.convertPoint(graph.container, mxEvent.getClientX(evt), mxEvent.getClientY(evt));
  7671. var tr = graph.view.translate;
  7672. var scale = graph.view.scale;
  7673. var x = pt.x / scale - tr.x;
  7674. var y = pt.y / scale - tr.y;
  7675. if (mxEvent.isAltDown(evt))
  7676. {
  7677. x = 0;
  7678. y = 0;
  7679. }
  7680. if (evt.dataTransfer.files.length > 0)
  7681. {
  7682. this.importFiles(evt.dataTransfer.files, x, y, this.maxImageSize, null, null, null, null,
  7683. mxEvent.isControlDown(evt), null, null, mxEvent.isShiftDown(evt));
  7684. }
  7685. else
  7686. {
  7687. var uri = (mxUtils.indexOf(evt.dataTransfer.types, 'text/uri-list') >= 0) ?
  7688. evt.dataTransfer.getData('text/uri-list') : null;
  7689. var data = this.extractGraphModelFromEvent(evt, this.pages != null);
  7690. if (data != null)
  7691. {
  7692. graph.setSelectionCells(this.importXml(data, x, y, true));
  7693. }
  7694. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/html') >= 0)
  7695. {
  7696. var html = evt.dataTransfer.getData('text/html');
  7697. var div = document.createElement('div');
  7698. div.innerHTML = html;
  7699. // The default is based on the extension
  7700. var asImage = null;
  7701. // Extracts single image
  7702. var imgs = div.getElementsByTagName('img');
  7703. if (imgs != null && imgs.length == 1)
  7704. {
  7705. html = imgs[0].getAttribute('src');
  7706. // Handles special case where the src attribute has no valid extension
  7707. // in which case the text would be inserted as text with a link
  7708. if (!(/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(html))
  7709. {
  7710. asImage = true;
  7711. }
  7712. }
  7713. else
  7714. {
  7715. // Extracts single link
  7716. var a = div.getElementsByTagName('a');
  7717. if (a != null && a.length == 1)
  7718. {
  7719. html = a[0].getAttribute('href');
  7720. }
  7721. }
  7722. var resizeImages = true;
  7723. var doInsert = mxUtils.bind(this, function()
  7724. {
  7725. graph.setSelectionCells(this.insertTextAt(html, x, y, true, asImage, null, resizeImages));
  7726. });
  7727. if (asImage && html.length > this.resampleThreshold)
  7728. {
  7729. this.confirmImageResize(function(doResize)
  7730. {
  7731. resizeImages = doResize;
  7732. doInsert();
  7733. }, mxEvent.isControlDown(evt));
  7734. }
  7735. else
  7736. {
  7737. doInsert();
  7738. }
  7739. }
  7740. else if (uri != null && (/\.(gif|jpg|jpeg|tiff|png|svg)$/i).test(uri))
  7741. {
  7742. this.loadImage(decodeURIComponent(uri), mxUtils.bind(this, function(img)
  7743. {
  7744. var w = Math.max(1, img.width);
  7745. var h = Math.max(1, img.height);
  7746. var maxSize = this.maxImageSize;
  7747. var s = Math.min(1, Math.min(maxSize / Math.max(1, w)), maxSize / Math.max(1, h));
  7748. graph.setSelectionCell(graph.insertVertex(null, null, '', x, y, w * s, h * s,
  7749. 'shape=image;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;' +
  7750. 'verticalAlign=top;aspect=fixed;imageAspect=0;image=' + uri + ';'));
  7751. }), mxUtils.bind(this, function(img)
  7752. {
  7753. graph.setSelectionCells(this.insertTextAt(uri, x, y, true));
  7754. }));
  7755. }
  7756. else if (mxUtils.indexOf(evt.dataTransfer.types, 'text/plain') >= 0)
  7757. {
  7758. graph.setSelectionCells(this.insertTextAt(evt.dataTransfer.getData('text/plain'), x, y, true));
  7759. }
  7760. }
  7761. }
  7762. evt.stopPropagation();
  7763. evt.preventDefault();
  7764. }), false);
  7765. }
  7766. this.initPages();
  7767. // Installs listener for fixing references in undo history in
  7768. // collaborative editing where terminals may have vanished
  7769. // Undo/Redo listener to update edit's references before executing undo/redo
  7770. this.editUpdateListener = mxUtils.bind(this, function(sender, evt)
  7771. {
  7772. var edit = evt.getProperty('edit');
  7773. if (edit != null)
  7774. {
  7775. this.updateEditReferences(edit);
  7776. }
  7777. });
  7778. this.editor.undoManager.addListener(mxEvent.BEFORE_UNDO, this.editUpdateListener);
  7779. this.editor.undoManager.addListener(mxEvent.BEFORE_REDO, this.editUpdateListener);
  7780. // Embedded mode
  7781. if (urlParams['embed'] == '1')
  7782. {
  7783. this.initializeEmbedMode();
  7784. }
  7785. this.installSettings();
  7786. };
  7787. /**
  7788. *
  7789. */
  7790. EditorUi.prototype.getLinkTitle = function(href)
  7791. {
  7792. var title = Graph.prototype.getLinkTitle.apply(this, arguments);
  7793. if (href.substring(0, 13) == 'data:page/id,')
  7794. {
  7795. var comma = href.indexOf(',');
  7796. if (comma > 0)
  7797. {
  7798. var page = this.getPageById(href.substring(comma + 1));
  7799. if (page != null)
  7800. {
  7801. title = page.getName();
  7802. }
  7803. else
  7804. {
  7805. title = mxResources.get('pageNotFound');
  7806. }
  7807. }
  7808. }
  7809. else if (href.substring(0, 5) == 'data:')
  7810. {
  7811. title = mxResources.get('action');
  7812. }
  7813. return title;
  7814. };
  7815. /**
  7816. *
  7817. */
  7818. EditorUi.prototype.handleCustomLink = function(href)
  7819. {
  7820. if (href.substring(0, 13) == 'data:page/id,')
  7821. {
  7822. var comma = href.indexOf(',');
  7823. var page = this.getPageById(href.substring(comma + 1));
  7824. if (page)
  7825. {
  7826. this.selectPage(page)
  7827. }
  7828. else
  7829. {
  7830. // Needs fallback for missing resource in case of viewer lightbox
  7831. throw new Error(mxResources.get('pageNotFound') || 'Page not found');
  7832. }
  7833. }
  7834. else
  7835. {
  7836. this.editor.graph.handleCustomLink(href);
  7837. }
  7838. };
  7839. /**
  7840. *
  7841. */
  7842. EditorUi.prototype.isSettingsEnabled = function()
  7843. {
  7844. return typeof window.mxSettings !== 'undefined' && (isLocalStorage || mxClient.IS_CHROMEAPP);
  7845. };
  7846. /**
  7847. * Creates the format panel and adds overrides.
  7848. */
  7849. EditorUi.prototype.installSettings = function()
  7850. {
  7851. if (this.isSettingsEnabled())
  7852. {
  7853. // Gets recent colors from settings
  7854. ColorDialog.recentColors = mxSettings.getRecentColors();
  7855. // Updates UI to reflect current edge style
  7856. this.fireEvent(new mxEventObject('styleChanged', 'keys', [], 'values', [], 'cells', []));
  7857. /**
  7858. * Persists custom fonts.
  7859. */
  7860. this.menus.customFonts = mxSettings.getCustomFonts();
  7861. this.addListener('customFontsChanged', mxUtils.bind(this, function(sender, evt)
  7862. {
  7863. mxSettings.setCustomFonts(this.menus.customFonts);
  7864. mxSettings.save();
  7865. }));
  7866. /**
  7867. * Persists copy on connect switch.
  7868. */
  7869. this.editor.graph.connectionHandler.setCreateTarget(mxSettings.isCreateTarget());
  7870. this.fireEvent(new mxEventObject('copyConnectChanged'));
  7871. this.addListener('copyConnectChanged', mxUtils.bind(this, function(sender, evt)
  7872. {
  7873. mxSettings.setCreateTarget(this.editor.graph.connectionHandler.isCreateTarget());
  7874. mxSettings.save();
  7875. }));
  7876. /**
  7877. * Persists default page format.
  7878. */
  7879. this.editor.graph.pageFormat = mxSettings.getPageFormat();
  7880. this.addListener('pageFormatChanged', mxUtils.bind(this, function(sender, evt)
  7881. {
  7882. mxSettings.setPageFormat(this.editor.graph.pageFormat);
  7883. mxSettings.save();
  7884. }));
  7885. /**
  7886. * Persists default grid color.
  7887. */
  7888. this.editor.graph.view.gridColor = mxSettings.getGridColor();
  7889. this.addListener('gridColorChanged', mxUtils.bind(this, function(sender, evt)
  7890. {
  7891. mxSettings.setGridColor(this.editor.graph.view.gridColor);
  7892. mxSettings.save();
  7893. }));
  7894. /**
  7895. * Persists autosave switch in Chrome app.
  7896. */
  7897. if (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)
  7898. {
  7899. this.editor.addListener('autosaveChanged', mxUtils.bind(this, function(sender, evt)
  7900. {
  7901. mxSettings.setAutosave(this.editor.autosave);
  7902. mxSettings.save();
  7903. }));
  7904. this.editor.autosave = mxSettings.getAutosave();
  7905. }
  7906. /**
  7907. *
  7908. */
  7909. if (this.sidebar != null)
  7910. {
  7911. this.sidebar.showPalette('search', mxSettings.settings.search);
  7912. }
  7913. /**
  7914. * Shows scratchpad if never shown.
  7915. */
  7916. if ((!this.editor.chromeless || this.editor.editable) &&
  7917. this.sidebar != null && (mxSettings.settings.isNew ||
  7918. parseInt(mxSettings.settings.version || 0) <= 8))
  7919. {
  7920. this.toggleScratchpad();
  7921. mxSettings.save();
  7922. }
  7923. // Saves app defaults for UI
  7924. this.addListener('formatWidthChanged', function()
  7925. {
  7926. mxSettings.setFormatWidth(this.formatWidth);
  7927. mxSettings.save();
  7928. });
  7929. }
  7930. };
  7931. /**
  7932. * Creates the format panel and adds overrides.
  7933. */
  7934. EditorUi.prototype.copyCells = function(elt, removeCells)
  7935. {
  7936. var graph = this.editor.graph;
  7937. if (!graph.isSelectionEmpty())
  7938. {
  7939. var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
  7940. // LATER: Add span with XML in data attribute
  7941. // var span = document.createElement('span');
  7942. // span.setAttribute('data-jgraph-type', 'application/vnd.jgraph.xml');
  7943. // span.setAttribute('data-jgraph-content', mxUtils.getXml(graph.encodeCells(clones)));
  7944. // Fixes cross-platform clipboard UTF8 issues by encoding as URI
  7945. var xml = mxUtils.getXml(this.editor.graph.encodeCells(cells));
  7946. mxUtils.setTextContent(elt, encodeURIComponent(xml));
  7947. if (removeCells)
  7948. {
  7949. graph.removeCells(cells, false);
  7950. graph.lastPasteXml = null;
  7951. }
  7952. else
  7953. {
  7954. graph.lastPasteXml = xml;
  7955. graph.pasteCounter = 0;
  7956. }
  7957. elt.focus();
  7958. document.execCommand('selectAll', false, null);
  7959. }
  7960. else
  7961. {
  7962. // Disables copy on focused element
  7963. elt.innerHTML = '';
  7964. }
  7965. };
  7966. /**
  7967. * Creates the format panel and adds overrides.
  7968. */
  7969. EditorUi.prototype.pasteCells = function(evt, elt)
  7970. {
  7971. if (!mxEvent.isConsumed(evt))
  7972. {
  7973. var spans = elt.getElementsByTagName('span');
  7974. if (spans != null && spans.length > 0 && spans[0].getAttribute('data-lucid-type') ===
  7975. 'application/vnd.lucid.chart.objects')
  7976. {
  7977. var content = spans[0].getAttribute('data-lucid-content');
  7978. if (content != null && content.length > 0)
  7979. {
  7980. this.convertLucidChart(content, mxUtils.bind(this, function(xml)
  7981. {
  7982. var graph = this.editor.graph;
  7983. graph.setSelectionCells(this.importXml(xml, 0, 0));
  7984. graph.scrollCellToVisible(graph.getSelectionCell());
  7985. }), mxUtils.bind(this, function(e)
  7986. {
  7987. this.handleError(e);
  7988. }));
  7989. mxEvent.consume(evt);
  7990. }
  7991. }
  7992. else
  7993. {
  7994. var graph = this.editor.graph;
  7995. var xml = mxUtils.trim((mxClient.IS_QUIRKS || document.documentMode == 8) ?
  7996. mxUtils.getTextContent(elt) : elt.textContent);
  7997. var compat = false;
  7998. // Workaround for junk after XML in VM
  7999. try
  8000. {
  8001. var idx = xml.lastIndexOf('%3E');
  8002. if (idx >= 0 && idx < xml.length - 3)
  8003. {
  8004. xml = xml.substring(0, idx + 3);
  8005. }
  8006. }
  8007. catch (e)
  8008. {
  8009. // ignore
  8010. }
  8011. // Checks for embedded XML content
  8012. try
  8013. {
  8014. var spans = elt.getElementsByTagName('span');
  8015. var tmp = (spans != null && spans.length > 0) ?
  8016. mxUtils.trim(decodeURIComponent(spans[0].textContent)) :
  8017. decodeURIComponent(xml);
  8018. if (this.isCompatibleString(tmp))
  8019. {
  8020. compat = true;
  8021. xml = tmp;
  8022. }
  8023. }
  8024. catch (e)
  8025. {
  8026. // ignore
  8027. }
  8028. if (graph.lastPasteXml == xml)
  8029. {
  8030. graph.pasteCounter++;
  8031. }
  8032. else
  8033. {
  8034. graph.lastPasteXml = xml;
  8035. graph.pasteCounter = 0;
  8036. }
  8037. var dx = graph.pasteCounter * graph.gridSize;
  8038. if (xml != null && xml.length > 0)
  8039. {
  8040. if (compat || this.isCompatibleString(xml))
  8041. {
  8042. graph.setSelectionCells(this.importXml(xml, dx, dx));
  8043. }
  8044. else
  8045. {
  8046. var pt = graph.getInsertPoint();
  8047. if (graph.isMouseInsertPoint())
  8048. {
  8049. dx = 0;
  8050. // No offset for insert at mouse position
  8051. if (graph.lastPasteXml == xml && graph.pasteCounter > 0)
  8052. {
  8053. graph.pasteCounter--;
  8054. }
  8055. }
  8056. graph.setSelectionCells(this.insertTextAt(xml, pt.x + dx, pt.y + dx, true));
  8057. }
  8058. if (!graph.isSelectionEmpty())
  8059. {
  8060. graph.scrollCellToVisible(graph.getSelectionCell());
  8061. if (this.hoverIcons != null)
  8062. {
  8063. this.hoverIcons.update(graph.view.getState(graph.getSelectionCell()));
  8064. }
  8065. try
  8066. {
  8067. mxEvent.consume(evt);
  8068. }
  8069. catch (e)
  8070. {
  8071. // ignore event no longer exists in async handler in IE8-
  8072. }
  8073. }
  8074. }
  8075. }
  8076. }
  8077. };
  8078. /**
  8079. * Adds a file drop handler for opening local files.
  8080. */
  8081. EditorUi.prototype.addFileDropHandler = function(elts)
  8082. {
  8083. // Installs drag and drop handler for files
  8084. if (Graph.fileSupport)
  8085. {
  8086. var dropElt = null;
  8087. for (var i = 0; i < elts.length; i++)
  8088. {
  8089. // Setup the dnd listeners
  8090. mxEvent.addListener(elts[i], 'dragleave', function(evt)
  8091. {
  8092. if (dropElt != null)
  8093. {
  8094. dropElt.parentNode.removeChild(dropElt);
  8095. dropElt = null;
  8096. }
  8097. evt.stopPropagation();
  8098. evt.preventDefault();
  8099. });
  8100. mxEvent.addListener(elts[i], 'dragover', mxUtils.bind(this, function(evt)
  8101. {
  8102. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  8103. {
  8104. // IE 10 does not implement pointer-events so it can't have a drop highlight
  8105. if (dropElt == null && (!mxClient.IS_IE || (document.documentMode > 10 && document.documentMode < 12)))
  8106. {
  8107. dropElt = this.highlightElement();
  8108. }
  8109. }
  8110. evt.stopPropagation();
  8111. evt.preventDefault();
  8112. }));
  8113. mxEvent.addListener(elts[i], 'drop', mxUtils.bind(this, function(evt)
  8114. {
  8115. if (dropElt != null)
  8116. {
  8117. dropElt.parentNode.removeChild(dropElt);
  8118. dropElt = null;
  8119. }
  8120. if (this.editor.graph.isEnabled() || urlParams['embed'] != '1')
  8121. {
  8122. if (evt.dataTransfer.files.length > 0)
  8123. {
  8124. this.hideDialog();
  8125. // Never open files in embed mode
  8126. if (urlParams['embed'] == '1')
  8127. {
  8128. this.importFiles(evt.dataTransfer.files, 0, 0, this.maxImageSize, null, null,
  8129. null, null, !mxEvent.isControlDown(evt) && !mxEvent.isShiftDown(evt));
  8130. }
  8131. else
  8132. {
  8133. this.openFiles(evt.dataTransfer.files, true);
  8134. }
  8135. }
  8136. else
  8137. {
  8138. // Handles open special files via text drag and drop
  8139. var data = this.extractGraphModelFromEvent(evt);
  8140. // Tries additional and async parsing of text content such as HTML, Gliffy data
  8141. if (data == null)
  8142. {
  8143. var provider = (evt.dataTransfer != null) ? evt.dataTransfer : evt.clipboardData;
  8144. if (provider != null)
  8145. {
  8146. if (document.documentMode == 10 || document.documentMode == 11)
  8147. {
  8148. data = provider.getData('Text');
  8149. }
  8150. else
  8151. {
  8152. var data = null;
  8153. if (mxUtils.indexOf(provider.types, 'text/uri-list') >= 0)
  8154. {
  8155. var data = evt.dataTransfer.getData('text/uri-list');
  8156. }
  8157. else
  8158. {
  8159. data = (mxUtils.indexOf(provider.types, 'text/html') >= 0) ? provider.getData('text/html') : null;
  8160. }
  8161. if (data != null && data.length > 0)
  8162. {
  8163. var div = document.createElement('div');
  8164. div.innerHTML = data;
  8165. // Extracts single image
  8166. var imgs = div.getElementsByTagName('img');
  8167. if (imgs.length > 0)
  8168. {
  8169. data = imgs[0].getAttribute('src');
  8170. }
  8171. }
  8172. else if (mxUtils.indexOf(provider.types, 'text/plain') >= 0)
  8173. {
  8174. data = provider.getData('text/plain');
  8175. }
  8176. }
  8177. if (data != null)
  8178. {
  8179. // Checks for embedded XML in PNG
  8180. if (data.substring(0, 22) == 'data:image/png;base64,')
  8181. {
  8182. var xml = this.extractGraphModelFromPng(data);
  8183. if (xml != null && xml.length > 0)
  8184. {
  8185. this.openLocalFile(xml, null, true);
  8186. }
  8187. }
  8188. else if (!this.isOffline() && this.isRemoteFileFormat(data))
  8189. {
  8190. new mxXmlRequest(OPEN_URL, 'format=xml&data=' + encodeURIComponent(data)).send(mxUtils.bind(this, function(req)
  8191. {
  8192. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  8193. {
  8194. this.openLocalFile(req.getText(), null, true);
  8195. }
  8196. }));
  8197. }
  8198. else if (/^https?:\/\//.test(data))
  8199. {
  8200. if (this.getCurrentFile() == null)
  8201. {
  8202. window.location.hash = '#U' + encodeURIComponent(data);
  8203. }
  8204. else
  8205. {
  8206. window.openWindow(((mxClient.IS_CHROMEAPP) ?
  8207. (EditorUi.drawHost + '/') : 'https://' + location.host + '/') +
  8208. window.location.search + '#U' + encodeURIComponent(data));
  8209. }
  8210. }
  8211. }
  8212. }
  8213. }
  8214. else
  8215. {
  8216. this.openLocalFile(data, null, true);
  8217. }
  8218. }
  8219. }
  8220. evt.stopPropagation();
  8221. evt.preventDefault();
  8222. }));
  8223. }
  8224. }
  8225. };
  8226. /**
  8227. * Highlights the given element
  8228. */
  8229. EditorUi.prototype.highlightElement = function(elt)
  8230. {
  8231. var x = 0;
  8232. var y = 0;
  8233. var w = 0;
  8234. var h = 0;
  8235. if (elt == null)
  8236. {
  8237. var b = document.body;
  8238. var d = document.documentElement;
  8239. w = (b.clientWidth || d.clientWidth) - 3;
  8240. h = Math.max(b.clientHeight || 0, d.clientHeight) - 3;
  8241. }
  8242. else
  8243. {
  8244. x = elt.offsetTop;
  8245. y = elt.offsetLeft;
  8246. w = elt.clientWidth;
  8247. h = elt.clientHeight;
  8248. }
  8249. var hl = document.createElement('div');
  8250. hl.style.zIndex = mxPopupMenu.prototype.zIndex + 2;
  8251. hl.style.border = '3px dotted rgb(254, 137, 12)';
  8252. hl.style.pointerEvents = 'none';
  8253. hl.style.position = 'absolute';
  8254. hl.style.top = x + 'px';
  8255. hl.style.left = y + 'px';
  8256. hl.style.width = Math.max(0, w - 3) + 'px';
  8257. hl.style.height = Math.max(0, h - 3) + 'px';
  8258. if (elt != null && elt.parentNode == this.editor.graph.container)
  8259. {
  8260. this.editor.graph.container.appendChild(hl);
  8261. }
  8262. else
  8263. {
  8264. document.body.appendChild(hl);
  8265. }
  8266. return hl;
  8267. };
  8268. /**
  8269. * Highlights the given element
  8270. */
  8271. EditorUi.prototype.stringToCells = function(xml)
  8272. {
  8273. var doc = mxUtils.parseXml(xml);
  8274. var node = this.editor.extractGraphModel(doc.documentElement);
  8275. var cells = [];
  8276. if (node != null)
  8277. {
  8278. var codec = new mxCodec(node.ownerDocument);
  8279. var model = new mxGraphModel();
  8280. codec.decode(node, model);
  8281. var parent = model.getChildAt(model.getRoot(), 0);
  8282. for (var j = 0; j < model.getChildCount(parent); j++)
  8283. {
  8284. cells.push(model.getChildAt(parent, j));
  8285. }
  8286. }
  8287. return cells;
  8288. };
  8289. /**
  8290. * Opens the given files in the editor.
  8291. */
  8292. EditorUi.prototype.openFiles = function(files, temp)
  8293. {
  8294. if (this.spinner.spin(document.body, mxResources.get('loading')))
  8295. {
  8296. for (var i = 0; i < files.length; i++)
  8297. {
  8298. (mxUtils.bind(this, function(file)
  8299. {
  8300. var reader = new FileReader();
  8301. reader.onload = mxUtils.bind(this, function(e)
  8302. {
  8303. try
  8304. {
  8305. var data = e.target.result;
  8306. var name = file.name;
  8307. if (name != null && name.length > 0)
  8308. {
  8309. if (!this.useCanvasForExport && /(\.png)$/i.test(name))
  8310. {
  8311. name = name.substring(0, name.length - 4) + '.drawio';
  8312. }
  8313. var handleResult = mxUtils.bind(this, function(xml)
  8314. {
  8315. var dot = name.lastIndexOf('.');
  8316. if (dot >= 0)
  8317. {
  8318. name = name.substring(0, name.lastIndexOf('.')) + '.drawio';
  8319. }
  8320. else
  8321. {
  8322. name = name + '.drawio';
  8323. }
  8324. if (xml.substring(0, 10) == '<mxlibrary')
  8325. {
  8326. // Creates new temporary file if library is dropped in splash screen
  8327. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8328. {
  8329. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8330. }
  8331. try
  8332. {
  8333. this.loadLibrary(new LocalLibrary(this, xml, name));
  8334. }
  8335. catch (e)
  8336. {
  8337. this.handleError(e, mxResources.get('errorLoadingFile'));
  8338. }
  8339. }
  8340. else
  8341. {
  8342. this.openLocalFile(xml, name, temp);
  8343. }
  8344. });
  8345. if (/(\.v(dx|sdx?))($|\?)/i.test(name) || /(\.vs(x|sx?))($|\?)/i.test(name))
  8346. {
  8347. this.importVisio(file, mxUtils.bind(this, function(xml)
  8348. {
  8349. this.spinner.stop();
  8350. handleResult(xml);
  8351. }));
  8352. }
  8353. else if (/(\.*<graphml )/.test(data))
  8354. {
  8355. this.importGraphML(data, mxUtils.bind(this, function(xml)
  8356. {
  8357. this.spinner.stop();
  8358. handleResult(xml);
  8359. }));
  8360. }
  8361. else if (Graph.fileSupport && !this.isOffline() && new XMLHttpRequest().upload &&
  8362. this.isRemoteFileFormat(data, name))
  8363. {
  8364. this.parseFile(file, mxUtils.bind(this, function(xhr)
  8365. {
  8366. if (xhr.readyState == 4)
  8367. {
  8368. this.spinner.stop();
  8369. if (xhr.status >= 200 && xhr.status <= 299)
  8370. {
  8371. handleResult(xhr.responseText);
  8372. }
  8373. else
  8374. {
  8375. this.handleError({message: mxResources.get((xhr.status == 413) ?
  8376. 'drawingTooLarge' : 'invalidOrMissingFile')},
  8377. mxResources.get('errorLoadingFile'));
  8378. }
  8379. }
  8380. }));
  8381. }
  8382. else if (this.isLucidChartData(data))
  8383. {
  8384. if (/(\.json)$/i.test(name))
  8385. {
  8386. name = name.substring(0, name.length - 5) + '.drawio';
  8387. }
  8388. // LATER: Add import step that produces cells and use callback
  8389. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  8390. {
  8391. this.spinner.stop();
  8392. this.openLocalFile(xml, name, temp);
  8393. }), mxUtils.bind(this, function(e)
  8394. {
  8395. this.spinner.stop();
  8396. this.handleError(e);
  8397. }));
  8398. }
  8399. else if (e.target.result.substring(0, 10) == '<mxlibrary')
  8400. {
  8401. this.spinner.stop();
  8402. // Creates new temporary file if library is dropped in splash screen
  8403. if (this.getCurrentFile() == null && urlParams['embed'] != '1')
  8404. {
  8405. this.openLocalFile(this.emptyDiagramXml, this.defaultFilename, temp);
  8406. }
  8407. try
  8408. {
  8409. this.loadLibrary(new LocalLibrary(this, e.target.result, file.name));
  8410. }
  8411. catch (e)
  8412. {
  8413. this.handleError(e, mxResources.get('errorLoadingFile'));
  8414. }
  8415. }
  8416. else
  8417. {
  8418. if (file.type.substring(0, 9) == 'image/png')
  8419. {
  8420. data = this.extractGraphModelFromPng(data);
  8421. }
  8422. this.spinner.stop();
  8423. this.openLocalFile(data, name, temp);
  8424. }
  8425. }
  8426. }
  8427. catch (e)
  8428. {
  8429. this.handleError(e);
  8430. }
  8431. });
  8432. reader.onerror = mxUtils.bind(this, function(e)
  8433. {
  8434. this.spinner.stop();
  8435. this.handleError(e);
  8436. window.openFile = null;
  8437. });
  8438. if (file.type.substring(0, 5) === 'image' && file.type.substring(0, 9) !== 'image/svg')
  8439. {
  8440. reader.readAsDataURL(file);
  8441. }
  8442. else
  8443. {
  8444. reader.readAsText(file);
  8445. }
  8446. }))(files[i]);
  8447. }
  8448. }
  8449. };
  8450. /**
  8451. * Shows the layers dialog if the graph has more than one layer.
  8452. */
  8453. EditorUi.prototype.openLocalFile = function(data, name, temp)
  8454. {
  8455. var currentFile = this.getCurrentFile();
  8456. var fn = mxUtils.bind(this, function()
  8457. {
  8458. window.openFile = null;
  8459. if (name == null && this.getCurrentFile() != null && this.isDiagramEmpty())
  8460. {
  8461. var doc = mxUtils.parseXml(data);
  8462. if (doc != null)
  8463. {
  8464. this.editor.setGraphXml(doc.documentElement);
  8465. this.editor.graph.selectAll();
  8466. }
  8467. }
  8468. else
  8469. {
  8470. this.fileLoaded(new LocalFile(this, data, name || this.defaultFilename, temp));
  8471. }
  8472. });
  8473. if (data != null && data.length > 0)
  8474. {
  8475. if (currentFile == null || (!currentFile.isModified() &&
  8476. (mxClient.IS_CHROMEAPP || EditorUi.isElectronApp)))
  8477. {
  8478. fn();
  8479. }
  8480. else if ((mxClient.IS_CHROMEAPP || EditorUi.isElectronApp) &&
  8481. currentFile != null && currentFile.isModified())
  8482. {
  8483. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8484. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8485. }
  8486. else
  8487. {
  8488. window.openFile = new OpenFile(function()
  8489. {
  8490. window.openFile = null;
  8491. });
  8492. window.openFile.setData(data, name);
  8493. window.openWindow(this.getUrl(), null, mxUtils.bind(this, function()
  8494. {
  8495. if (currentFile != null && currentFile.isModified())
  8496. {
  8497. this.confirm(mxResources.get('allChangesLost'), null, fn,
  8498. mxResources.get('cancel'), mxResources.get('discardChanges'));
  8499. }
  8500. else
  8501. {
  8502. fn();
  8503. }
  8504. }));
  8505. }
  8506. }
  8507. else
  8508. {
  8509. throw new Error(mxResources.get('notADiagramFile'));
  8510. }
  8511. };
  8512. /**
  8513. * Returns a list of all shapes used in the current file.
  8514. */
  8515. EditorUi.prototype.getBasenames = function()
  8516. {
  8517. var basenames = {};
  8518. if (this.pages != null)
  8519. {
  8520. for (var i = 0; i < this.pages.length; i++)
  8521. {
  8522. this.updatePageRoot(this.pages[i]);
  8523. this.addBasenamesForCell(this.pages[i].root, basenames);
  8524. }
  8525. }
  8526. else
  8527. {
  8528. this.addBasenamesForCell(this.editor.graph.model.getRoot(), basenames);
  8529. }
  8530. var result = [];
  8531. for (var key in basenames)
  8532. {
  8533. result.push(key);
  8534. }
  8535. return result;
  8536. };
  8537. /**
  8538. * Returns a list of all shapes used in the current file.
  8539. */
  8540. EditorUi.prototype.addBasenamesForCell = function(cell, basenames)
  8541. {
  8542. function addName(name)
  8543. {
  8544. if (name != null)
  8545. {
  8546. // LATER: Check if this case exists
  8547. var dot = name.lastIndexOf('.');
  8548. if (dot > 0)
  8549. {
  8550. name = name.substring(dot + 1, name.length);
  8551. }
  8552. if (basenames[name] == null)
  8553. {
  8554. basenames[name] = true;
  8555. }
  8556. }
  8557. };
  8558. var graph = this.editor.graph;
  8559. var style = graph.getCellStyle(cell);
  8560. var shape = style[mxConstants.STYLE_SHAPE];
  8561. addName(mxStencilRegistry.getBasenameForStencil(shape));
  8562. // Adds package names for markers in edges
  8563. if (graph.model.isEdge(cell))
  8564. {
  8565. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_STARTARROW]));
  8566. addName(mxMarker.getPackageForType(style[mxConstants.STYLE_ENDARROW]));
  8567. }
  8568. var childCount = graph.model.getChildCount(cell);
  8569. for (var i = 0; i < childCount; i++)
  8570. {
  8571. this.addBasenamesForCell(graph.model.getChildAt(cell, i), basenames);
  8572. }
  8573. };
  8574. /**
  8575. * Shows the layers dialog if the graph has more than one layer.
  8576. */
  8577. EditorUi.prototype.setGraphEnabled = function(enabled)
  8578. {
  8579. this.diagramContainer.style.visibility = (enabled) ? '' : 'hidden';
  8580. this.formatContainer.style.visibility = (enabled) ? '' : 'hidden';
  8581. this.sidebarFooterContainer.style.display = (enabled) ? '' : 'none';
  8582. this.sidebarContainer.style.display = (enabled) ? '' : 'none';
  8583. this.hsplit.style.display = (enabled) ? '' : 'none';
  8584. this.editor.graph.setEnabled(enabled);
  8585. if (this.tabContainer != null)
  8586. {
  8587. this.tabContainer.style.visibility = (enabled) ? '' : 'hidden';
  8588. }
  8589. if (!enabled)
  8590. {
  8591. if (this.actions.outlineWindow != null)
  8592. {
  8593. this.actions.outlineWindow.window.setVisible(false);
  8594. }
  8595. if (this.actions.layersWindow != null)
  8596. {
  8597. this.actions.layersWindow.window.setVisible(false);
  8598. }
  8599. if (this.menus.tagsWindow != null)
  8600. {
  8601. this.menus.tagsWindow.window.setVisible(false);
  8602. }
  8603. if (this.menus.findWindow != null)
  8604. {
  8605. this.menus.findWindow.window.setVisible(false);
  8606. }
  8607. }
  8608. };
  8609. /**
  8610. * Shows the layers dialog if the graph has more than one layer.
  8611. */
  8612. EditorUi.prototype.initializeEmbedMode = function()
  8613. {
  8614. this.setGraphEnabled(false);
  8615. var parent = window.opener || window.parent;
  8616. if (parent != window)
  8617. {
  8618. if (urlParams['spin'] != '1' || this.spinner.spin(document.body, mxResources.get('loading')))
  8619. {
  8620. this.installMessageHandler(mxUtils.bind(this, function(xml, evt, modified)
  8621. {
  8622. this.spinner.stop();
  8623. this.addEmbedButtons();
  8624. this.setGraphEnabled(true);
  8625. if (xml != null && xml.length > 0)
  8626. {
  8627. this.setFileData(xml);
  8628. if (!this.editor.isChromelessView())
  8629. {
  8630. this.showLayersDialog();
  8631. }
  8632. else if (this.editor.graph.isLightboxView())
  8633. {
  8634. this.lightboxFit();
  8635. }
  8636. if (this.chromelessResize)
  8637. {
  8638. this.chromelessResize();
  8639. }
  8640. }
  8641. else
  8642. {
  8643. this.editor.graph.model.clear();
  8644. this.editor.fireEvent(new mxEventObject('resetGraphView'));
  8645. }
  8646. this.editor.undoManager.clear();
  8647. this.editor.modified = (modified != null) ? modified : false;
  8648. this.updateUi();
  8649. // Workaround for no initial focus in FF
  8650. // (does not work in Conf Cloud with FF)
  8651. if (window.self !== window.top)
  8652. {
  8653. window.focus();
  8654. }
  8655. if (this.format != null)
  8656. {
  8657. this.format.refresh();
  8658. }
  8659. }));
  8660. }
  8661. }
  8662. };
  8663. /**
  8664. * Shows the layers dialog if the graph has more than one layer.
  8665. */
  8666. EditorUi.prototype.showLayersDialog = function()
  8667. {
  8668. if (this.editor.graph.getModel().getChildCount(this.editor.graph.getModel().getRoot()) > 1)
  8669. {
  8670. if (this.actions.layersWindow == null)
  8671. {
  8672. this.actions.get('layers').funct();
  8673. }
  8674. else
  8675. {
  8676. this.actions.layersWindow.window.setVisible(true);
  8677. }
  8678. }
  8679. };
  8680. /**
  8681. * Tries to find a public URL for the given file.
  8682. */
  8683. EditorUi.prototype.getPublicUrl = function(file, fn)
  8684. {
  8685. if (file != null)
  8686. {
  8687. file.getPublicUrl(fn);
  8688. }
  8689. else
  8690. {
  8691. fn(null);
  8692. }
  8693. };
  8694. /**
  8695. * Adds the buttons for embedded mode.
  8696. */
  8697. EditorUi.prototype.createLoadMessage = function(eventName)
  8698. {
  8699. var graph = this.editor.graph;
  8700. return {event: eventName, pageVisible: graph.pageVisible, translate: graph.view.translate,
  8701. bounds: graph.getGraphBounds(), currentPage: this.getSelectedPageIndex(),
  8702. scale: graph.view.scale, page: graph.view.getBackgroundPageBounds()};
  8703. };
  8704. /**
  8705. * Adds the buttons for embedded mode.
  8706. */
  8707. EditorUi.prototype.installMessageHandler = function(fn)
  8708. {
  8709. var changeListener = null;
  8710. var ignoreChange = false;
  8711. var autosave = false;
  8712. var lastData = null;
  8713. var updateStatus = mxUtils.bind(this, function(sender, eventObject)
  8714. {
  8715. if (!this.editor.modified || urlParams['modified'] == '0')
  8716. {
  8717. this.editor.setStatus('');
  8718. }
  8719. else if (urlParams['modified'] != null)
  8720. {
  8721. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(urlParams['modified'])));
  8722. }
  8723. });
  8724. this.editor.graph.model.addListener(mxEvent.CHANGE, updateStatus);
  8725. // Receives XML message from opener and puts it into the graph
  8726. mxEvent.addListener(window, 'message', mxUtils.bind(this, function(evt)
  8727. {
  8728. var validSource = window.opener || window.parent;
  8729. if (evt.source != validSource)
  8730. {
  8731. return;
  8732. }
  8733. var data = evt.data;
  8734. var extractDiagramXml = mxUtils.bind(this, function(data)
  8735. {
  8736. if (data != null && typeof data.charAt === 'function' && data.charAt(0) != '<')
  8737. {
  8738. try
  8739. {
  8740. if (data.substring(0, 22) == 'data:image/png;base64,')
  8741. {
  8742. data = this.extractGraphModelFromPng(data);
  8743. }
  8744. else if (data.substring(0, 26) == 'data:image/svg+xml;base64,')
  8745. {
  8746. data = atob(data.substring(26));
  8747. }
  8748. else if (data.substring(0, 24) == 'data:image/svg+xml;utf8,')
  8749. {
  8750. data = data.substring(24);
  8751. }
  8752. if (data != null)
  8753. {
  8754. if (data.charAt(0) == '%')
  8755. {
  8756. data = decodeURIComponent(data);
  8757. }
  8758. else if (data.charAt(0) != '<')
  8759. {
  8760. data = Graph.decompress(data);
  8761. }
  8762. }
  8763. }
  8764. catch (e)
  8765. {
  8766. // ignore compression errors and use empty data
  8767. }
  8768. }
  8769. return data;
  8770. });
  8771. if (urlParams['proto'] == 'json')
  8772. {
  8773. try
  8774. {
  8775. data = JSON.parse(data);
  8776. }
  8777. catch (e)
  8778. {
  8779. data = null;
  8780. }
  8781. if (data == null)
  8782. {
  8783. // Ignore
  8784. return;
  8785. }
  8786. else if (data.action == 'dialog')
  8787. {
  8788. this.showError((data.titleKey != null) ? mxResources.get(data.titleKey) : data.title,
  8789. (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message,
  8790. (data.buttonKey != null) ? mxResources.get(data.buttonKey) : data.button);
  8791. if (data.modified != null)
  8792. {
  8793. this.editor.modified = data.modified;
  8794. }
  8795. return;
  8796. }
  8797. else if (data.action == 'prompt')
  8798. {
  8799. this.spinner.stop();
  8800. var dlg = new FilenameDialog(this, data.defaultValue || '',
  8801. (data.okKey != null) ? mxResources.get(data.okKey) : null, function(value)
  8802. {
  8803. if (value != null)
  8804. {
  8805. parent.postMessage(JSON.stringify({event: 'prompt', value: value, message: data}), '*');
  8806. }
  8807. }, (data.titleKey != null) ? mxResources.get(data.titleKey) : data.title);
  8808. this.showDialog(dlg.container, 300, 80, true, false);
  8809. dlg.init();
  8810. return;
  8811. }
  8812. else if (data.action == 'draft')
  8813. {
  8814. var tmp = extractDiagramXml(data.xml);
  8815. this.spinner.stop();
  8816. var dlg = new DraftDialog(this, mxResources.get('draftFound', [data.name || this.defaultFilename]),
  8817. tmp, mxUtils.bind(this, function()
  8818. {
  8819. this.hideDialog();
  8820. parent.postMessage(JSON.stringify({event: 'draft', result: 'edit', message: data}), '*');
  8821. }), mxUtils.bind(this, function()
  8822. {
  8823. this.hideDialog();
  8824. parent.postMessage(JSON.stringify({event: 'draft', result: 'discard', message: data}), '*');
  8825. }), (data.editKey) ? mxResources.get(data.editKey) : null,
  8826. (data.discardKey) ? mxResources.get(data.discardKey) : null,
  8827. (data.ignore) ? mxUtils.bind(this, function()
  8828. {
  8829. this.hideDialog();
  8830. parent.postMessage(JSON.stringify({event: 'draft', result: 'ignore', message: data}), '*');
  8831. }) : null);
  8832. this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
  8833. {
  8834. if (cancel)
  8835. {
  8836. this.actions.get('exit').funct();
  8837. }
  8838. }));
  8839. try
  8840. {
  8841. dlg.init();
  8842. }
  8843. catch (e)
  8844. {
  8845. parent.postMessage(JSON.stringify({event: 'draft', error: e.toString(), message: data}), '*');
  8846. }
  8847. return;
  8848. }
  8849. else if (data.action == 'template')
  8850. {
  8851. this.spinner.stop();
  8852. var enableRecentDocs = data.enableRecent == 1;
  8853. var enableSearchDocs = data.enableSearch == 1;
  8854. var enableCustomTemp = data.enableCustomTemp == 1;
  8855. var dlg = new NewDialog(this, false, data.callback != null, mxUtils.bind(this, function(xml, name)
  8856. {
  8857. xml = xml || this.emptyDiagramXml;
  8858. // LATER: Add autosave option in template message
  8859. if (data.callback != null)
  8860. {
  8861. parent.postMessage(JSON.stringify({event: 'template', xml: xml,
  8862. blank: xml == this.emptyDiagramXml, name: name}), '*');
  8863. }
  8864. else
  8865. {
  8866. fn(xml, evt, xml != this.emptyDiagramXml);
  8867. // Workaround for status updated before modified applied
  8868. if (!this.editor.modified)
  8869. {
  8870. this.editor.setStatus('');
  8871. }
  8872. }
  8873. }), null, null, null, null, null, null, null,
  8874. enableRecentDocs? mxUtils.bind(this, function(recentReadyCallback)
  8875. {
  8876. this.remoteInvoke('getRecentDiagrams', null, null, recentReadyCallback, function()
  8877. {
  8878. recentReadyCallback(null, 'Network Error!');
  8879. });
  8880. }) : null,
  8881. enableSearchDocs? mxUtils.bind(this, function(searchStr, searchReadyCallback)
  8882. {
  8883. this.remoteInvoke('searchDiagrams', [searchStr], null, searchReadyCallback, function()
  8884. {
  8885. searchReadyCallback(null, 'Network Error!');
  8886. });
  8887. }) : null,
  8888. mxUtils.bind(this, function(url, info, name)
  8889. {
  8890. //If binary files are possible, we can get the file content using remote invokation, imported it, and send final mxFile back
  8891. parent.postMessage(JSON.stringify({event: 'template', docUrl: url, info: info,
  8892. name: name}), '*');
  8893. }), null, null,
  8894. enableCustomTemp? mxUtils.bind(this, function(customTempCallback)
  8895. {
  8896. this.remoteInvoke('getCustomTemplates', null, null, customTempCallback, function()
  8897. {
  8898. customTempCallback({}, 0); //ignore error by sending empty templates
  8899. });
  8900. }) : null);
  8901. this.showDialog(dlg.container, 620, 440, true, false, mxUtils.bind(this, function(cancel)
  8902. {
  8903. if (cancel)
  8904. {
  8905. this.actions.get('exit').funct();
  8906. }
  8907. }));
  8908. dlg.init();
  8909. return;
  8910. }
  8911. else if (data.action == 'textContent')
  8912. {
  8913. //TODO Remove this message and use remove invokation instead
  8914. var allPagesTxt = this.getDiagramTextContent();
  8915. parent.postMessage(JSON.stringify({event: 'textContent', data: allPagesTxt, message: data}), '*');
  8916. return;
  8917. }
  8918. else if (data.action == 'status')
  8919. {
  8920. if (data.messageKey != null)
  8921. {
  8922. this.editor.setStatus(mxUtils.htmlEntities(mxResources.get(data.messageKey)));
  8923. }
  8924. else if (data.message != null)
  8925. {
  8926. this.editor.setStatus(mxUtils.htmlEntities(data.message));
  8927. }
  8928. if (data.modified != null)
  8929. {
  8930. this.editor.modified = data.modified;
  8931. }
  8932. return;
  8933. }
  8934. else if (data.action == 'spinner')
  8935. {
  8936. var msg = (data.messageKey != null) ? mxResources.get(data.messageKey) : data.message;
  8937. if (data.show != null && !data.show)
  8938. {
  8939. this.spinner.stop();
  8940. }
  8941. else
  8942. {
  8943. this.spinner.spin(document.body, msg)
  8944. }
  8945. return;
  8946. }
  8947. else if (data.action == 'export')
  8948. {
  8949. if (data.format == 'png' || data.format == 'xmlpng')
  8950. {
  8951. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  8952. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  8953. {
  8954. var xml = (data.xml != null) ? data.xml : this.getFileData(true);
  8955. this.editor.graph.setEnabled(false);
  8956. var graph = this.editor.graph;
  8957. var postDataBack = mxUtils.bind(this, function(uri)
  8958. {
  8959. this.editor.graph.setEnabled(true);
  8960. this.spinner.stop();
  8961. var msg = this.createLoadMessage('export');
  8962. msg.format = data.format;
  8963. msg.message = data;
  8964. msg.data = uri;
  8965. msg.xml = encodeURIComponent(xml);
  8966. parent.postMessage(JSON.stringify(msg), '*');
  8967. });
  8968. var processUri = mxUtils.bind(this, function(uri)
  8969. {
  8970. if (uri == null)
  8971. {
  8972. uri = Editor.blankImage;
  8973. }
  8974. if (data.format == 'xmlpng')
  8975. {
  8976. uri = this.writeGraphModelToPng(uri, 'zTXt', 'mxGraphModel',
  8977. atob(Graph.compress(xml)));
  8978. }
  8979. // Removes temporary graph from DOM
  8980. if (graph != this.editor.graph)
  8981. {
  8982. graph.container.parentNode.removeChild(graph.container);
  8983. }
  8984. postDataBack(uri);
  8985. });
  8986. // LATER: Uses external export if current page (not first page) has mathEnabled
  8987. if (this.isExportToCanvas())
  8988. {
  8989. // Exports PNG for first page while other page is visible by creating a graph
  8990. // LATER: Add caching for the graph or SVG while not on first page
  8991. if (this.pages != null && this.currentPage != this.pages[0])
  8992. {
  8993. graph = this.createTemporaryGraph(graph.getStylesheet());
  8994. var graphGetGlobalVariable = graph.getGlobalVariable;
  8995. var page = this.pages[0];
  8996. graph.getGlobalVariable = function(name)
  8997. {
  8998. if (name == 'page')
  8999. {
  9000. return page.getName();
  9001. }
  9002. else if (name == 'pagenumber')
  9003. {
  9004. return 1;
  9005. }
  9006. return graphGetGlobalVariable.apply(this, arguments);
  9007. };
  9008. document.body.appendChild(graph.container);
  9009. graph.model.setRoot(page.root);
  9010. }
  9011. this.exportToCanvas(mxUtils.bind(this, function(canvas)
  9012. {
  9013. processUri(canvas.toDataURL('image/png'));
  9014. }), null, null, null, mxUtils.bind(this, function()
  9015. {
  9016. processUri(null);
  9017. }), null, null, data.scale, null, null, null, graph);
  9018. }
  9019. else
  9020. {
  9021. // Data from server is base64 encoded to avoid binary XHR
  9022. // Double encoding for XML arg is needed for UTF8 encoding
  9023. var req = new mxXmlRequest(EXPORT_URL, 'format=png&embedXml=' +
  9024. ((data.format == 'xmlpng') ? '1' : '0') +
  9025. (data.scale != null? '&scale=' + data.scale : '') +'&base64=1&xml=' +
  9026. encodeURIComponent(encodeURIComponent(xml)));
  9027. req.send(mxUtils.bind(this, function(req)
  9028. {
  9029. // Temp graph was never created at this point so we can
  9030. // skip processUri since it already contains the XML
  9031. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  9032. {
  9033. postDataBack('data:image/png;base64,' + req.getText());
  9034. }
  9035. else
  9036. {
  9037. processUri(null);
  9038. }
  9039. }), mxUtils.bind(this, function()
  9040. {
  9041. processUri(null);
  9042. }));
  9043. }
  9044. }
  9045. }
  9046. else
  9047. {
  9048. // SVG is generated from graph so parse optional XML
  9049. if (data.xml != null && data.xml.length > 0)
  9050. {
  9051. this.setFileData(data.xml);
  9052. }
  9053. var msg = this.createLoadMessage('export');
  9054. // Forces new HTML format if pages exists
  9055. if (data.format == 'html2' || (data.format == 'html' && (urlParams['pages'] != '0' ||
  9056. (this.pages != null && this.pages.length > 1))))
  9057. {
  9058. var node = this.getXmlFileData();
  9059. msg.xml = mxUtils.getXml(node);
  9060. msg.data = this.getFileData(null, null, true, null, null, null, node);
  9061. msg.format = data.format;
  9062. }
  9063. else if (data.format == 'html')
  9064. {
  9065. var xml = this.editor.getGraphXml();
  9066. msg.data = this.getHtml(xml, this.editor.graph);
  9067. msg.xml = mxUtils.getXml(xml);
  9068. msg.format = data.format;
  9069. }
  9070. else
  9071. {
  9072. // Creates a preview with no alt text for unsupported browsers
  9073. mxSvgCanvas2D.prototype.foAltText = null;
  9074. var bg = this.editor.graph.background;
  9075. if (bg == mxConstants.NONE)
  9076. {
  9077. bg = null;
  9078. }
  9079. msg.xml = this.getFileData(true);
  9080. msg.format = 'svg';
  9081. if (data.embedImages || data.embedImages == null)
  9082. {
  9083. if ((data.spin == null && data.spinKey == null) || this.spinner.spin(document.body,
  9084. (data.spinKey != null) ? mxResources.get(data.spinKey) : data.spin))
  9085. {
  9086. this.editor.graph.setEnabled(false);
  9087. if (data.format == 'xmlsvg')
  9088. {
  9089. this.getEmbeddedSvg(msg.xml, this.editor.graph, null, true, mxUtils.bind(this, function(svg)
  9090. {
  9091. this.editor.graph.setEnabled(true);
  9092. this.spinner.stop();
  9093. msg.data = this.createSvgDataUri(svg);
  9094. parent.postMessage(JSON.stringify(msg), '*');
  9095. }));
  9096. }
  9097. else
  9098. {
  9099. this.convertImages(this.editor.graph.getSvg(bg), mxUtils.bind(this, function(svgRoot)
  9100. {
  9101. this.editor.graph.setEnabled(true);
  9102. this.spinner.stop();
  9103. msg.data = this.createSvgDataUri(mxUtils.getXml(svgRoot));
  9104. parent.postMessage(JSON.stringify(msg), '*');
  9105. }));
  9106. }
  9107. }
  9108. return;
  9109. }
  9110. else
  9111. {
  9112. var svg = (data.format == 'xmlsvg') ? this.getEmbeddedSvg(this.getFileData(true),
  9113. this.editor.graph, null, true) : mxUtils.getXml(this.editor.graph.getSvg(bg));
  9114. msg.data = this.createSvgDataUri(svg);
  9115. }
  9116. }
  9117. parent.postMessage(JSON.stringify(msg), '*');
  9118. }
  9119. return;
  9120. }
  9121. else if (data.action == 'load')
  9122. {
  9123. autosave = data.autosave == 1;
  9124. this.hideDialog();
  9125. if (data.modified != null && urlParams['modified'] == null)
  9126. {
  9127. urlParams['modified'] = data.modified;
  9128. }
  9129. if (data.saveAndExit != null && urlParams['saveAndExit'] == null)
  9130. {
  9131. urlParams['saveAndExit'] = data.saveAndExit;
  9132. }
  9133. if (data.title != null && this.buttonContainer != null)
  9134. {
  9135. var tmp = document.createElement('span');
  9136. mxUtils.write(tmp, data.title);
  9137. if (uiTheme == 'atlas')
  9138. {
  9139. this.buttonContainer.style.paddingRight = '12px';
  9140. this.buttonContainer.style.paddingTop = '6px';
  9141. this.buttonContainer.style.right = '25px';
  9142. }
  9143. else if (uiTheme != 'min')
  9144. {
  9145. this.buttonContainer.style.paddingRight = '38px';
  9146. this.buttonContainer.style.paddingTop = '6px';
  9147. }
  9148. if (this.embedFilenameSpan != null)
  9149. {
  9150. this.embedFilenameSpan.parentNode.removeChild(this.embedFilenameSpan);
  9151. }
  9152. this.buttonContainer.appendChild(tmp);
  9153. this.embedFilenameSpan = tmp;
  9154. }
  9155. if (data.xmlpng != null)
  9156. {
  9157. data = this.extractGraphModelFromPng(data.xmlpng);
  9158. }
  9159. else
  9160. {
  9161. data = data.xml;
  9162. }
  9163. }
  9164. else if (data.action == 'remoteInvokeReady')
  9165. {
  9166. this.handleRemoteInvokeReady(parent);
  9167. return;
  9168. }
  9169. else if (data.action == 'remoteInvoke')
  9170. {
  9171. this.handleRemoteInvoke(data);
  9172. return;
  9173. }
  9174. else if (data.action == 'remoteInvokeResponse')
  9175. {
  9176. this.handleRemoteInvokeResponse(data);
  9177. return;
  9178. }
  9179. else
  9180. {
  9181. // Unknown message must stop execution
  9182. parent.postMessage(JSON.stringify({error: 'unknownMessage', data: JSON.stringify(data)}), '*');
  9183. return;
  9184. }
  9185. }
  9186. var doLoad = mxUtils.bind(this, function(data, evt)
  9187. {
  9188. ignoreChange = true;
  9189. try
  9190. {
  9191. fn(data, evt);
  9192. }
  9193. catch (e)
  9194. {
  9195. this.handleError(e);
  9196. }
  9197. ignoreChange = false;
  9198. if (urlParams['modified'] != null)
  9199. {
  9200. this.editor.setStatus('');
  9201. }
  9202. var getData = mxUtils.bind(this, function()
  9203. {
  9204. return (urlParams['pages'] != '0' || (this.pages != null && this.pages.length > 1)) ?
  9205. this.getFileData(true): mxUtils.getXml(this.editor.getGraphXml());
  9206. });;
  9207. lastData = getData();
  9208. if (autosave && changeListener == null)
  9209. {
  9210. changeListener = mxUtils.bind(this, function(sender, eventObject)
  9211. {
  9212. var data = getData();
  9213. if (data != lastData && !ignoreChange)
  9214. {
  9215. var msg = this.createLoadMessage('autosave');
  9216. msg.xml = data;
  9217. data = JSON.stringify(msg);
  9218. var parent = window.opener || window.parent;
  9219. parent.postMessage(data, '*');
  9220. }
  9221. lastData = data;
  9222. });
  9223. this.editor.graph.model.addListener(mxEvent.CHANGE, changeListener);
  9224. // Some options trigger autosave
  9225. this.editor.graph.addListener('gridSizeChanged', changeListener);
  9226. this.editor.graph.addListener('shadowVisibleChanged', changeListener);
  9227. this.addListener('pageFormatChanged', changeListener);
  9228. this.addListener('pageScaleChanged', changeListener);
  9229. this.addListener('backgroundColorChanged', changeListener);
  9230. this.addListener('backgroundImageChanged', changeListener);
  9231. this.addListener('foldingEnabledChanged', changeListener);
  9232. this.addListener('mathEnabledChanged', changeListener);
  9233. this.addListener('gridEnabledChanged', changeListener);
  9234. this.addListener('guidesEnabledChanged', changeListener);
  9235. this.addListener('pageViewChanged', changeListener);
  9236. }
  9237. // Sends the bounds of the graph to the host after parsing
  9238. if (urlParams['returnbounds'] == '1' || urlParams['proto'] == 'json')
  9239. {
  9240. parent.postMessage(JSON.stringify(this.createLoadMessage('load')), '*');
  9241. }
  9242. });
  9243. if (data != null && typeof data.substring === 'function' && data.substring(0, 34) == 'data:application/vnd.visio;base64,')
  9244. {
  9245. // Checks VND binary magic number in base64
  9246. var filename = (data.substring(34, 45) == '0M8R4KGxGuE') ? 'raw.vsd' : 'raw.vsdx';
  9247. this.importVisio(this.base64ToBlob(data.substring(data.indexOf(',') + 1)), function(xml)
  9248. {
  9249. doLoad(xml, evt);
  9250. }, mxUtils.bind(this, function(e)
  9251. {
  9252. this.handleError(e);
  9253. }), filename);
  9254. }
  9255. else if (data != null && typeof data.substring === 'function' && !this.isOffline() && new XMLHttpRequest().upload && this.isRemoteFileFormat(data, ''))
  9256. {
  9257. // Asynchronous parsing via server
  9258. this.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  9259. {
  9260. if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 299 &&
  9261. xhr.responseText.substring(0, 13) == '<mxGraphModel')
  9262. {
  9263. doLoad(xhr.responseText, evt);
  9264. }
  9265. }), '');
  9266. }
  9267. else if (data != null && typeof data.substring === 'function' && this.isLucidChartData(data))
  9268. {
  9269. this.convertLucidChart(data, mxUtils.bind(this, function(xml)
  9270. {
  9271. doLoad(xml);
  9272. }), mxUtils.bind(this, function(e)
  9273. {
  9274. this.handleError(e);
  9275. }));
  9276. }
  9277. else
  9278. {
  9279. data = extractDiagramXml(data);
  9280. doLoad(data, evt);
  9281. }
  9282. }));
  9283. // Requests data from the sender. This is a workaround for not allowing
  9284. // the opener to listen for the onload event if not in the same origin.
  9285. var parent = window.opener || window.parent;
  9286. var msg = (urlParams['proto'] == 'json') ? JSON.stringify({event: 'init'}) : (urlParams['ready'] || 'ready');
  9287. parent.postMessage(msg, '*');
  9288. };
  9289. /**
  9290. * Adds the buttons for embedded mode.
  9291. */
  9292. EditorUi.prototype.addEmbedButtons = function()
  9293. {
  9294. if (this.menubar != null)
  9295. {
  9296. var div = document.createElement('div');
  9297. div.style.display = 'inline-block';
  9298. div.style.position = 'absolute';
  9299. div.style.paddingTop = (uiTheme == 'atlas') ? '2px' : '3px';
  9300. div.style.paddingLeft = '8px';
  9301. div.style.paddingBottom = '2px';
  9302. var button = document.createElement('button');
  9303. button.className = 'geBigButton';
  9304. button.style.fontSize = '12px';
  9305. button.style.padding = '4px 6px 4px 6px';
  9306. button.style.borderRadius = '3px';
  9307. if (urlParams['noSaveBtn'] == '1')
  9308. {
  9309. mxUtils.write(button, mxResources.get('saveAndExit'));
  9310. button.setAttribute('title', mxResources.get('saveAndExit'));
  9311. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9312. {
  9313. this.actions.get('saveAndExit').funct();
  9314. }));
  9315. div.appendChild(button);
  9316. }
  9317. else
  9318. {
  9319. mxUtils.write(button, mxResources.get('save'));
  9320. button.setAttribute('title', mxResources.get('save') + ' (' + Editor.ctrlKey + '+S)');
  9321. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9322. {
  9323. this.actions.get('save').funct();
  9324. }));
  9325. div.appendChild(button);
  9326. if (urlParams['saveAndExit'] == '1')
  9327. {
  9328. button = document.createElement('a');
  9329. mxUtils.write(button, mxResources.get('saveAndExit'));
  9330. button.setAttribute('title', mxResources.get('saveAndExit'));
  9331. button.style.fontSize = '12px';
  9332. button.style.marginLeft = '6px';
  9333. button.style.padding = '4px';
  9334. button.style.cursor = 'pointer';
  9335. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9336. {
  9337. this.actions.get('saveAndExit').funct();
  9338. }));
  9339. div.appendChild(button);
  9340. }
  9341. }
  9342. button = document.createElement('a');
  9343. mxUtils.write(button, mxResources.get('exit'));
  9344. button.setAttribute('title', mxResources.get('exit'));
  9345. button.style.fontSize = '12px';
  9346. button.style.marginLeft = '6px';
  9347. button.style.marginRight = '20px';
  9348. button.style.padding = '4px';
  9349. button.style.cursor = 'pointer';
  9350. mxEvent.addListener(button, 'click', mxUtils.bind(this, function()
  9351. {
  9352. this.actions.get('exit').funct();
  9353. }));
  9354. div.appendChild(button);
  9355. this.toolbar.container.appendChild(div);
  9356. this.toolbar.staticElements.push(div);
  9357. div.style.right = (uiTheme != 'atlas') ? '52px' : '42px';
  9358. }
  9359. };
  9360. /**
  9361. *
  9362. */
  9363. EditorUi.prototype.showImportCsvDialog = function()
  9364. {
  9365. if (this.importCsvDialog == null)
  9366. {
  9367. this.importCsvDialog = new TextareaDialog(this, mxResources.get('csv') + ':',
  9368. Editor.defaultCsvValue, mxUtils.bind(this, function(newValue)
  9369. {
  9370. this.importCsv(newValue);
  9371. }), null, null, 620, 430, null, true, true, mxResources.get('import'));
  9372. }
  9373. this.showDialog(this.importCsvDialog.container, 640, 520, true, true);
  9374. this.importCsvDialog.init();
  9375. };
  9376. /**
  9377. * Runs the layout from the given JavaScript array which is of the form [{layout: name, config: obj}, ...]
  9378. * where name is the layout constructor name and config contains the properties of the layout instance.
  9379. */
  9380. EditorUi.prototype.executeLayoutList = function(layoutList, done)
  9381. {
  9382. var graph = this.editor.graph;
  9383. var cells = graph.getSelectionCells();
  9384. for (var i = 0; i < layoutList.length; i++)
  9385. {
  9386. var layout = new window[layoutList[i].layout](graph);
  9387. if (layoutList[i].config != null)
  9388. {
  9389. for (var key in layoutList[i].config)
  9390. {
  9391. layout[key] = layoutList[i].config[key];
  9392. }
  9393. }
  9394. this.executeLayout(function()
  9395. {
  9396. layout.execute(graph.getDefaultParent(), cells.length == 0 ? null : cells);
  9397. }, i == layoutList.length - 1, done);
  9398. }
  9399. };
  9400. /**
  9401. *
  9402. */
  9403. EditorUi.prototype.importCsv = function(text, done)
  9404. {
  9405. try
  9406. {
  9407. var lines = text.split('\n');
  9408. var allCells = [];
  9409. var cells = [];
  9410. var dups = {};
  9411. if (lines.length > 0)
  9412. {
  9413. // Internal lookup table
  9414. var lookups = {};
  9415. // Default values
  9416. var style = null;
  9417. var parentstyle = null;
  9418. var identity = null;
  9419. var parent = null;
  9420. var namespace = '';
  9421. var width = 'auto';
  9422. var height = 'auto';
  9423. var left = null;
  9424. var top = null;
  9425. var edgespacing = 40;
  9426. var nodespacing = 40;
  9427. var levelspacing = 100;
  9428. var padding = 0;
  9429. var graph = this.editor.graph;
  9430. var view = graph.view;
  9431. var bds = graph.getGraphBounds();
  9432. // Delayed after optional layout
  9433. var afterInsert = function()
  9434. {
  9435. if (done != null)
  9436. {
  9437. done(select);
  9438. }
  9439. else
  9440. {
  9441. graph.setSelectionCells(select);
  9442. graph.scrollCellToVisible(graph.getSelectionCell());
  9443. }
  9444. };
  9445. // Computes unscaled, untranslated graph bounds
  9446. var pt = graph.getFreeInsertPoint();
  9447. var x0 = pt.x;
  9448. var y0 = pt.y;
  9449. var y = y0;
  9450. // Default label value depends on column names
  9451. var label = null;
  9452. // Default layout to run.
  9453. var layout = 'auto';
  9454. // Name of the attribute that contains the parent reference
  9455. var parent = null;
  9456. // Name of the attribute that contains the references for creating edges
  9457. var edges = [];
  9458. // Name of the column for hyperlinks
  9459. var link = null;
  9460. // String array of names to remove from metadata
  9461. var ignore = null;
  9462. // Read processing instructions first
  9463. var index = 0;
  9464. while (index < lines.length && lines[index].charAt(0) == '#')
  9465. {
  9466. var text = lines[index];
  9467. index++;
  9468. while (index < lines.length && text.charAt(text.length - 1) == '\\' &&
  9469. lines[index].charAt(0) == '#')
  9470. {
  9471. text = text.substring(0, text.length - 1) + mxUtils.trim(lines[index].substring(1));
  9472. index++;
  9473. }
  9474. if (text.charAt(1) != '#')
  9475. {
  9476. // Processing instruction
  9477. var idx = text.indexOf(':');
  9478. if (idx > 0)
  9479. {
  9480. var key = mxUtils.trim(text.substring(1, idx));
  9481. var value = mxUtils.trim(text.substring(idx + 1));
  9482. if (key == 'label')
  9483. {
  9484. label = graph.sanitizeHtml(value);
  9485. }
  9486. else if (key == 'style')
  9487. {
  9488. style = value;
  9489. }
  9490. else if (key == 'parentstyle')
  9491. {
  9492. parentstyle = value;
  9493. }
  9494. else if (key == 'identity' && value.length > 0 && value != '-')
  9495. {
  9496. identity = value;
  9497. }
  9498. else if (key == 'parent' && value.length > 0 && value != '-')
  9499. {
  9500. parent = value;
  9501. }
  9502. else if (key == 'namespace' && value.length > 0 && value != '-')
  9503. {
  9504. namespace = value;
  9505. }
  9506. else if (key == 'width')
  9507. {
  9508. width = value;
  9509. }
  9510. else if (key == 'height')
  9511. {
  9512. height = value;
  9513. }
  9514. else if (key == 'left' && value.length > 0)
  9515. {
  9516. left = value;
  9517. }
  9518. else if (key == 'top' && value.length > 0)
  9519. {
  9520. top = value;
  9521. }
  9522. else if (key == 'ignore')
  9523. {
  9524. ignore = value.split(',');
  9525. }
  9526. else if (key == 'connect')
  9527. {
  9528. edges.push(JSON.parse(value));
  9529. }
  9530. else if (key == 'link')
  9531. {
  9532. link = value;
  9533. }
  9534. else if (key == 'padding')
  9535. {
  9536. padding = parseFloat(value);
  9537. }
  9538. else if (key == 'edgespacing')
  9539. {
  9540. edgespacing = parseFloat(value);
  9541. }
  9542. else if (key == 'nodespacing')
  9543. {
  9544. nodespacing = parseFloat(value);
  9545. }
  9546. else if (key == 'levelspacing')
  9547. {
  9548. levelspacing = parseFloat(value);
  9549. }
  9550. else if (key == 'layout')
  9551. {
  9552. layout = value;
  9553. }
  9554. }
  9555. }
  9556. }
  9557. if (lines[index] == null)
  9558. {
  9559. throw new Error(mxResources.get('invalidOrMissingFile'));
  9560. }
  9561. var keys = this.editor.csvToArray(lines[index]);
  9562. // Converts name of identity and parent to indexes of column
  9563. var identityIndex = null;
  9564. var parentIndex = null;
  9565. if (identity != null || parent != null)
  9566. {
  9567. for (var i = 0; i < keys.length; i++)
  9568. {
  9569. if (identity == keys[i])
  9570. {
  9571. identityIndex = i;
  9572. }
  9573. if (parent == keys[i])
  9574. {
  9575. parentIndex = i;
  9576. }
  9577. }
  9578. }
  9579. if (label == null)
  9580. {
  9581. label = '%' + keys[0] + '%';
  9582. }
  9583. if (edges != null)
  9584. {
  9585. for (var e = 0; e < edges.length; e++)
  9586. {
  9587. if (lookups[edges[e].to] == null)
  9588. {
  9589. lookups[edges[e].to] = {};
  9590. }
  9591. }
  9592. }
  9593. graph.model.beginUpdate();
  9594. try
  9595. {
  9596. for (var i = index + 1; i < lines.length; i++)
  9597. {
  9598. var values = this.editor.csvToArray(lines[i]);
  9599. if (values == null)
  9600. {
  9601. var short = (lines[i].length > 40) ? lines[i].substring(0, 40) + '...' : lines[i];
  9602. throw new Error(i + ' (' + short + ') ' + mxResources.get('containsValidationErrors'));
  9603. }
  9604. else if (values.length == keys.length)
  9605. {
  9606. var cell = null;
  9607. var id = (identityIndex != null) ? namespace + values[identityIndex] : null;
  9608. if (id != null)
  9609. {
  9610. cell = graph.model.getCell(id);
  9611. }
  9612. var exists = cell != null;
  9613. var newCell = new mxCell(label, new mxGeometry(x0, y,
  9614. 0, 0), style || 'whiteSpace=wrap;html=1;');
  9615. newCell.vertex = true;
  9616. newCell.id = id;
  9617. for (var j = 0; j < values.length; j++)
  9618. {
  9619. graph.setAttributeForCell(newCell, keys[j], values[j]);
  9620. }
  9621. graph.setAttributeForCell(newCell, 'placeholders', '1');
  9622. newCell.style = graph.replacePlaceholders(newCell, newCell.style);
  9623. if (exists)
  9624. {
  9625. graph.model.setGeometry(cell, newCell.geometry);
  9626. graph.model.setStyle(cell, newCell.style);
  9627. if (mxUtils.indexOf(cells, cell) < 0)
  9628. {
  9629. cells.push(cell);
  9630. }
  9631. }
  9632. cell = newCell;
  9633. if (!exists)
  9634. {
  9635. for (var e = 0; e < edges.length; e++)
  9636. {
  9637. lookups[edges[e].to][cell.getAttribute(edges[e].to)] = cell;
  9638. }
  9639. }
  9640. if (link != null && link != 'link')
  9641. {
  9642. graph.setLinkForCell(cell, cell.getAttribute(link));
  9643. // Removes attribute
  9644. graph.setAttributeForCell(cell, link, null);
  9645. }
  9646. // Sets the size
  9647. graph.fireEvent(new mxEventObject('cellsInserted', 'cells', [cell]));
  9648. var size = this.editor.graph.getPreferredSizeForCell(cell);
  9649. if (cell.vertex)
  9650. {
  9651. if (left != null && cell.getAttribute(left) != null)
  9652. {
  9653. cell.geometry.x = x0 + parseFloat(cell.getAttribute(left));
  9654. }
  9655. if (top != null && cell.getAttribute(top) != null)
  9656. {
  9657. cell.geometry.y = y0 + parseFloat(cell.getAttribute(top));
  9658. }
  9659. if (width.charAt(0) == '@' && cell.getAttribute(width.substring(1)) != null)
  9660. {
  9661. cell.geometry.width = parseFloat(cell.getAttribute(width.substring(1)));
  9662. }
  9663. else
  9664. {
  9665. cell.geometry.width = (width == 'auto') ? size.width + padding : parseFloat(width);
  9666. }
  9667. if (height.charAt(0) == '@' && cell.getAttribute(height.substring(1)) != null)
  9668. {
  9669. cell.geometry.height = parseFloat(cell.getAttribute(height.substring(1)));
  9670. }
  9671. else
  9672. {
  9673. cell.geometry.height = (height == 'auto') ? size.height + padding : parseFloat(height);
  9674. }
  9675. y += cell.geometry.height + nodespacing;
  9676. }
  9677. if (!exists)
  9678. {
  9679. var parent = (parentIndex != null) ? graph.model.getCell(
  9680. namespace + values[parentIndex]) : null;
  9681. allCells.push(cell);
  9682. if (parent != null)
  9683. {
  9684. parent.style = graph.replacePlaceholders(parent, parentstyle);
  9685. graph.addCell(cell, parent);
  9686. }
  9687. else
  9688. {
  9689. cells.push(graph.addCell(cell));
  9690. }
  9691. }
  9692. else
  9693. {
  9694. if (dups[id] == null)
  9695. {
  9696. dups[id] = [];
  9697. }
  9698. dups[id].push(cell);
  9699. }
  9700. }
  9701. }
  9702. var roots = cells.slice();
  9703. var select = cells.slice();
  9704. for (var e = 0; e < edges.length; e++)
  9705. {
  9706. var edge = edges[e];
  9707. for (var i = 0; i < cells.length; i++)
  9708. {
  9709. var cell = cells[i];
  9710. var insertEdge = mxUtils.bind(this, function(realCell, dataCell, edge)
  9711. {
  9712. var tmp = dataCell.getAttribute(edge.from);
  9713. if (tmp != null)
  9714. {
  9715. // Removes attribute
  9716. graph.setAttributeForCell(dataCell, edge.from, null);
  9717. var refs = tmp.split(',');
  9718. for (var j = 0; j < refs.length; j++)
  9719. {
  9720. var ref = lookups[edge.to][refs[j]];
  9721. if (ref != null)
  9722. {
  9723. var label = edge.label;
  9724. if (edge.fromlabel != null)
  9725. {
  9726. label = (dataCell.getAttribute(edge.fromlabel) || '') + (label || '');
  9727. }
  9728. if (edge.tolabel != null)
  9729. {
  9730. label = (label || '') + (ref.getAttribute(edge.tolabel) || '');
  9731. }
  9732. select.push(graph.insertEdge(null, null, label || '',
  9733. (edge.invert) ? ref : realCell, (edge.invert) ? realCell : ref,
  9734. edge.style || graph.createCurrentEdgeStyle()));
  9735. mxUtils.remove((edge.invert) ? realCell : ref, roots);
  9736. }
  9737. }
  9738. }
  9739. });
  9740. insertEdge(cell, cell, edge);
  9741. // Checks more entries
  9742. if (dups[cell.id] != null)
  9743. {
  9744. for (var j = 0; j < dups[cell.id].length; j++)
  9745. {
  9746. insertEdge(cell, dups[cell.id][j], edge);
  9747. }
  9748. }
  9749. }
  9750. }
  9751. // Removes ignored attributes after processing above
  9752. if (ignore != null)
  9753. {
  9754. for (var i = 0; i < allCells.length; i++)
  9755. {
  9756. var cell = allCells[i];
  9757. for (var j = 0; j < ignore.length; j++)
  9758. {
  9759. graph.setAttributeForCell(cell, mxUtils.trim(ignore[j]), null);
  9760. }
  9761. }
  9762. }
  9763. if (cells.length > 0)
  9764. {
  9765. var edgeLayout = new mxParallelEdgeLayout(graph);
  9766. edgeLayout.spacing = edgespacing;
  9767. var postProcess = function()
  9768. {
  9769. if (edgeLayout.spacing > 0)
  9770. {
  9771. edgeLayout.execute(graph.getDefaultParent());
  9772. }
  9773. // Aligns cells to grid and/or rounds positions
  9774. for (var i = 0; i < cells.length; i++)
  9775. {
  9776. var geo = graph.getCellGeometry(cells[i]);
  9777. geo.x = Math.round(graph.snap(geo.x));
  9778. geo.y = Math.round(graph.snap(geo.y));
  9779. if (width == 'auto')
  9780. {
  9781. geo.width = Math.round(graph.snap(geo.width));
  9782. }
  9783. if (height == 'auto')
  9784. {
  9785. geo.height = Math.round(graph.snap(geo.height));
  9786. }
  9787. }
  9788. };
  9789. if (layout.charAt(0) == '[')
  9790. {
  9791. // Required for layouts to work with new cells
  9792. var temp = afterInsert;
  9793. graph.view.validate();
  9794. this.executeLayoutList(JSON.parse(layout), function()
  9795. {
  9796. postProcess();
  9797. temp();
  9798. });
  9799. afterInsert = null;
  9800. }
  9801. else if (layout == 'circle')
  9802. {
  9803. var circleLayout = new mxCircleLayout(graph);
  9804. circleLayout.resetEdges = false;
  9805. var circleLayoutIsVertexIgnored = circleLayout.isVertexIgnored;
  9806. // Ignore other cells
  9807. circleLayout.isVertexIgnored = function(vertex)
  9808. {
  9809. return circleLayoutIsVertexIgnored.apply(this, arguments) ||
  9810. mxUtils.indexOf(cells, vertex) < 0;
  9811. };
  9812. this.executeLayout(function()
  9813. {
  9814. circleLayout.execute(graph.getDefaultParent());
  9815. postProcess();
  9816. }, true, afterInsert);
  9817. afterInsert = null;
  9818. }
  9819. else if (layout == 'horizontaltree' || layout == 'verticaltree' ||
  9820. (layout == 'auto' && select.length == 2 * cells.length - 1 && roots.length == 1))
  9821. {
  9822. // Required for layouts to work with new cells
  9823. graph.view.validate();
  9824. var treeLayout = new mxCompactTreeLayout(graph, layout == 'horizontaltree');
  9825. treeLayout.levelDistance = nodespacing;
  9826. treeLayout.edgeRouting = false;
  9827. treeLayout.resetEdges = false;
  9828. this.executeLayout(function()
  9829. {
  9830. treeLayout.execute(graph.getDefaultParent(), (roots.length > 0) ? roots[0] : null);
  9831. }, true, afterInsert);
  9832. afterInsert = null;
  9833. }
  9834. else if (layout == 'horizontalflow' || layout == 'verticalflow' ||
  9835. (layout == 'auto' && roots.length == 1))
  9836. {
  9837. // Required for layouts to work with new cells
  9838. graph.view.validate();
  9839. var flowLayout = new mxHierarchicalLayout(graph,
  9840. (layout == 'horizontalflow') ? mxConstants.DIRECTION_WEST : mxConstants.DIRECTION_NORTH);
  9841. flowLayout.intraCellSpacing = nodespacing;
  9842. flowLayout.parallelEdgeSpacing = edgespacing;
  9843. flowLayout.interRankCellSpacing = levelspacing;
  9844. flowLayout.disableEdgeStyle = false;
  9845. this.executeLayout(function()
  9846. {
  9847. flowLayout.execute(graph.getDefaultParent(), select);
  9848. // Workaround for flow layout moving cells to origin
  9849. graph.moveCells(select, x0, y0);
  9850. }, true, afterInsert);
  9851. afterInsert = null;
  9852. }
  9853. else if (layout == 'organic' || (layout == 'auto' &&
  9854. select.length > cells.length))
  9855. {
  9856. // Required for layouts to work with new cells
  9857. graph.view.validate();
  9858. var organicLayout = new mxFastOrganicLayout(graph);
  9859. organicLayout.forceConstant = nodespacing * 3;
  9860. organicLayout.resetEdges = false;
  9861. var organicLayoutIsVertexIgnored = organicLayout.isVertexIgnored;
  9862. // Ignore other cells
  9863. organicLayout.isVertexIgnored = function(vertex)
  9864. {
  9865. return organicLayoutIsVertexIgnored.apply(this, arguments) ||
  9866. mxUtils.indexOf(cells, vertex) < 0;
  9867. };
  9868. var edgeLayout = new mxParallelEdgeLayout(graph);
  9869. edgeLayout.spacing = edgespacing;
  9870. this.executeLayout(function()
  9871. {
  9872. organicLayout.execute(graph.getDefaultParent());
  9873. postProcess();
  9874. }, true, afterInsert);
  9875. afterInsert = null;
  9876. }
  9877. }
  9878. this.hideDialog();
  9879. }
  9880. finally
  9881. {
  9882. graph.model.endUpdate();
  9883. }
  9884. if (afterInsert != null)
  9885. {
  9886. afterInsert();
  9887. }
  9888. }
  9889. }
  9890. catch (e)
  9891. {
  9892. this.handleError(e);
  9893. }
  9894. };
  9895. /**
  9896. * Translates this point by the given vector.
  9897. *
  9898. * @param {number} dx X-coordinate of the translation.
  9899. * @param {number} dy Y-coordinate of the translation.
  9900. */
  9901. EditorUi.prototype.getSearch = function(exclude)
  9902. {
  9903. var result = '';
  9904. if (urlParams['offline'] != '1' && urlParams['demo'] != '1' && exclude != null && window.location.search.length > 0)
  9905. {
  9906. var amp = '?';
  9907. for (var key in urlParams)
  9908. {
  9909. if (mxUtils.indexOf(exclude, key) < 0 && urlParams[key] != null)
  9910. {
  9911. result += amp + key + '=' + urlParams[key];
  9912. amp = '&';
  9913. }
  9914. }
  9915. }
  9916. else
  9917. {
  9918. result = window.location.search;
  9919. }
  9920. return result;
  9921. };
  9922. /**
  9923. * Returns the URL for a copy of this editor with no state.
  9924. */
  9925. EditorUi.prototype.getUrl = function(pathname)
  9926. {
  9927. var href = (pathname != null) ? pathname : window.location.pathname;
  9928. var parms = (href.indexOf('?') > 0) ? 1 : 0;
  9929. if (urlParams['offline'] == '1')
  9930. {
  9931. href += window.location.search;
  9932. }
  9933. else
  9934. {
  9935. var ignored = ['tmp', 'libs', 'clibs', 'state', 'fileId', 'code', 'share', 'notitle',
  9936. 'data', 'url', 'embed', 'client', 'create', 'title', 'splash'];
  9937. // Removes template URL parameter for new blank diagram
  9938. for (var key in urlParams)
  9939. {
  9940. if (mxUtils.indexOf(ignored, key) < 0)
  9941. {
  9942. if (parms == 0)
  9943. {
  9944. href += '?';
  9945. }
  9946. else
  9947. {
  9948. href += '&';
  9949. }
  9950. if (urlParams[key] != null)
  9951. {
  9952. href += key + '=' + urlParams[key];
  9953. parms++;
  9954. }
  9955. }
  9956. }
  9957. }
  9958. return href;
  9959. };
  9960. /**
  9961. * Overrides link dialog.
  9962. */
  9963. EditorUi.prototype.showLinkDialog = function(value, btnLabel, fn)
  9964. {
  9965. var dlg = new LinkDialog(this, value, btnLabel, fn, true);
  9966. this.showDialog(dlg.container, 480, 130, true, true);
  9967. dlg.init();
  9968. };
  9969. /**
  9970. * Overrides createOutline
  9971. */
  9972. var editorUiCreateOutline = EditorUi.prototype.createOutline;
  9973. EditorUi.prototype.createOutline = function(wnd)
  9974. {
  9975. var outline = editorUiCreateOutline.apply(this, arguments);
  9976. var graph = this.editor.graph;
  9977. var outlineGetSourceGraphBounds = outline.getSourceGraphBounds;
  9978. outline.getSourceGraphBounds = function()
  9979. {
  9980. if (mxUtils.hasScrollbars(graph.container) && graph.pageVisible && this.source.minimumGraphSize != null)
  9981. {
  9982. var pb = this.source.getPagePadding();
  9983. var s = this.source.view.scale;
  9984. var result = new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width - 2 * pb.x / s),
  9985. Math.ceil(this.source.minimumGraphSize.height - 2 * pb.y / s));
  9986. return result;
  9987. }
  9988. return outlineGetSourceGraphBounds.apply(this, arguments);
  9989. };
  9990. var outlineGetSourceContainerSize = outline.getSourceContainerSize;
  9991. outline.getSourceContainerSize = function()
  9992. {
  9993. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  9994. {
  9995. var pad = this.source.getPagePadding();
  9996. var s = this.source.view.scale;
  9997. return new mxRectangle(0, 0, Math.ceil(this.source.minimumGraphSize.width * s - 2 * pad.x),
  9998. Math.ceil(this.source.minimumGraphSize.height * s - 2 * pad.y));
  9999. }
  10000. return outlineGetSourceContainerSize.apply(this, arguments);
  10001. };
  10002. outline.getOutlineOffset = function(scale)
  10003. {
  10004. if (mxUtils.hasScrollbars(graph.container) && this.source.minimumGraphSize != null)
  10005. {
  10006. var pb = this.source.getPagePadding();
  10007. var dx = Math.max(0, (outline.outline.container.clientWidth / scale - (this.source.minimumGraphSize.width - 2 * pb.x)) / 2);
  10008. var dy = Math.max(0, (outline.outline.container.clientHeight / scale - (this.source.minimumGraphSize.height - 2 * pb.y)) / 2);
  10009. // Why is vertical offset negative relative to dy
  10010. return new mxPoint(Math.round(dx - pb.x), Math.round(dy - pb.y - 5 / scale));
  10011. }
  10012. return new mxPoint(8 / scale, 8 / scale);
  10013. };
  10014. var outlineInit = outline.init;
  10015. outline.init = function()
  10016. {
  10017. outlineInit.apply(this, arguments);
  10018. // Problem: Need to override a function in the view but the view is created
  10019. // with the graph so a refresh of the page is needed to see this change.
  10020. outline.outline.view.getBackgroundPageBounds = function()
  10021. {
  10022. var layout = graph.getPageLayout();
  10023. var page = graph.getPageSize();
  10024. return new mxRectangle(this.scale * (this.translate.x + layout.x * page.width),
  10025. this.scale * (this.translate.y + layout.y * page.height),
  10026. this.scale * layout.width * page.width,
  10027. this.scale * layout.height * page.height);
  10028. };
  10029. outline.outline.view.validateBackgroundPage();
  10030. };
  10031. this.editor.addListener('pageSelected', function(sender, evt)
  10032. {
  10033. var change = evt.getProperty('change');
  10034. var graph = outline.source;
  10035. var g = outline.outline;
  10036. g.pageScale = graph.pageScale;
  10037. g.pageFormat = graph.pageFormat;
  10038. g.background = graph.background;
  10039. g.pageVisible = graph.pageVisible;
  10040. g.background = graph.background;
  10041. var current = mxUtils.getCurrentStyle(graph.container);
  10042. g.container.style.backgroundColor = current.backgroundColor;
  10043. if (graph.view.backgroundPageShape != null && g.view.backgroundPageShape != null)
  10044. {
  10045. g.view.backgroundPageShape.fill = graph.view.backgroundPageShape.fill;
  10046. }
  10047. outline.outline.view.clear(change.previousPage.root, true);
  10048. outline.outline.view.validate();
  10049. });
  10050. return outline;
  10051. };
  10052. /**
  10053. * Returns the number of storage options enabled
  10054. */
  10055. EditorUi.prototype.getServiceCount = function(allowBrowser, splash)
  10056. {
  10057. var serviceCount = 0;
  10058. if (this.drive != null || typeof window.DriveClient === 'function')
  10059. {
  10060. serviceCount++
  10061. }
  10062. if (!splash && (this.dropbox != null || typeof window.DropboxClient === 'function'))
  10063. {
  10064. serviceCount++
  10065. }
  10066. if (this.oneDrive != null || typeof window.OneDriveClient === 'function')
  10067. {
  10068. serviceCount++
  10069. }
  10070. if (!splash && (this.gitHub != null))
  10071. {
  10072. serviceCount++
  10073. }
  10074. if (!splash && (this.trello != null || typeof window.TrelloClient === 'function'))
  10075. {
  10076. serviceCount++
  10077. }
  10078. if (allowBrowser && isLocalStorage && urlParams['browser'] == '1')
  10079. {
  10080. serviceCount++
  10081. }
  10082. else
  10083. {
  10084. serviceCount++
  10085. }
  10086. return serviceCount;
  10087. }
  10088. /**
  10089. * Updates action and menu states depending on the file.
  10090. */
  10091. EditorUi.prototype.updateUi = function()
  10092. {
  10093. this.updateButtonContainer();
  10094. this.updateActionStates();
  10095. // Action states that only need update for new files
  10096. var file = this.getCurrentFile();
  10097. var active = file != null || (urlParams['embed'] == '1' &&
  10098. this.editor.graph.isEnabled());
  10099. this.menus.get('viewPanels').setEnabled(active);
  10100. this.menus.get('viewZoom').setEnabled(active);
  10101. var restricted = (urlParams['embed'] != '1' ||
  10102. !this.editor.graph.isEnabled()) &&
  10103. (file == null || file.isRestricted());
  10104. this.actions.get('makeCopy').setEnabled(!restricted);
  10105. this.actions.get('print').setEnabled(!restricted);
  10106. this.menus.get('exportAs').setEnabled(!restricted);
  10107. this.menus.get('embed').setEnabled(!restricted);
  10108. // Disables libraries and extras menu in embed mode
  10109. // while waiting for file data
  10110. var libsEnabled = urlParams['embed'] != '1' ||
  10111. this.editor.graph.isEnabled();
  10112. this.menus.get('extras').setEnabled(libsEnabled);
  10113. if (Editor.enableCustomLibraries)
  10114. {
  10115. this.menus.get('openLibraryFrom').setEnabled(libsEnabled);
  10116. this.menus.get('newLibrary').setEnabled(libsEnabled);
  10117. }
  10118. // Disables actions in the toolbar
  10119. var editable = (urlParams['embed'] == '1' &&
  10120. this.editor.graph.isEnabled()) ||
  10121. (file != null && file.isEditable());
  10122. this.actions.get('image').setEnabled(active);
  10123. this.actions.get('zoomIn').setEnabled(active);
  10124. this.actions.get('zoomOut').setEnabled(active);
  10125. this.actions.get('resetView').setEnabled(active);
  10126. // Updates undo history states
  10127. this.actions.get('undo').setEnabled(this.canUndo() && editable);
  10128. this.actions.get('redo').setEnabled(this.canRedo() && editable);
  10129. // Disables menus
  10130. this.menus.get('edit').setEnabled(active);
  10131. this.menus.get('view').setEnabled(active);
  10132. this.menus.get('importFrom').setEnabled(editable);
  10133. this.menus.get('arrange').setEnabled(editable);
  10134. // Disables connection drop downs in toolbar
  10135. if (this.toolbar != null)
  10136. {
  10137. if (this.toolbar.edgeShapeMenu != null)
  10138. {
  10139. this.toolbar.edgeShapeMenu.setEnabled(editable);
  10140. }
  10141. if (this.toolbar.edgeStyleMenu != null)
  10142. {
  10143. this.toolbar.edgeStyleMenu.setEnabled(editable);
  10144. }
  10145. }
  10146. if (this.isAppCache())
  10147. {
  10148. var appCache = applicationCache;
  10149. // NOTE: HTML5 Cache is deprecated
  10150. if (appCache != null && this.offlineStatus == null)
  10151. {
  10152. this.offlineStatus = document.createElement('div');
  10153. this.offlineStatus.className = 'geItem';
  10154. this.offlineStatus.style.position = 'absolute';
  10155. this.offlineStatus.style.fontSize = '8pt';
  10156. this.offlineStatus.style.top = '2px';
  10157. this.offlineStatus.style.right = '12px';
  10158. this.offlineStatus.style.color = '#666';
  10159. this.offlineStatus.style.margin = '4px';
  10160. this.offlineStatus.style.padding = '2px';
  10161. this.offlineStatus.style.verticalAlign = 'middle';
  10162. this.offlineStatus.innerHTML = '';
  10163. this.menubarContainer.appendChild(this.offlineStatus);
  10164. mxEvent.addListener(this.offlineStatus, 'click', mxUtils.bind(this, function()
  10165. {
  10166. var img = this.offlineStatus.getElementsByTagName('img');
  10167. if (img != null && img.length > 0)
  10168. {
  10169. this.alert(img[0].getAttribute('title'));
  10170. }
  10171. }));
  10172. var appCache = window.applicationCache;
  10173. var lastStatus = null;
  10174. var updateStatus = mxUtils.bind(this, function()
  10175. {
  10176. var newStatus = appCache.status;
  10177. var html = '';
  10178. if (newStatus == appCache.CHECKING)
  10179. {
  10180. newStatus = appCache.DOWNLOADING;
  10181. }
  10182. switch (newStatus)
  10183. {
  10184. case appCache.UNCACHED: // UNCACHED == 0
  10185. html = '';
  10186. break;
  10187. case appCache.IDLE: // IDLE == 1
  10188. html = (uiTheme == 'min') ? '' : '<img title="draw.io is up to date." border="0" src="' + IMAGE_PATH + '/checkmark.gif"/>';
  10189. break;
  10190. case appCache.DOWNLOADING: // DOWNLOADING == 3
  10191. html = '<img title="Downloading new version..." border="0" src="' + IMAGE_PATH + '/spin.gif"/>';
  10192. break;
  10193. case appCache.UPDATEREADY: // UPDATEREADY == 4
  10194. html = '<img title="' + mxUtils.htmlEntities(mxResources.get('restartForChangeRequired')) +
  10195. '" border="0" src="' + IMAGE_PATH + '/download.png"/>';
  10196. break;
  10197. case appCache.OBSOLETE: // OBSOLETE == 5
  10198. html = '<img title="Obsolete" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  10199. break;
  10200. default:
  10201. html = '<img title="Unknown" border="0" src="' + IMAGE_PATH + '/clear.gif"/>';
  10202. break;
  10203. }
  10204. if (newStatus != lastStatus)
  10205. {
  10206. this.offlineStatus.innerHTML = html;
  10207. lastStatus = newStatus;
  10208. }
  10209. });
  10210. mxEvent.addListener(appCache, 'checking', updateStatus);
  10211. mxEvent.addListener(appCache, 'noupdate', updateStatus);
  10212. mxEvent.addListener(appCache, 'downloading', updateStatus);
  10213. mxEvent.addListener(appCache, 'progress', updateStatus);
  10214. mxEvent.addListener(appCache, 'cached', updateStatus);
  10215. mxEvent.addListener(appCache, 'updateready', updateStatus);
  10216. mxEvent.addListener(appCache, 'obsolete', updateStatus);
  10217. mxEvent.addListener(appCache, 'error', updateStatus);
  10218. updateStatus();
  10219. }
  10220. }
  10221. else
  10222. {
  10223. this.updateUserElement();
  10224. }
  10225. };
  10226. /**
  10227. * Hook for subclassers
  10228. */
  10229. EditorUi.prototype.updateButtonContainer = function()
  10230. {
  10231. // do nothing
  10232. };
  10233. /**
  10234. * Hook for subclassers
  10235. */
  10236. EditorUi.prototype.updateUserElement = function()
  10237. {
  10238. // do nothing
  10239. };
  10240. /**
  10241. * Hook for subclassers
  10242. */
  10243. EditorUi.prototype.scheduleSanityCheck = function()
  10244. {
  10245. // do nothing
  10246. };
  10247. /**
  10248. * Hook for subclassers
  10249. */
  10250. EditorUi.prototype.stopSanityCheck = function()
  10251. {
  10252. // do nothing
  10253. };
  10254. /**
  10255. * Returns true if a diagram is cative and editable.
  10256. */
  10257. EditorUi.prototype.isDiagramActive = function()
  10258. {
  10259. var file = this.getCurrentFile();
  10260. return (file != null && file.isEditable()) ||
  10261. (urlParams['embed'] == '1' && this.editor.graph.isEnabled());
  10262. };
  10263. /**
  10264. * Updates action states depending on the selection.
  10265. */
  10266. var editorUiUpdateActionStates = EditorUi.prototype.updateActionStates;
  10267. EditorUi.prototype.updateActionStates = function()
  10268. {
  10269. editorUiUpdateActionStates.apply(this, arguments);
  10270. var graph = this.editor.graph;
  10271. var active = this.isDiagramActive();
  10272. var file = this.getCurrentFile();
  10273. var enabled = file != null || urlParams['embed'] == '1';
  10274. this.actions.get('pageSetup').setEnabled(active);
  10275. this.actions.get('autosave').setEnabled(file != null && file.isEditable() && file.isAutosaveOptional());
  10276. this.actions.get('guides').setEnabled(active);
  10277. this.actions.get('editData').setEnabled(active);
  10278. this.actions.get('shadowVisible').setEnabled(active);
  10279. this.actions.get('connectionArrows').setEnabled(active);
  10280. this.actions.get('connectionPoints').setEnabled(active);
  10281. this.actions.get('copyStyle').setEnabled(active && !graph.isSelectionEmpty());
  10282. this.actions.get('pasteStyle').setEnabled(active && !graph.isSelectionEmpty());
  10283. this.actions.get('editGeometry').setEnabled(graph.getModel().isVertex(graph.getSelectionCell()));
  10284. this.actions.get('createShape').setEnabled(active);
  10285. this.actions.get('createRevision').setEnabled(active);
  10286. this.actions.get('moveToFolder').setEnabled(file != null);
  10287. this.actions.get('makeCopy').setEnabled(file != null && !file.isRestricted());
  10288. this.actions.get('editDiagram').setEnabled(active && (file == null || !file.isRestricted()));
  10289. this.actions.get('publishLink').setEnabled(file != null && !file.isRestricted());
  10290. this.actions.get('tags').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10291. this.actions.get('find').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10292. this.actions.get('layers').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10293. this.actions.get('outline').setEnabled(this.diagramContainer.style.visibility != 'hidden');
  10294. this.actions.get('rename').setEnabled((file != null && file.isRenamable()) || urlParams['embed'] == '1');
  10295. this.actions.get('close').setEnabled(file != null);
  10296. this.menus.get('publish').setEnabled(file != null && !file.isRestricted());
  10297. var state = graph.view.getState(graph.getSelectionCell());
  10298. this.actions.get('editShape').setEnabled(active && state != null && state.shape != null && state.shape.stencil != null);
  10299. };
  10300. /**
  10301. * Overridden to remove export dialog in chromeless lightbox.
  10302. */
  10303. var editoUiDestroy = EditorUi.prototype.destroy;
  10304. EditorUi.prototype.destroy = function()
  10305. {
  10306. if (this.editUpdateListener)
  10307. {
  10308. this.editor.undoManager.removeListener(this.editUpdateListener);
  10309. this.editUpdateListener = null;
  10310. }
  10311. if (this.exportDialog != null)
  10312. {
  10313. this.exportDialog.parentNode.removeChild(this.exportDialog);
  10314. this.exportDialog = null;
  10315. }
  10316. editoUiDestroy.apply(this, arguments);
  10317. };
  10318. /**
  10319. * Overrides export dialog for using ui functions for save and setting global switches.
  10320. */
  10321. if (window.ExportDialog != null)
  10322. {
  10323. ExportDialog.showXmlOption = false;
  10324. ExportDialog.showGifOption = false;
  10325. ExportDialog.exportFile = function(editorUi, name, format, bg, s, b)
  10326. {
  10327. var graph = editorUi.editor.graph;
  10328. if (format == 'xml')
  10329. {
  10330. editorUi.hideDialog();
  10331. editorUi.saveData(name, 'xml', mxUtils.getXml(editorUi.editor.getGraphXml()), 'text/xml');
  10332. }
  10333. else if (format == 'svg')
  10334. {
  10335. editorUi.hideDialog();
  10336. editorUi.saveData(name, 'svg', mxUtils.getXml(graph.getSvg(bg, s, b)), 'image/svg+xml');
  10337. }
  10338. else
  10339. {
  10340. var data = editorUi.getFileData(true, null, null, null, null, true);
  10341. var bounds = graph.getGraphBounds();
  10342. var w = Math.floor(bounds.width * s / graph.view.scale);
  10343. var h = Math.floor(bounds.height * s / graph.view.scale);
  10344. if (data.length <= MAX_REQUEST_SIZE && w * h < MAX_AREA)
  10345. {
  10346. editorUi.hideDialog();
  10347. if ((format == 'png' || format == 'jpg' || format == 'jpeg') && editorUi.isExportToCanvas())
  10348. {
  10349. if (format == 'png')
  10350. {
  10351. editorUi.exportImage(s, bg == null || bg == 'none', true,
  10352. false, false, b, true, false);
  10353. }
  10354. else
  10355. {
  10356. editorUi.exportImage(s, false, true,
  10357. false, false, b, true, false, 'jpeg');
  10358. }
  10359. }
  10360. else
  10361. {
  10362. editorUi.saveRequest(name, format,
  10363. function(newTitle, base64)
  10364. {
  10365. return new mxXmlRequest(EXPORT_URL, 'format=' + format + '&base64=' + (base64 || '0') +
  10366. ((newTitle != null) ? '&filename=' + encodeURIComponent(newTitle) : '') +
  10367. '&bg=' + ((bg != null) ? bg : 'none') + '&w=' + w + '&h=' + h +
  10368. '&border=' + b + '&xml=' + encodeURIComponent(data));
  10369. });
  10370. }
  10371. }
  10372. else
  10373. {
  10374. mxUtils.alert(mxResources.get('drawingTooLarge'));
  10375. }
  10376. }
  10377. };
  10378. }
  10379. /*********************************************************************************************
  10380. * This section is a fix for undo/redo edits having stale 1st- and 2nd-order references *
  10381. * The code might be reworked or even thrown out when a conceptually nicer solution is found *
  10382. *********************************************************************************************/
  10383. /**
  10384. * Updates all references in all edits and their changes in order to correspond to current model
  10385. */
  10386. EditorUi.prototype.updateEditReferences = function(edit)
  10387. {
  10388. for (var i = 0; i < edit.changes.length; i++)
  10389. {
  10390. var change = edit.changes[i];
  10391. if (change != null && change.constructor == mxChildChange)
  10392. {
  10393. if (change.child != null)
  10394. {
  10395. var child = change.child;
  10396. if (child.source != null && child.source.id != null)
  10397. {
  10398. var modelSource = this.getFutureCellForEdit(change.model, edit, child.source.id);
  10399. if (modelSource != child.source)
  10400. {
  10401. child.source = modelSource
  10402. }
  10403. }
  10404. if (child.target != null && child.target.id != null)
  10405. {
  10406. var modelTarget = this.getFutureCellForEdit(change.model, edit, child.target.id);
  10407. if (modelTarget != child.target)
  10408. {
  10409. child.target = modelTarget
  10410. }
  10411. }
  10412. }
  10413. }
  10414. }
  10415. };
  10416. /**
  10417. * Looks ahead in edit's changes to see if the last child change containing ID is one that creates a cell, then returns it.
  10418. * If cell already exists in a model, returns it first.
  10419. */
  10420. EditorUi.prototype.getFutureCellForEdit = function(model, edit, id)
  10421. {
  10422. var result = model.getCell(id);
  10423. if (result == null)
  10424. {
  10425. // Scans changes backwards
  10426. for (var i = edit.changes.length - 1; i >= 0; i--)
  10427. {
  10428. var change = edit.changes[i];
  10429. if (change.constructor == mxChildChange)
  10430. {
  10431. // Checks if child is being added in this change
  10432. if (change.child != null && change.child.id == id)
  10433. {
  10434. // Checks if cell is being removed
  10435. if (model.contains(change.previous))
  10436. {
  10437. result = change.child;
  10438. }
  10439. // Stops scan in any case, at the end of the edit
  10440. // the cell will be either added or deleted
  10441. break;
  10442. }
  10443. }
  10444. }
  10445. }
  10446. return result;
  10447. };
  10448. EditorUi.prototype.getDiagramTextContent = function()
  10449. {
  10450. this.editor.graph.setEnabled(false);
  10451. var graph = this.editor.graph;
  10452. var allPagesTxt = '';
  10453. if (this.pages != null)
  10454. {
  10455. for (var i = 0; i < this.pages.length; i++)
  10456. {
  10457. var pageGraph = graph;
  10458. if (this.currentPage != this.pages[i])
  10459. {
  10460. pageGraph = this.createTemporaryGraph(graph.getStylesheet());
  10461. pageGraph.model.setRoot(this.pages[i].root);
  10462. }
  10463. allPagesTxt += this.pages[i].getName() + ' ' + pageGraph.getIndexableText() + ' ';
  10464. }
  10465. }
  10466. else
  10467. {
  10468. allPagesTxt = graph.getIndexableText();
  10469. }
  10470. this.editor.graph.setEnabled(true);
  10471. return allPagesTxt;
  10472. };
  10473. EditorUi.prototype.showRemotelyStoredLibrary = function(title)
  10474. {
  10475. var selectedLibs = {};
  10476. var div = document.createElement('div');
  10477. div.style.whiteSpace = 'nowrap';
  10478. var graph = this.editor.graph;
  10479. var hd = document.createElement('h3');
  10480. mxUtils.write(hd, mxUtils.htmlEntities(title));
  10481. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  10482. div.appendChild(hd);
  10483. var libsSection = document.createElement('div');
  10484. libsSection.style.cssText = 'border:1px solid lightGray;overflow: auto;height:300px';
  10485. libsSection.innerHTML = '<img src="/images/spin.gif">';
  10486. var loadedLibs = {};
  10487. try
  10488. {
  10489. var custLibs = mxSettings.getCustomLibraries();
  10490. for (var j = 0; j < custLibs.length; j++)
  10491. {
  10492. var l = custLibs[j];
  10493. if (l.substring(0, 1) == 'R')
  10494. {
  10495. var libDesc = JSON.parse(decodeURIComponent(l.substring(1)));
  10496. loadedLibs[libDesc[0]] = {
  10497. id: libDesc[0],
  10498. title: libDesc[1],
  10499. downloadUrl: libDesc[2]
  10500. };
  10501. }
  10502. }
  10503. }
  10504. catch(e){}
  10505. this.remoteInvoke('getCustomLibraries', null, null, function(libsList)
  10506. {
  10507. libsSection.innerHTML = '';
  10508. if (libsList.length == 0)
  10509. {
  10510. libsSection.innerHTML = '<div style="text-align:center;padding-top:20px;color:gray;">' +
  10511. mxUtils.htmlEntities(mxResources.get('noLibraries')) + '</div>';
  10512. }
  10513. else
  10514. {
  10515. for (var i = 0; i < libsList.length; i++)
  10516. {
  10517. var lib = libsList[i];
  10518. if (loadedLibs[lib.id])
  10519. {
  10520. selectedLibs[lib.id] = lib;
  10521. }
  10522. var libCheck = this.addCheckbox(libsSection, lib.title, loadedLibs[lib.id]);
  10523. (function(lib2, check)
  10524. {
  10525. mxEvent.addListener(check, 'change', function()
  10526. {
  10527. if (this.checked)
  10528. {
  10529. selectedLibs[lib2.id] = lib2;
  10530. }
  10531. else
  10532. {
  10533. delete selectedLibs[lib2.id];
  10534. }
  10535. });
  10536. })(lib, libCheck)
  10537. }
  10538. }
  10539. }, function()
  10540. {
  10541. this.handleError(null, mxResources.get('errorLoadingFile'));
  10542. });
  10543. div.appendChild(libsSection);
  10544. var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
  10545. {
  10546. this.spinner.spin(document.body, mxResources.get('loading'));
  10547. var pendingLibs = 0;
  10548. for (var id in selectedLibs)
  10549. {
  10550. if (loadedLibs[id] != null) continue; //already loaded!
  10551. pendingLibs++;
  10552. (mxUtils.bind(this, function(lib)
  10553. {
  10554. this.remoteInvoke('getFileContent', [lib.downloadUrl], null, mxUtils.bind(this, function(libContent)
  10555. {
  10556. pendingLibs--;
  10557. if (pendingLibs == 0) this.spinner.stop();
  10558. try
  10559. {
  10560. this.loadLibrary(new RemoteLibrary(this, libContent, lib));
  10561. }
  10562. catch (e)
  10563. {
  10564. this.handleError(e, mxResources.get('errorLoadingFile'));
  10565. }
  10566. }), mxUtils.bind(this, function()
  10567. {
  10568. pendingLibs--;
  10569. if (pendingLibs == 0) this.spinner.stop();
  10570. this.handleError(null, mxResources.get('errorLoadingFile'));
  10571. }));
  10572. }))(selectedLibs[id]);
  10573. }
  10574. for (var id in loadedLibs)
  10575. {
  10576. if (!selectedLibs[id]) //Removed
  10577. {
  10578. this.closeLibrary(new RemoteLibrary(this, null, loadedLibs[id])); //create a dummy library such that we can call closeLibrary
  10579. }
  10580. }
  10581. if (pendingLibs == 0) this.spinner.stop();
  10582. }), null, null, 'https://desk.draw.io/support/solutions/articles/16000092763');
  10583. this.showDialog(dlg.container, 340, 375, true, true);
  10584. };
  10585. //Remote invokation, currently limited to functions in EditorUi (and its sub objects) for security reasons
  10586. //White-listed functions and some info about it
  10587. EditorUi.prototype.remoteInvokableFns = {
  10588. getDiagramTextContent: {isAsync: false}
  10589. };
  10590. EditorUi.prototype.remoteInvokeCallbacks = [];
  10591. EditorUi.prototype.remoteInvokeQueue = [];
  10592. EditorUi.prototype.handleRemoteInvokeReady = function(remoteWin)
  10593. {
  10594. this.remoteWin = remoteWin;
  10595. for (var i = 0; i < this.remoteInvokeQueue.length; i++)
  10596. {
  10597. remoteWin.postMessage(this.remoteInvokeQueue[i], '*');
  10598. }
  10599. this.remoteInvokeQueue = [];
  10600. };
  10601. EditorUi.prototype.handleRemoteInvokeResponse = function(msg)
  10602. {
  10603. var msgMarkers = msg.msgMarkers;
  10604. var callback = this.remoteInvokeCallbacks[msgMarkers.callbackId];
  10605. if (msg.error)
  10606. {
  10607. if (callback.error) callback.error(msg.error.errResp);
  10608. }
  10609. else if (callback.callback)
  10610. {
  10611. callback.callback.apply(this, msg.resp);
  10612. }
  10613. this.remoteInvokeCallbacks[msgMarkers.callbackId] = null; //set it to null only to keep the index
  10614. };
  10615. EditorUi.prototype.remoteInvoke = function(remoteFn, remoteFnArgs, msgMarkers, callback, error)
  10616. {
  10617. msgMarkers = msgMarkers || {};
  10618. msgMarkers.callbackId = this.remoteInvokeCallbacks.length;
  10619. this.remoteInvokeCallbacks.push({callback: callback, error: error});
  10620. var msg = JSON.stringify({event: 'remoteInvoke', funtionName: remoteFn, functionArgs: remoteFnArgs, msgMarkers: msgMarkers});
  10621. if (this.remoteWin != null) //remote invoke is ready
  10622. {
  10623. this.remoteWin.postMessage(msg, '*');
  10624. }
  10625. else
  10626. {
  10627. this.remoteInvokeQueue.push(msg);
  10628. }
  10629. };
  10630. EditorUi.prototype.handleRemoteInvoke = function(msg)
  10631. {
  10632. var sendResponse = mxUtils.bind(this, function(resp, error)
  10633. {
  10634. var respMsg = {event: 'remoteInvokeResponse', msgMarkers: msg.msgMarkers};
  10635. if (error != null)
  10636. {
  10637. respMsg.error = {errResp: error};
  10638. }
  10639. else if (resp != null)
  10640. {
  10641. respMsg.resp = resp;
  10642. }
  10643. this.remoteWin.postMessage(JSON.stringify(respMsg), '*');
  10644. });
  10645. try
  10646. {
  10647. //Remote invoke are allowed to call functions in AC
  10648. var funtionName = msg.funtionName;
  10649. var functionInfo = this.remoteInvokableFns[funtionName];
  10650. if (functionInfo != null && typeof this[funtionName] === 'function')
  10651. {
  10652. var functionArgs = msg.functionArgs;
  10653. //Confirm functionArgs are not null and is array, otherwise, discard it
  10654. if (!Array.isArray(functionArgs))
  10655. {
  10656. functionArgs = [];
  10657. }
  10658. //for functions with callbacks (async) we assume last two arguments are success, error
  10659. if (functionInfo.isAsync)
  10660. {
  10661. //success
  10662. functionArgs.push(function()
  10663. {
  10664. sendResponse(Array.prototype.slice.apply(arguments));
  10665. });
  10666. //error
  10667. functionArgs.push(function(err)
  10668. {
  10669. sendResponse(null, err || 'Unkown Error');
  10670. });
  10671. this[funtionName].apply(this, functionArgs);
  10672. }
  10673. else
  10674. {
  10675. var resp = this[funtionName].apply(this, functionArgs);
  10676. sendResponse([resp]);
  10677. }
  10678. }
  10679. else
  10680. {
  10681. sendResponse(null, 'Invalid Call: ' + funtionName + ' is not found.');
  10682. }
  10683. }
  10684. catch(e)
  10685. {
  10686. sendResponse(null, 'Invalid Call: An error occured, ' + e.message);
  10687. }
  10688. };
  10689. /**
  10690. *
  10691. * Comments: We need these functions as wrapper of File functions in order to facilitate overriding them if comments are needed without having a file
  10692. * (e.g. Confluence Plugin)
  10693. *
  10694. */
  10695. /**
  10696. * Are comments supported
  10697. */
  10698. EditorUi.prototype.commentsSupported = function()
  10699. {
  10700. var file = this.getCurrentFile();
  10701. return file != null? file.commentsSupported() : false;
  10702. };
  10703. /**
  10704. * Show refresh button?
  10705. */
  10706. EditorUi.prototype.commentsRefreshNeeded = function()
  10707. {
  10708. var file = this.getCurrentFile();
  10709. return file != null? file.commentsRefreshNeeded() : true;
  10710. };
  10711. /**
  10712. * Show save button?
  10713. */
  10714. EditorUi.prototype.commentsSaveNeeded = function()
  10715. {
  10716. var file = this.getCurrentFile();
  10717. return file != null? file.commentsSaveNeeded() : false;
  10718. };
  10719. /**
  10720. * Get comments
  10721. */
  10722. EditorUi.prototype.getComments = function(success, error)
  10723. {
  10724. var file = this.getCurrentFile();
  10725. if (file != null)
  10726. {
  10727. file.getComments(success, error);
  10728. }
  10729. else
  10730. {
  10731. success([]); //placeholder
  10732. }
  10733. };
  10734. /**
  10735. * Add a comment
  10736. */
  10737. EditorUi.prototype.addComment = function(comment, success, error)
  10738. {
  10739. var file = this.getCurrentFile();
  10740. if (file != null)
  10741. {
  10742. file.addComment(comment, success, error);
  10743. }
  10744. else
  10745. {
  10746. success(Date.now()); //placeholder
  10747. }
  10748. };
  10749. /**
  10750. * Can add a reply to a reply
  10751. */
  10752. EditorUi.prototype.canReplyToReplies = function()
  10753. {
  10754. var file = this.getCurrentFile();
  10755. return file != null? file.canReplyToReplies() : true;
  10756. };
  10757. /**
  10758. * Can add comments (The permission to comment)
  10759. */
  10760. EditorUi.prototype.canComment = function()
  10761. {
  10762. var file = this.getCurrentFile();
  10763. return file != null? file.canComment() : true;
  10764. };
  10765. /**
  10766. * Get a new comment object
  10767. */
  10768. EditorUi.prototype.newComment = function(content, user)
  10769. {
  10770. var file = this.getCurrentFile();
  10771. if (file != null)
  10772. {
  10773. return file.newComment(content, user)
  10774. }
  10775. else
  10776. {
  10777. return new DrawioComment(this, null, content, Date.now(), Date.now(), false, user);
  10778. }
  10779. };
  10780. //==================================================== End of comments =================================================================
  10781. /**
  10782. * Does revisions history available
  10783. */
  10784. EditorUi.prototype.isRevisionHistorySupported = function()
  10785. {
  10786. var file = this.getCurrentFile();
  10787. return file != null && file.isRevisionHistorySupported();
  10788. };
  10789. /**
  10790. * Get revisions of current file
  10791. */
  10792. EditorUi.prototype.getRevisions = function(success, error)
  10793. {
  10794. var file = this.getCurrentFile();
  10795. if (file != null && file.getRevisions)
  10796. {
  10797. file.getRevisions(success, error);
  10798. }
  10799. else
  10800. {
  10801. error({message: mxResources.get('unknownError')});
  10802. }
  10803. };
  10804. /**
  10805. * Is revisions history enabled
  10806. */
  10807. EditorUi.prototype.isRevisionHistoryEnabled = function()
  10808. {
  10809. var file = this.getCurrentFile();
  10810. return file != null &&
  10811. ((file.constructor == DriveFile && file.isEditable()) ||
  10812. file.constructor == DropboxFile);
  10813. };
  10814. })();
  10815. /**
  10816. * Comments Window, It is used by both editor and viewer. So, it is here in a common place
  10817. */
  10818. var CommentsWindow = function(editorUi, x, y, w, h, saveCallback)
  10819. {
  10820. var readOnly = !editorUi.canComment();
  10821. var canReplyToReplies = editorUi.canReplyToReplies();
  10822. var curEdited = null;
  10823. var div = document.createElement('div');
  10824. div.className = 'geCommentsWin';
  10825. div.style.background = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10826. var tbarHeight = (!EditorUi.compactUi) ? '30px' : '26px';
  10827. var listDiv = document.createElement('div');
  10828. listDiv.className = 'geCommentsList';
  10829. listDiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10830. listDiv.style.bottom = (parseInt(tbarHeight) + 7) + 'px';
  10831. div.appendChild(listDiv);
  10832. var noComments = document.createElement('span');
  10833. noComments.style.cssText = 'display:none;padding-top:10px;text-align:center;';
  10834. mxUtils.write(noComments, mxResources.get('noCommentsFound'));
  10835. var selectionComment = null;
  10836. var ldiv = document.createElement('div');
  10837. ldiv.className = 'geToolbarContainer geCommentsToolbar';
  10838. ldiv.style.height = tbarHeight;
  10839. ldiv.style.padding = (!EditorUi.compactUi) ? '1px' : '4px 0px 3px 0px';
  10840. ldiv.style.backgroundColor = (Dialog.backdropColor == 'white') ? 'whiteSmoke' : Dialog.backdropColor;
  10841. if (mxClient.IS_QUIRKS)
  10842. {
  10843. ldiv.style.filter = 'none';
  10844. }
  10845. var link = document.createElement('a');
  10846. link.className = 'geButton';
  10847. if (mxClient.IS_QUIRKS)
  10848. {
  10849. link.style.filter = 'none';
  10850. }
  10851. function updateNoComments()
  10852. {
  10853. var divs = listDiv.getElementsByTagName('div');
  10854. var visibleCount = 0;
  10855. for (var i = 0; i < divs.length; i++)
  10856. {
  10857. if (divs[i].style.display != 'none' && divs[i].parentNode == listDiv)
  10858. {
  10859. visibleCount++;
  10860. }
  10861. }
  10862. noComments.style.display = (visibleCount == 0) ? 'block' : 'none';
  10863. };
  10864. function editComment(comment, cdiv, saveCallback, deleteOnCancel)
  10865. {
  10866. curEdited = {div: cdiv, comment: comment, saveCallback: saveCallback, deleteOnCancel: deleteOnCancel};
  10867. var commentTxt = cdiv.querySelector('.geCommentTxt');
  10868. var actionsDiv = cdiv.querySelector('.geCommentActionsList');
  10869. var textArea = document.createElement('textarea');
  10870. textArea.className = 'geCommentEditTxtArea';
  10871. textArea.style.minHeight = commentTxt.offsetHeight + 'px';
  10872. textArea.value = comment.content;
  10873. cdiv.insertBefore(textArea, commentTxt);
  10874. var btnDiv = document.createElement('div');
  10875. btnDiv.className = 'geCommentEditBtns';
  10876. function reset()
  10877. {
  10878. cdiv.removeChild(textArea);
  10879. cdiv.removeChild(btnDiv);
  10880. actionsDiv.style.display = 'block';
  10881. commentTxt.style.display = 'block';
  10882. };
  10883. var cancelBtn = mxUtils.button(mxResources.get('cancel'), function()
  10884. {
  10885. if (deleteOnCancel)
  10886. {
  10887. cdiv.parentNode.removeChild(cdiv);
  10888. updateNoComments();
  10889. }
  10890. else
  10891. {
  10892. reset();
  10893. }
  10894. curEdited = null;
  10895. });
  10896. cancelBtn.className = 'geCommentEditBtn';
  10897. btnDiv.appendChild(cancelBtn);
  10898. var saveBtn = mxUtils.button(mxResources.get('save'), function()
  10899. {
  10900. commentTxt.innerHTML = '';
  10901. comment.content = textArea.value;
  10902. mxUtils.write(commentTxt, comment.content);
  10903. reset();
  10904. saveCallback(comment);
  10905. curEdited = null;
  10906. });
  10907. // Updates modified state and handles placeholder text
  10908. mxEvent.addListener(textArea, 'keydown', mxUtils.bind(this, function(evt)
  10909. {
  10910. if (!mxEvent.isConsumed(evt))
  10911. {
  10912. if ((mxEvent.isControlDown(evt) || (mxClient.IS_MAC &&
  10913. mxEvent.isMetaDown(evt))) && evt.keyCode == 13 /* Ctrl+Enter */)
  10914. {
  10915. saveBtn.click();
  10916. mxEvent.consume(evt);
  10917. }
  10918. else if (evt.keyCode == 27 /* Escape */)
  10919. {
  10920. cancelBtn.click();
  10921. mxEvent.consume(evt);
  10922. }
  10923. }
  10924. }));
  10925. // Focused to include in viewport before focusin textbox
  10926. saveBtn.focus();
  10927. saveBtn.className = 'geCommentEditBtn gePrimaryBtn';
  10928. btnDiv.appendChild(saveBtn);
  10929. cdiv.insertBefore(btnDiv, commentTxt);
  10930. actionsDiv.style.display = 'none';
  10931. commentTxt.style.display = 'none';
  10932. textArea.focus();
  10933. };
  10934. function writeCommentDate(comment, dateDiv)
  10935. {
  10936. dateDiv.innerHTML = '';
  10937. var str = editorUi.timeSince(new Date(comment.modifiedDate));
  10938. if (str == null)
  10939. {
  10940. str = mxResources.get('lessThanAMinute');
  10941. }
  10942. mxUtils.write(dateDiv, mxResources.get('timeAgo', [str], '{1} ago'));
  10943. };
  10944. function showBusy(commentDiv)
  10945. {
  10946. var busyImg = document.createElement('img');
  10947. busyImg.className = 'geCommentBusyImg';
  10948. busyImg.src= '/images/spin.gif';
  10949. commentDiv.appendChild(busyImg);
  10950. commentDiv.busyImg = busyImg;
  10951. };
  10952. function showError(commentDiv)
  10953. {
  10954. commentDiv.style.border = '1px solid red';
  10955. commentDiv.removeChild(commentDiv.busyImg);
  10956. };
  10957. function showDone(commentDiv)
  10958. {
  10959. commentDiv.style.border = '';
  10960. commentDiv.removeChild(commentDiv.busyImg);
  10961. };
  10962. function addComment(comment, parentArr, parent, level, showResolved)
  10963. {
  10964. //Skip resolved comments if showResolved is not set
  10965. if (!showResolved && comment.isResolved)
  10966. {
  10967. return;
  10968. }
  10969. noComments.style.display = 'none';
  10970. var cdiv = document.createElement('div');
  10971. cdiv.className = 'geCommentContainer';
  10972. cdiv.setAttribute('data-commentId', comment.id);
  10973. cdiv.style.marginLeft = (level * 20 + 5) + 'px';
  10974. if (comment.isResolved && uiTheme != 'dark')
  10975. {
  10976. cdiv.style.backgroundColor = 'ghostWhite';
  10977. }
  10978. var headerDiv = document.createElement('div');
  10979. headerDiv.className = 'geCommentHeader';
  10980. var userImg = document.createElement('img');
  10981. userImg.className = 'geCommentUserImg';
  10982. userImg.src = comment.user.pictureUrl || Editor.userImage;
  10983. headerDiv.appendChild(userImg);
  10984. var headerTxt = document.createElement('div');
  10985. headerTxt.className = 'geCommentHeaderTxt';
  10986. headerDiv.appendChild(headerTxt);
  10987. var usernameDiv = document.createElement('div');
  10988. usernameDiv.className = 'geCommentUsername';
  10989. mxUtils.write(usernameDiv, comment.user.displayName || '');
  10990. headerTxt.appendChild(usernameDiv);
  10991. var dateDiv = document.createElement('div');
  10992. dateDiv.className = 'geCommentDate';
  10993. dateDiv.setAttribute('data-commentId', comment.id);
  10994. writeCommentDate(comment, dateDiv);
  10995. headerTxt.appendChild(dateDiv);
  10996. cdiv.appendChild(headerDiv);
  10997. var commentTxtDiv = document.createElement('div');
  10998. commentTxtDiv.className = 'geCommentTxt';
  10999. mxUtils.write(commentTxtDiv, comment.content || '');
  11000. cdiv.appendChild(commentTxtDiv);
  11001. var actionsDiv = document.createElement('div');
  11002. actionsDiv.className = 'geCommentActions';
  11003. var actionsList = document.createElement('ul');
  11004. actionsList.className = 'geCommentActionsList';
  11005. actionsDiv.appendChild(actionsList);
  11006. function addAction(name, evtHandler, hide)
  11007. {
  11008. var action = document.createElement('li');
  11009. action.className = 'geCommentAction';
  11010. var actionLnk = document.createElement('a');
  11011. actionLnk.className = 'geCommentActionLnk';
  11012. mxUtils.write(actionLnk, name);
  11013. action.appendChild(actionLnk);
  11014. mxEvent.addListener(actionLnk, 'click', function(evt)
  11015. {
  11016. evtHandler(evt, comment);
  11017. evt.preventDefault();
  11018. mxEvent.consume(evt);
  11019. });
  11020. actionsList.appendChild(action);
  11021. if (hide) action.style.display = 'none';
  11022. };
  11023. function collectReplies()
  11024. {
  11025. var replies = [];
  11026. var pdiv = cdiv;
  11027. function collectReplies(comment)
  11028. {
  11029. replies.push(pdiv);
  11030. if (comment.replies != null)
  11031. {
  11032. for (var i = 0; i < comment.replies.length; i++)
  11033. {
  11034. pdiv = pdiv.nextSibling;
  11035. collectReplies(comment.replies[i]);
  11036. }
  11037. }
  11038. }
  11039. collectReplies(comment);
  11040. return {pdiv: pdiv, replies: replies};
  11041. };
  11042. function addReply(initContent, editIt, saveCallback, doResolve, doReopen)
  11043. {
  11044. var pdiv = collectReplies().pdiv;
  11045. var newReply = editorUi.newComment(initContent, editorUi.getCurrentUser());
  11046. newReply.pCommentId = comment.id;
  11047. if (comment.replies == null) comment.replies = [];
  11048. var replyComment = addComment(newReply, comment.replies, pdiv, level + 1);
  11049. function doAddReply()
  11050. {
  11051. showBusy(replyComment);
  11052. comment.addReply(newReply, function(id)
  11053. {
  11054. newReply.id = id;
  11055. comment.replies.push(newReply);
  11056. showDone(replyComment);
  11057. if (saveCallback) saveCallback();
  11058. }, function(err)
  11059. {
  11060. doEdit();
  11061. showError(replyComment);
  11062. editorUi.handleError(err, null, null, null,
  11063. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  11064. }, doResolve, doReopen);
  11065. };
  11066. function doEdit()
  11067. {
  11068. editComment(newReply, replyComment, function(newReply)
  11069. {
  11070. doAddReply();
  11071. }, true);
  11072. };
  11073. if (editIt)
  11074. {
  11075. doEdit();
  11076. }
  11077. else
  11078. {
  11079. doAddReply();
  11080. }
  11081. };
  11082. if (!readOnly && (level == 0 || canReplyToReplies))
  11083. {
  11084. addAction(mxResources.get('reply'), function()
  11085. {
  11086. addReply('', true);
  11087. }, comment.isResolved);
  11088. }
  11089. var user = editorUi.getCurrentUser();
  11090. if (user != null && user.id == comment.user.id && !readOnly)
  11091. {
  11092. addAction(mxResources.get('edit'), function()
  11093. {
  11094. function doEditComment()
  11095. {
  11096. editComment(comment, cdiv, function()
  11097. {
  11098. showBusy(cdiv);
  11099. comment.editComment(comment.content, function()
  11100. {
  11101. showDone(cdiv);
  11102. }, function(err)
  11103. {
  11104. showError(cdiv);
  11105. doEditComment();
  11106. editorUi.handleError(err, null, null, null,
  11107. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  11108. });
  11109. });
  11110. };
  11111. doEditComment();
  11112. }, comment.isResolved);
  11113. addAction(mxResources.get('delete'), function()
  11114. {
  11115. editorUi.confirm(mxResources.get('areYouSure'), function()
  11116. {
  11117. showBusy(cdiv);
  11118. comment.deleteComment(function()
  11119. {
  11120. var replies = collectReplies(comment).replies;
  11121. for (var i = 0; i < replies.length; i++)
  11122. {
  11123. listDiv.removeChild(replies[i]);
  11124. }
  11125. for (var i = 0; i < parentArr.length; i++)
  11126. {
  11127. if (parentArr[i] == comment)
  11128. {
  11129. parentArr.splice(i, 1);
  11130. break;
  11131. }
  11132. }
  11133. noComments.style.display = (listDiv.getElementsByTagName('div').length == 0) ? 'block' : 'none';
  11134. }, function(err)
  11135. {
  11136. showError(cdiv);
  11137. editorUi.handleError(err, null, null, null,
  11138. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  11139. });
  11140. });
  11141. }, comment.isResolved);
  11142. }
  11143. if (!readOnly && level == 0) //Resolve is a top-level action only
  11144. {
  11145. function toggleResolve(evt)
  11146. {
  11147. function doToggle()
  11148. {
  11149. var resolveActionLnk = evt.target;
  11150. resolveActionLnk.innerHTML = '';
  11151. comment.isResolved = !comment.isResolved;
  11152. mxUtils.write(resolveActionLnk, comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'));
  11153. var actionsDisplay = comment.isResolved? 'none' : '';
  11154. var replies = collectReplies(comment).replies;
  11155. var color = (uiTheme == 'dark') ? 'transparent' : (comment.isResolved? 'ghostWhite' : 'white');
  11156. for (var i = 0; i < replies.length; i++)
  11157. {
  11158. replies[i].style.backgroundColor = color;
  11159. var forOpenActions = replies[i].querySelectorAll('.geCommentAction');
  11160. for (var j = 0; j < forOpenActions.length; j ++)
  11161. {
  11162. if (forOpenActions[j] == resolveActionLnk.parentNode) continue;
  11163. forOpenActions[j].style.display = actionsDisplay;
  11164. }
  11165. if (!resolvedChecked)
  11166. {
  11167. replies[i].style.display = 'none';
  11168. }
  11169. }
  11170. updateNoComments();
  11171. };
  11172. if (comment.isResolved)
  11173. {
  11174. addReply(mxResources.get('reOpened') + ': ', true, doToggle, false, true);
  11175. }
  11176. else
  11177. {
  11178. addReply(mxResources.get('markedAsResolved'), false, doToggle, true);
  11179. }
  11180. };
  11181. addAction(comment.isResolved? mxResources.get('reopen') : mxResources.get('resolve'), toggleResolve);
  11182. }
  11183. cdiv.appendChild(actionsDiv);
  11184. if (parent != null)
  11185. {
  11186. listDiv.insertBefore(cdiv, parent.nextSibling);
  11187. }
  11188. else
  11189. {
  11190. listDiv.appendChild(cdiv);
  11191. }
  11192. for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
  11193. {
  11194. var reply = comment.replies[i];
  11195. reply.isResolved = comment.isResolved; //copy isResolved to child comments (replies)
  11196. addComment(reply, comment.replies, null, level + 1, showResolved);
  11197. }
  11198. if (curEdited != null)
  11199. {
  11200. if (curEdited.comment.id == comment.id)
  11201. {
  11202. var origContent = comment.content;
  11203. comment.content = curEdited.comment.content;
  11204. editComment(comment, cdiv, curEdited.saveCallback, curEdited.deleteOnCancel);
  11205. comment.content = origContent;
  11206. }
  11207. else if (curEdited.comment.id == null && curEdited.comment.pCommentId == comment.id)
  11208. {
  11209. listDiv.appendChild(curEdited.div);
  11210. editComment(curEdited.comment, curEdited.div, curEdited.saveCallback, curEdited.deleteOnCancel);
  11211. }
  11212. }
  11213. return cdiv;
  11214. };
  11215. if (!readOnly)
  11216. {
  11217. var addLink = link.cloneNode();
  11218. addLink.innerHTML = '<div class="geSprite geSprite-plus" style="display:inline-block;"></div>';
  11219. addLink.setAttribute('title', mxResources.get('create') + '...');
  11220. mxEvent.addListener(addLink, 'click', function(evt)
  11221. {
  11222. var newComment = editorUi.newComment('', editorUi.getCurrentUser());
  11223. var newCommentDiv = addComment(newComment, comments, null, 0);
  11224. function doAddComment()
  11225. {
  11226. editComment(newComment, newCommentDiv, function(newComment)
  11227. {
  11228. showBusy(newCommentDiv);
  11229. editorUi.addComment(newComment, function(id)
  11230. {
  11231. newComment.id = id;
  11232. comments.push(newComment);
  11233. showDone(newCommentDiv);
  11234. }, function(err)
  11235. {
  11236. showError(newCommentDiv);
  11237. doAddComment();
  11238. editorUi.handleError(err, null, null, null,
  11239. mxUtils.htmlEntities(mxResources.get('objectNotFound')));
  11240. });
  11241. }, true);
  11242. }
  11243. doAddComment();
  11244. evt.preventDefault();
  11245. mxEvent.consume(evt);
  11246. });
  11247. ldiv.appendChild(addLink);
  11248. }
  11249. var resolvedLink = link.cloneNode();
  11250. resolvedLink.innerHTML = '<img src="/images/check.png" style="width: 16px; padding: 2px;">';
  11251. resolvedLink.setAttribute('title', mxResources.get('showResolved'));
  11252. var resolvedChecked = false;
  11253. if (uiTheme == 'dark')
  11254. {
  11255. resolvedLink.style.filter = 'invert(100%)';
  11256. }
  11257. mxEvent.addListener(resolvedLink, 'click', function(evt)
  11258. {
  11259. resolvedChecked = !resolvedChecked;
  11260. this.className = resolvedChecked? 'geButton geCheckedBtn' : 'geButton';
  11261. refresh();
  11262. evt.preventDefault();
  11263. mxEvent.consume(evt);
  11264. });
  11265. ldiv.appendChild(resolvedLink);
  11266. if (editorUi.commentsRefreshNeeded())
  11267. {
  11268. var refreshLink = link.cloneNode();
  11269. refreshLink.innerHTML = '<img src="/images/update16.png" style="width: 16px; padding: 2px;">';
  11270. refreshLink.setAttribute('title', mxResources.get('refresh'));
  11271. if (uiTheme == 'dark')
  11272. {
  11273. refreshLink.style.filter = 'invert(100%)';
  11274. }
  11275. mxEvent.addListener(refreshLink, 'click', function(evt)
  11276. {
  11277. refresh();
  11278. evt.preventDefault();
  11279. mxEvent.consume(evt);
  11280. });
  11281. ldiv.appendChild(refreshLink);
  11282. }
  11283. if (editorUi.commentsSaveNeeded())
  11284. {
  11285. var saveLink = link.cloneNode();
  11286. saveLink.innerHTML = '<img src="/images/save.png" style="width: 20px; padding: 2px;">';
  11287. saveLink.setAttribute('title', mxResources.get('save'));
  11288. if (uiTheme == 'dark')
  11289. {
  11290. saveLink.style.filter = 'invert(100%)';
  11291. }
  11292. mxEvent.addListener(saveLink, 'click', function(evt)
  11293. {
  11294. saveCallback();
  11295. evt.preventDefault();
  11296. mxEvent.consume(evt);
  11297. });
  11298. ldiv.appendChild(saveLink);
  11299. }
  11300. div.appendChild(ldiv);
  11301. var comments = [];
  11302. var refresh = mxUtils.bind(this, function()
  11303. {
  11304. if (curEdited != null)
  11305. {
  11306. curEdited.div = curEdited.div.cloneNode(true);
  11307. var commentEditTxt = curEdited.div.querySelector('.geCommentEditTxtArea');
  11308. var commentEditBtns = curEdited.div.querySelector('.geCommentEditBtns');
  11309. curEdited.comment.content = commentEditTxt.value;
  11310. commentEditTxt.parentNode.removeChild(commentEditTxt);
  11311. commentEditBtns.parentNode.removeChild(commentEditBtns);
  11312. }
  11313. listDiv.innerHTML = '<div style="padding-top:10px;text-align:center;"><img src="/images/spin.gif" valign="middle"> ' +
  11314. mxUtils.htmlEntities(mxResources.get('loading')) + '...</div>';
  11315. canReplyToReplies = editorUi.canReplyToReplies();
  11316. if (editorUi.commentsSupported())
  11317. {
  11318. editorUi.getComments(function(list)
  11319. {
  11320. function sortReplies(replies)
  11321. {
  11322. if (replies != null)
  11323. {
  11324. //Sort replies old to new
  11325. replies.sort(function(r1, r2)
  11326. {
  11327. return new Date(r1.modifiedDate) - new Date(r2.modifiedDate);
  11328. });
  11329. for (var i = 0; i < replies.length; i++)
  11330. {
  11331. sortReplies(replies[i].replies);
  11332. }
  11333. }
  11334. };
  11335. //Sort comments old to new
  11336. list.sort(function(c1, c2)
  11337. {
  11338. return new Date(c1.modifiedDate) - new Date(c2.modifiedDate);
  11339. });
  11340. listDiv.innerHTML = '';
  11341. listDiv.appendChild(noComments);
  11342. noComments.style.display = 'block';
  11343. comments = list;
  11344. for (var i = 0; i < comments.length; i++)
  11345. {
  11346. sortReplies(comments[i].replies);
  11347. addComment(comments[i], comments, null, 0, resolvedChecked);
  11348. }
  11349. //New comment case
  11350. if (curEdited != null && curEdited.comment.id == null && curEdited.comment.pCommentId == null)
  11351. {
  11352. listDiv.appendChild(curEdited.div);
  11353. editComment(curEdited.comment, curEdited.div, curEdited.saveCallback, curEdited.deleteOnCancel);
  11354. }
  11355. }, function()
  11356. {
  11357. listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error'));
  11358. });
  11359. }
  11360. else
  11361. {
  11362. //TODO if comments are not supported, close the dialog
  11363. listDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('error'));
  11364. }
  11365. });
  11366. refresh();
  11367. this.refreshComments = refresh;
  11368. //Refresh the modified date of each comment if the window is visible
  11369. var refreshCommentsTime = mxUtils.bind(this, function()
  11370. {
  11371. if (!this.window.isVisible()) return; //only update if it is visible
  11372. var modDateDivs = listDiv.querySelectorAll('.geCommentDate');
  11373. var modDateDivsMap = {};
  11374. for (var i = 0; i < modDateDivs.length; i++)
  11375. {
  11376. var div = modDateDivs[i];
  11377. modDateDivsMap[div.getAttribute('data-commentId')] = div;
  11378. }
  11379. function processComment(comment)
  11380. {
  11381. var div = modDateDivsMap[comment.id];
  11382. if (div == null) return; //resolved comments
  11383. writeCommentDate(comment, div);
  11384. for (var i = 0; comment.replies != null && i < comment.replies.length; i++)
  11385. {
  11386. processComment(comment.replies[i]);
  11387. }
  11388. };
  11389. for (var i = 0; i < comments.length; i++)
  11390. {
  11391. processComment(comments[i]);
  11392. }
  11393. });
  11394. //Periodically refresh time every one minute
  11395. setInterval(refreshCommentsTime, 60000);
  11396. this.refreshCommentsTime = refreshCommentsTime;
  11397. this.window = new mxWindow(mxResources.get('comments'), div, x, y, w, h, true, true);
  11398. this.window.minimumSize = new mxRectangle(0, 0, 300, 200);
  11399. this.window.destroyOnClose = false;
  11400. this.window.setMaximizable(false);
  11401. this.window.setResizable(true);
  11402. this.window.setClosable(true);
  11403. this.window.setVisible(true);
  11404. this.window.addListener(mxEvent.SHOW, mxUtils.bind(this, function()
  11405. {
  11406. this.window.fit();
  11407. }));
  11408. this.window.setLocation = function(x, y)
  11409. {
  11410. var iw = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
  11411. var ih = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight;
  11412. x = Math.max(0, Math.min(x, iw - this.table.clientWidth));
  11413. y = Math.max(0, Math.min(y, ih - this.table.clientHeight - 48));
  11414. if (this.getX() != x || this.getY() != y)
  11415. {
  11416. mxWindow.prototype.setLocation.apply(this, arguments);
  11417. }
  11418. };
  11419. var resizeListener = mxUtils.bind(this, function()
  11420. {
  11421. var x = this.window.getX();
  11422. var y = this.window.getY();
  11423. this.window.setLocation(x, y);
  11424. });
  11425. mxEvent.addListener(window, 'resize', resizeListener);
  11426. this.destroy = function()
  11427. {
  11428. mxEvent.removeListener(window, 'resize', resizeListener);
  11429. this.window.destroy();
  11430. }
  11431. };
  11432. /**
  11433. *
  11434. */
  11435. var ConfirmDialog = function(editorUi, message, okFn, cancelFn, okLabel, cancelLabel, okImg, cancelImg, showRememberOption, imgSrc)
  11436. {
  11437. var div = document.createElement('div');
  11438. div.style.textAlign = 'center';
  11439. var p2 = document.createElement('div');
  11440. p2.style.padding = '6px';
  11441. p2.style.overflow = 'auto';
  11442. p2.style.maxHeight = '44px';
  11443. p2.style.lineHeight = '1.2em';
  11444. if (mxClient.IS_QUIRKS)
  11445. {
  11446. p2.style.height = '60px';
  11447. }
  11448. mxUtils.write(p2, message);
  11449. div.appendChild(p2);
  11450. if (imgSrc != null)
  11451. {
  11452. var p3 = document.createElement('div');
  11453. p3.style.padding = '6px 0 6px 0';
  11454. var img = document.createElement('img');
  11455. img.setAttribute('src', imgSrc);
  11456. p3.appendChild(img);
  11457. div.appendChild(p3);
  11458. }
  11459. var btns = document.createElement('div');
  11460. btns.style.textAlign = 'center';
  11461. btns.style.whiteSpace = 'nowrap';
  11462. var cb = document.createElement('input');
  11463. cb.setAttribute('type', 'checkbox');
  11464. var cancelBtn = mxUtils.button(cancelLabel || mxResources.get('cancel'), function()
  11465. {
  11466. editorUi.hideDialog();
  11467. if (cancelFn != null)
  11468. {
  11469. cancelFn(cb.checked);
  11470. }
  11471. });
  11472. cancelBtn.className = 'geBtn';
  11473. if (cancelImg != null)
  11474. {
  11475. cancelBtn.innerHTML = cancelImg + '<br>' + cancelBtn.innerHTML;
  11476. cancelBtn.style.paddingBottom = '8px';
  11477. cancelBtn.style.paddingTop = '8px';
  11478. cancelBtn.style.height = 'auto';
  11479. cancelBtn.style.width = '40%';
  11480. }
  11481. if (editorUi.editor.cancelFirst)
  11482. {
  11483. btns.appendChild(cancelBtn);
  11484. }
  11485. var okBtn = mxUtils.button(okLabel || mxResources.get('ok'), function()
  11486. {
  11487. editorUi.hideDialog();
  11488. if (okFn != null)
  11489. {
  11490. okFn(cb.checked);
  11491. }
  11492. });
  11493. btns.appendChild(okBtn);
  11494. if (okImg != null)
  11495. {
  11496. okBtn.innerHTML = okImg + '<br>' + okBtn.innerHTML + '<br>';
  11497. okBtn.style.paddingBottom = '8px';
  11498. okBtn.style.paddingTop = '8px';
  11499. okBtn.style.height = 'auto';
  11500. okBtn.className = 'geBtn';
  11501. okBtn.style.width = '40%';
  11502. }
  11503. else
  11504. {
  11505. okBtn.className = 'geBtn gePrimaryBtn';
  11506. }
  11507. if (!editorUi.editor.cancelFirst)
  11508. {
  11509. btns.appendChild(cancelBtn);
  11510. }
  11511. div.appendChild(btns);
  11512. if (showRememberOption)
  11513. {
  11514. btns.style.marginTop = '10px';
  11515. var p2 = document.createElement('p');
  11516. p2.style.marginTop = '20px';
  11517. p2.appendChild(cb);
  11518. var span = document.createElement('span');
  11519. mxUtils.write(span, ' ' + mxResources.get('rememberThisSetting'));
  11520. p2.appendChild(span);
  11521. div.appendChild(p2);
  11522. mxEvent.addListener(span, 'click', function(evt)
  11523. {
  11524. cb.checked = !cb.checked;
  11525. mxEvent.consume(evt);
  11526. });
  11527. }
  11528. else
  11529. {
  11530. btns.style.marginTop = '12px';
  11531. }
  11532. this.init = function()
  11533. {
  11534. okBtn.focus();
  11535. };
  11536. this.container = div;
  11537. };